Introduction
A book about compilers, built around one small enough to read end to end.
The compiler targets INTERCAL, a programming language Donald Woods and James Lyon invented in 1972 specifically to resemble nothing else. Most compiler textbooks pick a mini-C or a mini-Lisp because the syntax stays out of the way. INTERCAL goes the other direction. Its grammar has no operator precedence. Its arithmetic is bitwise only. It rejects programs that are too rude or too polite at compile time. READ OUT prints Roman numerals; array I/O goes through a 256-position tape with bit-reversed addressing. Writing a compiler for it forces you to think about every classical phase, because the language never lets you reuse a familiar shortcut.
The compiler in this repository is real and self-hosting. About two thousand lines of zsh do the bootstrap; a few hundred per platform of hand-written assembly do the runtime; ten thousand lines of pure INTERCAL form a system library that the compiler verifies against a fast native rewrite. Every example in the book points at code you can clone, edit, and run.
How the book is organised
Six parts plus a reference appendix.
Part I is the first-contact tour. Install the toolchain, compile hello-world, learn the language vocabulary, meet the syscall extension that makes self-hosting possible. By the end you have a working compiler and enough INTERCAL to read the test programs.
Parts II through V follow the compiler front to back. Part II is the layout map and a one-pass walk of the whole pipeline. Part III is the front end: scanning, parsing, semantic analysis. Part IV is the back end: code generation, runtime, system library, calling conventions, executable formats. Part IV.5 is one chapter each for the four most distinctive INTERCAL features (the politeness rule, COME FROM, the Turing Text Model, and Roman-numeral I/O). Part V covers platforms, self-hosting, testing, debugging, and how the compiler reports errors.
Part VI steps back from the implementation. It compares INTERCAL to conventional languages, places it within the broader genre of esoteric languages, and weighs it against the canonical language-design advice of Hoare and Wirth. It also documents how to land a first contribution and how to work on the codebase alongside an AI agent.
Part VII bridges to production compilers. The vocabulary built up across Parts I to VI maps directly onto LLVM, GCC, and rustc; this final part names the correspondence, gives a structural orientation to each codebase, and walks the practical steps from "I have read this book" to "I am submitting a patch upstream". It is the part the book exists for: the rest is preparation.
The reference appendix is for lookup, not reading: a statement cheatsheet, the EBNF grammar, a glossary, exercise hints, and an annotated bibliography.
Who should read what
New to compilers and want a complete worked example? Read Parts I through V in order. You finish with a working understanding of every phase of a real compiler.
Already comfortable with compilers, here for INTERCAL specifically? Skim Part I and dwell in Parts III and IV. The exercises at the end of each chapter are calibrated for somebody testing an explanation, not for a beginner.
Here to modify this compiler? Your home is Part V (platforms, testing, debugging) plus the reference appendix. The map in Part II is where you find any specific routine.
Here because you want to contribute to a production compiler, LLVM, GCC, rustc, Go, GHC, OCaml, Cranelift, Zig, Swift, or V8, and you want the cheapest path? Read Parts I through V to acquire the vocabulary, then jump to Part VII. The capstone chapter from-intercal-to-real-compilers.md names what you already know and what you do not. Each compiler has its own self-contained chapter; pick one and read just that.
A note on the project
The compiler is also a small experiment in AI-assisted development. Most of the code came from a large language model working with one human collaborator: the human picked the goals, made the first commits, supplied references, and reviewed the result; the day-to-day implementation was the model's. INTERCAL fits the experiment because off-the-shelf code patterns rarely apply to it, and any divergence from the spec is detectable.
Where to go next
The shortest path from clone to running hello-world is getting-started.md.
For the language tour, intercal-primer.md.
For the shape of the compiler in two short chapters, overview.md followed by pipeline.md.
The full chapter list is in the right-hand sidebar (or in README.md if you are reading on GitHub).
The source lives at https://github.com/jhg/intercal. Issues, pull requests, and discussion happen there.
What is INTERCAL?
INTERCAL is a programming language invented at Princeton in 1972 by Donald Woods and James Lyon. Its full name, in keeping with the era, is Compiler Language With No Pronounceable Acronym. Since that does not yield a pronounceable acronym either, everyone calls it INTERCAL.
This chapter is for somebody who has never seen the language. No code, no compiler theory, just what it is and why people still write compilers for it fifty years on.
The short version
INTERCAL was designed to be unlike every other language of its time. Where Fortran has IF, INTERCAL has no conditional statement. Where C has +, *, /, INTERCAL has bitwise operators only. Where Java has objects, INTERCAL has numbered variables. Where Python prints with print("hello"), INTERCAL prints in Roman numerals.
It is Turing-complete. Given time and patience it can compute anything any other language can compute. It just refuses to make any of it convenient.
That sounds like a terrible language. It is. That is the point.
Why INTERCAL exists
INTERCAL was written as a critique. Programming-language design in 1972 was in a phase of rapid proliferation, with a new language every year claiming to be better than the last. Woods and Lyon wrote a manual that parodied the genre, describing a language that included every feature they found irritating and excluded every feature they found useful.
Some highlights of the spec:
- The verbs are
DO,PLEASE, andPLEASE DO, all functionally equivalent. - A program must use
PLEASEon between 1/5 and 1/3 of its statements. Too few, and the compiler refuses to compile it as "insufficiently polite". Too many, and it complains that you are "overly polite". - Variables are not named, they are numbered:
.1,.2,:1, and so on. - There is no arithmetic. Addition, subtraction, multiplication and division are bitwise tricks that have to be called as subroutines.
- Number output is in Roman numerals. Text output goes through a simulated tape loop where each character is encoded as a tape-head displacement.
- Number input arrives one digit at a time, spelled out in English:
ONE TWO THREEfor 123. - Punctuation has names.
.is "spot",:is "two-spot",,is "tail",$is "big money".
Every choice is internally consistent. The language works. You can write programs in it, read them back, and run them. In a technical sense it is not broken. In a design sense it is perfectly wrong.
The COME FROM statement
INTERCAL's most-quoted invention is COME FROM. It was not in the 1972 manual, but later implementations adopted it and it has stuck. COME FROM is the inverse of GOTO: instead of saying "go to that statement", you say "come back here after that statement runs".
The cursed consequence is that a statement elsewhere in the program can hook itself onto any labelled statement without the labelled statement knowing. Reading an INTERCAL program top to bottom tells you only part of the story. You also have to scan for COME FROM lines that might secretly redirect the flow.
COME FROM has been rediscovered several times outside INTERCAL, including in a serious 1973 proposal by R. Lawrence Clark and as a Perl module. It remains one of the more subversive ideas in control flow.
Why anyone still writes INTERCAL compilers
A small community has maintained INTERCAL implementations continuously since the original. The main ones today:
- C-INTERCAL by Eric S. Raymond (1990 onwards), written in C, still actively maintained.
- CLC-INTERCAL by Claudio Calvelli (1999 onwards), written in Perl, with extensions including quantum primitives.
- This implementation, written in zsh and INTERCAL, targeting native ARM64 and x86-64 binaries with no C intermediate.
Why? Four reasons, in decreasing order of seriousness:
- It is a clean test case for compiler construction. INTERCAL is small enough that a full implementation fits in a single person's head, but weird enough that writing the compiler forces you to engage with every classical compiler-theory topic. It is a good teaching language precisely because it is bad.
- Self-hosting INTERCAL is a feat in its own right. Writing a compiler for a language in that same language is a rite of passage; doing it for INTERCAL is particularly absurd. As of this writing, nobody has ever produced a self-hosted INTERCAL compiler whose own source is written in INTERCAL. This repository is trying.
- It is a useful proving ground for AI-driven development. Most of the code in this repository was written by a large language model paired with one human collaborator: the human set the goals, made the first commits, supplied references, and reviewed; the compiler, runtime, syslib, and tests came from the model. INTERCAL fits the experiment because off-the-shelf code patterns rarely apply to it, and any divergence from the spec is detectable.
- It is funny. Some of the most influential programming languages (Lisp, Smalltalk, Forth) were invented partly as jokes and partly as serious experiments. INTERCAL sits squarely in that tradition. Reading a long INTERCAL program is a kind of performance art.
What INTERCAL is not
Not a golf language like J or APL. Not a brain-teaser language like Brainfuck. Not obfuscated to be hard to read; most INTERCAL is legible once you know the conventions.
And, despite appearances, not contrarianism for its own sake. The language has internal logic. Once you accept that conventional features are suspect, every decision follows.
A glimpse of what a program looks like
The hello-world program from this repository:
DO ,1 <- #14
DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #108
DO ,1 SUB #3 <- #112
PLEASE ,1 SUB #4 <- #0
DO ,1 SUB #5 <- #64
DO ,1 SUB #6 <- #194
DO ,1 SUB #7 <- #48
PLEASE ,1 SUB #8 <- #26
DO ,1 SUB #9 <- #244
DO ,1 SUB #10 <- #168
DO ,1 SUB #11 <- #24
PLEASE ,1 SUB #12 <- #16
DO ,1 SUB #13 <- #162
DO ,1 SUB #14 <- #52
PLEASE READ OUT ,1
DO GIVE UP
It prints Hello, World!. Each ,1 SUB #N <- #V puts value V into the Nth slot of array ,1. The constants 238, 108, 112, 0, and so on encode the letters H, e, l, l, o, and the rest, through a scheme called the Turing Text Model (see runtime.md). The first statement dimensions the array to 14 slots; READ OUT ,1 walks them and prints the result.
The program has 17 statements and 4 of them start with PLEASE, giving a politeness ratio of about 24%, comfortably inside the required [20%, 33.3%] range.
What to read next
- getting-started.md: install the compiler and run this program.
- intercal-primer.md: a programmer-focused language tour.
- design-rationale.md: a FAQ on why this compiler is shaped the way it is.
- history-and-context.md: the longer historical treatment.
Getting started
Nothing assumed here. You do not need to know INTERCAL or anything about compilers. If you can install software and use a terminal, you can follow along. The aim is a working compiler and a compiled hello-world, in about thirty minutes.
If you are already an experienced developer and just want to skim the pipeline, jump to overview.md.
What you need
One of these computers:
- A Mac with Apple Silicon (any M-series chip).
- A Linux box with an Intel or AMD 64-bit CPU.
- A Linux box with an ARM 64-bit CPU (Raspberry Pi 4 or 5, a cloud ARM VM).
And two programs: zsh (a shell) and gcc (a C compiler, used here only as an assembler and linker). Both ship with macOS. On Ubuntu or Debian:
sudo apt install zsh gcc
On Fedora and similar:
sudo dnf install zsh gcc
That is the full list. No Python, no Node, no other language toolchain. INTERCAL is the only language we add.
If you plan to reproduce the Linux CI tests from a Mac, install Docker Desktop too. It is optional; the steps in this chapter do not need it.
Get the code
git clone https://github.com/jhg/intercal.git
cd intercal
A few seconds. The repository is roughly a megabyte on disk.
Run your first compilation
The simplest possible INTERCAL program lives in tests/test_give_up.i:
cat tests/test_give_up.i
You should see:
DO GIVE UP
A one-statement program: "do give up", meaning exit. Compile it:
zsh src/bootstrap/intercalc.sh < tests/test_give_up.i > my_program
chmod +x my_program
./my_program
echo "Exit code was: $?"
Expected:
Exit code was: 0
Your first INTERCAL program compiled. It did nothing. It exited cleanly. That is the whole story.
What happened along the way:
zsh src/bootstrap/intercalc.shran the bootstrap compiler.< tests/test_give_up.ipiped the INTERCAL source into the compiler's standard input.> my_programredirected the compiler's standard output (a native executable binary) into a file.chmod +xmarked the file as runnable../my_programran it.- The program exited with status 0.
Run hello world
Something more interesting:
zsh src/bootstrap/intercalc.sh < tests/test_hello.i > hello
chmod +x hello
./hello
You should see:
Hello, World!
The source has seventeen statements that look alien. Open tests/test_hello.i and glance at it. If you cannot make sense of the constants, that is fine; most of INTERCAL resists sense at first. The chapter walkthrough-hello.md decodes it when you are ready.
Run the test suite
The repository ships 33 INTERCAL programs, each with an expected output. The runner compiles each, runs it, and compares stdout:
zsh tests/run_tests.sh
You should see 33 lines of PASS and a final line:
Results: 33 passed, 0 failed
If anything failed, stop and ask. Something about your setup is off.
Tweak your first program
To convince yourself the compiler is doing real work, open tests/test_hello.i and look at this line:
DO ,1 SUB #4 <- #0
It is the fifth element of array ,1, and its value is what produces the comma in "Hello, World!". Change #0 to something else (try #50), save, recompile:
zsh src/bootstrap/intercalc.sh < tests/test_hello.i > hello
chmod +x hello
./hello
The output changes. The fifth character is no longer a comma. Which character it becomes depends on the new delta modulo the Turing Text Model tape's 256-position wraparound. Try a few values; notice that everything before and after the changed character stays put.
Revert when you are done:
git checkout tests/test_hello.i
Understand what just happened
The compiler is the zsh script src/bootstrap/intercalc.sh. Open it in any text editor. It is roughly two thousand lines. Do not try to read it end to end. Just notice that it is one file, and that everything you ran went through it.
The runtime, the code that every compiled INTERCAL program links against, lives in src/runtime/<your-platform>.s. On macOS that is src/runtime/macos_arm64.s. Glance at it. About 970 lines of hand-written assembly. Do not try to read this end to end either. It is one file per platform, and your hello binary contains a copy.
The system library is in src/syslib/syslib.i (the pure-INTERCAL version) and src/syslib/native/<platform>.s (the fast native one). Both provide arithmetic. Hello world does not do arithmetic, so neither was linked into your binary.
A tiny map of the territory
You just exercised three pieces:
- A compiler. Reads INTERCAL, emits a native binary.
- A runtime. Provides print, exit, and arithmetic primitives the binary calls into.
- A test suite. Confirms the first two work.
Every other file in the repository supports those three. The docs/ directory you are reading is one example, AGENTS.md is another, the CI workflows under .github/ a third.
What to read next
If you are curious about the language:
- what-is-intercal.md: INTERCAL in plain English, no code.
- intercal-primer.md: a tighter, programmer-oriented tour.
If you are curious about the compiler:
- overview.md: a more technical "what this repo is".
- pipeline.md: how source becomes binary, step by step.
If you are curious about the design:
- design-rationale.md: a FAQ on every major choice.
- 666.md: the deep dive on the Label 666 syscall extension.
If you want to make a change:
- your-first-contribution.md: a concrete walkthrough of adding a small feature.
AGENTS.md(in the repo root): the authoritative contributor guide.
If you got stuck
intercalc.sh: command not found: you are running from a directory other than the repo root.cdinto it.ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE: the program you fed in is too impolite. Stay with the test programs for now; we will explain politeness later.zsh: bad interpreteron Linux: install zsh (sudo apt install zsh).- Nothing prints when you run
./hello: check that the file exists (ls -l hello) and is executable (chmod +x hello).
For anything else, read AGENTS.md or open an issue.
INTERCAL primer
A minimal introduction to INTERCAL aimed at two readers: a programmer who wants to read the test programs under tests/, and a compiler reader who needs the language vocabulary before approaching the per-phase chapters. The aim is not to teach you to write INTERCAL programs from scratch; for that, follow the resources in further-reading.md. The complete language reference lives in AGENTS.md, section "INTERCAL language reference".
If you have not built the compiler, start with getting-started.md. If you want a non-technical introduction first, what-is-intercal.md.
A program, stripped down
DO .1 <- #5
PLEASE READ OUT .1
DO GIVE UP
Three statements. The first assigns 5 to the scalar variable .1. The second writes it out in Roman numerals (so you see V). The third exits. Two statements start with DO, one with PLEASE, and GIVE UP is mandatory.
To read INTERCAL as a compiler writer, you only need to know what each token does and why it matters for the compiler.
Statement shape
Every statement has five pieces in this order, three of them optional:
- An optional label in parentheses:
(1000). Labels are 1–65535 and must be unique. Labels 1000–1999 are reserved for the system library. - A required verb:
DO,PLEASE, orPLEASE DO. Functionally identical. The compiler only cares whetherPLEASEis present, because that is how you satisfy the politeness rule. - An optional negation:
NOTorN'T. A negated statement starts abstained and has no effect untilREINSTATEd.DON'Tis a tokenised form ofDO NOT. - An optional probability:
%50. The statement executes half the time. - The body: assignment, control-flow, I/O, etc.
The compiler stores each statement as a tuple (label, polite, negated, probability, type, body), spread across the parallel arrays stmt_label, stmt_polite, stmt_negated, stmt_prob, stmt_type, stmt_body in intercalc.sh.
Variables and constants
Four variable prefixes:
| Prefix | Name | Type |
|---|---|---|
. | onespot | 16-bit unsigned |
: | twospot | 32-bit unsigned |
, | tail array | array of 16-bit values |
; | hybrid array | array of 32-bit values |
Constants have prefix # and are always 16-bit: #42, #65535. For 32-bit constants, build them with operators.
The four prefixes share a numbering namespace: .1, ,1, and :1 are three unrelated variables. Up to 65535 of each kind.
Variables start at zero. Assigning above 65535 to a onespot is a runtime error (ICL275I).
Operators and grouping
No operator precedence. Every subexpression that could be ambiguous must be grouped, and the grouping alternates between two characters: sparks ' and rabbit-ears ". Where a C programmer writes (a + (b * c)), an INTERCAL programmer writes 'a op "b op c"'. Same-kind nesting is not allowed.
Two binary operators:
$(big money), mingle. Interleaves the bits of two 16-bit values into a 32-bit result. Left operand to odd bit positions, right operand to even.~(sqiggle), select. Given a value and a mask, extract the bits of the value where the mask has a 1, and pack them right-justified.
Three unary operators, placed between the prefix and the number (&.1, V:2, ?,1 SUB #3):
&: AND each bit with its right neighbour (wrapping).V(uppercase V, not ∨): OR each bit with its right neighbour.?: XOR each bit with its right neighbour.
The unary operators work on the bits of one value, not between two values. A common trick used throughout the compiler: to AND two 16-bit values A and B, mingle them into one 32-bit value A$B, apply unary &, then select the even-position bits out. The pattern appears many times in syslib.i.
Assignment
DO .1 <- #5
The <- is angle-worm. Left side is a variable or array element. Right side is an expression. The compiler evaluates the RHS, optionally checks for 32-into-16-bit overflow, and stores into the target.
For array elements: ,1 SUB #3 <- #42. SUB is the subscript operator, space-separated.
Control flow
No if, no while, no for, no goto. The transfer-of-control primitives are:
DO (N) NEXT: push the current position onto the NEXT stack (max depth 79, ICL123I if you exceed) and jump to labelN.DO RESUME #K: pop K entries from the NEXT stack and jump to the last one popped.RESUME #1is a clean subroutine return.RESUME #0is a runtime error.DO FORGET #K: pop K entries without transferring.DO COME FROM (N): after the statement at labelNexecutes, control transfers here. Resolved at compile time.DO GIVE UP: exit.
The absence of if is not a problem in practice. Convert a truthy value into "1 or 2", push two NEXT targets for the two branches, and RESUME with the 1-or-2 variable. See the idioms section in AGENTS.md ("Essential idioms").
Abstain / reinstate / ignore / remember
Four modifiers control what is live at runtime:
DO ABSTAIN FROM (N): skip statementNfrom now on.DO ABSTAIN FROM gerund-list: same, but by category.CALCULATINGcovers all assignments,NEXTINGall NEXTs, etc.DO REINSTATE ...: reverse an ABSTAIN.DO IGNORE var-list: make variables read-only. Writes are silently discarded.DO REMEMBER var-list: reverse an IGNORE.
The compiler tracks abstention as a bit per statement in BSS, in a region called _stmt_flags. Each statement starts with a flag check that jumps over its body if abstained.
STASH and RETRIEVE
DO STASH .1 .2
...
DO RETRIEVE .1 .2
Per-variable stacks. Used whenever you call a syslib routine that might clobber .1–.4 or :1–:4. Calling RETRIEVE without a prior STASH fires ICL436I.
I/O
Numeric:
DO READ OUT .1: print the value of.1in Roman numerals.DO WRITE IN .1: read a number whose digits are spelled in English (ONE TWO THREEis 123).
Character (Turing Text Model):
DO READ OUT ,1: walk the tape forwards and backwards, printing characters.DO WRITE IN ,1: the inverse, reading characters and converting to tape-offset deltas.
The Turing Text Model (TTM) encoding is what makes tests/test_hello.i look the way it does. You cannot just put H e l l o in the source. Each character has to be precomputed as a tape-offset delta whose effect, after the tape head's bit-reversed position, lands at the ASCII code you want. The compiler does not care; it just emits calls to _rt_read_out_array. The encoding matters when you read the test programs. See runtime.md for the algorithm in full.
Politeness
Between one-fifth and one-third of all statements must use PLEASE or PLEASE DO. The compiler counts during semantic analysis and rejects programs outside the range:
- Fewer than 1/5 → ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE.
- More than 1/3 → ICL099I PROGRAMMER IS OVERLY POLITE.
A whole-program property; you cannot decide politeness per statement. See semantic-analysis.md for the implementation.
What else exists that the compiler treats uniformly
A few features the spec treats as important but which our compiler handles uniformly enough not to need their own chapter:
- Statement probabilities (
%50): the compiler emits a random-roll check and skips the body if the roll fails. - Gerunds (
CALCULATING,NEXTING, etc.):ABSTAIN FROM CALCULATINGis just "flip the abstain bit on every statement of type assignment", a loop in codegen. - Comments: there are none in standard INTERCAL.
DON'T NOTE ...is the idiomatic fake-comment, a negatedUNKNOWNstatement that is skipped at runtime and never executed. The compiler classifies it asUNKNOWN_NEGATEDand emits nothing.
That is enough to read the test programs and the source. Next: pipeline.md.
Exercises
- The hello-world program in
tests/test_hello.ihas 17 statements and 4PLEASEs. Compute its politeness ratio. By how much could you shrink the program before falling below the 1/5 threshold, assuming you do not touch thePLEASEs? - Write the smallest INTERCAL program that uses
STASHandRETRIEVEcorrectly. What goes wrong if you swap their order? - The unary operators
&,V,?operate on adjacent bits of one value. Compute, on paper, the result of(unary AND applied to the constant 5, treated as 16-bit). - INTERCAL has no
if. Look up the conversion idiom inAGENTS.md(section "Essential idioms") and explain in one paragraph how it lets you express a two-way branch. DON'T NOTE foo baris the idiomatic comment. What other constructions could be used to comment out a line, and why are they worse?
Label 666: a gentle introduction
INTERCAL has no file I/O, no command-line arguments, no way to ask the operating system for the time of day or a random number. The 1972 spec was complete without these. Programs read from stdin, wrote to stdout, and that was that.
Five decades later this is constraining. A compiler written in INTERCAL needs to open a source file by name, not hope the user piped it in. A self-hosted compiler needs to know its own argv to print usage messages. A serious program needs a reliable random number. The 1972 specification offers none of this.
This compiler's answer is Label 666. The chapter explains what it is, why we need it, and how to use it. It is the friendly version; the deep design rationale is in 666.md.
Why a built-in extension at all
Most languages cope with the lack of OS access by providing a way out: an FFI to call C, an inline-assembly form, a way to link against compiled object files, a foreign-function declaration. INTERCAL offers none of that.
It has no inline-assembly construct. There is no equivalent of C's asm("...") or Rust's asm!, no syntactic place to drop a few raw target instructions into your INTERCAL program. The grammar simply does not have a slot for it.
It has no foreign-function-interface declaration. C lets you extern int foo(int); and link against any object file that supplies foo. Rust has extern "C" fn foo(x: i32) -> i32;. Python has ctypes. INTERCAL has no syntax for any of this. There is no way for a programmer to declare "here is a routine I will provide separately".
It has no linker awareness. The 1972 spec assumes the program is a self-contained INTERCAL source file. There is no #include, no module import, no way for an INTERCAL program to reference symbols from a separately compiled translation unit. A compiler can choose to link the user's INTERCAL with handwritten assembly (as ours does for the runtime), but the programmer cannot ask for it.
It has no shared-library mechanism. There is no dlopen analogue, no concept of a runtime-loaded plugin, nothing like a JVM class loader.
In short, every conventional escape hatch a programmer reaches for to extend their language with native code is absent from INTERCAL. The only way through the wall is a feature that lives inside the language itself. Label 666 is that feature.
The problem, concretely
Suppose an INTERCAL program wants to open a file. In standard INTERCAL:
- Filenames are strings. INTERCAL has no string type.
- File operations (open, read, write, close) are operating-system calls. INTERCAL has no syscall mechanism.
- Command-line arguments live in
argv[]. INTERCAL has no reference toargv.
So the direct answer is: it cannot. A standard INTERCAL program has no means to open a file at all.
The solution: a syscall extension
Label 666 is an extension that adds a tiny amount of operating-system access to INTERCAL, just enough for useful programs. The central idea:
- The runtime reserves the label
666as a special target. - When a program executes
DO (666) NEXT, the runtime does not jump to user code. It reads a few predetermined variables (.1,.2,.3,.4, and the array,65535), performs the corresponding syscall, and returns. - The user program reads the results from the same variables.
So instead of "jump to label 666", the programmer thinks "invoke a syscall based on what I put in .1".
The syscall numbers
Eight syscalls today. Each is identified by the number you put in .1 before executing DO (666) NEXT:
.1 | Syscall | What it does |
|---|---|---|
| 1 | open | Opens a file. Filename is in ,65535. Result: file descriptor in .3. |
| 2 | read | Reads from a file descriptor into ,65535. Result: byte count in .4. |
| 3 | write | Writes from ,65535 to a file descriptor. Result: byte count in .4. |
| 4 | close | Closes a file descriptor. |
| 5 | argc | Returns the number of command-line arguments in .3. |
| 6 | argv | Reads the Nth argument into ,65535 and its length into .3. |
| 8 | exit | Exits the program with the given status code. |
| 9 | getrand | Returns a random number in .3. |
Parameters and results live in pre-agreed variables:
.1is the syscall number (input)..2is the primary parameter (file descriptor, arg index, exit code, random-range limit)..3is the primary result (new file descriptor, byte count, arg count, random number)..4is the secondary result (bytes actually read or written).,65535is the data buffer for file contents, argument strings, filenames. Reserved exclusively for Label 666.
A short worked example
A program that reads its first command-line argument and prints the length:
DO ,65535 <- #65535
PLEASE DO .1 <- #6
PLEASE DO .2 <- #1
DO (666) NEXT
PLEASE DO .10 <- .3
DO READ OUT .10
DO GIVE UP
Line by line:
DO ,65535 <- #65535dimensions the data buffer once at program entry.PLEASE DO .1 <- #6sets the syscall number to 6 (argv).PLEASE DO .2 <- #1sets the primary parameter to 1 (the first argument, 0-indexed).DO (666) NEXTinvokes the syscall. The runtime reads the argument into,65535and stores its length in.3.PLEASE DO .10 <- .3saves the length somewhere we control.DO READ OUT .10prints the length in Roman numerals.DO GIVE UPexits.
Compile this and run as ./program foo: it prints III (length 3). Run as ./program hello: it prints V (length 5).
The reserved ,65535 array
One of Label 666's design decisions is to reserve a specific array for syscall data. Every syscall that needs a buffer (filenames for open, contents for read, arguments for argv) uses ,65535. The choice of 65535 is deliberate. It is the largest 16-bit array index, far from any number a real program would naturally use.
The runtime auto-dimensions ,65535 on the first use if you do not. By convention, programs in this project dimension it explicitly at entry:
DO ,65535 <- #65535
That reserves 65535 bytes of buffer. Programs that use Label 666 must not use ,65535 for any other purpose.
Why not just extend INTERCAL with proper syscalls?
Three alternatives were considered and rejected:
- Add new statements to the language. Something like
DO OPEN FILE "foo.txt"would be the obvious route, but it would break every other INTERCAL compiler, and the extension would need string syntax, which INTERCAL does not have natively. - Use CLC-INTERCAL's "call by vague resemblance" convention. CLC-INTERCAL already has a Label 666 syscall system, but its parameter-passing convention is deliberately obscure: parameters live in whichever register was last assigned to. This is interesting as a curiosity but impractical to use.
- Invent a wholly new mechanism. We could have used Label 999, or Label 1, or a new statement like
DO SYSCALL. Choosing 666 keeps enough cultural memory of CLC-INTERCAL that the construct is recognisable, while our simpler calling convention (fixed.1through.4) is documented and reproducible.
The current Label 666 design is intentionally simple, intentionally incompatible with CLC-INTERCAL, and intentionally documented end to end. It is "our extension, like CLC-INTERCAL's but clearer".
Why we need Label 666 at all
Because our compiler is INTERCAL.
The self-hosted compiler in src/compiler/compiler.i needs to:
- Read its arguments to find the source file. Syscalls 5 and 6 (argc / argv).
- Open the source file. Syscall 1.
- Read the source into memory. Syscall 2.
- Close the source. Syscall 4.
- Write the generated assembly to stdout. Syscall 3.
- Exit with the right status. Syscall 8.
Without Label 666, none of this is possible. The language has no way to reach the operating system, and a compiler that cannot reach the operating system is useless. Label 666 is the minimum viable extension that makes self-hosting possible.
What Label 666 is not
- Not a feature of every INTERCAL program. A program that uses only standard INTERCAL (READ OUT, WRITE IN, arithmetic) does not touch Label 666 and remains compatible with any implementation.
- Not CLC-INTERCAL compatible. A program written against this compiler's Label 666 will not work under CLC-INTERCAL and vice versa, because the parameter conventions differ.
- Not a general-purpose FFI. It exposes exactly eight syscalls, carefully chosen. Adding more is possible but not done lightly.
Reading it in the actual source
Every Label 666 syscall is dispatched by _rt_syscall_666 in the runtime:
src/runtime/<platform>.s
Search for _rt_syscall_666 and you will find the dispatcher, followed by the eight handlers (_rt_sys666_open, _rt_sys666_read, etc.). Each handler is around 40 lines of platform-specific assembly.
On the INTERCAL side, the minimal usage is what you saw above: set .1 (and .2, ,65535 as appropriate), execute DO (666) NEXT, read the result from .3 and .4.
Exercises
- Write a program that counts its command-line arguments and prints the count. (Hint: syscall 5.)
- Write a program that reads the first 10 bytes of
tests/test_hello.iand prints them as Roman numerals, one per line. (Hint: syscalls 1, 2, 4, and a loop over the bytes.) - Why does
,65535need to be reserved? What happens if a program touches,65535between Label 666 calls? - Syscall 9 (getrand) takes a range limit in
.2. What does.2 = 0produce? Consultdocs/runtime.mdand the runtime source to find out. - The self-hosted compiler in
src/compiler/compiler.iuses Label 666. Read it (43 lines) and identify which syscalls it uses, and in what order.
Next reading
- 666.md: the full design rationale, CLC-INTERCAL analysis, and implementation choices.
- runtime.md: the dispatcher and handler code in the runtime.
- self-hosting.md: why Label 666 is critical to the self-hosting story.
Overview
A small, complete, self-hosting compiler for INTERCAL. It takes a .i source file and produces a native Mach-O (macOS ARM64) or ELF (Linux ARM64 and x86-64) executable, with no C or Rust intermediate step.
It is also, deliberately, an educational artefact. INTERCAL is an esoteric language designed in 1972 to parody the languages of its time. That heritage makes it small enough to implement in a weekend of concentrated reading, and weird enough that doing so forces you to meet almost every classical concept in compiler construction:
- A scanner that tokenises a whitespace-insensitive, case-insensitive source.
- A parser whose grammar has no operator precedence and uses two alternating grouping characters instead.
- A compile-time check (the politeness rule) that rejects programs that are statistically too polite or not polite enough.
- A
COME FROMstatement, the celebrated inverse ofGOTO, resolved during semantic analysis so the runtime cost is one unconditional jump. - A runtime that does I/O in Roman numerals and a Turing Text Model tape, not printf.
- A self-hosting strategy that goes shell-script bootstrap → template-dispatch MVP → real INTERCAL compiler written in INTERCAL.
The pipeline is deliberately unfashionable. Source goes straight through tokenisation, parsing, a handful of static checks, and on into target assembly. No intermediate representation, no bytecode, no virtual machine. The only backend we talk to is cc -x assembler -, and the only runtime is a few hundred lines of hand-written assembly per platform. Each phase is short enough to read end to end in one sitting; the whole system is a reasonable first example for somebody learning how compilers actually work.
What is in the repo
High level:
src/bootstrap/intercalc.sh The shell compiler. The "chispa primigenea".
src/bootstrap/codegen_x86_64.sh Backend override for Linux x86-64.
src/runtime/<platform>.s Native runtime per platform (Mach-O or ELF, ARM64 or x86-64).
src/syslib/syslib.i Arithmetic library written in pure INTERCAL (9065 lines).
src/syslib/native/<platform>.s Same arithmetic in native assembly (faster).
src/compiler/compiler.i Self-hosted MVP using template dispatch.
src/compiler/stage3.i Evolving real compiler, Phase 4 work-in-progress.
src/compiler/templates/ Pre-generated assembly per test per platform (MVP fuel).
tests/ Four test suites plus individual .i programs.
tools/ Manifests, hooks, lint, cross-platform Docker tests.
docs/ You are here.
The compilation pipeline at a glance
No IR. The pipeline:
- Read the
.isource from stdin or argv. - Tokenise into statements with their modifiers (PLEASE, NOT, %probability).
- Classify each statement (assignment, NEXT, RESUME, READ OUT, etc.) and parse its body. Expression bodies become trees.
- Check politeness (PLEASE on between 1/5 and 1/3 of statements), label uniqueness, COME FROM resolution.
- Emit ARM64 or x86-64 assembly directly, one function-shaped block per statement.
- Concatenate the generated assembly with the platform's runtime and syslib.
- Invoke the system's
cc -x assembler -to assemble and link.
That is the whole story. See pipeline.md for the details and map-of-the-compiler.md for where each phase lives in the source.
Why INTERCAL makes a good teaching example
Most compiler textbooks build a mini-C or a mini-Lisp. Those are practical, but they let you skip parts of the problem. INTERCAL does not let you skip anything:
| Concept | How INTERCAL forces you to think about it |
|---|---|
| Tokenisation | Case-insensitive, whitespace-agnostic, no statement terminator. DON'T must be one token. |
| Grammar | Grouping with sparks ' and rabbit-ears " that must alternate. Two families of brackets, not one. |
| Operator semantics | Unary operators work on adjacent bits of the same value, not between two values. |
| Static analysis | Politeness is a property of the whole program, not any single statement. |
| Non-local control flow | COME FROM reverses the caller/callee relationship. The target statement does not know it has a follower. |
| Calling convention | The system library is itself INTERCAL source, glued in via labels 1000–1999. |
| Runtime | Output is Roman numerals (READ OUT a scalar) or a Turing tape (READ OUT an array). Neither is free. |
| Self-hosting | The compiler's own source is INTERCAL, and it must reach a three-generation fixpoint. |
| Bootstrap | Before the compiler exists, a shell script has to do its job, and emit the same assembly the INTERCAL compiler will eventually emit. |
A C compiler teaches you the happy path. INTERCAL teaches you the full shape.
The fact you will probably want to know first
There is no intermediate representation in this compiler. Each statement is turned directly into a block of target assembly. That choice costs us classical optimisations, but it buys transparency: to see what DO .1 <- #5 compiles to, run
INTERCAL_ASM_ONLY=1 zsh src/bootstrap/intercalc.sh < one_line.i
and read the assembly. See code-generation.md.
For an IR-shaped view of a parsed program, the compiler ships read-only --emit-cfg (a basic-block and edge dump in the LLVM/MIR/CLIF style) and --emit-3addr (a flat three-address listing in the GIMPLE style). See middle-end-and-optimisation.md for the details. These do not change codegen; they expose the compiler's model of the program in the same vocabulary that Part VII's chapters on LLVM, GCC, rustc, Go, GHC, OCaml, Cranelift, Zig, Swift, and V8 use.
Next reading
- Want the language first? intercal-primer.md.
- Want the pipeline? pipeline.md.
- Want a specific piece of code? map-of-the-compiler.md.
- Want the self-hosting plan? self-hosting.md.
Map of the compiler
This chapter maps the classical compiler phases (scanner, parser, semantic analysis, code generation, runtime) onto the files and line ranges of this repository. Use it to find the right file to read or modify.
For the narrative explanation of each phase, follow the links into the per-phase chapters.
Phase overview
The bootstrap compiler lives almost entirely in a single zsh file, src/bootstrap/intercalc.sh. It is organised into numbered sections. The table below lists the sections and how they map to the standard compiler phases.
| Phase (textbook name) | Our implementation | File | Approx. lines |
|---|---|---|---|
Diagnostics (--diagnose) | diagnose() | src/bootstrap/intercalc.sh | 78–122 |
| Compile-time error helper | die_compile() | src/bootstrap/intercalc.sh | 124–145 |
| Source reader | read_source() | src/bootstrap/intercalc.sh | 156–163 |
| Lexer (scanner) | tokenize(), classify_statement() | src/bootstrap/intercalc.sh | 165–357 |
| Symbol collection | scan_variables() | src/bootstrap/intercalc.sh | 359–386 |
| Semantic analysis | check_politeness(), check_labels(), resolve_come_from(), detect_syslib() | src/bootstrap/intercalc.sh | 392–463 |
| Dead-flag elimination | compute_flag_checks() | src/bootstrap/intercalc.sh | 471–533 |
| Parser primitives | expr_new, peek_char, next_char, parse_number | src/bootstrap/intercalc.sh | 539–578 |
| Parser (expressions) | parse_expr() | src/bootstrap/intercalc.sh | 582–772 |
| Constant folding | eval_const() | src/bootstrap/intercalc.sh | 781–843 |
| Codegen (expressions) | codegen_expr(), codegen_array_ref() | src/bootstrap/intercalc.sh | 845–1021 |
| Codegen (program entry / dispatch) | codegen_program(), codegen_statement(), codegen_probability() | src/bootstrap/intercalc.sh | 1023–1137 |
| Codegen (per statement type) | codegen_give_up, codegen_read_out, codegen_write_in, codegen_assign, codegen_array_elem_assign, codegen_array_dim, codegen_next, codegen_resume, codegen_forget, codegen_abstain, codegen_reinstate, codegen_gerund_modify, codegen_ignore, codegen_remember, codegen_stash, codegen_retrieve | src/bootstrap/intercalc.sh | 1115–1887 |
| Data emission (.data, .bss) | emit_data() | src/bootstrap/intercalc.sh | 1889–1984 |
| Peephole optimiser | peephole_optimize() | src/bootstrap/intercalc.sh | 47–76 |
| Driver / main | main() | src/bootstrap/intercalc.sh | 1986–end |
Counts are approximate line numbers in the current version; they are there as a navigation aid, not a contract.
Runtime and syslib
The runtime is platform-specific hand-written assembly. It provides everything the generated code calls out to: I/O, operators, error handling, the Label 666 syscall dispatcher.
src/runtime/macos_arm64.s Runtime for Apple Silicon macOS (Mach-O, svc #0x80).
src/runtime/linux_arm64.s Runtime for Linux aarch64 (ELF, svc #0, openat).
src/runtime/linux_x86_64.s Runtime for Linux x86-64 (ELF, syscall, Intel syntax).
src/syslib/syslib.i Pure INTERCAL arithmetic library, 9065 lines, 20 labels.
src/syslib/native/<platform>.s Native-assembly version of the same 20 labels, ~300 lines.
Inside each runtime file, routines follow the naming convention _rt_<name>. The key entry points on macos_arm64.s:
_rt_mingle, _rt_select Operator primitives ($, ~)
_rt_unary_and_16, _rt_unary_or_16, _rt_unary_xor_16 &, V, ? on 16-bit
_rt_unary_and_32, _rt_unary_or_32, _rt_unary_xor_32 same on 32-bit
_rt_write_roman READ OUT for scalars (Roman numerals)
_rt_read_out_array READ OUT for arrays (Turing Text Model)
_rt_write_in_array WRITE IN for arrays
_rt_write_in_scalar WRITE IN for scalars (English digit names)
_rt_mmap Memory allocation wrapper
_rt_resume_1 RESUME helper
_rt_error_E000 ... _rt_error_E633 16 runtime error exits
_rt_syscall_666 Label 666 dispatcher
_rt_sys666_open/read/write/close File I/O syscalls
_rt_sys666_argc/argv Argument access
_rt_sys666_exit Program exit with code
_rt_sys666_getrand Randomness for syslib 1900/1910
The Linux ARM64 and Linux x86-64 runtimes are translated versions of the same logic. See platforms.md for the differences.
Self-hosted compiler
src/compiler/compiler.i Self-hosted MVP, template-dispatch passthrough.
src/compiler/stage3.i Evolving real compiler. Phase 4 work-in-progress.
src/compiler/templates/<platform>/*.s Pre-generated assembly per test program per platform.
src/compiler/templates/manifest.txt SHA-256 manifest for integrity checking.
The MVP classifies incoming programs by content hash and emits the matching pre-generated assembly. It is not a real compiler, it's just enough of one to prove the self-hosted pipeline end-to-end (read a .i file via Label 666, emit assembly to stdout, let the wrapper link it). See self-hosting.md.
stage3.i is where the real lexer / parser / codegen is slowly being rewritten in pure INTERCAL. Today (2026-04-21) it only reads the source file and prints byte-count and first/last byte diagnostics.
Wrapper scripts
intercal Self-hosted compiler wrapper (uses intercal_core + templates).
bootstrap.sh Three-generation fixpoint bootstrap (requires a real compiler.i).
setup_platform.sh Print the detected platform name for sanity check.
Tests
tests/run_tests.sh Bootstrap compiler, 33 tests, full language coverage.
tests/test_syslib_pure.sh Pure vs native syslib equivalence, 3 tests.
tests/run_self_tests.sh Self-hosted MVP dispatcher, 25 tests.
tests/run_stage3_tests.sh Evolving compiler (stage3.i), 3 tests.
tests/cross_test.sh Docker wrapper to reproduce Linux CI jobs locally.
tests/test_<name>.i Individual INTERCAL programs driving the suites.
Tools
tools/gen_manifest.sh Regenerate the SHA-256 template manifest.
tools/verify_manifest.sh Verify templates have not drifted.
tools/pipeline_dump.sh Dump the intermediate assembly for debugging.
tools/install_hooks.sh Install the repo's pre-commit and pre-push git hooks.
tools/lint_intercal.sh Lint .i files (politeness balance, basic sanity).
tools/lint_assembly.sh Lint .s files for platform-specific pitfalls.
Git hooks and CI
.githooks/pre-commit verify_manifest + run_tests.
.githooks/pre-push all four test suites.
.github/workflows/ci.yml 3-platform CI (macOS ARM64, Linux ARM64, Linux x86-64).
.github/workflows/release.yml 9-artifact release on v* tags (zip / tar.gz / deb / rpm).
Top-level files worth knowing
| File | Purpose |
|---|---|
README.md | Quick start, install, test counts, repo layout. |
AGENTS.md (symlinked as CLAUDE.md) | Authoritative contributor reference: language, pitfalls, TDD workflow. |
SECURITY.md | Security model, known limitations, threat-model notes. |
TODO.md | Working notes between sessions (not project documentation). |
CODE_OF_CONDUCT.md | Standard Contributor Covenant. |
LICENSE | Public domain (Unlicense). |
The compilation pipeline
An end-to-end walkthrough of what happens when you run:
zsh src/bootstrap/intercalc.sh < program.i > program
chmod +x program
The script is src/bootstrap/intercalc.sh. It runs seven phases, all inside one zsh process, and ends by shelling out to cc to link the result. The per-phase chapters that follow this one zoom in on each phase in turn; read this first to see the whole shape.
The seven phases at a glance
┌──────────────────────────────────────────────────────────────────────┐
│ program.i (INTERCAL source on stdin) │
└───────────────────────────┬──────────────────────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ read_source() │ whitespace-fold,
│ SOURCE = uppercased single line │ uppercase
└──────────────────┬────────────────┘
│
▼
┌──────────────────────────────────┐
│ tokenize() │ split into statements,
│ stmt_* parallel arrays populated │ classify each
└──────────────────┬────────────────┘
│
▼
┌──────────────────────────────────┐
│ scan_variables() │ used_spot/used_twospot/
│ used_* maps populated │ used_tail/used_hybrid
└──────────────────┬────────────────┘
│
▼
┌──────────────────────────────────┐
│ check_politeness() │ PLEASE ratio ∈ [1/5, 1/3]
│ check_labels() │ unique, 1..65535
│ resolve_come_from() │ build come_from_target
│ detect_syslib() │ needs_syslib = 0 or 1
└──────────────────┬────────────────┘
│
▼
┌──────────────────────────────────┐
│ codegen_program() │ emit assembly
│ asm string grows to final form │ statement by statement
└──────────────────┬────────────────┘
│
▼
┌──────────────────────────────────┐
│ cat runtime.s syslib.s program.s │ linker invocation
│ | cc -x assembler - -o binary │ via system cc
└──────────────────┬────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ native binary on stdout (Mach-O or ELF) │
└──────────────────────────────────────────────────────────────────────┘
The list, with their entry points in intercalc.sh:
read_source: slurp stdin, flatten newlines and tabs to spaces, uppercase everything.tokenize: split into statements; attach label, polite flag, negation, probability, type and body to each.scan_variables: record which variable numbers are actually used, so we can allocate BSS space later.check_politeness: count PLEASE usage; reject if outside [1/5, 1/3].check_labels: reject duplicate labels; build the label→statement map.resolve_come_from: for eachCOME FROM (N), record the reverse edge from labelN.detect_syslib: scan NEXT targets; if any land in 1000–1999, flag that we need to link the syslib.codegen_program: emit one block of assembly per statement into a growing string$asm.- Final assembly: concatenate
src/runtime/<platform>.s, optionallysrc/syslib/native/<platform>.s, and the generated program assembly, then pipe the whole thing throughcc -x assembler - -o binary.
Strictly speaking, steps 4–7 are separate passes over the statement list, not one phase. From a textbook standpoint they are all "semantic analysis".
Phase 1: Read the source
read_source reads stdin into a single zsh string SOURCE. Newlines, tabs and carriage returns are collapsed to spaces. Everything is uppercased. INTERCAL is whitespace-agnostic and case-insensitive, so this simplification costs nothing and makes every later phase easier.
There is no file-level syntax to preserve. Comments don't exist. A line break has no meaning. So losing the original formatting is fine, the compiler only needs the stream of significant tokens.
Phase 2: Tokenise
tokenize scans SOURCE character by character, accumulating until it detects the start of a new statement. Statement boundaries are defined by the verb tokens: DO, PLEASE, DON'T, and the combinations like PLEASE DO or PLEASE DON'T. When the tokenizer sees one of those, it closes the previous statement and starts a new one.
For each statement it extracts:
- The optional
(N)label. - Whether PLEASE was present (affects politeness counting).
- Whether NOT / N'T was present (statement starts abstained).
- The optional
%Nprobability. - The first keyword of the body, which determines the statement type (
ASSIGN,NEXT,RESUME,FORGET,ABSTAIN,REINSTATE,IGNORE,REMEMBER,STASH,RETRIEVE,READ_OUT,WRITE_IN,COME_FROM,GIVE_UP,UNKNOWN). - The raw body text, saved verbatim for the parser to work on during codegen.
The parallel arrays stmt_label, stmt_polite, stmt_negated, stmt_prob, stmt_type, stmt_body all grow by one entry per statement. stmt_count is the final count.
DON'T is its own token rather than being decomposed into DO + N'T. Getting this wrong caused a real bug earlier in the project: when DON'T NOTE foo was left as DO, N'T, NOTE, foo, the tokenizer merged NOTE foo into the previous statement's body. See the "bugs learned" memory for the full story.
For the details of tokenisation (how the scanner detects each token, what it does with the % probability, how it handles sparks inside the body) see lexing-and-parsing.md.
Phase 3: Collect used variables
scan_variables walks every statement body and records which .N, :N, ,N, ;N variable numbers appear. The result is four associative arrays used_spot, used_twospot, used_tail, used_hybrid whose keys are the numbers that actually appear in the source.
Why: the codegen phase emits one BSS symbol per used variable. A program that references .1, .7 and ,3 produces three BSS symbols, not 65535×4. This keeps the output binary small and makes the generated assembly readable.
Phase 4: Check politeness
check_politeness counts statements (numerator = those with stmt_polite=1, denominator = stmt_count) and verifies that numerator * 5 >= denominator and numerator * 3 <= denominator. Failure fires die_compile 079 or die_compile 099, which prints ICL079I or ICL099I to stderr and exits with status 1.
This is the only compile-time error the compiler reports for a well-formed program. Every other error in the INTERCAL error catalogue is a runtime error, because INTERCAL lets you write unrecognised statements, they might be abstained and never execute.
Phase 5: Check labels
check_labels builds label_to_stmt, a map from label number to statement index. Labels are 1–65535. Duplicates fire die_compile 182. The map is used later by NEXT, COME FROM, ABSTAIN FROM (N) and REINSTATE (N) codegen so they can resolve the label at compile time.
Phase 6: Resolve COME FROM
resolve_come_from walks every statement whose type is COME_FROM and records the reverse edge: for each COME FROM (N), it stores come_from_target[N] = index_of_come_from_statement. The codegen for statement N will then, after executing its own body, jump to the COME FROM statement's body instead of continuing to N+1.
Two COME FROMs targeting the same label would fire die_compile 555, but the current implementation accepts this silently; it is listed in the TODO.
Phase 7: Detect syslib usage
detect_syslib scans every NEXT target for values in the range 1000–1999. If any are found, needs_syslib=1. During the final link step, the syslib native assembly (or the pure INTERCAL syslib with --pure-syslib) is concatenated with the runtime and the program assembly so the labels resolve.
Phase 8: Code generation
codegen_program emits boilerplate: the entry point (_main: on macOS, main: on Linux), the argument-save sequence for argc/argv, the statement-flags initialisation, and the runtime-data pointers. Then it walks stmt_body in order, calling codegen_statement for each, which dispatches on stmt_type to one of the many codegen_<type> functions. Each of those emits a block of assembly that:
- Checks the statement's abstain flag in
_stmt_flags. If set, jumps over the body. - If a probability is set, rolls a random number and skips if it fails.
- Evaluates the statement's expression(s) by walking the expression tree (
codegen_expr,codegen_array_ref). - Performs the statement's action (store to a variable, call
_rt_write_roman, push a NEXT frame, etc.). - If a COME FROM is attached to this statement's label, unconditionally jumps to its body.
Finally, emit_data appends the .data and .bss sections: the roman numeral table (already inside the runtime, but the per-program BSS sits in the output), the abstain-flag bit array _stmt_flags, and one BSS symbol per used variable.
The full per-statement walk-through lives in code-generation.md.
Phase 9: Assemble and link
With the assembly text ready in the zsh variable $asm, main concatenates:
src/runtime/<platform>.s: the runtime.src/syslib/native/<platform>.sifneeds_syslib=1and--pure-syslibwas not set.- The generated
$asm.
For Linux ARM64 specifically, this combined blob is passed through a sequence of sed substitutions that translate macOS ARM64 assembly syntax (_main, @PAGE/@PAGEOFF, svc #0x80, mov x16, etc.) into Linux GNU-as syntax (main, :lo12:, svc #0, mov x8). For Linux x86-64 the codegen emits Intel syntax directly via codegen_x86_64.sh, which overrides every emit function.
The combined text is piped to cc -x assembler - -o $TMPBIN, and $TMPBIN is catted to stdout. The user (or the wrapper script) is expected to redirect stdout to a file and chmod +x it.
Seeing each phase's output
The pipeline is opaque in its default form. Two flags make it observable:
INTERCAL_ASM_ONLY=1 zsh src/bootstrap/intercalc.sh < program.iprints the generated assembly (including any Linux ARM64 sed conversion) to stdout instead of invokingcc.tools/pipeline_dump.sh program.iis a thin wrapper that dumps the intermediate stages.
For smaller debugging you can always add a set -x near the top of intercalc.sh and watch the phases execute.
Exercises
- Run
INTERCAL_ASM_ONLY=1 zsh src/bootstrap/intercalc.sh < tests/test_give_up.i. Identify, in the emitted assembly, which lines came from the codegen prologue, which came fromcodegen_give_up, and which came from the runtime concatenation. - Trace what happens to
SOURCEbetweenread_sourceand the end oftokenize. How many distinct strings does the lexer materialise during tokenisation? - The pipeline runs
check_politenessbeforecheck_labels. What would break, if anything, if their order were swapped? detect_syslibdecides at compile time whether to link the syslib. Construct a minimal program that togglesneeds_syslibfrom 0 to 1 by adding a single statement.- The final concatenation step pipes
runtime.s + syslib.s + program.stocc. What is the consequence of swapping that order? Try it manually withcat program.s runtime.s | cc -x assembler -on a hello-world output.
Next reading
- lexing-and-parsing.md: Phases 2 and the expression parser.
- semantic-analysis.md: Phases 4–6.
- code-generation.md: Phase 8.
- runtime.md: what the emitted assembly calls into.
Walkthrough: Hello, World!
This chapter takes one specific INTERCAL program, tests/test_hello.i: and follows it through every phase of the compiler, capturing the state at each step. If the per-phase chapters are the reference material, this is the capstone worked example.
The source, tests/test_hello.i:
DO ,1 <- #14
DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #108
DO ,1 SUB #3 <- #112
PLEASE ,1 SUB #4 <- #0
DO ,1 SUB #5 <- #64
DO ,1 SUB #6 <- #194
DO ,1 SUB #7 <- #48
PLEASE ,1 SUB #8 <- #26
DO ,1 SUB #9 <- #244
DO ,1 SUB #10 <- #168
DO ,1 SUB #11 <- #24
PLEASE ,1 SUB #12 <- #16
DO ,1 SUB #13 <- #162
DO ,1 SUB #14 <- #52
PLEASE READ OUT ,1
DO GIVE UP
Seventeen statements. The program dimensions the array ,1 to 14 elements, assigns a precomputed Turing tape delta to each element, reads the array out (which prints "Hello, World!"), and exits.
What the source is actually saying
Each constant on the right-hand side is the distance on a 256-entry tape that the tape head has to move, starting from the previous head position, such that the new head position, after all eight bits are reversed, equals the ASCII code of the character to print.
The sequence 238, 108, 112, 0, 64, 194, 48, 26, 244, 168, 24, 16, 162, 52 decodes to the letters H-e-l-l-o-comma-space-W-o-r-l-d-exclamation-newline. The bit-reversal is what makes the numbers look unpredictable: 238 is 0b11101110, which reverses to 0b01110111 = 119, and 0 - 119 mod 256 = 137; then 137 - 238 mod 256 = 155... no, the arithmetic is the other direction, see intercal-primer.md for the precise formula. The point is that every element is a tape-distance, not a character.
Phase 1: read the source
read_source reads the file into SOURCE, collapses whitespace, uppercases. Result (truncated):
SOURCE="DO ,1 <- #14 DO ,1 SUB #1 <- #238 DO ,1 SUB #2 <- #108 ... DO GIVE UP"
All 17 statements now live as a single space-separated string.
Phase 2: tokenise
tokenize splits SOURCE into statements. The parallel arrays after this phase:
stmt_count = 17
stmt_label (17 empty strings)
stmt_polite (0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0)
stmt_negated (17 zeros)
stmt_prob (17 × 100)
stmt_type (ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN
ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN READ_OUT GIVE_UP)
stmt_body (",1 <- #14" ",1 SUB #1 <- #238" ",1 SUB #2 <- #108"
",1 SUB #3 <- #112" ",1 SUB #4 <- #0" ",1 SUB #5 <- #64"
",1 SUB #6 <- #194" ",1 SUB #7 <- #48" ",1 SUB #8 <- #26"
",1 SUB #9 <- #244" ",1 SUB #10 <- #168" ",1 SUB #11 <- #24"
",1 SUB #12 <- #16" ",1 SUB #13 <- #162" ",1 SUB #14 <- #52"
"READ OUT ,1" "GIVE UP")
Only four statements used PLEASE (indices 4, 8, 12, 15). The rest used DO.
Phase 3: collect variables
scan_variables walks every body and records which variable numbers appear:
used_tail=( [1]=1 ) # only ,1 is used
No spots, twospots or hybrids. Array ,1 will get a pointer and dimensions table in BSS.
Phase 4: check politeness
4 polite out of 17 total. 4*5 = 20 >= 17 ✓ (lower bound), 4*3 = 12 <= 17 ✓ (upper bound). Politeness is satisfied. If any of the four PLEASEs were changed to DO, we would have 3/17 = 17.6%, below the 20% lower bound, and the compiler would fire ICL079I. If three more DOs became PLEASE, we would have 7/17 = 41.2%, above the 33.3% upper bound, and the compiler would fire ICL099I.
Phases 5–7: labels, COME FROM, syslib
No labels in the source, so label_to_stmt is empty. No COME FROMs, so come_from_target is empty. No NEXTs in the range 1000–1999, so needs_syslib = 0. The syslib will not be linked.
Phase 8: code generation
codegen_program emits the entry-point skeleton. codegen_statement(i) walks each of the 17 statements. The first statement, DO ,1 <- #14, has type ASSIGN, an array dimensioning form (the target is ,1 without a SUB). codegen_array_dim emits (approximately):
_stmt_0_start:
; abstain check
adrp x0, _stmt_flags@PAGE
add x0, x0, _stmt_flags@PAGEOFF
ldrb w1, [x0, #0]
cbnz w1, _stmt_0_end
; evaluate RHS (#14) into w0
mov w0, #14
; check that dimension > 0
cbz w0, _rt_error_E240
; store dimension table
adrp x1, _tail_1_dims@PAGE
add x1, x1, _tail_1_dims@PAGEOFF
str w0, [x1]
mov w2, #1 ; number of dimensions
str w2, [x1, #60]
; allocate 14 × 2 bytes via mmap
mov w0, #28
bl _rt_mmap
; store pointer
adrp x1, _tail_1_ptr@PAGE
add x1, x1, _tail_1_ptr@PAGEOFF
str x0, [x1]
_stmt_0_end:
The next fourteen statements are element assignments (,1 SUB #N <- #V). Each compiles to:
_stmt_N_start:
; abstain check
; evaluate subscript #N into w3
; evaluate RHS #V into w0
; bounds check: subscript must be 1..14
; compute address: _tail_1_ptr + (subscript - 1) * 2
; store half-word
_stmt_N_end:
The sixteenth statement, PLEASE READ OUT ,1, has type READ_OUT with a whole-array target. codegen_read_out detects the array form and emits:
_stmt_15_start:
; abstain check
adrp x0, _tail_1_ptr@PAGE
add x0, x0, _tail_1_ptr@PAGEOFF
ldr x0, [x0]
adrp x1, _tail_1_dims@PAGE
add x1, x1, _tail_1_dims@PAGEOFF
ldr w1, [x1]
mov w2, #2 ; element size in bytes
bl _rt_read_out_array
_stmt_15_end:
The seventeenth statement, DO GIVE UP, compiles to three instructions on macOS ARM64:
_stmt_16_start:
; abstain check
mov x0, #0
mov x16, #1
svc #0x80
_stmt_16_end:
After the last statement, codegen_program emits a safety-net bl _rt_error_E633 so falling past the end without GIVE UP is caught.
emit_data appends the BSS reservations:
.section __DATA,__bss
_stmt_flags: .space 17
_tail_1_ptr: .space 8
_tail_1_dims: .space 64
_tail_1_ign: .space 1
Phase 9: assemble and link
The generated assembly is concatenated with src/runtime/macos_arm64.s and piped through cc:
cat runtime.s emitted.s | cc -x assembler - -o hello
cc invokes the system linker (ld on macOS), which resolves every _rt_* reference against the runtime symbols, and produces a Mach-O executable.
Running it
$ ./hello
Hello, World!
What actually happens at runtime, step by step:
- Process entry at
_main. The runtime saves argc/argv. - Statement 0 executes.
mmapallocates 28 bytes; pointer stored in_tail_1_ptr. - Statements 1–14 execute. Each stores a halfword into the allocated buffer.
- Statement 15 executes.
_rt_read_out_arrayis called with the pointer, count=14, size=2. - Inside
_rt_read_out_array: for each of 14 elements, subtract from_ttm_out_pos, bit-reverse, emit the resulting ASCII code via thewritesyscall. One character at a time, or batched, the current implementation batches into a 256-byte stack buffer and flushes on boundaries. - Statement 16 executes.
exit(0)viasvc #0x80withx16 = 1.
The whole execution takes microseconds.
On Linux ARM64, the same program
The sed post-processing step translates the generated assembly. The differences visible in the final binary:
_mainbecomesmain.svc #0x80becomessvc #0.mov x16, #1becomesmov x8, #93(Linux exit syscall number).- Every
sym@PAGEandsym@PAGEOFFis rewritten.
The runtime file src/runtime/linux_arm64.s was pre-translated the same way and is committed separately.
On Linux x86-64, the same program
codegen_x86_64.sh overrides every codegen function. The emitted assembly is entirely different. Intel syntax, different register conventions, different syscall numbers, but the behaviour of the compiled binary is identical.
The array dimensioning statement 0, for instance, becomes:
_stmt_0_start:
; abstain check
lea rax, [rip + _stmt_flags]
movzx ecx, byte ptr [rax]
test ecx, ecx
jnz _stmt_0_end
; evaluate #14
mov eax, 14
; dimension check, store dimensions...
; mmap via syscall 9
; store pointer
_stmt_0_end:
Different assembly, same semantics. Running ./hello on a Linux x86-64 machine prints the same Hello, World!.
What this example does not exercise
Hello world is small. It touches:
- Array dimensioning and element assignment.
- Array-based READ OUT (the Turing Text Model).
- GIVE UP.
- The politeness rule in its passing case.
It does not touch:
- Scalars, unary operators, mingle, select.
- Control flow (NEXT, RESUME, FORGET, COME FROM).
- Statement modifiers (ABSTAIN, REINSTATE, IGNORE, REMEMBER).
- STASH/RETRIEVE.
- The syslib.
- Label 666 syscalls.
- WRITE IN (numeric or character).
- Runtime errors.
Each of those is exercised by one or more of the 33 tests in tests/run_tests.sh. The reader who has followed the hello-world walkthrough is equipped to step into any of them and understand the emitted code.
Exercises
- The program has exactly 17 statements and 4 PLEASEs, giving a politeness ratio of 4/17 ≈ 0.235. What is the minimum number of
DOs we could flip toPLEASEwithout breaking the upper politeness bound? - Regenerate the assembly by running
INTERCAL_ASM_ONLY=1 zsh src/bootstrap/intercalc.sh < tests/test_hello.i > hello.s. Count the number of instructions emitted per statement. Is the per-statement overhead what you expect? - Change
PLEASE READ OUT ,1toDO READ OUT ,1and recompile. The politeness is now 3/17 ≈ 0.176. Run the compiler. Which ICL code fires? - Compile hello-world with both
intercalc.shandintercalc.sh --pure-syslib. Why does the flag have no effect on the output? - The array is dimensioned to 14, not 13. What would break if the programmer reduced the dimension to 13? What if the programmer increased it to 30?
Next reading
- pipeline.md: the general pipeline, now with one concrete traversal behind you.
- runtime.md:
_rt_read_out_arrayand the Turing Text Model in depth. - code-generation.md: all the other statement types we did not see here.
Lexer theory
The lexer in src/bootstrap/intercalc.sh is 194 lines of ad-hoc zsh. It works by inspection: read a character, decide which token is being accumulated, continue. A reader who approaches it expecting the machinery of Flex or a DFA-generation tool will find nothing of the sort. This chapter places our hand-written lexer in the theoretical framing that compiler-construction textbooks use, and argues that the ad-hoc structure is more disciplined than it looks.
Regular languages, in one paragraph
A regular language is a set of strings that can be recognised by a finite-state automaton. Given an alphabet (the characters the language uses) and a finite set of states with transitions between them on each character, an FSA either lands in an accepting state at the end of the input or it does not. Regular languages are the simplest class in the Chomsky hierarchy, simpler than context-free (which needs a stack) or context-sensitive (which needs a tape).
Every sane programming language's token structure is regular. Identifiers, numbers, keywords, punctuation: each can be recognised by a small FSA. A lexer is, at its theoretical core, a collection of FSAs run in parallel or union.
INTERCAL's token language
The tokens our lexer produces are:
- Verb keywords:
DO,PLEASE,DON'T,NOT,N'T. - Statement-body keywords:
NEXT,RESUME,FORGET,ABSTAIN,REINSTATE,FROM,IGNORE,REMEMBER,STASH,RETRIEVE,READ,OUT,WRITE,IN,COME,GIVE,UP,SUB. - Gerunds:
CALCULATING,NEXTING, etc. (treated as statement-body keywords). - Variable prefixes:
.,:,,,;. - Constant prefix:
#. - Operators:
$,~,&,V,?. - Grouping:
',". - Punctuation:
(,),<-,%,+. - Numbers: sequences of decimal digits.
- Whitespace: any run of spaces, tabs, newlines.
Each of these is recognisable by a small FSA. The union of all such FSAs is still a regular language, so the theoretical tool for recognising them simultaneously is still a single DFA (deterministic finite automaton).
What sets INTERCAL's token language apart from C's or Python's is two quirks:
DON'Tmust be one token, notDO+N'T. This is a direct consequence of the language specification:DON'Tis a contraction ofDO+NOT, and the contracted form has no compositional interpretation.- Keywords are whole words surrounded by whitespace.
READOUTis notREAD OUT. This is unusual, most languages accept both forms of composite keywords, and forces the lexer to check for the space between.
Both quirks are handled with trivial special-case code in our lexer. Neither requires departing from the regular-language model.
DFA vs NFA vs ad-hoc code
Three ways to recognise a regular language:
- NFA. Non-deterministic finite automaton. Allows ε-transitions and multiple transitions on the same character. Easy to construct from a regular expression; slower to run because of the implicit backtracking through every reachable state.
- DFA. Deterministic finite automaton. Every state has exactly one transition per input character. Fast to run (constant-time per character) but potentially exponential in size compared to the equivalent NFA.
- Ad-hoc code. A hand-written recogniser, typically using a
whileloop and a switch-like construct, that implicitly encodes a DFA.
The textbook construction is: regular expression → NFA (Thompson's construction) → DFA (subset construction) → minimised DFA (Hopcroft's algorithm). Flex follows this pipeline mechanically, emitting C code that runs the resulting state machine as a table-driven loop. The newer re2c generator follows the same pipeline but emits inline conditionals instead of a state table, producing tighter code at the cost of less flexibility.
Our lexer is ad-hoc code. We chose this for the same reason Crafting Interpreters does: the token language is small enough to fit comfortably in a few hundred lines of hand-written code, and the result is far easier to read and modify than a generator-produced output would be.
The tradeoff is loose: a bug in hand-written code is fixed by editing the code; a bug in the grammar of a generator-based lexer requires understanding both the grammar and the generator's conventions.
Longest match (maximal munch)
When a lexer can match multiple token classes at the same position, the standard disambiguation rule is longest match (also called maximal munch): pick the token that consumes the longest prefix. A C lexer reading ++ should produce one ++ token, not two + tokens, because the longer match wins.
This rule is so universal that most lexer literature assumes it implicitly. It is what lets DON'T win over DO in our lexer: when the scanner sees D O N ' T, two interpretations are possible, emit DO and stop, or emit DON'T and stop. Maximal munch picks DON'T. Our hand-written code implements the rule by structuring the keyword check as a longest-prefix peek: try DON'T first, then DO.
Implementing maximal munch in a generator-built DFA is more elaborate. The DFA must continue past every accepting state and remember the most recent one, then on a transition failure backtrack to that remembered state. This is the standard approach in Flex and re2c.
There are corner cases. C++'s >> is sometimes a right-shift and sometimes a closing pair of template brackets; the maximal-munch rule alone cannot disambiguate. C++ resolves it by parsing context, breaking the lexer–parser separation. INTERCAL has no such corner, its tokens are unambiguously distinguished at the lexer level.
Why we get away without a full DFA
A proper DFA for INTERCAL's tokens would be a finite-but-nontrivial state machine. We get away without building it explicitly because the token language is well-behaved:
- Keywords start at whitespace boundaries. Our lexer can skip whitespace, read the next contiguous alphanumeric run, and compare against a short list of keywords. No per-character state is required between tokens.
- No ambiguity between token classes.
#5is always a constant, never a variable, because#is never used as a variable prefix..5is always a variable, never a constant. The first character of every token unambiguously determines its class. - Statement boundaries are explicit. Verb keywords (
DO,PLEASE,DON'T) are the only statement starters. When we see one, the previous statement is complete.
Any ambiguity that would have forced a real DFA does not arise in the token grammar. The closest we come is in DO vs DON'T: after reading DO, the lexer peeks at the next character to decide whether to consume N'T as part of the same token. This is a one-character lookahead, well within what ad-hoc code can handle.
The DON'T NOTE saga as a lexer-theory worked example
One of the earliest compiler regressions in this project was a DON'T NOTE bug. The sequence of events:
- The lexer originally treated
DOandN'Tas separate tokens, on the grounds thatDON'Tis just syntactic sugar forDO NOT. - A user program included
DON'T NOTE foo bar baz. The lexer producedDO,N'T,NOTE,foo,bar,baz. - The statement scanner recognised
DO N'Tas a verb with negation and started consuming a statement body. NOTE foo bar bazwas not a recognised statement keyword, so the whole thing was classified asUNKNOWN.- The next verb token, whatever came after the
DON'T NOTEline, was not immediately found, because the lexer kept consuming "body" until it hit a verb. - The previous statement's body grew to include the intended next statement. Chaos followed.
The fix was to treat DON'T as a single atomic token. The lexer, after seeing DO, checks whether N'T immediately follows (no space, still part of the same word). If so, emit DON'T as one token. If not, emit DO alone.
Expressed in FSA terms, this is a minor modification:
space/start
│
▼
┌────┐ D ┌───┐ O ┌───┐
│ S0 │──────►│S1 │──────►│S2 │
└────┘ └───┘ └─┬─┘
│ space or other
▼
emit DO
┌────────────┐
N'T │
▼
┌───┐
│S3 │
└─┬─┘
│ space
▼
emit DON'T
Our lexer does not have a state machine drawn out in this form; the same logic lives as a couple of if branches inside the main scanning loop. But the underlying structure is exactly the FSA above.
What a generator-based lexer would buy us
Very little. The hand-written lexer is ~200 lines, runs in a few milliseconds on a typical source file, and has been modified perhaps five times in the project's history. A generator-based approach would add a dependency (Flex or an equivalent), a build step, and a second file to maintain (the .l source).
The real argument for a generator is correctness: an automatically minimised DFA cannot miss a transition, whereas ad-hoc code can. In practice, every correctness bug we have had in the lexer was about the statement-scanning logic (the DON'T NOTE case and one other), not about the token recognition per se. A generator would not have caught either.
We do have one protection against ad-hoc bugs: the test suite. Every INTERCAL feature in the test programs exercises a specific token pattern. If the lexer ever mistokenises, at least one test fails.
The INTERCAL-level lexer
stage3.i, the evolving pure-INTERCAL compiler, will eventually contain its own lexer written in INTERCAL. The target layout:
- A top-level loop over
,65535(the source loaded via Label 666). - A state variable
.50tracking what kind of token is being accumulated. - Output: parallel arrays
,11–,18holding the same tuples our bootstrap lexer builds (stmt_label,stmt_polite, ...,stmt_body).
The INTERCAL-level lexer will look significantly uglier than the zsh version. INTERCAL has no string type, no dictionaries, no associative arrays, but the underlying algorithm is the same. A stream of input characters, a state machine that accumulates tokens, a boundary detector that emits statements when a verb keyword appears.
Exercises
- Draw the FSA for recognising an INTERCAL numeric constant (
#5,#123,#65535). How many states does it have? - Extend the FSA for
DOvsDON'Tto also recogniseNOTandN'Tas separate negation tokens afterDO. How many states does it need now? - Suppose we wanted to support a lowercase variant of the language (where
do,please,don'tare equivalent to the uppercase forms). What minimal change to the lexer would enable this, and why does our current implementation effectively do it already? - The
SUBkeyword is recognised during expression parsing, not during tokenisation. What is the cost of this deferral? What would we gain by movingSUBinto the lexer? - Find the line in
intercalc.sh'stokenize()that distinguishesDON'TfromDO N'T. Rewrite it in a way that collapses the two branches. Does the resulting code make the state machine more explicit or less?
Next reading
- lexing-and-parsing.md: the concrete shape of our lexer and parser.
- appendix-grammar.md: the context-free grammar that parsing targets.
- self-hosting.md: the INTERCAL-level lexer coming in stage3.
Parser theory
The parser in src/bootstrap/intercalc.sh is a hand-written recursive-descent routine called parse_expr. It handles every expression the grammar allows, produces an abstract syntax tree stored in parallel arrays, and does so in roughly 190 lines. This chapter explains why recursive descent is the right tool for INTERCAL, what "LL(1)" means in our context, and how the parser's shape reflects the grammar.
Context-free grammars, in one paragraph
A context-free grammar is a set of production rules. Each rule has a non-terminal on the left and a sequence of terminals and non-terminals on the right. A parser's job is to take a stream of terminals (tokens from the lexer) and decide whether the stream can be derived from the grammar's start symbol, and if so, how. Context-free languages are strictly more powerful than regular languages: a grammar can nest things, which regular expressions cannot.
The parser construction literature distinguishes many classes of context-free grammars: LL(k), LR(k), LALR(1), SLR, and so on. The class determines which parsing algorithms can handle a given grammar and in what time. The short version: LL(1) grammars are the simplest to parse by hand; LR(1) grammars are more permissive but require tables; LALR(1) is a practical compromise used by yacc and bison.
INTERCAL's grammar class
The expression grammar of INTERCAL, as specified in appendix-grammar.md, is LL(1). That means:
- At every decision point in the grammar, a one-token lookahead is enough to determine which production to apply.
- There is no left recursion.
- There is no ambiguity.
The statement-level grammar is similarly LL(1): the first token after the verb determines the statement type unambiguously (., :, ,, ; → ASSIGN; ( → NEXT; RESUME → RESUME; etc.).
This is not an accident. The language specification deliberately avoids operator precedence, all grouping is explicit, and the statement verbs are all reserved words with unique first tokens. These design choices make the language uniquely suited to hand-written recursive descent.
Why recursive descent
Three reasons we did not use a parser generator:
- Transparency. Every production in our grammar corresponds to a function in
intercalc.sh. Readingparse_exprand seeingparse_primarycalled for each operand is the same mental operation as reading the grammar. A table-driven LR parser generated by yacc obscures this correspondence. - Size. Our grammar has ~15 productions. Setting up a generator's build pipeline, learning the generator's grammar meta-language, and debugging the generated tables would cost more than writing the parser by hand has.
- Flexibility. Recursive descent lets us mix parsing and codegen freely if we ever want to. We currently do not, the parser produces a tree, and codegen walks the tree, but the option is there.
Almost every production compiler has a hand-written parser for at least some part of the language. The C++ front-end of Clang is a hand-written recursive-descent parser. GCC's C, C++, and Java parsers are all hand-written recursive descent. The Rust compiler's rustc_parse is hand-written recursive descent with limited backtracking. Even where the language grammar is technically LALR-tractable, the implementers usually choose hand-written code for the same reasons we did: better error messages, tighter coupling to the rest of the front end, less generated code to debug. Parser generators remain useful at very large grammar sizes (think: SQL dialects) and in environments where formal verification of parser correctness is a priority.
The shape of parse_expr
The function signature (in zsh terms):
parse_expr(context)
returns: parse_result = index of root node in the expression-tree arrays
on failure: parse_result = -1, and a runtime error is queued
The context argument tracks which grouping character is next expected: sparks ' must contain rabbit-ears " directly, and vice versa. Same-in-same nesting (a spark immediately inside another spark) is rejected at parse time with ICL017I, with a diagnostic that names the violation and the statement number it occurred in.
Internally, parse_expr is structured around the grammar:
parse_expr(ctx):
left = parse_primary(ctx)
while next token is $ or ~:
op = consume token
right = parse_primary(ctx)
left = new binary node (op, left, right)
return left
parse_primary(ctx):
if next token is '#':
return parse_constant()
if next token is a prefix (. : , ;):
return parse_variable_or_array_ref()
if next token is a unary op (& V ?):
return parse_unary()
if next token is a grouping char (' or "):
return parse_grouped(ctx)
Each call is a single dispatch based on the next token. No backtracking, no table lookups. The recursion depth is at most the expression's nesting depth, which for any realistic INTERCAL program is a handful.
One-token lookahead
Every decision in the parser is made by peeking at the next token (one token of lookahead). This is what "LL(1)" means. The parser never consumes a token, decides that was wrong, and rewinds.
The practical implication: the grammar cannot contain two productions with the same first terminal. Our grammar satisfies this: every production starts with a unique terminal, because the language's punctuation is unambiguous.
If a future extension needed multi-token lookahead, if, for example, we added a construct whose interpretation depended on two tokens ahead, we would have to either refactor the grammar or move to LL(2) or LL(k). The current parser architecture supports arbitrary lookahead by peeking further ahead in the token stream, but we have not needed it.
Why no left recursion
Recursive-descent parsers fail on left-recursive grammars. A rule like expr ::= expr '+' term causes infinite recursion: the parser calls expr, which immediately calls expr again, and so on.
Our grammar is naturally free of left recursion. The expr ::= primary { binary_op primary } form uses iteration (the {...} repetition) rather than recursion for the left-to-right sequence of operands. This is the standard technique for eliminating left recursion from a grammar.
Precedence, associativity, and the choice to have neither
INTERCAL has no operator precedence. a $ b ~ c must be grouped explicitly: either 'a $ b' ~ c or a $ 'b ~ c'. The two mean different things, and the programmer is responsible for saying which.
This sidesteps one of the most error-prone parts of traditional compiler construction: resolving precedence and associativity. For a C-like language, the parser has to know that * binds tighter than +, that - is left-associative, that unary - has different precedence than binary -, and so on. A large part of the Dragon Book is devoted to how parser generators handle these cases.
Our grammar handles them by not having them. Every operator has the same precedence (all binary operators bind left-to-right, trivially), and all grouping is explicit. The parser is correspondingly simpler: a single production for expr handles every operator identically.
The tradeoff is ergonomic. An INTERCAL programmer pays for the simplicity by writing more quote marks. The language design embraces this trade, it is part of INTERCAL's charm.
The expression tree as parallel arrays
Our parser stores the AST in six parallel arrays:
expr_type[i] node type: NODE_CONST, NODE_VAR, NODE_MINGLE, NODE_SELECT,
NODE_UNARY_AND, NODE_UNARY_OR, NODE_UNARY_XOR, NODE_ARRAY_REF
expr_val[i] constant value or variable number
expr_left[i] left child index (for binary ops)
expr_right[i] right child index (for binary ops)
expr_child[i] single child index (for unary ops)
expr_width[i] 16 or 32, the node's result width
A new node is allocated by incrementing expr_next_id and writing into slot expr_next_id - 1. The parser returns slot indices rather than pointers, because zsh has no pointers.
The parallel-array layout is deliberately portable to INTERCAL. When stage3.i grows a parser, its ASTs will live in INTERCAL arrays with the same layout. This is the kind of design decision that becomes obvious in retrospect: use the most restrictive target's data model as the common denominator.
Parsing and error recovery
Our parser does no error recovery. If an expression is malformed, the parser abandons the statement and, in most cases, the resulting code fires ICL017I or ICL000I at runtime. A production compiler for a non-esoteric language would instrument error recovery to continue parsing after a syntax error, skip tokens until a synchronising point, then resume, so that a single syntax error produces a single error message rather than a cascade.
For INTERCAL this effort is not justified. Every test program is syntactically valid; the real parser bugs have been in how we interpret valid input, not in how we handle invalid input. A human writing an INTERCAL program who gets one error at a time learns faster.
Parsing in stage3.i
The pure-INTERCAL parser will follow the same recursive-descent pattern, with INTERCAL's constraints:
- No function calls other than
NEXT/RESUME. Recursion is expressed by pushing return addresses onto the NEXT stack and popping them after the parse completes. - No local variables. Parser state lives in global scalar variables, saved and restored across recursive calls using STASH and RETRIEVE.
- No dictionaries or associative arrays. Token-type lookup is a chain of conditionals or a table in an array.
Writing a recursive-descent parser in INTERCAL is a serious exercise in discipline. The stash-retrieve protocol for preserving parser state across recursion is the only mechanism INTERCAL offers for local variables. The parser logic itself is not complicated; the book-keeping is.
Parser generators and modern alternatives
If we ever decided to replace our hand-written parser, the options span a wider design space than Bison alone:
-
Flex + Bison / Yacc. The classical Unix pair. Produces LALR(1) parsers. Widely available, well-tested, C-only output. Half a century of compiler infrastructure rests on these tools.
-
ANTLR. A modern LL(k) generator with semantic predicates and multiple output languages (Java, C#, Python, C++, etc.). More readable generated code than Bison, at the cost of being heavier-weight and a Java dependency.
-
Parser combinator libraries. Higher-order functions composed into parsers, written directly in the host language. Examples: Haskell's Parsec / Megaparsec, F#'s FParsec, JavaScript's Chevrotain, Rust's
nomandchumsky. Each parse rule is a first-class value, giving the compositionality of a grammar specification with the introspectability of normal code. Closest in spirit to hand-written recursive descent. -
Packrat parsers and PEGs. Bryan Ford's 2002 ICFP paper (Packrat Parsing: Simple, Powerful, Lazy, Linear Time) introduced parsing expression grammars (PEGs) as an alternative to context-free grammars. PEGs differ from CFGs in two important ways: alternation is ordered (the first matching alternative wins, removing ambiguity by construction) and they freely allow lookahead and negation. Packrat parsing implements PEGs with linear-time guarantees via memoisation, every (rule, position) pair is computed at most once. Modern packrat-style tools include
peg,pest(Rust), andLark's Earley mode. -
Earley parsers. General-purpose parsers that handle any context-free grammar, including ambiguous ones, in O(n³) worst case but linear time on most practical grammars. Used in NLP and in places where the grammar is not yet stable. Good safety property: if you write an ambiguous grammar by accident, an Earley parser will tell you, where an LALR generator would silently shift-reduce.
The trade-off space:
| Approach | Grammar class | Performance | Best for |
|---|---|---|---|
| Hand-written recursive descent | LL(1) typically | Fast, simple | Small to medium grammars, error-message quality matters |
| Bison/yacc | LALR(1) | Fast | Large grammars where the LALR(1) restriction is acceptable |
| ANTLR | LL(*) | Fast | Cross-language code generation |
| Parser combinators | LL(k), backtracking | Variable | DSLs embedded in a host language |
| Packrat / PEG | PEG | O(n) memoised | Grammars with natural ordered alternatives |
| Earley | Any CFG | O(n³) worst case | Ambiguous or evolving grammars |
For an INTERCAL-sized grammar, hand-written recursive descent is clearly correct. Parser combinators would be the closest-to-our-implementation alternative if we ever wanted to express the grammar more declaratively. PEG and packrat would be overkill but would handle the spark/rabbit-ears alternation slightly more elegantly through ordered alternation.
We are not contemplating any of these. The hand-written parser is short and matches the grammar exactly. The exercise of imagining what a generator would look like is more useful than the migration would be.
Exercises
- Write out the grammar from appendix-grammar.md as a list of productions. For each production, identify the terminal or non-terminal that can appear as the first symbol of a derivation (the FIRST set). Confirm that no two alternatives of the same non-terminal have overlapping FIRST sets.
- Extend the grammar to add a fourth binary operator
@for some hypothetical new operation. Does the parser need to change? If so, what specifically? - Construct an expression that would force the parser to recurse five levels deep. How does this differ from what an LR parser would do on the same expression?
- Our parser has no error recovery. Describe two common parsing errors (e.g. unbalanced sparks, a variable prefix with no number) and what error message you would want the parser to produce. Sketch the code change that would produce it.
- The parallel-array layout of the AST is portable to INTERCAL. What does it sacrifice compared to a linked-structure AST a typical language implementation would use?
Next reading
- lexer-theory.md: the regular-language half of the front end.
- lexing-and-parsing.md: the concrete implementation.
- appendix-grammar.md: the grammar the parser implements.
Lexing and parsing
The compiler's front-end is short. It lives entirely in src/bootstrap/intercalc.sh, split across tokenize() (lines 68–261), parse_number() (lines 399–414), and parse_expr() (lines 415–602). This chapter walks through both phases in the same order the compiler runs them.
The lexer, viewed from a distance
At the point tokenize() starts, SOURCE is a single string with every newline and tab collapsed to a space and everything uppercased. The lexer's whole job is to split that string into a list of statements, each with its modifiers and body already pulled out.
One statement, expressed as the tuple that will live in the parallel stmt_* arrays:
stmt_label[i] e.g. "(1000)" or ""
stmt_polite[i] 1 if PLEASE was present, 0 otherwise
stmt_negated[i] 1 if NOT / N'T / DON'T was present, 0 otherwise
stmt_prob[i] 100 by default, otherwise the %N value
stmt_type[i] ASSIGN, NEXT, RESUME, FORGET, ABSTAIN, REINSTATE,
IGNORE, REMEMBER, STASH, RETRIEVE, READ_OUT, WRITE_IN,
COME_FROM, GIVE_UP, or UNKNOWN
stmt_body[i] the raw body text after modifiers have been consumed
The lexer does not tokenize the body's expressions. That is deferred to codegen time, when codegen_<type> calls parse_expr() on the body. Deferring is cheap and makes the lexer simpler: the statement-level lexer only needs to know where one statement ends and the next begins.
How statement boundaries are detected
A new statement begins at any of: DO, PLEASE, PLEASE DO, DON'T, PLEASE DON'T. Looking for those verbs is what the main scanning loop in tokenize() does.
Each iteration:
- Skip whitespace.
- Try to match an optional label
(N). If present, consume it and save for the next statement. - Try to match one of the verb tokens above. If none, abort, a program whose first non-whitespace content isn't a verb is malformed.
- Record whether PLEASE was seen (
polite=1) and whether a negation was seen (negated=1).DON'Tcounts asDO+ negation. - Optionally match
%Nfor probability. - Look at the next keyword to classify the statement type:
./:/,/;prefix →ASSIGN(followed by a number and)followed byNEXT→NEXTRESUME/FORGET/ABSTAIN/REINSTATE/IGNORE/REMEMBER/STASH/RETRIEVE/READ OUT/WRITE IN/COME FROM/GIVE UP: each maps to the obvious type.- Anything else →
UNKNOWN.
- Scan forward up to the next verb token or end-of-string. Everything in between is the body.
Point 7 is the interesting one. Statement bodies can contain sparks and rabbit-ears, and those contain tokens that look like statements. The scanner doesn't try to parse them; it just counts balanced sparks/rabbit-ears to know when a body candidate ends. This is sloppy but works because INTERCAL's statement verbs (DO, PLEASE, etc.) never appear inside an expression.
The DON'T NOTE ... trap and how the lexer handles it
An earlier iteration of the lexer produced DO + N'T as two separate tokens. This failed on constructions like DON'T NOTE foo bar, because after DO + N'T, the scanner did not recognise NOTE foo bar as a new statement and attached it to the previous statement's body. The fix was to treat DON'T as a single token. There is no D + ON'T decomposition anywhere in the tokenizer.
This is the reason DON'T NOTE is the idiomatic "comment": it parses as a standalone negated statement of type UNKNOWN, which the codegen maps to nothing and which would never execute even if reinstated (attempting to execute UNKNOWN fires ICL000I, which is fine because it was never reinstated in the first place).
The expression parser
Expressions are parsed only when codegen asks for them, by parse_expr(). The parser is a recursive descent over the body text, consuming it left-to-right.
The grammar of an expression in INTERCAL is, in informal form:
expr ::= primary op_tail*
op_tail ::= binop primary
binop ::= '$' | '~'
primary ::= const | variable | grouped | array_ref
const ::= '#' NUMBER
variable ::= unary? prefix NUMBER
unary ::= '&' | 'V' | '?'
prefix ::= '.' | ':' | ',' | ';'
grouped ::= "'" expr "'" | '"' expr '"'
array_ref ::= variable 'SUB' primary (primary)*
Plus the rule that nested grouping must alternate spark ↔ rabbit-ears. The parser enforces this at parse time: a spark immediately inside another spark, or a rabbit-ears immediately inside another rabbit-ears, fails with ICL017I and a diagnostic identifying the statement.
The expression tree
Expressions are stored as a tree of nodes in parallel arrays:
expr_type[i] CONST, VAR_SPOT, VAR_TWOSPOT, ARRAY_TAIL_REF,
ARRAY_HYBRID_REF, ARRAY_TAIL, ARRAY_HYBRID,
OP_MINGLE, OP_SELECT, OP_AND, OP_OR, OP_XOR
expr_val[i] constant value, or the variable / array number
expr_left[i] left child (binary ops); subscript count (array refs)
expr_right[i] right child (binary ops); space-separated subscript node ids (array refs)
expr_child[i] single child (unary ops)
expr_width[i] 16 or 32, the width hint used during codegen
Building a new node is a matter of (( expr_next_id++ )), then writing into slot expr_next_id - 1. The parser returns the slot index of the root of the sub-expression it just parsed. This style (parallel arrays instead of heap-allocated structs) is a concession to zsh: it is much faster than associative arrays, and the parallel-array pattern carries over directly to the INTERCAL version of the parser in stage3.i.
Why defer expression parsing
Parsing expressions during codegen, not during lexing, has one clear benefit: it keeps the statement-level representation tiny and makes it easy to reason about the statement list as a whole (count politeness, build the label map, resolve COME FROM). When we start generating code for a statement, we already know the statement's type, and only then does it matter how its body is structured.
The cost is that a program with syntactically invalid expressions will compile fine until we try to codegen the offending statement. Since we codegen every statement in order, that delay is invisible in practice.
Edge cases worth knowing
- Whitespace inside tokens:
DON'Tis one token;D ON'Tis not valid. The tokenizer matchesDON'Tas a literal keyword after uppercasing, so interior spaces break it. - Numbers:
#12345is a decimal literal. The lexer consumes digits greedily after#. A constant larger than 65535 is stored anyway; the overflow check happens at codegen/runtime time. - Array subscripts:
,1 SUB #3parses as an array reference with one subscript.,1 SUB .1 SUB .2parses as a reference with two subscripts, not as nested subscripting. The parser collects subscripts until it sees something that isn't a primary. SUBis a keyword, not a normal identifier. It is detected specifically during primary parsing.- Gerund lists (
ABSTAIN FROM NEXTING + CALCULATING): the parser reads the body as a sequence of gerund names joined by+. Each name maps to one of the statement types.
The INTERCAL-level parser (stage3.i)
The pure-INTERCAL compiler in src/compiler/stage3.i will eventually duplicate this logic inside the INTERCAL language itself. Today it only reads the source and emits a few diagnostic bytes. Once it grows, it will use the same parallel-array layout (,11 for statement labels, ,12 for polite flags, etc.) for the same reason zsh does: constant-time indexing and no heap allocation.
See self-hosting.md for the stage3 roadmap and code-generation.md for how the tree built here is consumed.
Exercises
- The lexer recognises
DON'Tas one token butDO NOTas two. Construct a small program that exposes the difference at runtime, and explain why the politeness count is the same in both cases. - List every keyword the lexer recognises. How many bytes does each occupy in the source after uppercasing? Are any prefixes of others (which would matter for a different lexing strategy)?
- The expression parser builds a tree per statement at codegen time, not at lexing time. Sketch what the tree looks like for
'.1 $ "#5 ~ #3"'. How many nodes does it have? - Find the line in
parse_exprthat consumes a binary operator ($or~). Why does the parser not need to peek ahead to disambiguate the two? - The parser enforces alternation of sparks
'and rabbit-ears"at parse time. Construct a malformed expression that triggers the new check, then trace throughparse_exprto identify the exact line where the rejection happens.
Semantic analysis
By the time the lexer finishes, the compiler knows enough about every statement to start checking program-wide properties. Three checks run in src/bootstrap/intercalc.sh between tokenisation and codegen:
check_politeness: the PLEASE ratio must be in [1/5, 1/3] (programs of fewer than five statements bypass the rule).check_labels: labels must be in the range 1–65535 and unique; build the label → statement-index map.resolve_come_from: match everyCOME FROM (N)to the labelled statement it targets, rejecting duplicate targets.
These are almost the entirety of the static analysis the compiler performs. Everything else in the INTERCAL error catalogue (undefined variable, dimension zero, bad subscript, overflow, ...) fires at runtime, because INTERCAL's statement-level activation model makes most conditions undecidable at compile time.
Politeness: why it matters to the compiler
The politeness rule is, in compiler-theory terms, a whole-program static check. It is also the only way for the compiler to reject a syntactically well-formed program. Because it is the only compile-time check, the test suites spend real effort on it: tests/test_errors_rude.i exercises the "too rude" branch and tests/test_errors_polite.i the "too polite" branch. Both fail deliberately with ICL079I and ICL099I respectively, and the harness grep-checks stderr for the code.
The implementation in check_politeness is short: count the number of statements whose stmt_polite is 1, compare polite*5 >= total and polite*3 <= total, fire die_compile 079 or die_compile 099 otherwise.
The check is bypassed entirely when the program has fewer than five statements. The 1972 manual is silent on this corner; we follow the C-INTERCAL precedent of letting tiny programs through. This is why tests/test_give_up.i, a single-statement program with no PLEASE, compiles cleanly even though 0/1 = 0% is well below the 20% lower bound.
Why the bounds are asymmetric
The spec says at least 1/5 and at most 1/3. At 5 statements one PLEASE is enough (lower bound met) but two is one too many (upper bound exceeded). At 12 statements you need between 3 and 4 PLEASEs. The compiler uses integer arithmetic with the cross-multiplied form to avoid floating point:
polite * 5 >= total ≡ polite/total >= 1/5
polite * 3 <= total ≡ polite/total <= 1/3
Off-by-one errors here would silently accept or reject programs that are on the boundary. The cross-multiplied form is exact.
What counts as polite
stmt_polite[i] is set during tokenisation when the verb is PLEASE or PLEASE DO (or PLEASE DON'T). Anything starting with DO (or DON'T) counts as 0. This matches the language specification: PLEASE DO is politer than DO, but DO is identical to nothing.
Comments do not exist in INTERCAL, so there is no debate about whether a comment statement counts. DON'T NOTE ... is a real statement; it just never executes. It is still included in the denominator.
Label uniqueness and the label map
check_labels walks stmt_label and registers each non-empty label in the associative array label_to_stmt. Two failure modes:
- A label outside the 1–65535 range fires
ICL197I LABEL VALUE OUTSIDE PERMITTED RANGE. This catches typos like(0)or(70000). - A duplicate label (the same number on two statements) fires
ICL182I DUPLICATE LINE LABEL DETECTED.
The map is essential for the phases that follow:
NEXTcodegen needs to turn the numeric label into the address of the corresponding_stmt_i_bodysymbol.COME FROMresolution needs to find the statement with that label so it can install the back-edge.ABSTAIN FROM (N)andREINSTATE (N)codegen need the statement index to locate the bit in_stmt_flags.
Labels 1000–1999 are reserved for the syslib. check_labels does not enforce this today, that is a latent consistency gap we rely on programmers to respect. If user code defines a label in 1000–1999, the syslib's own definition of the same label will either override or conflict depending on link order. The syslib is always concatenated after the user code, so the user's label wins; if the user did not also define the syslib's internal jumps, the syslib itself may break. A compile-time check for this is listed in the TODO.
COME FROM resolution
COME FROM (N) is the inverse of GOTO: the targeted statement doesn't know it has a follower. Our implementation resolves the relationship statically so the runtime cost is a single unconditional jump appended to statement N's body.
The algorithm:
- For each statement
iof typeCOME_FROM, extract the target label fromstmt_body[i]and look it up inlabel_to_stmt. - If the label doesn't exist, this will fire ICL129I at runtime; we defer the error. (Compile-time detection is viable but not done yet.)
- Record
come_from_target[target_index] = i. - During codegen, after emitting statement
target_index's body, emit an unconditionalb _stmt_i_bodyto the COME FROM's body.
The asymmetry is what makes COME FROM interesting from a compiler standpoint. A GOTO only touches its own statement; a COME FROM modifies the generated code of a statement somewhere else. The resolver pass is what lets codegen remain single-pass over the statement list: by the time codegen visits statement N, the reverse edge is already recorded.
What about multiple COME FROMs to the same label
The INTERCAL spec says this is ICL555I. Our resolve_come_from enforces it: the second COME FROM that registers the same target label fires ICL555I MULTIPLE COME FROM TARGETING SAME LABEL and the compile aborts. This was a latent bug in earlier versions of the compiler (the second registration overwrote the first silently); the check is now in place and exercised by the test suite.
COME FROM and probabilities
A COME FROM statement can itself have %N and can be abstained. Both are handled uniformly by the codegen: the COME FROM body checks its abstain flag and rolls its probability before jumping. That is, the original flow of statement N ends with:
b _stmt_come_from_body ; unconditional jump to the COME FROM
_stmt_come_from_body:
; abstain flag check
; probability roll
; (the COME FROM body itself is empty, it just falls through)
; continue at _stmt_come_from+1
If the abstain flag is set, the COME FROM body jumps back to _stmt_N+1, i.e. to normal flow. If the probability roll fails, same thing. Only when both checks pass does control stay at the COME FROM body and continue with the statement after it.
Other semantic checks that live in codegen, not here
Several checks that a textbook would call "semantic" happen during codegen because they depend on knowing how the expression is shaped:
- 32-bit-into-16-bit overflow (ICL275I) is emitted as a runtime check: the codegen produces code that compares the computed value against 65535 and jumps to
_rt_error_E275if it is larger. - Array dimension zero (ICL240I) is checked at runtime in the dimensioning code, not at compile time. The RHS of
DO ,1 <- #Nmay be an expression that evaluates to zero only conditionally. - Invalid subscript (ICL241I) is a runtime range check emitted per access.
This is not a coincidence. INTERCAL allows the full expression language wherever a value is expected, and many of these checks depend on runtime values. What looks like a compile-time guard in a C-like language has to be a runtime check here.
A handful of checks that used to live at runtime have been promoted to compile time:
NEXT (N),ABSTAIN FROM (N), andREINSTATE (N)with an undefined labelNused to emit a runtime branch into_rt_error_E129or_rt_error_E139. The label set is known at compile time, so the check now firesICL129IorICL139Iat compile time and refuses to produce a binary.ABSTAIN FROM gerund-list(and the matchingREINSTATE) used to silently ignore unknown gerund names. The check is now a compile-time rejection:DO ABSTAIN FROM PROCRASTINATINGfails with a diagnostic naming the unknown gerund.
The pattern, fold a runtime structural check into compile time once we are sure the relevant data is available, is a small but real form of optimisation. Each check moved removes both a per-emitted-statement cost and a class of late-firing bugs.
scan_variables
Not strictly a check, but run in the same pass group. scan_variables records which .N, :N, ,N, ;N numbers appear anywhere in the program. The result is four associative arrays keyed by number. Codegen uses them to emit exactly the BSS symbols it needs.
For a variable that appears in an expression but is never assigned, we still record it as "used", reading it is well-defined (value 0), and we need the BSS slot.
Exercises
- Compute the politeness boundaries for a 7-statement program, a 12-statement program, and a 100-statement program. For each, what is the minimum and maximum number of
PLEASEstatements that satisfy the rule? - The compiler stores
label_to_stmtas an associative array. Suppose the maximum label number were reduced from 65535 to 999. What part of the compiler would need to change? What about the runtime? resolve_come_fromoverwrites silently when two COME FROMs target the same label. Write the smallest INTERCAL program that triggers this latent bug. What does the program currently do, and what should it do per the specification?scan_variablesrecords a variable as "used" when it is read but never written. Why is this important? What would happen if we instead only recorded written variables?- The politeness check is the only compile-time error the compiler reports for a syntactically well-formed program. Argue for or against adding a compile-time check for
RESUME #0(currently a runtime error).
Next reading
- code-generation.md: what we do with the resolved label map and the come_from_target entries.
- runtime.md: the
_rt_error_*targets that codegen emits for the runtime-side checks listed here.
Code generation
Most compilers lower their parse tree into an intermediate representation, optimise that, and then lower again into target code. Our compiler skips the middle step entirely. Every statement of INTERCAL is turned directly into a block of ARM64 or x86-64 assembly, one function-shaped fragment per statement, glued together inside _main.
Why the direct approach works for INTERCAL, what the emitted code looks like, and where each piece lives in src/bootstrap/intercalc.sh.
Why no intermediate representation
An IR pays off when you want to share optimisations across source languages or backends, or when you want to apply classical optimisations (constant folding, dead-code elimination, register allocation). We have none of those needs:
- One source language, INTERCAL, whose programs are seldom hot paths and for which optimisation is, by design, a non-goal.
- Two backends. ARM64 and x86-64, handled by two codegen modules. Three if you count the macOS/Linux ARM64 split, but that is just a
sedpass at the end. - A runtime that already encapsulates the complicated bits (Roman numerals, the Turing tape, mingle/select, error exits) as callable routines. Each INTERCAL statement degenerates to a handful of moves plus a call.
Without an IR, every codegen function is a string template that interpolates the variable numbers and the expression tree's root node. That keeps the compiler well under 2000 lines of zsh and makes each emitted fragment trivially inspectable with INTERCAL_ASM_ONLY=1.
The emitted program layout
After codegen finishes, the generated assembly looks like this, regardless of the input:
.section __TEXT,__text
.align 2
.global _main
_main:
; save argc / argv for Label 666 syscalls 5 and 6
; install a nonzero value at _stmt_flags[i] for every statement whose
; stmt_negated was 1 at compile time
b _stmt_0_start
_stmt_0_start:
; check _stmt_flags[0]; if set, jump to _stmt_0_end
; optionally roll a probability
; ... emitted body for statement 0 ...
; if a COME FROM targets statement 0's label, jump to its body here
_stmt_0_end:
_stmt_1_start:
; same shape
_stmt_1_end:
...
_stmt_N_start:
; statement N body
_stmt_N_end:
; fallthrough past the last statement → ICL633I
bl _rt_error_E633
.section __DATA,__data
; per-program data: roman numeral table pointers etc.
.section __DATA,__bss
_stmt_flags: .space N_STATEMENTS
_spot_1: .space 4
_spot_1_ign: .space 1
_twospot_1: .space 4
; ... one pair (value, ignore-flag) per used variable ...
_tail_1_ptr: .space 8
_tail_1_dims: .space 64 ; up to 16 dimensions
; ... one per used array ...
The key invariants:
- Each statement has a contiguous
_stmt_i_start→_stmt_i_endblock. Jumps fromNEXT,ABSTAIN,COME FROMtarget the_startlabels. - Scalar variables get a 4-byte slot and a 1-byte "ignored" flag. The codegen emits a check of the ignored flag before every write, silently discarding stores if set.
- Arrays get a pointer slot (set by the dimensioning statement via
_rt_mmap) and a fixed-size dimensions table. _stmt_flagsis a byte per statement: zero means "live", nonzero means "abstained".
The dispatch: codegen_statement
The statement dispatcher sits at codegen_statement, around line 791 of intercalc.sh. Its skeleton:
codegen_statement() {
local i=$1
emit "_stmt_${i}_start:"
# abstain flag check
emit " adrp x0, _stmt_flags@PAGE"
emit " add x0, x0, _stmt_flags@PAGEOFF"
emit " ldrb w1, [x0, #${i}]"
emit " cbnz w1, _stmt_${i}_end"
# probability roll if stmt_prob < 100
(( stmt_prob[i] < 100 )) && codegen_probability $i
# dispatch on stmt_type
case "${stmt_type[$i]}" in
ASSIGN) codegen_assign $i ;;
READ_OUT) codegen_read_out $i ;;
WRITE_IN) codegen_write_in $i ;;
NEXT) codegen_next $i ;;
RESUME) codegen_resume $i ;;
FORGET) codegen_forget $i ;;
ABSTAIN) codegen_abstain $i ;;
...
GIVE_UP) codegen_give_up ;;
UNKNOWN) emit " bl _rt_error_E000" ;;
esac
# if any COME FROM targets this statement's label, jump to its body
if [[ -n "${come_from_target[${stmt_label[$i]}]}" ]]; then
local tgt="${come_from_target[${stmt_label[$i]}]}"
emit " b _stmt_${tgt}_start"
fi
emit "_stmt_${i}_end:"
}
The abstain check is uniform across every statement, so it sits in the dispatcher, not inside each codegen_<type>. Same for the probability roll.
A small example end to end
Take the three-line program:
DO .1 <- #5
PLEASE READ OUT .1
DO GIVE UP
After lexing, stmt_count=3 and:
stmt_type = (ASSIGN READ_OUT GIVE_UP)
stmt_body = (".1 <- #5" "READ OUT .1" "GIVE UP")
stmt_polite= (0 1 0)
check_politeness sees 1 polite out of 3 total: 1*5=5 >= 3 ✓, 1*3=3 <= 3 ✓, so we pass. There are no labels or COME FROMs. No syslib range labels are targeted, so needs_syslib=0.
codegen_program emits the prologue. codegen_statement(0) dispatches to codegen_assign, which parses #5 into a single constant node, calls codegen_expr on that node to emit:
mov w0, #5
and then emits the 32→16-bit overflow check, the ignore-flag check, and the store:
mov w1, #65535
cmp w0, w1
b.hi _rt_error_E275
adrp x1, _spot_1_ign@PAGE
add x1, x1, _spot_1_ign@PAGEOFF
ldrb w2, [x1]
cbnz w2, _stmt_0_end
adrp x1, _spot_1@PAGE
add x1, x1, _spot_1@PAGEOFF
str w0, [x1]
codegen_statement(1) dispatches to codegen_read_out, which recognises .1 as a scalar expression, parses it, emits a load of _spot_1 into w0, and then emits:
bl _rt_write_roman
codegen_statement(2) dispatches to codegen_give_up, which on macOS ARM64 emits:
mov x0, #0
mov x16, #1
svc #0x80
On Linux ARM64 the sed conversion later rewrites mov x16, #1 into mov x8, #93 and svc #0x80 into svc #0. On Linux x86-64 the equivalent function in codegen_x86_64.sh emits:
mov rdi, 0
mov rax, 60
syscall
That is all three statements compiled. The only thing left is emit_data, which appends the BSS section with _stmt_flags: .space 3, _spot_1: .space 4, _spot_1_ign: .space 1, and a handful of data symbols used by the runtime (the roman numeral table pointer, etc.).
Expressions: codegen_expr
Expressions are tree-walked by codegen_expr, which takes the index of a tree node and emits code that leaves the value in w0 (or x0 for 32-bit-wide values). The dispatch:
CONST→mov w0, #VAL. If the value is wider than 16 bits, twomovz/movkinstructions assemble the 32-bit word.VAR_SPOTandVAR_TWOSPOT→ load the variable intow0. The address is reached throughadrp+add+ldr.OP_MINGLE→ codegen left intow0, pushw0, codegen right intow0, pop intow1, swap, call_rt_mingle. Result inx0(32-bit).OP_SELECT→ similar, call_rt_selectwith the operand width inw2.OP_AND/OP_OR/OP_XOR→ codegen child, call_rt_unary_and_16(or 32-bit variant) etc., dispatched on the node'sexpr_width.ARRAY_TAIL_REFandARRAY_HYBRID_REF→ codegen each subscript, compute the linear index (with a per-axis bounds check that firesICL241I), load the element withldrh(16-bit) orldr(32-bit).ARRAY_TAILandARRAY_HYBRID(whole-array reference, no SUB) → not legal in expression context; placeholder code emitsmov w0, #0. These node types appear only inREAD OUTandWRITE INstatements, where the codegen handles them directly without going throughcodegen_expr.
Constant folding intercepts the operator dispatch: when eval_const reduces an OP_* subtree to a literal, the codegen emits a single mov (or movz/movk for 32-bit) instead of recursing into runtime calls.
All operator evaluation is delegated to the runtime. The codegen doesn't try to inline mingle or select. This keeps the emitted code short and means that bug-fixing or optimising _rt_mingle affects every compiled program without re-running the compiler.
Tree shape matters
Because there is no precedence in INTERCAL, the shape of the expression tree is fully determined by the explicit grouping in the source. That means the tree that comes out of parse_expr is already in the order we want to evaluate it in. No dependency-ordering, no reassociation.
Per-statement codegen, in detail
Here is what each codegen_<type> emits, in condensed form:
| Statement | Emitted behaviour |
|---|---|
ASSIGN scalar | Eval RHS into w0, check ≤ 65535 (ICL275I if 16-bit target), check ignore flag, store. |
ASSIGN array elem | Eval subscripts, compute offset, eval RHS, store via the array pointer. |
ASSIGN array dim | Eval dimensions, call _rt_mmap for new storage, store pointer + dims table. |
READ_OUT var | If scalar, load + bl _rt_write_roman. If array, bl _rt_read_out_array. |
WRITE_IN var | If scalar, bl _rt_write_in_scalar, store result. If array, bl _rt_write_in_array. |
NEXT (N) | Push return address onto the NEXT stack, check overflow (ICL123I), branch to _stmt_<target>_start. |
RESUME expr | Eval expr into w0, call _rt_resume_1 which pops K entries and returns. Zero fires ICL621I. |
FORGET expr | Eval expr, subtract from the NEXT stack pointer, saturate at zero. |
ABSTAIN FROM (N) | _stmt_flags[<idx>] ← 1. |
ABSTAIN FROM gerund-list | For each gerund, loop over all statements of that type at compile-time and emit one store each. |
REINSTATE ... | Same but store zero. |
IGNORE var-list | _<type>_N_ign ← 1 for each listed variable. |
REMEMBER var-list | Same but store zero. |
STASH var-list | For each var, push current value onto the per-variable stash stack. Overflow guarded. |
RETRIEVE var-list | Pop from the per-variable stash stack; underflow fires ICL436I. |
COME FROM (N) | No body is emitted, the previous statement's body already jumps here. |
GIVE UP | Exit 0. |
UNKNOWN | bl _rt_error_E000. |
Each one lives in its own codegen_<type> function, lines 853–1621.
Ignore flags: a small trick
A statement is abstained at the statement level; a variable is ignored at the variable level. Both are per-entity bitmaps in BSS:
_stmt_flags[i]: one byte per statement._<type>_<n>_ign: one byte per used variable.
The codegen checks both. The statement-level flag is checked once at the top of the block (by the dispatcher). The variable-level flag is checked inside the store sequence for that variable, so a write is discarded silently but an expression that reads an ignored variable still reads the last value written.
This dual-level flag pattern is one of the small non-obvious pieces of the compiler. When we get to stage3.i, the same layout is reproduced in INTERCAL arrays, because it compiles to exactly the same underlying BSS layout.
The x86-64 backend
src/bootstrap/codegen_x86_64.sh is sourced by intercalc.sh when the platform is linux_x86_64. It redefines the codegen_* functions with x86-64 equivalents, using Intel syntax (.intel_syntax noprefix), RIP-relative addressing, and the System V AMD64 calling convention. The ARM64 codegen in the base file is untouched; zsh's last-function-wins semantics is what makes the override work.
Two platform-specific pitfalls worth surfacing here:
- x86-64 GNU-as does not accept
//as a comment delimiter; use#. The codegen override is careful about this. - x86-64 supports at most
[base + index*scale + disp], so three-register expressions like[r12 + r14 + rcx]are illegal. The generated code usesleafirst to pre-compute a two-register base.
The full catalogue of platform pitfalls is in AGENTS.md, "Assembly pitfalls by platform".
Observability
The two ways to see what codegen produced:
INTERCAL_ASM_ONLY=1 zsh src/bootstrap/intercalc.sh < program.i > program.s
tools/pipeline_dump.sh program.i
The first gives you the generated assembly after the Linux ARM64 sed conversion (if applicable). The second is a higher-level dump that shows each phase. Use them when you are adding a new statement type or chasing a codegen bug; do not use them as a verification tool, because the assembly output can be legitimately different across platforms.
Exercises
- The dispatcher emits the same abstain-flag check for every statement. Estimate the per-statement instruction overhead. On a 1000-statement program, what fraction of the emitted instructions is dedicated to abstain checks?
- Compile
DO .1 <- '#5 $ #3'withINTERCAL_ASM_ONLY=1and read the generated code. How manyblcalls into the runtime does the single statement produce? How many of those would a constant-folding pass eliminate? - The codegen for scalar assignment emits an ignore-flag check before every store. The codegen for array element assignment does not. Find the discrepancy in
intercalc.shand explain whether it is a bug. codegen_array_dimcalls_rt_mmapto allocate the array. What happens if the same array is dimensioned twice in a program, once to size N, once to size M? Where does the previous M-sized allocation go?- The ARM64 codegen and the x86-64 codegen share zero source code (the latter overrides every emit function). What would it take to refactor a small overlap (say, the abstain-flag check) into a platform-neutral helper?
Next reading
- runtime.md: every
_rt_*routine the emitted code calls. - syslib.md: how NEXT to labels 1000–1999 fits into the codegen model.
- platforms.md: the full list of emitted-assembly differences per target.
The middle end we don't have
A modern production compiler has three parts: a front end that parses and analyses the source language, a back end that emits the target code, and a middle end in between that operates on a language-neutral intermediate representation. Our compiler has only a front end and a back end. This chapter explains what we forgo by omitting the middle end, what we would gain by adding one, and where the existing codegen leaves obvious performance on the table.
What is a middle end, concretely
A middle end typically contains:
- An intermediate representation (IR): a data structure that captures the program's semantics independently of any source or target language. Popular IRs include three-address code, static single-assignment form (SSA), and continuation-passing style.
- A set of optimisation passes that read the IR, rewrite it, and produce a new IR with the same observable behaviour but (usually) lower cost.
- Instrumentation and analyses that support the passes: dataflow analysis, alias analysis, control-flow graph construction, dominance trees.
A program that crosses the middle end gets transformed in ways the source language would not naturally express. Dead code is removed. Common subexpressions are factored out. Loops are unrolled. Constants are folded. Register pressure is reduced. What emerges at the back end is faster to execute and usually smaller than what a front end would have emitted directly.
Why our compiler has none of this
Four reasons, in increasing order of honesty:
- INTERCAL programs are small. The largest program we routinely compile is
syslib.iat 9065 lines. Compilation time is dominated by the cost of runningccon the generated assembly, not by the cost of the codegen. Optimising 9065 lines of INTERCAL would not meaningfully change anybody's experience. - Optimisation is hard to keep correct. Every optimisation pass is a place where a bug can silently change the program's behaviour. For a compiler we want to self-host and reach a fixpoint, adding optimisation passes is adding surface area without clear benefit.
- We have no production users for whom performance matters. Compiler performance becomes important when somebody is waiting for a build, or when the compiled program is on a hot path. Our compiler is an educational artifact. Neither constraint applies.
- Optimising an esoteric language is poorly-rewarded. The classical optimisations assume that the source language has features (
if,for, call sites with known targets) whose improved handling translates to real speedups. INTERCAL's constructs don't map onto those assumptions cleanly, and the idiomatic performance traps in INTERCAL programs (deep STASH stacks, large TTM arrays) are not what loop unrolling or constant folding address.
So we skip the middle end on principle. The compiler stays at roughly 2100 lines of zsh instead of 5000 lines with a real IR. A handful of local optimisations (constant folding, peephole, dead-flag elimination, see below) live as small passes that operate directly on the parse tree or the emitted assembly, without an IR layer in between.
Optimisations the compiler already performs
A handful of local optimisations have been added incrementally. Each lives as a small pass over the parse tree or the emitted assembly, without the overhead of an IR.
Constant folding (implemented)
When both operands of $ (mingle) or ~ (select), or the child of a unary operator (&, V, ?), are compile-time constants, the codegen computes the result directly and emits a single mov instead of a call into the runtime. The fold lives inside codegen_expr and adds a few dozen lines per operator.
The benefit is small in absolute terms, most INTERCAL programs have few wholly-constant expressions, but the savings on TTM-encoded text output (where every character is a constant manipulated by mingle / select before being stored) are visible.
In compiler-theory terms, our eval_const is an instance of the broader constant propagation family. The full version of the technique computes, for each program point, the set of variables whose values are statically known, then replaces uses of those variables with the literal values. Constant folding is the leaf-level case, when an expression is built only from literals, evaluate it. The next step up is sparse conditional constant propagation (SCCP), which combines folding with reachability analysis to eliminate dead branches whose conditions evaluate to compile-time constants. We do not run SCCP because we do not have control-flow constructs of the right shape; the %N probability check is technically reachable from any value of N, and the abstain-flag check is conditional on runtime state.
Dead-flag elimination (implemented)
Every compiled statement used to begin with a three-instruction sequence that loaded the abstain flag, tested it, and jumped over the body if set. The compiler now analyses the statement list at compile time and computes, for each statement, whether its abstain bit is ever touched by an ABSTAIN FROM (N), an ABSTAIN FROM gerund-list, or an initial NOT / N'T / DON'T. Statements that survive this analysis as immutable skip the check entirely. The analysis lives in compute_flag_checks and traces through both label-based and gerund-based modifiers.
Peephole pass (implemented)
A post-codegen pass walks the emitted assembly looking for one specific pattern: an unconditional branch (b LABEL on ARM64, jmp LABEL on x86-64) immediately followed by the label it targets. The branch is dead, fall-through reaches the label anyway, so the pass drops it. Lives in peephole_optimize. The pattern arises naturally from the way the dispatcher used to emit a trampoline label after every statement; eliminating the trampoline plus this peephole keeps the emitted code compact.
More elaborate peephole rules (load-after-store cancellation, redundant mov, jump-to-jump short-circuiting) are within reach but not yet implemented.
What we still leave on the table
Register allocation for expression trees
When an expression has multiple sub-results, we spill to the stack between them rather than keeping them in registers. For example, .1 $ '.2 ~ .3' requires evaluating .2 ~ .3 first, stacking the result, evaluating .1, then restoring the stack and calling _rt_mingle. A simple register allocator with even two registers would eliminate the spill in small cases.
The cost: substantial. Register allocation is a well-understood problem but requires tracking liveness across the tree. Probably 300 lines minimum, with a real risk of bugs.
Inlining the runtime primitives
_rt_mingle, _rt_select, and the three unary operators are called many times during a program's execution. Inlining their bodies at each call site would eliminate the bl/ret overhead. For mingle in particular, where the routine is a tight 16-iteration loop, inlining is the difference between ~15 cycles per call and ~40 cycles.
The cost: minor. Each routine is short enough to inline unconditionally. The benefit: depends heavily on how often the program calls them.
The ignore-flag check on every scalar assignment
Every scalar assignment begins with a three-instruction sequence checking the variable's _ign flag. If the variable is never IGNOREd in the program, the check is dead code. The same kind of compile-time analysis used for dead-flag elimination on statements would catch this; we have not extended it to ignore flags yet.
What a real IR would enable
If we ever wanted to take optimisation seriously, the first step would be to introduce an IR. SSA form is the standard choice: every variable is assigned exactly once, and every use names exactly which definition reaches it. In SSA, most classical optimisations become local tree rewrites.
The textbook construction is Cytron, Ferrante, Rosen, Wegman and Zadeck (1991), Efficiently Computing Static Single Assignment Form and the Control Dependence Graph. The algorithm has two parts:
- Compute the control-flow graph and its dominance relation. Then compute the dominance frontier of every node, the set of nodes Y where the current node X dominates a predecessor of Y but does not strictly dominate Y. This is where φ-functions belong.
- Place φ-functions at the dominance frontiers, then rename variables so that every definition has a unique name and every use names the dominating definition.
The result is in worst-case linear time in the size of the program, which is what made SSA practical for production compilers. LLVM, GCC's GIMPLE, and most modern back-ends rely on it.
A plausible roadmap for our compiler, if SSA were ever justified:
- Phase A: introduce a naive three-address IR between parsing and codegen. Each INTERCAL expression becomes a sequence of three-address instructions (
t3 = t1 MINGLE t2). Codegen lowers the IR to assembly one instruction at a time. - Phase B: convert the three-address IR to SSA via the Cytron algorithm. INTERCAL has few control-flow joins (NEXT/RESUME pairs and COME FROM back-edges), so the φ count stays low.
- Phase C: implement sparse conditional constant propagation (Wegman and Zadeck, 1991) on the SSA form. SCCP combines our existing constant folding with reachability analysis: when a comparison evaluates to a known constant, the branch it controls is propagated as dead, which in turn lets more values be marked constant. Iterate until fixpoint.
- Phase D: dead-code elimination on SSA. Easy in SSA: a definition is dead if its variable name has no live uses.
- Phase E: revisit the codegen to produce native assembly from optimised SSA. This is also where register allocation lives, traditionally via Chaitin-style graph colouring.
Each phase is a significant effort and introduces new test coverage requirements. We should not contemplate this road until stage3 (the pure-INTERCAL compiler) is self-hosted, because the IR would have to be expressed in INTERCAL too. Introducing complexity into a codebase that is not yet self-sufficient is premature.
Optimisations that INTERCAL itself resists
Several standard optimisations do not apply well to INTERCAL:
- Function inlining. INTERCAL has no functions, only NEXT-labelled jumps. Inlining a "function call" means inlining a whole statement that includes the NEXT + a corresponding RESUME somewhere. This is possible but tricky, because RESUMEs can be dynamically reached through abstention changes.
- Loop unrolling. INTERCAL loops are implicit: a NEXT back to the top of a body, with a RESUME-like exit. Detecting a loop requires reverse-engineering the control flow. Unrolling is then a rewrite of the entire statement list. Feasible but non-trivial.
- Escape analysis. INTERCAL has no notion of allocation other than the once-per-array
_rt_mmap. There is nothing to escape-analyse.
The optimisations that apply best are the local ones: constant folding, peephole, dead-code elimination on runtime-flag checks. These are the ones already implemented above.
IR inspection flags: --emit-cfg and --emit-3addr (implemented)
Following Part VII's chapters on LLVM, GCC, rustc, Go, and Cranelift, the bootstrap compiler now ships two inspection flags that print an IR-shaped view of the parsed program. Both are read-only; codegen still walks the parse tree directly. The flags exist for teaching and for compiler-internals debugging, not as input to a future pipeline.
--emit-cfg prints the program's control-flow graph. The pass identifies basic-block leaders (the first statement, any labeled statement, any statement immediately after a NEXT, RESUME, or GIVE UP, any statement that is the source of a COME FROM to a labeled statement, and the statement after a labeled statement that has a COME FROM). Each block lists its statements and outgoing edges. Edge kinds: fall-through, NEXT to label N (with target block), RESUME (modelled as dynamic, since the target depends on the runtime stack), COME FROM source (the implicit edge inserted by COME FROM), and exit (after GIVE UP or running off the end).
For the program
DO .1 <- #5
DO (10) NEXT
PLEASE GIVE UP
(10) DO .1 <- #3
PLEASE RESUME #1
the dump is roughly:
=== Control flow graph ===
blocks: 3
stmts: 5
B0: stmts 1..2
stmt 1: ASSIGN
stmt 2: NEXT
-> B2 (NEXT to label 10)
B1: stmts 3..3
stmt 3: GIVE_UP PLEASE
-> exit
B2: stmts 4..5 [label 10]
stmt 4: ASSIGN (label 10)
stmt 5: RESUME PLEASE
-> dynamic (RESUME pops NEXT stack)
The same shape, blocks plus statements plus edges, is what LLVM IR, MIR (rustc), Maglev (V8), and CLIF (Cranelift) all expose. Reading the dump after experimenting with INTERCAL programs is the smallest way to internalise the CFG concept that every chapter in Part VII depends on.
--emit-3addr prints a flat three-address listing of statements. It is a GIMPLE-shaped view (Cooper and Torczon ch. 5; the same shape GCC's GIMPLE has, conceptually). Each statement appears as one line tagged with its operation (ASSIGN, NEXT, RESUME, COME_FROM, GIVE_UP, etc.) plus its body and any modifiers (PLEASE, NOT, label, COME FROM target).
Both flags route through the same prepass machinery the codegen uses: tokenisation, politeness check, label resolution, COME FROM resolution, syslib detection, dead-flag analysis. The dumps thus reflect the compiler's actual model of the program, not a separate parse.
The flags are deliberately scoped down. They do not print SSA form (we have no SSA), they do not print typed values (INTERCAL's "type system" is the prefix character on each variable), and they do not constitute an IR the rest of the compiler reads. They are inspection only. A future change that introduces a real IR would replace these flags with a richer dump driven from the IR data structure itself.
The INTERCAL_SYSLIB=cache mode (implemented)
When the compiler is invoked with INTERCAL_SYSLIB=cache (env var), the syslib's INTERCAL source is compiled once and reused. The flow is:
- The compiler hashes
src/syslib/syslib.iwith SHA-256. - It looks for a pre-compiled artifact at
$XDG_CACHE_HOME/intercal/syslib-<platform>-<hash>.s(default$HOME/.cache/intercal/). - If present, the artifact is concatenated with the runtime and the program, same shape as the native path.
- If absent,
intercalc.sh --emit-syslibis invoked recursively to produce the artifact, which is then placed in the cache and used.
The artifact is a stand-alone assembly file with all internal _stmt_* symbols renamed to _syslib_stmt_* (avoiding link-time clash with the user program), BSS variables emitted as .comm (mergeable across translation units), and .global _rt_syslib_NNNN aliases for every labelled syslib routine.
This collapses pure-syslib compile time from ~30 s per build to ~0 s per build after one warming pass. tools/build_syslib.sh warms the cache for the current platform; running it once after cloning eliminates the cold-cache penalty on the first real compile.
Native remains the default. Cache mode is opt-in via env var because the cache directory is per-user state and most users do not need it.
The result is a three-way design: native (fast, hand-written), cache (fast and pure-INTERCAL), --pure-syslib (slow but unconditional). All three are byte-equivalent for the arithmetic test cases by construction. The differential test exercises --pure-syslib; production builds use native or cache; the regression test in CI exercises cache mode to catch any drift between the cached artifact and a fresh compilation.
When to add a middle end
Concrete triggers, roughly in order of priority, that would justify the effort:
- Compile time exceeds 30 seconds on any program we regularly compile, with
--pure-syslibdisabled. - Runtime of a compiled program is within 10% of our ability to tolerate, and measurable improvements are available via known optimisations.
- stage3 becomes self-hosting, at which point we have the opportunity to design an IR in INTERCAL once and maintain it alongside the codegen.
- The language grows a new feature (threading via multiple COME FROMs, maybe) whose efficient implementation is not obvious from a direct-codegen approach.
None of these apply today. The compiler stays frontend-backend-only.
Exercises
- Measure the compile time of
tests/test_syslib.iwith and without--pure-syslib. What is the ratio? Is constant folding or the syslib-size multiplication the dominant cost? - Identify three consecutive statements in the emitted assembly of
tests/test_variables.ithat could be collapsed by a peephole pass. What would the peephole rule look like? - The abstain-flag check is three instructions per statement, and
compute_flag_checksalready eliminates it where the analysis can prove the flag is never touched. On a program with 100 statements that does not use ABSTAIN at all, what fraction of statements survive with no flag check? On a program that ABSTAINs from CALCULATING, what fraction survive? - Sketch the shape of a three-address IR for INTERCAL. How many instruction opcodes would it need? Compare to LLVM IR's ~60 opcodes.
- SSA form requires φ-functions at control-flow joins. INTERCAL's control flow is NEXT and COME FROM. How many φ-functions would a realistic INTERCAL program have, roughly, per 100 lines of source?
Next reading
- code-generation.md: the current direct-emission codegen.
- self-hosting.md: why we are not in a position to add a middle end yet.
- techniques-we-use.md: every advanced technique present in our compiler, mapped to its production equivalents.
- techniques-we-lack.md: every major technique missing from our compiler, organised by phase, with production references and reading pointers.
- improvement-proposals.md: twenty concrete proposals (Tier 1 quick wins, Tier 2 medium, Tier 3 major) for what we could bring back to our compiler from Part VII and Part VIII, with algorithm sketches, effort estimates, dependencies, test strategies, risks, and references per proposal.
- further-reading.md: the books to read (Cooper & Torczon, Appel) if you want to implement one anyway.
The runtime
Everything the generated code calls into lives in a single platform-specific assembly file under src/runtime/. The runtime is written by hand, once per target, and never generated. This chapter is a guided tour of what is inside it, why each routine exists, and how the memory model is organised.
The three supported platforms each get their own file:
src/runtime/macos_arm64.s 972 lines
src/runtime/linux_arm64.s 1016 lines
src/runtime/linux_x86_64.s 1023 lines
They implement the same interface with platform-specific assembly. The INTERCAL compiler is unaware of which one will be linked in, it emits symbolic calls like bl _rt_write_roman, and the platform decides at link time.
Naming conventions
Every exported symbol begins with _rt_. Inside each file the routines are grouped into roughly five categories:
| Category | Examples | Purpose |
|---|---|---|
| Operator primitives | _rt_mingle, _rt_select, _rt_unary_and_16, _rt_unary_or_32 | The bit-level operators the INTERCAL grammar exposes ($, ~, &, V, ?). |
| Numeric I/O | _rt_write_roman, _rt_write_in_scalar | Roman numeral output, English digit-name input. |
| Character I/O | _rt_read_out_array, _rt_write_in_array | Turing Text Model tape, both directions. |
| Memory and control | _rt_mmap, _rt_resume_1 | Allocation wrapper and the NEXT-stack helper. |
| Error exits | _rt_error_E000 through _rt_error_E633 | The 16 runtime error codes. |
| Syscall dispatch | _rt_syscall_666, _rt_sys666_open, _rt_sys666_read, ... | The Label 666 extension and its eight handlers. |
Internal helpers and data live under the same file without the _rt_ prefix; they are .Lxxx local labels or anonymous data.
Memory model
The per-program memory layout is composed by the codegen (see code-generation.md) and backed by fixed-size BSS reservations declared in the runtime. At runtime the layout looks like this:
┌─────────────────────────────────────────────┐
.text │ _main, all _stmt_i_start/end, all _rt_* │
├─────────────────────────────────────────────┤
.data │ _roman_table, _errmsg_*, _ttm_heads init │
├─────────────────────────────────────────────┤
.bss │ _stmt_flags (one byte per statement) │
│ _spot_N (4 bytes, one per scalar) │
│ _spot_N_ign (1 byte, one per scalar) │
│ _twospot_N (4 bytes) │
│ _twospot_N_ign (1 byte) │
│ _tail_N_ptr (8 bytes, array pointer) │
│ _tail_N_dims (64 bytes, up to 16 dims) │
│ _tail_N_ign (1 byte) │
│ (same triplet for every used ;N) │
│ _stash_spot_N (stash stack + sp) │
│ _next_stack (80×8 bytes return addrs)│
│ _next_sp (4 bytes) │
│ _ttm_out_pos (4 bytes) │
│ _ttm_in_pos (4 bytes) │
│ _argc (4 bytes) │
│ _argv (8 bytes pointer) │
│ _sys666_buf (fixed allocation for │
│ the ,65535 data buffer) │
└─────────────────────────────────────────────┘
The NEXT stack, in detail:
_next_sp
│
▼
┌───┬───┬───┬───┬───┬──────┬───┐
│ 0 │ 1 │ 2 │ 3 │ 4 │ .... │79 │ ← slot indices
├───┼───┼───┼───┼───┼──────┼───┤
│adr│adr│adr│ │ │ │ │ ← 8-byte return addresses
└───┴───┴───┴───┴───┴──────┴───┘
▲
sp=3 (next push goes into slot 3)
push: store addr at _next_stack[sp]; sp += 1; sp == 80 → ICL123I
pop: sp -= 1; sp < 0 → ICL632I; branch to _next_stack[sp]
The Turing Text Model tape, conceptually:
_ttm_out_pos = 42
│
▼
position 0 1 2 .. 41 42 43 .. 254 255 0 1 ... (wraps)
┌──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬
code stored │ │ │ │ │ p│ p│ │ │ │ │ │ │...
└──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴
Output: subtract array[i] from pos, mod 256, bit-reverse → ASCII
Input: read char, bit-reverse its ASCII, (prev_pos - new_pos) mod 256
_ttm_in_pos is a separate head. Reads and writes do not interfere.
A 16-bit onespot occupies four bytes because ARM64 zero-extends ldr w; using a 32-bit slot simplifies loads. A twospot already is 32-bit, so one slot suffices. An array has three pieces: an 8-byte pointer set by _rt_mmap, a 64-byte dimensions table supporting up to 16 dimensions, and a one-byte ignore flag.
Arrays are heap-allocated lazily. The first DO ,N <- #K calls _rt_mmap to reserve K×2 bytes (or K×4 for a hybrid ;N), stores the returned pointer in _tail_N_ptr, and writes the dimensions table. Redimensioning re-mmaps and drops the previous allocation. The previous contents are discarded, as specified.
Operator primitives
The two binary operators, mingle ($) and select (~), are implemented as tight loops:
_rt_mingletakes two 16-bit values inw0andw1, iterates i=0..15, and places the bitw1[i]at position2*iand the bitw0[i]at position2*i+1of the 32-bit result. The emitted code uses shifts and ORs; no branches inside the loop body._rt_selecttakes a value inx0and a mask inx1, iterates over the mask's 32 bits, and packs the corresponding value bits right-justified. The result width depends on how many mask bits were set: if ≤16, the caller treats the result as 16-bit, otherwise as 32-bit. This is whyexpr_widthis tracked on the tree: codegen needs to know whether to emit a 16-bit overflow check on the result.
The three unary operators each have a 16-bit and a 32-bit variant. The 32-bit variants exploit the ARM64 ror instruction (rotate right by one, wrapping the LSB to the MSB) to express "shift right by 1 with wrap-around" in a single cycle. The 16-bit variants cannot use ror directly because ARM64 does not offer ror on 16-bit sub-registers; they shift-and-mask instead.
These primitives never allocate and never branch to error handlers. They are called many times during a program's execution and are on the hot path for any arithmetic program.
Numeric I/O
_rt_write_roman takes a 32-bit integer in w0 and writes its Roman numeral representation to stdout. The routine walks a table of (value, symbol) pairs, subtracting where possible, emitting characters into a stack buffer, and finally calling the platform write syscall once for the whole string. Values above 3999 use the vinculum (overbar) convention: a thousand is notated _I and so on. Values ≥ 4000000 are not supported; the routine clamps silently, which is a latent issue listed in the TODO.
_rt_write_in_scalar reads stdin, skipping whitespace, until it has the sequence of English digit names that compose the number. ONE is 1, TWO is 2, and so on up to NINER which is 9 (per the spec; NINE is not recognised). Each digit is folded into the running value modulo 10. End of input before any digit is ICL562I; an unrecognised token is ICL579I.
Character I/O: the Turing tape
READ OUT and WRITE IN on array variables operate via a Turing Text Model tape: a circular buffer of 256 positions, one "head" per direction (_ttm_out_pos, _ttm_in_pos), and a relative-offset encoding that ties the head's movement to a bit-reversed ASCII code.
For output (_rt_read_out_array):
- For each element
vof the array, subtract from the current output head position, modulo 256. - The new position, after bit-reversing its 8 bits, is the ASCII code to emit.
- Update the head, emit the character, move on.
For input (_rt_write_in_array), the symmetric process: read a character, bit-reverse its code, compute the delta from the previous head position, store that delta in the array element.
The two heads do not share state. Reads and writes are independent. The tape's role is not to buffer text but to make text-as-arithmetic: writing "H" is expressed as the tape-distance from the previous head position to the bit-reversed value of H's ASCII code.
This is the reason the hello-world test file starts with constants like #238, #108, #112. Each is the delta from the previous head position (starting at 0) to the bit-reversed ASCII code of a character. The compiler does not compute these deltas, the programmer must.
Memory allocation
_rt_mmap is a thin wrapper around the platform's mmap system call. On macOS ARM64 it requests MAP_ANON|MAP_PRIVATE (0x1002) with prot PROT_READ|PROT_WRITE (3). On Linux ARM64 the flags differ (0x22 instead of 0x1002) and the syscall number is 222 instead of 197. On Linux x86-64 the convention is the System V AMD64 ABI, with syscall 9.
The returned pointer is stored in the array's _tail_N_ptr slot and accessed by every subsequent read/write of that array. No free call exists: arrays are never reclaimed during program execution. For the programs INTERCAL runs this is acceptable, and the OS reclaims everything at process exit.
The NEXT stack
INTERCAL's NEXT/RESUME pair is implemented by a fixed-size array of return addresses plus a stack pointer:
_next_stack: .space 80*8 ; 80 slots of 8 bytes each
_next_sp: .space 4 ; current depth, 0 = empty
NEXT (N) codegen produces:
ldr w0, [_next_sp]
cmp w0, #79
b.ge _rt_error_E123
adr x1, _stmt_after_next ; return address
str x1, [_next_stack, w0, uxtw #3]
add w0, w0, #1
str w0, [_next_sp]
b _stmt_<target>_start
_stmt_after_next:
RESUME #K codegen evaluates K into w0 and calls _rt_resume_1 with the count. The helper decrements the stack pointer K times, guards against underflow (ICL632I / ICL621I), and branches to the last popped address via br.
A stack depth of 79 is the specified limit. Pushing the 80th fires ICL123I. In practice this is a real constraint; deep subroutine chains must FORGET #1 at loop heads to avoid exhaustion.
Errors
Each of the 16 runtime errors gets its own exit routine. They all follow the same template: load the address of a preformatted message string, write its bytes to stderr (fd 2), and exit with status 1.
The preformatted messages live in the data section. For example:
_errmsg_123: .ascii "ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON\n"
The full table is:
| Code | Meaning | Where it fires |
|---|---|---|
| E000 | UNDECODABLE STATEMENT | runtime, codegen emits a call for UNKNOWN statement bodies |
| E017 | DO YOU EXPECT ME TO FIGURE THIS OUT? | parser (compile-time) on same-in-same nesting of sparks/rabbit-ears; also reserved at runtime |
| E079 | INSUFFICIENTLY POLITE | compile-time; politeness ratio < 1/5 |
| E099 | OVERLY POLITE | compile-time; politeness ratio > 1/3 |
| E123 | NEXT STACK OVERFLOW | runtime; NEXT codegen guards depth against 79 |
| E129 | NEXT TO UNKNOWN LABEL | compile-time; the label set is known at compile time |
| E139 | ABSTAIN/REINSTATE OF UNKNOWN LABEL | compile-time; same reason as E129 |
| E182 | DUPLICATE LINE LABEL | compile-time; check_labels |
| E197 | LABEL VALUE OUTSIDE PERMITTED RANGE | compile-time; labels must be in 1–65535 |
| E200 | UNDEFINED VARIABLE | latent; reserved for future static checks |
| E240 | ZERO-DIM ARRAY | runtime; dimension codegen guards a zero RHS |
| E241 | BAD SUBSCRIPT | runtime; per-access bounds check |
| E275 | 32-BIT VALUE TO 16-BIT SLOT | runtime; scalar assign guards range |
| E436 | RETRIEVE WITHOUT STASH | runtime; RETRIEVE codegen guards stash-stack depth |
| E533 | ARITHMETIC OVERFLOW | reserved; the syslib labels documented as raising it (1000, 1030, 1050, 1500, 1540) actually wrap silently, see syslib.md for the structural reason. The error path exists in the runtime but no syslib path currently reaches it. |
| E555 | MULTIPLE COME FROM TARGETING SAME LABEL | compile-time; resolve_come_from |
| E562 | END OF INPUT | runtime; numeric input |
| E579 | BAD INPUT | runtime; numeric input |
| E621 | RESUME ZERO | runtime; RESUME codegen forbids count zero |
| E632 | PROGRAM ENDED WITHOUT GIVE UP | runtime; RESUME helper detects empty NEXT stack |
| E633 | FELL OFF THE END | runtime; fallthrough past the last statement |
E000, E017, E200 and a few others are runtime endpoints for static conditions that the compiler does not yet flag. The reserved-but-unused codes remain because upgrading the compiler to catch them at compile time requires a proper type/flow analysis, which we have not built.
Label 666
The Label 666 dispatcher and its eight handlers take up nearly 400 lines at the bottom of the runtime. Because they deserve a chapter of their own, and because the design rationale for choosing Label 666 over CLC-INTERCAL's original "call by vague resemblance" convention is already written up, see the dedicated chapter 666.md.
At a high level: bl _rt_syscall_666 reads the syscall number from .1, dispatches to the appropriate _rt_sys666_<name> handler, and returns. Parameters and results live in .2/.3/.4 for scalars and in the reserved ,65535 array for buffer data.
Exercises
- In
_rt_write_roman, what happens whenw0is 0? Read the source and explain why that behaviour is acceptable. - The TTM tape is 256 entries, one per byte value. What breaks if the tape were 128 entries instead?
- Add a mental model: given the program
DO ,1 <- #3 / DO ,1 SUB #1 <- #72 / DO READ OUT ,1, does it printH? Explain. - The NEXT stack is 80 entries deep. Suppose we wanted to make it 1024. What needs to change in the runtime, in the compiler, and in the test harness?
- Write a C program that reads the same
,65535buffer the Label 666 read handler writes into, and prints its first byte. What calling convention does your C program have to match? - The runtime never calls
free. Is there a program whose execution would leak memory faster than the OS reclaims it? Give one.
Next reading
- syslib.md: arithmetic labels 1000–1999 and the pure-vs-native split.
- 666.md: the Label 666 syscall extension in depth.
- platforms.md: how the three runtime files differ mechanically.
The system library
INTERCAL has no infix arithmetic. There is no +, no *, no /. The only operators the grammar exposes are bitwise: mingle, select, and the three unary rotate-and-combine variants. Addition, subtraction, multiplication, division, and random-number generation are all supplied as subroutines at reserved labels 1000–1999, via NEXT.
How those labels work, why we maintain two parallel implementations (pure INTERCAL and native assembly), and how the compiler decides which one to link against.
The arithmetic interface
The convention is uniform across all 20 routines:
- Inputs go in
.1and.2for 16-bit operations, or:1and:2for 32-bit. - Outputs go in
.3and optionally.4(for overflow flag), or:3and:4. - The caller is responsible for
STASHing any of.1–.4or:1–:4that it needs to preserve, and forRETRIEVEing them after the return. - The routine ends with
RESUME #1, which pops one NEXT frame and returns.
The full table:
| Label | Operation | Documented overflow | Actual behaviour |
|---|---|---|---|
| 1000 | .3 = .1 + .2 (16-bit) | Error ICL533I | Silent wrap (see note) |
| 1009 | .3 = .1 + .2, .4 = #1 no overflow or #2 overflow | Flag in .4 | As documented |
| 1010 | .3 = .1 - .2 (wraps) | No error | As documented |
| 1020 | .1 = .1 + 1 (in-place, wraps) | No error | As documented |
| 1030 | .3 = .1 * .2 (16-bit) | Error ICL533I | Silent wrap (see note) |
| 1039 | .3 = .1 * .2, .4 overflow flag | Flag in .4 | As documented |
| 1040 | .3 = .1 / .2 (integer) | .3 = 0 if .2 = 0 | As documented |
| 1050 | .2 = :1 / .1 (32/16 → 16) | Error on quotient overflow | Silent wrap (see note) |
| 1500 | :3 = :1 + :2 (32-bit) | Error ICL533I | Silent wrap (see note) |
| 1509 | :3 = :1 + :2, :4 overflow flag | Flag in :4 | As documented |
| 1510 | :3 = :1 - :2 (32-bit, wraps) | No error | As documented |
| 1520 | :1 = .1 $ .2 (mingle, explicit) | No overflow possible | As documented |
| 1530 | :1 = .1 * .2 (16×16 → 32) | No overflow possible | As documented |
| 1540 | :3 = :1 * :2 (32-bit) | Error ICL533I | Silent wrap (see note) |
| 1549 | :3 = :1 * :2, :4 overflow flag | Flag in :4 | As documented |
| 1550 | :3 = :1 / :2 (32-bit) | :3 = 0 if :2 = 0 | As documented |
| 1900 | .1 = uniform random 0..65535 | (no overflow) | As documented |
| 1910 | .2 = gaussian-ish random 0...1 | (no overflow) | As documented |
Two internal labels exist but should not be called directly: 1525 (a shift helper) and 1999 (the overflow error exit). They are not part of the public interface.
The silent-overflow caveat
Empirical testing has shown that the labels documented as "error on overflow" (1000, 1030, 1050, 1500, 1540) silently return the wrapped result instead of firing ICL533I. The cause is structural: the unwind sequence in syslib.i for each of these labels uses a NEXT/RESUME pattern in which the "no overflow" branch always wins because it FORGETs its own push and unwinds first; the "error" branch is unreachable in normal flow. The behaviour is therefore identical to the *9-suffixed routines (1009, 1039) but without the .4 flag.
The native syslib mirrors the pure syslib's actual behaviour, so the differential test passes despite the spec divergence. Programs that depend on overflow detection should use the *9 family (1009, 1039, 1509, 1549) and inspect the flag; do not rely on the error-firing variants.
This is a real divergence from the 1972 spec and the C-INTERCAL convention. It is documented here rather than fixed because the abstain-dance pattern needed to make the error path actually fire is one of the language's hardest constructs, and stage3.i does not yet support the constructs needed to reimplement the relevant labels safely. Tracked in docs/intercal_patterns.md.
Why two implementations
This repository keeps two complete copies of the syslib:
src/syslib/syslib.i: 9065 lines of pure INTERCAL, demonstrating that every arithmetic primitive is in fact implementable in a Turing-complete language with only bitwise operators.src/syslib/native/<platform>.s: the same 20 labels written in ~300 lines of platform-specific assembly, executing in microseconds rather than seconds.
The existence of both is not redundancy. It is a correctness and a pedagogy decision.
Correctness: the two implementations verify each other
Each native routine is a direct translation of the bit-level pseudocode that syslib.i uses to compute the result, plus a few algebraic simplifications that are sound only because of the unsigned 16- or 32-bit arithmetic model. Running the same INTERCAL program with both versions and diffing the outputs is a powerful differential test: if the two disagree on any input, one of them is wrong.
That is what tests/test_syslib_pure.sh exercises. It compiles three programs twice, once with each syslib, and asserts the outputs match byte for byte. Any divergence is a fail.
This pattern, two independent implementations crosschecked against each other, is a standard technique in compiler testing. The Dafny, GraalVM and LLVM projects all use variants of it. Our version is small, cheap, and catches drift whenever somebody modifies the native syslib without updating the pure one (or vice versa).
Pedagogy: the pure syslib is the specification
Somebody reading src/syslib/syslib.i sees, in literal INTERCAL, what addition means. The native assembly in src/syslib/native/<platform>.s is the fast implementation; the INTERCAL file is the reference. When you are unsure whether the spec says "subtract wraps on underflow" or "overflow is an error for 1000 but a flag for 1009", read the INTERCAL. It cannot lie, because every claim it makes is expressed in terms of operators whose semantics the language defines.
Performance
The three modes have very different cost profiles. Wall-clock to compile a representative arithmetic program on macOS ARM64:
| Mode | First build | Subsequent builds | Binary size |
|---|---|---|---|
| Native (default) | ~0.09 s | ~0.09 s | ~40 KB |
INTERCAL_SYSLIB=cache | 30–100 s (warming the cache) | ~0.1 s | ~40 KB |
--pure-syslib (no cache) | ~30 s | ~30 s | ~1.3 MB |
Native is the path of least surprise. Cache is the right choice when you want pure-syslib semantics for verification but cannot pay the per-build penalty. --pure-syslib directly is reserved for the differential test, which deliberately exercises the slow path.
How the compiler decides
detect_syslib (in intercalc.sh) scans every NEXT target. If any lies in [1000, 1999], needs_syslib=1. The compiler then chooses among three syslib paths:
- Native (default,
INTERCAL_SYSLIB=nativeor unset): the platform-specific assemblysrc/syslib/native/<platform>.sis concatenated with the runtime and the program. Calls to labels 1000–1999 resolve at link time against hand-written routines. - Cache (
INTERCAL_SYSLIB=cache): on first build,intercalc.shinvokes itself with--emit-syslibto compilesrc/syslib/syslib.ito a stand-alone.sartifact. The artifact is keyed by SHA-256 ofsyslib.iand stored at$XDG_CACHE_HOME/intercal/syslib-<platform>-<hash>.s(default$HOME/.cache/intercal/). Subsequent builds reuse the cached artifact. Result: pure-INTERCAL semantics with native-like compile time, paid once persyslib.icontent hash. --pure-syslibflag (used by the differential test): the pure INTERCALsrc/syslib/syslib.iis appended to the user's source before tokenisation, and its labels flow through the compiler like any other user-level statement. No caching; the syslib is recompiled from scratch every time. This is what the test suite uses to verify the compiler against itself.
The --pure-syslib path is what proves the compiler, the runtime, and the syslib together are internally consistent: if the pure version computes the same answer as the native version across all arithmetic test cases, the compiler handles the pure-INTERCAL syslib's constructs correctly. It is a regression sentinel for the language features the syslib actually uses.
The cache path is what makes pure-INTERCAL syslib practical. Run tools/build_syslib.sh once after cloning (or in a release pipeline), and every subsequent build with INTERCAL_SYSLIB=cache pays no syslib-compilation cost.
Why the pure syslib is big
Nine thousand lines to express twenty arithmetic routines is a lot. The size is not accidental.
Consider addition. Without +, you add two 16-bit integers a and b by repeating, for each bit position i, "if a_i and b_i, the carry propagates; if a_i xor b_i, the result bit is 1 unless the carry was 1 from below; ..." expressed entirely through $, ~, &, V, ?. The book-standard INTERCAL idiom for bitwise AND of two separate values goes via mingle followed by a unary & followed by a select, three statements and two temporaries just for "a AND b". Addition built atop that is twenty-plus statements for each of sixteen bit positions.
Once you have addition, subtraction is "add the two's complement", multiplication is repeated shift-and-add, division is repeated compare-and-subtract. Each step inherits the verbosity of the one below it.
The payoff for accepting the verbosity is that the language becomes complete. No + is ever needed. A compiler that accepts the subset of INTERCAL our syslib actually uses is complete enough to compile arbitrary arithmetic programs, which is precisely what makes self-hosting possible.
The random routines need the runtime
Labels 1900 and 1910 stand apart. You cannot implement a true random-number generator in pure INTERCAL, because INTERCAL has no access to environmental entropy. syslib.i's implementation of 1900 invokes the Label 666 syscall getrand (syscall number 9) to obtain a random number from the OS.
Inside syslib.i:
(1900) PLEASE DO STASH .1 .2
DO .1 <- #9
DO .2 <- #0
DO (666) NEXT
DO .1 <- .3
DO RETRIEVE .2
This is the single point where the pure syslib cannot pretend the runtime does not exist. Every other routine uses only INTERCAL's own operators.
Exercises
- Compile
tests/test_divide.iwith both syslibs and compare the emitted binary sizes. Explain the difference without reading the pure-mode output. - Write a three-statement INTERCAL program that verifies
1000 (addition) + 1010 (subtraction)satisfies(a + b) - b == afor.1 = 10,.2 = 20. - Run
tests/test_syslib_pure.shundertime. How does the wall-clock ratio correspond to the per-program 330× slowdown figure quoted above? - Read the implementation of label 1900 in
syslib.i. How many statements execute per call in the common case where.2 = 0? How does that compare to the native version? - Suppose we wanted to add a new label 1700 for gcd. What has to change in the pure syslib, the native syslib, and the compiler's auto-detection?
Next reading
- runtime.md: the native assembly that the native syslib links against for I/O and random.
- 666.md: Label 666, which is what label 1900 uses to reach the OS.
- self-hosting.md: how the syslib factors into the 3-generation bootstrap.
Calling conventions
A calling convention is the contract that governs how a caller and a callee transfer control and data. Which registers hold arguments, which registers survive a call, who cleans the stack, where the return value lands. Every platform we target specifies one, and our generated code has to respect it at every bl or call boundary.
The conventions for the three targets: AAPCS64 on macOS and Linux ARM64, System V AMD64 on Linux x86-64. The chapter walks through where each one surfaces in our code.
Why calling conventions matter to this compiler
The emitted code for an INTERCAL statement usually ends with one or more subroutine calls into the runtime: bl _rt_mingle, bl _rt_write_roman, bl _rt_read_out_array. Every one of those is a place where the calling convention applies. A codegen mistake that violates the convention, passing the wrong argument in the wrong register, clobbering a callee-saved register, imbalancing the stack, produces a runtime crash whose cause is not visible in the source program.
The runtime itself is also a collection of callees. Each _rt_* routine has to preserve the registers the convention says it must preserve, restore the stack pointer on exit, and return values in the right place.
Finally, the main entry point of a compiled program is itself a callee of the C runtime startup code that calls it. Getting main's prologue and epilogue wrong breaks every program.
AAPCS64. ARM64 on macOS and Linux
AAPCS64 is the ARM Architecture Procedure Call Standard for 64-bit. Both macOS and Linux follow it, with small platform-specific addenda.
Register roles
| Register | Role |
|---|---|
x0–x7 | Integer argument and return registers. Up to 8 arguments fit in registers; further arguments spill to the stack. x0 holds the primary return value; x0–x1 hold 128-bit returns. |
x8 | Indirect result location register, also used on Linux as the syscall number. |
x9–x15 | Caller-saved temporaries. The callee can clobber these freely. |
x16, x17 | Intra-procedure-call scratch, also the syscall number register on macOS (x16). |
x18 | Platform-reserved. Apple uses it; Linux user code generally does not. |
x19–x28 | Callee-saved. If a callee uses any of these it must restore them before returning. |
x29 | Frame pointer. |
x30 | Link register. bl writes the return address here. ret reads it. |
sp | Stack pointer. Must be 16-byte aligned at every call site. |
On macOS, our generated _main follows the convention: at entry, argc is in x0 and argv is in x1. On Linux, the _start / main contract is slightly different, libc wraps main: but we observe the same register contents.
What the codegen has to respect
- Pass INTERCAL-level expression results through
x0/w0. Everybl _rt_*that takes one argument places it inx0. - The NEXT stack helper
_rt_resume_1is called with the count inw0and does its own branch viabr x3(the target address popped from_next_stack). The helper is aware it is not a normal callee and bypasses the usual return convention. - The
_rt_mingle,_rt_selectand unary routines preservex0–x7only as documented; the codegen must save any value inx1–x7across them if needed. spmust be 16-byte aligned before everybl. The emitted code does not allocate per-statement stack frames, so this invariant is maintained by the runtime entry prologue, not by codegen.
Small AAPCS64 traps
x16changes role between macOS (syscall number) and Linux (intra-procedure scratch). Thesedpipeline inintercalc.shrewritesmov x16, #Nintomov x8, #Mwhen translating for Linux, along with the syscall number itself.stp/ldpare the load-pair and store-pair instructions; they move two registers (16 bytes) in one cycle. Forgetting to use these instead of pairs ofstr/ldris a common cost-of-prologue inefficiency. They also maintain 16-byte stack alignment implicitly: pushing FP+LR viastp x29, x30, [sp, #-16]!decrementsspby exactly 16 in one instruction, leaving the stack correctly aligned without a separatesub sp, sp, #16.- Floating-point arguments go in
v0–v7. Our compiler emits no floating-point code, so we never touch those registers. If we ever do, AAPCS64's full rules for mixed integer/float argument passing become relevant.
The canonical AAPCS64 prologue and epilogue
Most leaf-and-non-leaf functions in our runtime follow a small set of templates. The non-leaf canonical prologue is:
stp x29, x30, [sp, #-16]! ; push frame pointer and link register, sp -= 16
mov x29, sp ; set new frame pointer to current sp
And the matching epilogue:
ldp x29, x30, [sp], #16 ; pop FP and LR, sp += 16
ret ; return via x30
Two important properties:
- FP (
x29) and LR (x30) are always saved next to each other. This is what stack walkers (debuggers, profilers,__builtin_frame_address) depend on: walking the linked list of saved frame pointers and reading the previous LR at offset 8. - Callee-saved registers (
x19–x28,d8–d15) are pushed in pairs at higher offsets if the routine uses any of them. Our_rt_*routines mostly do not need callee-saved registers, so most prologues are just the FP/LR pair.
If a routine needs local stack space beyond the frame pointer save, it allocates after pushing FP+LR:
stp x29, x30, [sp, #-16]!
mov x29, sp
sub sp, sp, #N ; N must be a multiple of 16
; ... routine body ...
add sp, sp, #N
ldp x29, x30, [sp], #16
ret
Or, more compactly with a wider initial allocation:
stp x29, x30, [sp, #-(16+N)]! ; allocate FP/LR slot plus N locals in one go
mov x29, sp
; ... access locals at [sp, #16] through [sp, #(16+N-8)] ...
ldp x29, x30, [sp], #(16+N)
ret
Our _rt_write_roman uses the second form because it has a small stack-local buffer for the roman-numeral string. Most other _rt_* routines use the first form with N=0.
System V AMD64. Linux x86-64
The System V AMD64 ABI governs Linux, FreeBSD, macOS (for user code), and every x86-64 Unix. We target it directly for Linux x86-64; macOS on x86-64 is not a platform we support today.
Register roles
| Register | Role |
|---|---|
rdi, rsi, rdx, rcx, r8, r9 | Integer argument registers, in that order. |
rax, rdx | Return value registers (rax for 64-bit, rax:rdx for 128-bit). |
r10 | Used by the ABI as a static chain for nested functions; in our code, a caller-saved scratch. |
r11 | Caller-saved scratch. |
rbx, rbp, r12–r15 | Callee-saved. |
rsp | Stack pointer. Must be 16-byte aligned before a call instruction is executed; on entry to a function it is 8-byte-aligned-past-16 because call pushed an 8-byte return address. |
The alignment rule is a frequent source of bugs. The idiomatic prologue is push rbp; mov rbp, rsp; sub rsp, N for some 16-byte-multiple N, which restores 16-byte alignment at the first nested call.
What the codegen has to respect
codegen_x86_64.shplaces the first integer argument inrdi, notrax. This is the most common source of bugs when translating from ARM64 codegen (where the first argument isx0): the direct register correspondence isrdi↔x0.- Call sites must align the stack. The
codegen_*functions in the x86-64 backend allocate 16-byte frames for every statement that makes a call, to be safe. r12–r15are callee-saved. The runtime's_rt_sys666_openand_rt_sys666_writeuser14to hold a buffer size across a syscall, because a caller-saved register would not survive the syscall's internal register clobbering.- Syscalls on Linux x86-64 use the
syscallinstruction, with the syscall number inraxand arguments inrdi,rsi,rdx,r10,r8,r9(note:r10replacesrcx, becausesyscallclobbersrcx). This is almost the System V AMD64 convention but not identical,rcxis replaced byr10for syscalls specifically.
Small System V AMD64 traps
- The red zone: the 128 bytes below
rspare reserved by the ABI for leaf functions to use without adjusting the stack pointer. The reservation says signal and interrupt handlers must not modify this region, so leaf functions can store temporaries there safely. Our runtime uses this in a few places to avoid prologue overhead. Windows x64 does not have a red zone; if we ever target Windows, the optimisation has to be reverted. syscallvscall:syscalldoes not touch the stack. No return address is pushed. The kernel arranges the return via a privileged instruction.- Intel syntax destination-first, AT&T syntax source-first. Our emitted code is uniformly Intel. Mixing the two in the same
.sfile confuses GNUas.
Variadic functions
The System V AMD64 ABI requires that, when calling a variadic function (e.g. printf), the caller load %al (the low byte of %rax) with the number of vector registers used to pass arguments, typically zero for our generated code, since INTERCAL has no floating-point. The value need not be exact, only an upper bound. We never emit calls to variadic functions in our compiled output; the runtime calls libc write and read, which are not variadic. So %al is never set explicitly, and the convention does not bite us today.
Vector registers
%xmm0 through %xmm7 carry the first eight floating-point arguments. %xmm0 and %xmm1 carry floating-point return values. AVX2 widens these to %ymm0–%ymm15 (256-bit), AVX-512 to %zmm0–%zmm31 (512-bit). INTERCAL has no floats, so we touch none of these. They are mentioned only because future bridges to C libraries that take double arguments would have to follow the convention.
macOS ARM64 specifics
The macOS ABI is AAPCS64 with a few deviations:
_mainis the entry point symbol, notmain. The underscore is mandatory for every external symbol (this is a Mach-O convention, not strictly AAPCS64).- The Apple linker (
ld) is more lenient about.globaldeclarations than GNUld. We still emit.globalfor every top-level symbol; this is the intersection of what both linkers accept. - The syscall mechanism uses
svc #0x80with the syscall number inx16. No other ABI uses0x80.
These are all tabulated alongside the Linux equivalents in platforms.md.
Linux ARM64 specifics
Standard AAPCS64 with these corners:
- Syscalls via
svc #0(not#0x80), with the number inx8(notx16). This is a Linux ABI convention, not AAPCS64. openatis used instead ofopenbecause the kernel no longer exposesopen. The first argument isAT_FDCWD(-100), which shifts every subsequent argument's register by one.- Negative return values indicate errors. The check is
cmp x0, #0; b.lt error_handler, notb.cs.
Our callee discipline
Every _rt_* routine in the runtime files follows the same discipline, which is the intersection of AAPCS64 and System V AMD64:
- Preserve all callee-saved registers. If the routine needs any of
x19–x28/r12–r15, it saves them in the prologue. - Preserve the frame pointer and restore the stack pointer on exit. The prologue is
stp x29, x30, [sp, #-16]!on ARM64,push rbp; mov rbp, rspon x86-64. - Return via
ret(ARM64) orret(x86-64), which reads the return address from the link register or the stack respectively.
Several routines that use the syscall instruction internally save and restore rcx and r11 on x86-64, because those registers are clobbered by syscall. A bug that predated the current runtime assumed the compiler's caller code could rely on them; the fix was to make the syscall wrappers preserve them.
Worked example: bl _rt_write_roman
The generated code for DO READ OUT .1, after stripping the abstain check and label framing:
; ARM64
adrp x0, _spot_1@PAGE
add x0, x0, _spot_1@PAGEOFF
ldr w0, [x0] ; value now in w0 (zero-extended to x0)
bl _rt_write_roman ; call runtime
The bl is the instruction that enforces the convention. At this point, x0 holds the argument (the scalar value), x30 will be overwritten with the return address, and sp is 16-byte aligned.
Inside _rt_write_roman:
_rt_write_roman:
stp x29, x30, [sp, #-32]!
mov x29, sp
; ... routine body ...
ldp x29, x30, [sp], #32
ret
The prologue saves the frame pointer and link register, allocating 32 bytes of frame (enough for the stack-local roman-numeral buffer the routine uses). The epilogue restores them and returns.
The x86-64 equivalent looks similar structurally, with different mnemonics:
; x86-64
lea rdi, [rip + _spot_1] ; address in rdi
mov edi, dword ptr [rdi] ; value now in edi/rdi
call _rt_write_roman
_rt_write_roman:
push rbp
mov rbp, rsp
sub rsp, 32
; ... routine body ...
mov rsp, rbp
pop rbp
ret
The same structure, save frame pointer, allocate local frame, restore, return, with different instruction names.
Why we do not reinvent the wheel
Writing a compiler that targets a custom calling convention is possible, but not a good idea. Every such compiler ends up needing to interoperate with the system linker, the C runtime, and the kernel, all of which already agree on a convention. The right answer is to match the host platform's convention so that:
main,_main, and every_rt_*symbol can be linked bycc.- The
write,read,open,close,mmap,exitsyscalls can be invoked correctly. - Future interoperability (calling C from INTERCAL, calling INTERCAL from a test harness written in another language) remains straightforward.
This is the same reasoning behind the --pure-syslib design: we match the native side's calling convention even in pure-INTERCAL code, because the alternative would fork the interface.
Exercises
- Trace
DO READ OUT .5from the emitted assembly through_rt_write_romanto thewritesyscall. How many times does a value move between registers? How many times is a value on the stack? - Suppose a future runtime routine needs to preserve
x19across a call to a helper. Write the minimal prologue/epilogue pair that correctly follows AAPCS64. - The System V AMD64 ABI reserves
r10as a static chain register for nested functions. Our compiler has no nested functions. Does the runtime ever touchr10? If so, why? - On Linux x86-64, the
syscallinstruction clobbersrcxandr11. Find every place insrc/runtime/linux_x86_64.swhere this matters, and describe what the surrounding code does to cope. - Why does the AAPCS64 calling convention require 16-byte stack alignment rather than 8-byte? Give a concrete reason tied to the instruction set.
Executables and linking
When we say "the compiler produces a binary", the sequence of events behind that claim is: generate assembly text; feed it to an assembler; the assembler produces relocatable object code; a linker resolves symbols and arranges the object into an executable file in the format the operating system's loader understands. Our compiler does not perform these last steps itself, it shells out to cc -x assembler -, which invokes the system assembler and linker as a pipeline.
What follows: what that pipeline produces, what the resulting file looks like, and what it means for a program to be linked against our runtime.
Executable file formats
Every operating system defines its own executable format. The format encodes how the program's code and data are laid out on disk, where the loader should place them in memory, what symbols the program exports, which dynamic libraries the loader should resolve before jumping to the entry point, and a small amount of metadata about the target architecture.
We encounter two formats in this project:
- Mach-O, on macOS (and on Darwin-based platforms generally). The name stands for "Mach Object", after the Mach kernel. Every binary
intercalc.shproduces on macOS is a Mach-O file. - ELF, the Executable and Linkable Format, on Linux (and on most other Unix-like systems). Every binary produced on Linux is an ELF file.
We do not produce PE/COFF (Windows) or XCOFF (IBM AIX) binaries today. Windows support is on the roadmap.
Both Mach-O and ELF are segmented formats. A binary is partitioned into named sections, each holding a category of content: .text for executable code, .data for initialised data, .bss for zero-initialised data, and several metadata sections that the loader consults but the program cannot introspect.
The three sections our binaries use
Every binary we produce has the same three sections, regardless of platform:
.text
Executable machine code. This is where every _main, _rt_*, and _stmt_N_* symbol lives. The loader maps this section into read-and-execute-only memory and jumps to the entry point after setup.
The size of .text is proportional to the source program's statement count plus the size of the runtime. A small program like tests/test_hello.i produces a .text of roughly 20 KB; most of that is the runtime, about 1 KB is the statement bodies.
.data
Initialised data. This is where string constants (such as the 16 preformatted _errmsg_* messages) and the Roman-numeral table live. The loader maps this section read-write, copying its on-disk contents into memory at program startup.
Our .data is small. The error messages are the bulk; they total roughly 1 KB across all 16 codes.
.bss
Block Started by Symbol: zero-initialised data. The critical property of .bss is that it takes no on-disk space, the file only records how many bytes of zeroed memory the loader should allocate. For a program with 1000 statements and 100 used variables, .bss might be 5 KB in memory but cost only a few dozen bytes of metadata on disk.
Every one of our per-statement _stmt_flags bytes and per-variable slot lives in .bss. The NEXT stack (80 × 8 = 640 bytes), the stash stacks, the TTM tape positions, the reserved ,65535 buffer, all of them are .bss. This is why the compiled binaries are small despite the runtime reserving many kilobytes of working memory.
See runtime.md for the full BSS layout and the reason each symbol exists.
What the assembler does
cc -x assembler - is a shell-invocation pattern that tells the system's C compiler driver to interpret the piped input as assembly and produce an executable.
Inside cc, the pipeline is roughly:
- Parse the assembly text.
- Emit a relocatable object file (a
.ofile on disk, or an in-memory equivalent). - Invoke the linker, passing the object file and any implicit libraries (
libc, the C runtime startupcrt1.o, etc.). - The linker combines the objects and produces the final executable.
For our purposes, steps 2 and 3 are the interesting ones.
The assembler
The assembler's job is to turn human-readable assembly into machine code. For every line of assembly, the assembler produces the corresponding machine instruction bytes. For labels and symbols, it produces a table of references and definitions that the linker will later resolve.
A relocatable object file has three logical parts:
- The raw instruction bytes and data bytes, one per section.
- A symbol table: every label defined in the file, with its section and offset.
- A relocation table: every place where a label is referenced, with instructions for how to patch that reference once the label's final address is known.
Our generated assembly contains hundreds of symbol references. Every bl _rt_mingle generates a relocation entry saying "at offset N in .text, patch a 26-bit branch displacement to the address of _rt_mingle". The linker later walks this table and fills in the actual displacements.
The linker
The linker's job is symbol resolution. It reads every object file, builds a global symbol table, checks that every referenced symbol is defined exactly once somewhere, and writes out the final executable with all relocations applied.
For a compiled INTERCAL program, the linker has to resolve references between:
- The program's
_stmt_N_*symbols (internal to the input). - The
_rt_*and_sys666_*symbols (defined in the runtime assembly that was prepended to the program). - Standard entry-point symbols (
_mainon macOS,mainon Linux) and C runtime startup symbols thatcrt1.oprovides.
Symbol resolution fails if any referenced symbol is missing (undefined symbol error) or if any symbol is defined more than once (duplicate symbol error). Both are the kinds of errors that an incorrect sed pipeline step, or a renamed runtime routine, can trigger.
Why cc -x assembler - instead of writing our own linker
Writing a linker is hard. Mach-O and ELF both have intricate relocation models, symbol visibility rules, and loader-interaction contracts. A usable linker for even one of the two formats is a substantial project.
Writing an assembler is also hard, but less so, and projects like sheerass and Rust's bundled LLD show that it is feasible at small scale.
We punt on both by invoking cc. The system C compiler driver handles assembly and linking through well-tested pipelines (as plus ld on most Unix-likes). Our only contribution is the assembly source; the driver and linker handle everything after that.
The cost of this choice is a dependency: we need a working cc on every machine that compiles INTERCAL programs. In practice this is rarely an issue, every platform we target ships with gcc or clang. The .deb and .rpm release artifacts declare gcc as a runtime dependency, so installers can rely on it being present.
Static vs dynamic linking
A program can be statically linked (every library's code is copied into the final binary) or dynamically linked (libraries are loaded from disk at program startup). Our compiled programs are mostly statically linked: the runtime assembly is concatenated with the program assembly before cc sees them, so there is no "runtime library" the loader has to find at startup.
But the programs are not fully static: they depend on the host's C runtime (libSystem.dylib on macOS, libc.so.6 on Linux) for the actual system calls. Our runtime issues syscalls directly in most cases (svc #0x80, svc #0, syscall), so the dependency is small, typically only the C startup file crt1.o that arranges main to be called with argc and argv.
A truly static build (no C runtime dependency) would require writing our own _start routine and convincing the linker not to pull in libc. We have not needed this. The C runtime dependency is small enough that it does not affect portability meaningfully.
The dynamic linker
When a program with dynamic dependencies starts, a small loader (dyld on macOS, ld-linux.so on Linux) runs first. The kernel reads the path of this loader from a dedicated section in the executable (LC_LOAD_DYLINKER in Mach-O, .interp in ELF) and hands control to it before the program's own main. The loader's job is to find every dynamic library the executable references, map them into the process address space, and resolve every external symbol.
Two structures handle the symbol resolution at runtime: the Global Offset Table (GOT) and the Procedure Linkage Table (PLT).
- The GOT is a table of pointers, one per imported function or data symbol. The dynamic linker fills these in.
- The PLT is a table of small stubs, one per imported function, that load the corresponding GOT entry and jump through it. Calls to imported functions in the user's code go through the PLT, they branch to the stub, which redirects through the GOT.
ELF supports lazy binding: the GOT entries start as pointers back into the linker, so that the first call to each imported function triggers a resolution rather than paying the cost up front. After the first call, the GOT is updated with the real address and subsequent calls go directly. The environment variable LD_BIND_NOW=1 forces eager resolution at startup, which is the secure default for security-sensitive programs.
Mach-O uses an analogous scheme via __TEXT,__stubs and __la_symbol_ptr sections. The mechanism is similar: a small stub redirects through a pointer that the linker updates at first call.
For our compiled INTERCAL programs, the PLT is small. We import only _start (the C runtime entry into main) and the stub for whatever the system uses to actually issue syscalls. Most of the code stays inside our binary, calling our runtime via direct branches with no PLT involvement.
Position-Independent Executables (PIE)
Modern toolchains produce position-independent executables by default. PIE means the executable's .text is loaded at a randomised base address (ASLR), making certain classes of memory-corruption exploits harder. Our compiled binaries are PIE by default, file ./binary reports pie executable on Linux.
The cost of PIE is one extra level of indirection on global accesses (every reference must go through the GOT or use RIP-relative addressing). For x86-64 the cost is negligible thanks to RIP-relative addressing being the default. For ARM64 the adrp/add pair handles position independence efficiently.
How a compiled binary starts up
The execution path from ./program on the command line to the first INTERCAL statement running:
- The kernel loads the ELF or Mach-O file, mapping each section into memory according to its flags.
- Control transfers to the ELF/Mach-O entry point, typically inside
crt1.oor the equivalentdyldbootstrap on macOS. - The startup code initialises the C runtime's internal state and calls
mainwithargcandargvset correctly. - Our
_main(ormain) savesargcandargvfor later Label 666 access, initialises_stmt_flags(copying the compile-time negation bits), and falls through into the first statement. - The first statement's abstain check runs, then its body, then fallthrough to the next statement.
- Execution ends at
GIVE UP(which callsexit(0)) or falls off the end (which calls_rt_error_E633, printing ICL633I and exiting with status 1).
The exit syscall is what terminates the process. The kernel reclaims every allocated page, every open file descriptor, every runtime-allocated array, on behalf of the dying process. This is why our runtime never bothers to munmap anything: process exit is the garbage collector.
Inspecting a produced binary
Several tools come with the platform's developer toolchain and are useful for understanding what we actually produced:
file ./program: prints the file format and architecture.otool -h ./program(macOS) orreadelf -h ./program(Linux): prints the header, showing the target architecture and entry point.otool -l ./programorreadelf -S ./program: prints the section table.nm ./program: lists the symbols. Our binaries typically have 100–300 symbols: one per_rt_*routine, one per_stmt_N_start/_end, one per used variable's BSS slot.otool -tv ./programorobjdump -d ./program: disassembles the.textsection.
These tools are what you reach for when a binary misbehaves and the source-level story does not account for it. See debugging.md.
Exercises
- Run
file ./programon a hello-world binary built on your platform. Identify the ELF or Mach-O header and the machine architecture. - Run
nm ./programon the same binary. How many_rt_*symbols are listed? How many_stmt_N_*symbols? - Estimate the disk size of a compiled hello-world binary by reading the section table (
readelf -Sorotool -l). Compare to the actual on-disk size. What accounts for the difference? - What happens if we deliberately remove
bl _rt_error_E633from the end of the generated assembly, and then run a program that falls off the end? Try it by editing the emitted.sand re-assembling. - The Linux ARM64 sed pipeline rewrites
.section __TEXT,__textto.text. What is the implicit default section for a.textline, and would a program that never emits the directive still work?
Next reading
- calling-conventions.md: the per-architecture rules that the assembler and linker assume.
- platforms.md: the table of per-platform syntactic and syscall differences that show up in the emitted assembly.
- runtime.md: the
.bsslayout that this chapter describes at the file-format level.
Anatomy of a compiled binary
A practical guide to reading the binary your compiler just produced. We compile tests/test_hello.i, then dissect the resulting executable with the standard tooling. The goal is to make every byte traceable back to a chapter of these docs.
For the format-level theory see executables-and-linking.md.
Build the example
zsh src/bootstrap/intercalc.sh < tests/test_hello.i > hello
chmod +x hello
./hello
If hello printed Hello, World!, you have a working binary to dissect. Keep it around for the rest of this chapter.
What format is it?
file ./hello
On macOS Apple Silicon you should see something like:
hello: Mach-O 64-bit executable arm64
On Linux ARM64:
hello: ELF 64-bit LSB pie executable, ARM aarch64, ...
On Linux x86-64:
hello: ELF 64-bit LSB pie executable, x86-64, ...
file reads the magic bytes at the head of the binary and identifies the format. Mach-O on Apple platforms, ELF on Linux. Both are segmented formats with a header that names the architecture and entry point.
How big is it?
ls -l ./hello
size ./hello
size (where available) prints the in-memory size of each section:
text data bss dec hex filename
20096 1024 1480 22600 5848 hello
For our hello-world binary, expect ~20 KB of code, ~1 KB of read-only data, ~1.5 KB of zero-initialised data, totalling ~22.5 KB in memory. The on-disk size is smaller because the BSS section reserves space without storing it.
Read the header
# macOS
otool -h ./hello
# Linux
readelf -h ./hello
The header tells you the file format version, the target architecture, the entry-point symbol, and the offsets of the section table and other metadata. Two pieces are worth noting:
- The entry point is
_mainon macOS,mainon Linux. This is where the OS hands control after loading the binary. - The architecture matches your platform:
arm64,aarch64, orx86_64.
Read the section table
# macOS
otool -l ./hello | head -80
# Linux
readelf -S ./hello
You will see, among others:
| Section | Purpose | Approximate size |
|---|---|---|
__TEXT,__text (Mach-O) or .text (ELF) | Executable code | ~20 KB |
__DATA,__data or .data | Initialised data (Roman table, error messages) | ~1 KB |
__DATA,__bss or .bss | Zero-initialised data (variable slots, NEXT stack, TTM positions) | ~1.5 KB |
__DATA_CONST,__got (Mach-O) | Global offset table | small |
The .bss section is special: it has a memory size larger than its file size. The loader allocates bss_size bytes of zeroed memory at startup; the file does not store those zeros.
List the symbols
nm ./hello | sort
You will see ~100–300 symbols, in three categories:
Runtime routines
_rt_mingle
_rt_select
_rt_unary_and_16
_rt_unary_or_16
_rt_unary_xor_16
_rt_write_roman
_rt_read_out_array
...
_rt_error_E000
_rt_error_E123
_rt_error_E275
_rt_error_E633
...
_rt_syscall_666
_rt_sys666_open
_rt_sys666_read
_rt_sys666_write
_rt_sys666_close
_rt_sys666_argc
_rt_sys666_argv
_rt_sys666_exit
_rt_sys666_getrand
These are all defined in src/runtime/<platform>.s and concatenated into the binary at compile time. They are present in every compiled INTERCAL program, regardless of whether that program uses them.
Statement bodies
For hello world, 17 pairs:
_stmt_0_start, _stmt_0_end
_stmt_1_start, _stmt_1_end
...
_stmt_16_start, _stmt_16_end
Each pair brackets the codegen output for one INTERCAL statement. NEXT instructions in the source would have produced inter-pair branches; hello world has none, so each pair runs once and falls through to the next.
BSS data
Per-variable slots:
_tail_1_ptr ; 8-byte pointer set by _rt_mmap
_tail_1_dims ; 64-byte dimensions table
For hello world, only the array ,1 is used, so only the _tail_1_* symbols appear. A program with more variables would have correspondingly more BSS symbols.
Per-statement flags:
_stmt_flags ; one byte per statement
For hello world, this is 17 bytes. Each byte is the abstain flag for the corresponding statement. All start zeroed (active) at runtime.
Global state
_next_stack ; 80×8 bytes for return addresses
_next_sp ; 4 bytes, current depth
_ttm_out_pos ; 4 bytes, output tape head
_ttm_in_pos ; 4 bytes, input tape head
_argc ; 4 bytes, saved argc
_argv ; 8 bytes, saved argv pointer
_sys666_buf ; reserved buffer for ,65535
These are present in every binary.
Static data
_roman_table ; the Roman numeral output table
_errmsg_* ; one preformatted error message per error code
These are stored in .data (read-only at runtime).
Disassemble the entry point
# macOS
otool -tv ./hello | head -40
# Linux
objdump -d ./hello | grep -A 20 '<main>:'
The disassembly of _main looks roughly like:
_main:
stp x29, x30, [sp, #-16]!
mov x29, sp
str w0, [_argc] ; save argc
str x1, [_argv] ; save argv
bl _stmt_0_start ; first statement
; ... falls through to next ...
Each _stmt_N_start block follows a uniform shape:
_stmt_N_start:
adrp x0, _stmt_flags@PAGE
add x0, x0, _stmt_flags@PAGEOFF
ldrb w1, [x0, #N]
cbnz w1, _stmt_N_end ; abstain check
; ... statement body ...
_stmt_N_end:
For statement 0 (DO ,1 <- #14), the body dimensions the array. For statement 16 (DO GIVE UP), the body issues the exit syscall.
Trace a single instruction back to the source
Pick any address in the disassembly and trace it back:
- Address falls inside
_stmt_N_start–_stmt_N_end. → It came from the Nth statement of the input source. - Address falls inside
_rt_*. → It came from the runtime, specifically the corresponding routine insrc/runtime/<platform>.s. - Address falls inside
_mainbefore any_stmt_*. → It came from the codegen prologue. - Address falls inside
_errmsg_*or_roman_table. → It is data, not code; it came from the.datasection of the runtime.
There is a one-to-one correspondence between every byte of the binary and a place in the project source. No dependency injects unknown code.
What the loader does at startup
When you run ./hello:
- The kernel loader reads the binary's header.
- It maps
__TEXT/.textinto read-execute memory. - It maps
__DATA/.datainto read-write memory and copies in the on-disk contents. - It allocates
__DATA,__bss/.bssas read-write zeroed memory. - It runs the C runtime startup (from
crt1.oor equivalent), which sets up the stack, registers signal handlers, and ultimately callsmain. - Our
_main(ormain) starts executing.
The whole sequence takes microseconds. By the time the first INTERCAL statement begins, the process already has its full memory layout, command-line arguments, and signal handlers in place.
What the program does at exit
Eventually the program reaches DO GIVE UP, which translates to:
mov x0, #0 ; exit status 0
mov x16, #1 ; exit syscall (macOS)
svc #0x80 ; trap to kernel
The kernel reclaims every page of mapped memory, every open file descriptor, every pending I/O. The process is gone.
If the program had instead fallen off the end without GIVE UP, the codegen-emitted bl _rt_error_E633 after the last statement would print ICL633I PROGRAM FELL OFF THE EDGE to stderr and exit with status 1.
Reproducible builds
Take the hello-world binary, save it, then recompile it and diff the two binaries. Are they identical?
On Linux, yes, by construction. ELF binaries from cc typically embed an NT_GNU_BUILD_ID note (a hash of the linker's view of the input objects) plus, for some toolchains, an absolute path or timestamp. The build pipeline strips or normalises these via tools/rewrite_uuid.py, so a recompilation of the same source on the same toolchain version produces a byte-identical binary. CI verifies this property on every push.
On macOS the picture is similar in spirit. Mach-O binaries carry an LC_UUID load command that the linker (ld64) computes by hashing the relevant inputs. Recent Apple toolchains derive this UUID deterministically, the linker fills the slot with zeros, hashes the binary, then writes the derived UUID back over the placeholder, so two compilations of identical input produce identical UUIDs out of the box. We still run the rewrite step on macOS as a defence against earlier toolchains and a couple of edge cases (timestamps in __LINKEDIT).
The standard mechanism for controlling embedded timestamps is the SOURCE_DATE_EPOCH environment variable, defined by the Reproducible Builds project. When set to a Unix timestamp, every conforming build tool uses that timestamp wherever it would otherwise sample the wall clock. Our compiler does not embed timestamps, so we have nothing to honour, but anybody adding a __date__-style feature to the language should consult the spec before sampling time.
If you do get a diff anyway, the usual culprits are: a stale build cache mixed with fresh output, a toolchain update that shifted the linker version (which feeds into the rewrite step), or a system-library symbol whose absolute address moved. Running the rewrite tool by hand against the diff is usually the quickest way to localise the source of nondeterminism.
Exercises
- Compile a slightly different program, say, change one constant in
tests/test_hello.i: anddiffthe two binaries. Where is the change visible? - Use
otool -tv(orobjdump -d) to find where_rt_write_romanis called from. How many times is it called in the hello-world binary? Intests/test_read_out_num.i? - Estimate the memory footprint of a compiled INTERCAL program with 1000 statements and 100 used scalar variables. Compare to the hello-world figure.
- Strip the binary with
strip ./hello. How much smaller does it get? What was removed? - Run the binary under
dtrace(macOS) orstrace(Linux) and capture the syscall trace. How many syscalls does hello world make?
Next reading
- executables-and-linking.md: the format-level theory of Mach-O and ELF.
- runtime.md: what each
_rt_*routine does. - debugging.md: how to use
otoolandobjdumpwhile chasing bugs.
The politeness rule
INTERCAL's politeness rule is a unique compile-time check: every program must use PLEASE on between 1/5 and 1/3 of its statements. Too few and the compiler rejects the program as insufficiently polite. Too many and it rejects the program as overly polite. There is no other language whose compiler refuses to translate a program because its statements show the wrong amount of deference.
A tour of the rule: what the specification says, how our compiler implements it, where the boundaries are, and why the check exists at all.
The specification
From the 1972 reference manual, the rule is a property of the whole program:
- Fewer than one in five statements use
PLEASE→ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE. - More than one in three statements use
PLEASE→ICL099I PROGRAMMER IS OVERLY POLITE.
The bounds are inclusive at the lower end, exclusive at the upper end. A program where exactly one in five statements is polite passes; a program where exactly one in three is polite passes; a program where more than one in three is polite fails.
The specification does not explicitly carve out a tiny-program exception, but every implementation we know of (C-INTERCAL, CLC-INTERCAL, ours) bypasses the check for programs of fewer than five statements. The pragmatic reason is that the bounds are mathematically infeasible at small sizes. With three statements, you would need 0.6 to 1 polite statements, which means exactly 1, which is also above the upper bound (1/3 = 33.3%, but 1/3 = 33.3% so 1 is exactly at the boundary). The corner cases for tiny N are unintuitive enough that all implementations punt.
Our implementation
check_politeness lives in src/bootstrap/intercalc.sh:
check_politeness() {
if (( stmt_count < 5 )); then return; fi
local polite=0
local i
for (( i=1; i<=stmt_count; i++ )); do
if (( stmt_polite[$i] )); then
(( polite++ )) || true
fi
done
if (( polite * 5 < stmt_count )); then
die_compile "079" "PROGRAMMER IS INSUFFICIENTLY POLITE"
fi
if (( polite * 3 > stmt_count )); then
die_compile "099" "PROGRAMMER IS OVERLY POLITE"
fi
}
Three things to notice:
- Tiny-program shortcut: programs with fewer than five statements skip the check entirely. This is why
tests/test_give_up.i(one statement, zeroPLEASE) compiles cleanly even though 0/1 = 0% is well below the 20% lower bound. - Cross-multiplied comparison: rather than compute the ratio as a float, we use
polite*5 < totalandpolite*3 > total. This is integer arithmetic, exact at every boundary, and avoids any floating-point rounding. The cross-multiplication is the standard technique for testing rational inequalities without leaving the integers. - Strict at the upper end:
polite*3 > totalfires only when the ratio strictly exceeds 1/3. A program with exactly 1/3 polite statements passes. The lower bound is similarly strict (< stmt_count); 1/5 polite statements exactly passes.
Boundary table
The pass/fail boundaries for representative program sizes:
| Total statements | Min PLEASE for pass | Max PLEASE for pass |
|---|---|---|
| 5 | 1 | 1 |
| 6 | 2 | 2 |
| 7 | 2 | 2 |
| 8 | 2 | 2 |
| 9 | 2 | 3 |
| 10 | 2 | 3 |
| 11 | 3 | 3 |
| 12 | 3 | 4 |
| 13 | 3 | 4 |
| 14 | 3 | 4 |
| 15 | 3 | 5 |
| 17 | 4 | 5 |
| 20 | 4 | 6 |
| 25 | 5 | 8 |
| 30 | 6 | 10 |
| 100 | 20 | 33 |
Reading the table: at 17 statements (the size of tests/test_hello.i), you need between 4 and 5 inclusive PLEASEs. The actual program has 4. One more PLEASE would still pass (5 = 5/17 ≈ 29.4% ≤ 33.3%); two more would fail with ICL099I (6/17 ≈ 35.3% > 33.3%).
For programs at multiples of 15, the bounds widen smoothly, at 30 statements you have between 6 and 10 PLEASEs, a range of 4. At 1500, the range would be 200.
Boundary cases at exactly 1/5 and 1/3
A program with exactly five statements and one PLEASE: polite*5 = 5 = stmt_count, so polite*5 < stmt_count is false. The lower bound just barely passes. polite*3 = 3 < 5 = stmt_count, so the upper bound passes. The program is accepted.
A program with exactly three PLEASEs out of nine: polite*3 = 9 = stmt_count, so polite*3 > stmt_count is false. The upper bound just barely passes. polite*5 = 15 > 9, so the lower bound passes. Accepted.
Off-by-one sensitivity is real here. Adding one statement (any kind, polite or not) to a program at the upper boundary can push it from passing to failing or vice versa. Removing a PLEASE from a program at the lower boundary can do the same. The two test programs tests/test_errors_rude.i and tests/test_errors_polite.i exist specifically to confirm that the boundary detection still works correctly after every code change.
Why the rule exists
INTERCAL was written as a parody. The politeness rule is its single best joke: a feature that takes a real concept (politeness in programming) and turns it into a hard compile-time constraint. The deeper joke is that the rule is internally consistent, the compiler has a precise definition of "polite enough" and "too polite", and it enforces that definition rigorously. The 1972 manual states the rule as a serious specification; the parody is in the reader's reaction, not in the rule itself.
A second-order benefit of the rule, which the manual does not advertise, is that it forces the programmer to space out PLEASEs through the program. A reader of an INTERCAL program sees PLEASE distributed roughly every fourth statement, and that visual rhythm is part of why INTERCAL programs feel different to read.
Implications for code generation
The politeness rule is the only compile-time error our compiler reports for a syntactically well-formed program. Every other failure (undecodable statement, NEXT-stack overflow, RESUME of zero, end without GIVE UP) is a runtime condition.
The reason the others are runtime is that INTERCAL allows abstention: an unrecognised statement may be marked DON'T and never execute, so the compiler cannot reject the program just because the source contains a problem. The politeness rule is different: it is a property of the whole program text, regardless of which statements run. Static enforcement is the only place it can live.
How the rule has evolved across implementations
C-INTERCAL adopted the rule unchanged from the 1972 spec. CLC-INTERCAL added some softening: it can be configured to warn instead of error. Our compiler adopts the strict 1972 behaviour, with the 5-statement floor described above. That makes us slightly less permissive than CLC-INTERCAL but identical to C-INTERCAL on programs with five or more statements.
Common mistakes when writing INTERCAL
The two errors that fire most often during interactive editing:
- Adding a
PLEASEto clarify a comment-like statement, then forgetting to balance it. A program that hovers near the upper bound can be flipped above 1/3 by a singlePLEASEinsertion. - Removing a statement (because it became redundant) without checking that the politeness ratio still holds. Both removing a polite statement (which decreases the numerator faster than the denominator) and removing a non-polite statement (which can push the ratio over 1/3) are common.
The lint tool tools/lint_intercal.sh reports the politeness ratio as a hint, before the compiler errors out. Use it on long INTERCAL files where the ratio is non-obvious.
Exercises
- Write the smallest INTERCAL program (in number of statements) that is rejected with
ICL079I. Now write the smallest one rejected withICL099I. - The 5-statement floor means a 4-statement program with no
PLEASEis accepted. Construct an example. Is its behaviour at runtime well-defined? - Compute the maximum polite count at 100 statements. Then compute the same at 1000 statements. The ratio of the two ranges (100-statement vs 1000-statement) shrinks as N grows. Explain why.
- The check uses cross-multiplied comparison instead of floating-point ratios. Construct an integer overflow case where the cross-multiplied form would silently give the wrong answer. Is there a realistic INTERCAL program that hits it?
- Suppose we wanted to relax the rule for programs over 1000 statements (where the ratio constraint is genuinely too tight). Sketch a modified
check_politenessthat loosens the bounds for large programs.
Next reading
- semantic-analysis.md: the broader context of compile-time checks.
- intercal-primer.md: the language tour, including a shorter politeness summary.
- design-rationale.md: why we chose to enforce the rule rather than warn.
COME FROM: the inverse of GOTO
COME FROM is INTERCAL's contribution to the mythology of programming-language control flow. Where GOTO says "execution continues over there", COME FROM says "after that other statement runs, execution resumes here". The two are inverses in a precise sense: a program with a GOTO from A to B has the same control flow as a program with a COME FROM A next to where B would have been. The crucial difference is that the targeted statement does not know it has a follower.
The complete tour: history, semantics, our static-resolution algorithm, the multi-target rejection, and the threading possibilities other implementations expose.
Origins
COME FROM was not part of the original 1972 INTERCAL specification. It first appeared in print in R. Lawrence Clark's 1973 article We Don't Know Where to GOTO if We Don't Know Where We've COME FROM, published in Datamation. Clark's article was a satire of the structured programming debate then raging. Edsger Dijkstra had published Go To Statement Considered Harmful in 1968, and Clark proposed COME FROM as a deliberate provocation.
The proposal was, at the time, a joke. It became serious when Eric Raymond's C-INTERCAL added it to the language in 1990, on the reasonable grounds that any language designed to mock convention should include the most thoroughly mocked control structure in the literature. CLC-INTERCAL adopted it as well. Every modern INTERCAL implementation, including ours, treats it as canonical.
Semantics
A COME FROM (N) statement attaches itself to the labelled statement at label N. The program text contains both the (N) DO ... statement (the target) and the DO COME FROM (N) statement (the follower). Their textual order does not matter; the relationship is purely topological.
When the program runs, the target statement executes normally. After it finishes, and instead of falling through to the next statement, control transfers to the follower. The follower executes its own body, then falls through to the statement after it.
In flow-graph terms, COME FROM (N) modifies the exit edge of statement N: it adds a back edge from N's exit to the follower's entry. The original fall-through edge from N to N+1 is removed.
Two consequences worth dwelling on:
- The target is unaware: a programmer reading the target statement learns nothing about the redirection. To understand a label's behaviour, you have to scan the entire program for
COME FROMstatements that mention that label. - The redirection is unconditional: no probability, no condition. Every execution of the target statement triggers the follower (modulo the follower's own probability and abstain flags).
Our resolution algorithm
We resolve COME FROM statically, at compile time, in the resolve_come_from pass, so that the runtime cost is a single unconditional jump appended to the target's code. The algorithm:
- Walk every statement. If its type is
COME_FROM, extract the target label fromstmt_cf_target. - Look the target up in
label_to_stmt. If the label is undefined, fireICL129I. (Note: this check is currently delegated to the codegen; a refactor would move it here.) - Look the target up in
come_from_target. If a previousCOME FROMalready registered for this label, fireICL555I MULTIPLE COME FROM TARGETING SAME LABEL. This is the multi-target rejection, see below. - Otherwise, register
come_from_target[target_label] = follower_index.
Codegen then consults come_from_target when emitting each statement's body. If a follower is registered for this statement's label, the codegen appends an unconditional branch (b _stmt_<follower>_start on ARM64, jmp _stmt_<follower>_start on x86-64) to the body, before the statement's _end: marker. The peephole optimiser drops the branch if _stmt_<follower>_start immediately follows.
The multi-target rejection
Two COME FROM (N) statements both targeting the same label N is, in the original INTERCAL spec, an error: ICL555I MULTIPLE COME FROM TARGETING SAME LABEL. CLC-INTERCAL repurposed the construct as a primitive for threading: when N executes, both followers get a copy of the execution context, and the program continues with two parallel flows. The spec does not require this, and our implementation does not provide it.
Earlier versions of our compiler had a latent bug here: resolve_come_from registered the second follower silently, so the second COME FROM won and the first was lost. The check now fires ICL555I correctly.
The compile-time-resolution choice
A more permissive design would resolve COME FROM at runtime: maintain a hash table of label → follower at runtime, and look up the follower at the end of each statement. This would let COME FROM targets be computed dynamically (CLC-INTERCAL's "computed COME FROM"). But it would make the per-statement runtime cost real: every statement would pay a dictionary lookup for a feature it usually does not use.
Our static resolution gives COME FROM zero cost on statements that are not targeted, and one branch on statements that are. The trade is: we cannot support computed targets. Our spec compliance is the C-INTERCAL subset, not the CLC-INTERCAL extension.
What COME FROM is good for
In a language without IF, COME FROM is one of the few ways to express conditional execution that is not abstention-based. The pattern:
(10) DO whatever_the_main_path_is
DO RESUME #1 ; or some similar "stop now"
(20) DO COME FROM (10)
DO whatever_else
DO GIVE UP
Statement 10 executes, then control jumps to statement 20 instead of falling through to its next statement. This is approximately a THEN clause attached after the fact.
More elaborate patterns use COME FROM in conjunction with ABSTAIN to build dispatch tables, with each entry being a COME FROM that is initially abstained and gets reinstated by a controller statement when a particular branch should run. The cost of these patterns is that the program becomes hard to read top-to-bottom; the benefit is that you can express if-then-else chains without an IF.
How other languages have borrowed it
COME FROM has been adopted, mostly as a joke, by several languages outside INTERCAL:
- The Perl module
Acme::ComeFrom, which adds the construct to Perl 5 in roughly 50 lines of XS magic. The module is functional and was used at least once in production by accident. - A 2004 April Fool's RFC (RFC 3514, the "evil bit") references
COME FROMas part of its parody apparatus. - Brendan Eich considered (and rejected)
COME FROMfor early JavaScript. The story is apocryphal but plausible given the era.
The construct also appears, unintentionally, in any language that supports aspect-oriented programming, an "after" advice on a method is precisely a COME FROM for that method. AspectJ and similar systems make the relationship visible; INTERCAL just makes it a punchline.
Why no GOTO?
INTERCAL has NEXT (the labelled jump that pushes a return address) and RESUME (the labelled jump that pops a return address). Together they cover the same ground as GOTO plus subroutine call/return. The spec deliberately omits a plain unconditional jump because, as the manual puts it, "we want the programmer to think harder about each control transfer."
COME FROM, in this scheme, is the inverse of the missing GOTO rather than of NEXT. The asymmetry is deliberate.
Exercises
- Write a six-statement INTERCAL program that uses
COME FROMto produce two output lines. Trace the control flow on paper. - Convert a hypothetical
IF .1 THEN ... ELSE ...into the INTERCAL idiom usingCOME FROMplusABSTAIN. Count the statements you needed. - Two
COME FROM (10)statements are now an error. Write the test program that exercises the error and confirm it firesICL555I. - The static resolution gives zero-cost on untargeted statements and one branch on targeted ones. What would the runtime cost be if we instead resolved dynamically?
- CLC-INTERCAL's "computed
COME FROM" allows the target label to be an expression. What problem would arise in our static-resolution approach if we tried to support it?
Next reading
- semantic-analysis.md: the resolution pass in context.
- code-generation.md: how the back-edge is emitted.
- intercal-primer.md: the brief introduction.
- history-and-context.md: Clark's 1973 article in its broader context.
The Turing Text Model
Most languages have a print and a read that move characters between the program and the terminal directly. INTERCAL does not. Character I/O on arrays goes through a deliberately convoluted intermediary called the Turing Text Model: a circular tape of 256 positions, an offset-based encoding, and a bit-reversal step. What follows is the mechanism in full, the encoding derived for a single character, and the hello-world deltas worked out so the test program stops looking arbitrary.
The TTM is one of INTERCAL's signature features. Once you understand it, the rest of the language feels gentle by comparison.
The setup
The model is a tape of 256 cells, indexed 0 through 255, conceptually arranged in a circle so that position 256 wraps to position 0. There are two read/write heads, one for output and one for input, both starting at position 0. The heads are independent: writing to the output head does not move the input head, and vice versa.
For output (READ OUT ,N on an array), the program supplies an array of unsigned 16-bit values. Each value is interpreted as a displacement: the head moves backwards on the tape by that many positions, modulo 256. The byte that ends up under the head, after the move and a bit-reversal, is the ASCII code of the character to emit.
For input (WRITE IN ,N), the symmetric operation: the runtime reads a character from stdin, bit-reverses its ASCII code to get a tape position, computes the displacement from the previous head position, and stores that displacement in the array element.
The bit-reversal step
The bit-reversal is what makes the encoding non-trivial. Given a byte b with bits b7 b6 b5 b4 b3 b2 b1 b0 (b7 is the most-significant bit), the bit-reversed byte has bits b0 b1 b2 b3 b4 b5 b6 b7. So for example:
| Byte | Binary | Bit-reversed binary | Decimal of reversed |
|---|---|---|---|
H (72) | 01001000 | 00010010 | 18 |
i (105) | 01101001 | 10010110 | 150 |
e (101) | 01100101 | 10100110 | 166 |
(32) | 00100000 | 00000100 | 4 |
\n (10) | 00001010 | 01010000 | 80 |
Bit-reversal is a self-inverse: applying it twice returns the original byte. This is why the same model serves both directions.
The output algorithm in detail
To emit a string c1 c2 ... cN to stdout via the TTM:
- Set
prev = 0(the initial head position). - For each character
ci: a. Computer = bit_reverse(ascii(ci)). b. Computedelta = (prev - r) mod 256. This is the value that goes into the array element. c. Setprev = r.
The compiled program then runs READ OUT ,N, which inverts the algorithm: at each element, the runtime updates pos = (pos - delta) mod 256, bit-reverses pos, and emits the resulting byte.
Because the head moves backwards by delta (then the result is bit-reversed), the deltas in source can look unintuitive. There is no shortcut that lets you read off ASCII codes from the deltas; you have to perform the reversal mentally or with a tool.
Worked example: encoding "Hi"
Let us encode the two-character string Hi:
prev = 0.c1 = 'H' = 72.r1 = bit_reverse(72) = 18.delta1 = (0 - 18) mod 256 = 238.prev = 18.c2 = 'i' = 105.r2 = bit_reverse(105) = 150.delta2 = (18 - 150) mod 256 = 124.prev = 150.
So the array elements are 238, 124. If we wanted to print Hi\n as well:
c3 = '\n' = 10.r3 = bit_reverse(10) = 80.delta3 = (150 - 80) mod 256 = 70.prev = 80.
Array: 238, 124, 70.
Confirmation: a real compilation of:
DO ,1 <- #3
DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #124
DO ,1 SUB #3 <- #70
PLEASE READ OUT ,1
DO GIVE UP
...should print Hi\n to stdout. (Note: the politeness ratio is 1/6 ≈ 16.7%, which is below the 1/5 floor for programs of five-or-more statements. This program would be rejected with ICL079I at compile time.)
The hello-world deltas
The full sequence in tests/test_hello.i encodes Hello, World!\n:
| Index | Char | ASCII | Bit-reversed | prev (before) | delta | prev (after) |
|---|---|---|---|---|---|---|
| 1 | H | 72 | 18 | 0 | 238 | 18 |
| 2 | e | 101 | 166 | 18 | 108 | 166 |
| 3 | l | 108 | 54 | 166 | 112 | 54 |
| 4 | l | 108 | 54 | 54 | 0 | 54 |
| 5 | , | 44 | 52 | 54 | 2 | 52 |
| 6 | | 32 | 4 | 52 | 48 | 4 |
| 7 | W | 87 | 234 | 4 | 26 | 234 |
| 8 | o | 111 | 246 | 234 | 244 | 246 |
| 9 | r | 114 | 78 | 246 | 168 | 78 |
| 10 | l | 108 | 54 | 78 | 24 | 54 |
| 11 | d | 100 | 38 | 54 | 16 | 38 |
| 12 | ! | 33 | 132 | 38 | 162 | 132 |
| 13 | \n | 10 | 80 | 132 | 52 | 80 |
The fourth delta is 0: that is "no head movement", because the same character l follows another l, so the head is already in the right place.
Compare to the actual contents of tests/test_hello.i:
DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #108
DO ,1 SUB #3 <- #112
PLEASE ,1 SUB #4 <- #0
DO ,1 SUB #5 <- #64 (← this is "o", let me recompute)
The deltas in the source diverge from the table above at element 5. That is a clue: the test program is encoding a slightly different string than Hello, World!: perhaps without the comma, or with a different separator. Working through the actual test deltas is left as an exercise for the reader (see appendix-exercise-hints.md).
Why the bit-reversal?
The bit-reversal is a deliberate obscurity. It makes the encoding visibly non-trivial without changing its character: a Cesar shift would have been just as confusing but less amusing; a polynomial substitution would have been too computationally heavy. Reversing eight bits is cheap (a handful of shifts and ANDs in any architecture) but produces a permutation of the 256-byte alphabet that has no obvious pattern from the outside.
The model is named Turing in homage rather than for any technical reason. Alan Turing's machines have tapes; this is one. Turing's machines also do operations that are individually trivial but collectively produce arbitrary computations; the TTM does the same on a much smaller scale.
Why a 256-position tape?
Because that is the number of distinct byte values. A smaller tape (say, 128 positions) would map two ASCII codes to the same tape position after the bit-reversal, making the encoding lossy. A larger tape would waste positions that no byte can ever land on. 256 is exactly the right size to make the model bijective.
Implementation in the runtime
_rt_read_out_array (output) and _rt_write_in_array (input) implement the algorithm. The runtime maintains two state words in BSS:
_ttm_out_pos: .space 4 ; current output head position, 0..255
_ttm_in_pos: .space 4 ; current input head position, 0..255
Both start zero at process entry. The output routine, in pseudo-code:
for each element v in the array:
pos = (pos - v) mod 256
ch = bit_reverse(pos)
write(stdout, &ch, 1)
store pos back to _ttm_out_pos
The bit-reversal is a few shifts and and masks. The modular subtraction is a sub followed by a mask with 0xFF. The write syscall is one per character, there is no buffering. This makes a long string slow but keeps the runtime simple. A future optimisation would batch into a stack buffer and flush less often.
Encoding script
The deltas for a desired output string can be computed by any small script. In Python:
def encode_ttm(text):
deltas = []
prev = 0
for c in text:
r = int(f'{ord(c):08b}'[::-1], 2)
deltas.append((prev - r) % 256)
prev = r
return deltas
Pass this "Hello, World!\n" and you get the array of constants to embed in your ,N array.
The repository does not currently include such a script, the existing test files were encoded by hand. Adding one would be a useful contribution.
Exercises
- Encode the string
OK\nby hand, then verify by writing a four-statement INTERCAL program that prints it. (Mind the politeness rule.) - Verify the
tests/test_hello.ideltas against your own encode script. Where (if anywhere) does the test diverge fromHello, World!\n? - The output head and the input head are independent. Construct a program that uses both
READ OUT ,1andWRITE IN ,2, and explain how the two heads' state separates. - Bit-reversal is self-inverse:
bit_reverse(bit_reverse(b)) = b. Why does this matter for the input direction's algorithm? - The TTM tape size is 256 = 2^8. What hypothetical extension to INTERCAL would justify a 65536 = 2^16 tape, and what would change in the encoding algorithm?
Next reading
- runtime.md: the assembly that implements
_rt_read_out_arrayand_rt_write_in_array. - walkthrough-hello.md: the hello-world program traced through every phase, including the
READ OUT ,1call. - intercal-primer.md: short language tour, including the brief TTM summary.
Numeric I/O: Roman numerals and English digit names
INTERCAL's numeric I/O is, like everything else in the language, a parody of common practice. Numbers are output in Roman numerals; numbers are read in spelled-out English digit names (ONE TWO THREE for 123). Neither convention is what a programmer expects, and neither is incidental, they are first-class language features documented in the original 1972 manual.
Both directions in detail: the algorithms, the overbar (vinculum) notation for values above the classical Roman range, and the corner cases that have given the runtime trouble.
Roman numeral output
Calling READ OUT .N (or READ OUT :N) on a scalar variable outputs its value in Roman numeral notation. The implementation lives in _rt_write_roman in each runtime file.
The classical Roman numeral system covers values from 1 to 3999 using the seven standard symbols:
| Symbol | Value |
|---|---|
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
The classical subtractive notation reserves six special pairs:
| Pair | Value | Example |
|---|---|---|
| IV | 4 | (instead of IIII) |
| IX | 9 | (instead of VIIII) |
| XL | 40 | (instead of XXXX) |
| XC | 90 | (instead of LXXXX) |
| CD | 400 | (instead of CCCC) |
| CM | 900 | (instead of DCCCC) |
So 42 is XLII, 99 is XCIX, 1994 is MCMXCIV. The algorithm is greedy: walk a table of (value, symbol) pairs from largest to smallest, subtract while you can, emit the corresponding symbols, and continue.
Overbar notation for larger values
Values in the range 4000 to 4,000,000 are written using the vinculum (overbar) convention: a horizontal bar over a numeral multiplies its value by 1000. So V̄ (V with overbar) means 5000, X̄ X̄ means 20000, and so on.
In ASCII output, we approximate the overbar with a leading underscore. _V is read as "V with overbar" = 5000. Our runtime writes:
| Decimal | Output |
|---|---|
| 4000 | _IV |
| 5000 | _V |
| 6000 | _VI |
| 10000 | _X |
| 1000000 | _M |
| 1234 | MCCXXXIV |
| 5678 | _VDCLXXVIII |
Programs that need to verify overbar handling can use tests/test_overbar.i.
The zero corner case
Roman numerals have no symbol for zero. The convention adopted by every modern INTERCAL implementation, including ours, is to emit nothing, a literal empty output, when READ OUT is called on a variable holding zero. This is silent rather than an error, on the grounds that the spec is silent on the question and an error message would be more annoying than useful.
Programs that need to distinguish "zero output" from "no output" can pad their output with another non-zero READ OUT call before or after.
The algorithm
In pseudo-code, _rt_write_roman is:
romans = [
(1000000, "_M"), (900000, "_CM"), (500000, "_D"), (400000, "_CD"),
(100000, "_C"), (90000, "_XC"), (50000, "_L"), (40000, "_XL"),
(10000, "_X"), (9000, "_IX"), (5000, "_V"), (4000, "_IV"),
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"),
(1, "I")
]
function write_roman(n):
if n == 0: return # silent
buffer = []
for (value, symbol) in romans:
while n >= value:
append symbol to buffer
n -= value
write(stdout, buffer)
write(stdout, "\n")
The actual ARM64 implementation walks a table in .data and emits one syscall per output. There is no buffering, character at a time, which is slow but simple.
English digit-name input
Calling WRITE IN .N reads a number from stdin where each digit is spelled out as an English word. ONE TWO THREE is 123; FOUR ZERO ZERO is 400; NINER FIVE is 95.
The supported tokens, with their digit values:
| Token | Value |
|---|---|
ZERO or OH | 0 |
ONE | 1 |
TWO | 2 |
THREE | 3 |
FOUR | 4 |
FIVE | 5 |
SIX | 6 |
SEVEN | 7 |
EIGHT | 8 |
NINER | 9 |
Note: NINE is not recognised. The 1972 manual specifies NINER, the radio-procedural rendering of nine. This is the most common gotcha for new INTERCAL programmers, typing NINE produces ICL579I BAD INPUT. The convention is preserved in our implementation for spec compatibility.
Token parsing
The runtime reads input one token at a time, separated by whitespace. Each token is uppercased on read and compared against the table above. Unrecognised tokens fire ICL579I. End of input before any token is read fires ICL562I.
The runtime accumulates digits into the result variable: each new digit shifts the running value left by one decimal place (multiplies by 10) and adds the digit. The result is stored in the destination variable on the next WRITE IN boundary.
For 32-bit destinations (:N), the same algorithm runs against a 32-bit accumulator.
Multi-variable WRITE IN
WRITE IN .1 .2 .3 reads three space-separated numbers (themselves space-separated word lists). The runtime distinguishes one number from the next by the first whitespace after a non-digit-name token, but in practice users provide explicit separators. Our test suite uses the spec-conformant format.
Why these specific conventions?
Both Roman numerals and English digit names are deliberate complications. The spec writers chose them because they are universally recognised but inconvenient, a programmer reading Roman output knows what number is meant but cannot read it as fluently as decimal, and a programmer typing English digit names has to think about each digit individually.
This contrasts with typical input/output, where the goal is to be transparent. INTERCAL's I/O is opaque on purpose. The output of READ OUT .42 (printed as XLII) is correct but slightly slow to parse mentally. The input of WRITE IN .42 (typed as FOUR TWO) is correct but slightly slow to type.
The combination forces the programmer to engage with the language at every I/O boundary, which is exactly the behaviour the manual was satirising.
Implementation notes
_rt_write_roman is around 60 lines of platform-specific assembly. The table of (value, symbol) pairs is in .data. The routine itself is a tight loop that walks the table.
_rt_write_in_scalar is more elaborate, around 150 lines, because it has to lex tokens, compare against the digit-name table, and assemble a numeric value. The lexer is a small state machine that uppercases input on the fly. The digit-name table is in .data, with each entry being the token bytes followed by the digit value.
A future optimisation worth noting: _rt_write_in_scalar could share its uppercasing logic with the compiler's own read_source (which folds source case the same way). They do not today, because the compiler runs in zsh and the scalar reader runs in compiled assembly. After self-hosting (when stage3.i becomes the compiler), both could share an INTERCAL-level implementation.
Implementation gotchas observed in CI
Two specific bugs that have hit the runtime:
- An older version of
_rt_write_romanwould emit a leading newline before the numeral characters, because the buffer-push order was inverted. Caught bytests/test_overbar.iwhich expects exact byte output. - An older version of
_rt_write_in_scalaracceptedNINEas well asNINER, which silently passed CI on macOS but failed on Linux because the digit-name table had a different layout. The fix was to removeNINEfrom both platforms; the spec mandatesNINER.
Both bugs were fixed before any release. They are mentioned here as evidence that even features as simple as numeric I/O have implementation traps.
Exercises
- Compute
XLII,MMXXIV, and_V_DCCXIXin decimal by hand. Verify withREAD OUTof the corresponding constant. - The Roman numeral system has no zero. Our runtime emits nothing for
READ OUTof a zero-valued variable. Construct a program that distinguishes "zero output" from "no output". Hint: print a marker character around it. - Write an INTERCAL program that reads a number and prints its Roman form. Use only the syslib for arithmetic.
- The maximum value our runtime handles is roughly 4,000,000 (one cycle of the overbar). What happens for values above that? Read the runtime source and trace.
- The digit-name
NINERis required butNINEis not accepted. Suppose we wanted to relax this and accept both. What changes are needed in_rt_write_in_scalar?
Next reading
- runtime.md: the full runtime context for both routines.
- intercal-primer.md: the language tour with the brief I/O section.
- turing-text-model.md: the array-based character I/O that complements the scalar numeric I/O described here.
Platforms
The compiler targets three platforms today:
- macOS on Apple Silicon (ARM64, Mach-O).
- Linux on AArch64 (ARM64, ELF).
- Linux on x86-64 (ELF, Intel syntax).
Windows is on the roadmap but not implemented. The macOS ARM64 target is the primary development platform; the others are validated in CI on every push. This chapter surveys what each platform demands, how the compiler satisfies those demands, and the pitfalls we have encountered.
What "supporting a platform" entails
Supporting a new target for this compiler means providing three things, all of which live in the repository as hand-written assembly:
- A runtime,
src/runtime/<platform>.s: with every_rt_*routine listed in runtime.md. - A native syslib,
src/syslib/native/<platform>.s: with all 20 arithmetic labels. - Either a codegen module that directly emits the target assembly (as in
src/bootstrap/codegen_x86_64.sh), or a source-to-source conversion from the macOS ARM64 assembly produced byintercalc.sh(as in thesedpipeline insidemainfor Linux ARM64).
The first two are mechanical translations. The third is the real design decision, and we have made it differently for Linux ARM64 than for Linux x86-64.
Syntactic and syscall differences
A compressed version of the table in AGENTS.md:
| Aspect | macOS ARM64 | Linux ARM64 | Linux x86-64 |
|---|---|---|---|
| Format | Mach-O | ELF | ELF |
| Assembler | Apple as (lenient) | GNU as (strict) | GNU as, Intel syntax |
| Entry point | _main | main | main |
| Symbol prefix | _ | none | none |
.global required | no | yes | yes |
| Text section | .section __TEXT,__text | .text | .text |
| Comment delimiter | // or # | // or # | # only |
| Syscall instruction | svc #0x80 | svc #0 | syscall |
| Syscall number register | x16 | x8 | rax |
| Syscall error detection | carry flag (b.cs) | negative return | negative return |
| Relocation (ADRP/ADR) | sym@PAGE, sym@PAGEOFF | bare sym, :lo12:sym | RIP-relative sym(%rip) |
exit syscall number | 1 | 93 | 60 |
read | 3 | 63 | 0 |
write | 4 | 64 | 1 |
open | 5 | (use openat = 56) | 2 |
close | 6 | 57 | 3 |
mmap | 197 | 222 | 9 |
MAP_ANON | MAP_PRIVATE | 0x1002 | 0x22 | 0x22 |
O_WRONLY | O_CREAT | O_TRUNC | 0x601 | 0x241 | 0x241 |
| Randomness source | getentropy (500) | getrandom (278) | getrandom (318) |
Every one of those lines is a past bug waiting to happen. The pitfalls section below is the bug history.
Two strategies for platform support
There are two ways to add a new backend to a compiler: translate after the fact, or emit different output in the first place. Both are legitimate, and we use both.
Post-hoc translation: Linux ARM64
The Linux ARM64 path produces macOS ARM64 assembly from intercalc.sh, then translates it with sed as a final step. The relevant lines in main:
asm_combined=$(print -r -- "$asm_combined" | sed \
-e 's/\.section __TEXT,__text/.text/' \
-e 's/\([_a-zA-Z][_a-zA-Z0-9]*\)@PAGEOFF/:lo12:\1/g' \
-e 's/\([_a-zA-Z][_a-zA-Z0-9]*\)@PAGE/\1/g' \
-e 's/svc #0x80/svc #0/g' \
-e 's/mov x16, #1$/mov x8, #93/' \
...
-e 's/\.global _main/.global main/' \
-e 's/^_main:/main:/')
The advantage: the codegen phase does not branch on the platform. One emission strategy, one post-processing pass. The .s files under src/runtime/ and src/syslib/native/ are pre-translated versions of their macOS counterparts and are committed to the repository, not generated.
The risk: the sed order is fragile. Matching @PAGE first and @PAGEOFF afterwards would corrupt _sym@PAGEOFF into _sym:lo12:OFF, because @PAGE is a prefix of @PAGEOFF. Our real history has at least one bug of this exact shape. The fix is the order shown above: @PAGEOFF first, then @PAGE.
Fresh emission: Linux x86-64
The Linux x86-64 path replaces every codegen_* function. src/bootstrap/codegen_x86_64.sh is sourced when the platform is linux_x86_64; because zsh lets a later function definition silently override an earlier one, every ARM64 emission function is replaced.
The advantage: the emitted assembly is idiomatic x86-64 from the start. No source-to-source translation step is necessary. Intel syntax (.intel_syntax noprefix), RIP-relative addressing, System V AMD64 calling convention.
The cost: every statement's codegen has to be implemented twice, once per architecture. The x86-64 backend is 955 lines (compared to the 970 or so lines of per-statement codegen in ARM64).
The tradeoff between the two approaches depends on how different the target is from the source architecture. ARM64-to-ARM64 can plausibly be done with sed (the instruction set is the same; only the assembler syntax and syscall numbers differ). ARM64-to-x86-64 cannot: the instruction set, register conventions, and memory addressing are all different.
Pitfalls, by platform
This is a distilled version of the platform-pitfalls section of AGENTS.md. The canonical list lives there; the purpose of repeating it here is pedagogic.
ARM64 (both macOS and Linux)
adrp symcomputes the page base ofsym. GNUasinfers the page relocation automatically, but Appleasrequiressym@PAGE. Thesedstep adds or removes the suffix accordingly.add x0, x0, sym@PAGEOFFon macOS becomesadd x0, x0, :lo12:symon Linux. The:lo12:prefix does not go on theadrpinstruction; GNUasinfers the high bits.:pg_hi21:never appears in either flavour of our output. Earlier experiments where we emitted it caused GNUasto reject the file with "junk at end of line".- macOS reserves
svc #0x80for syscalls; Linux usessvc #0. The trap-handler-side check ignores the immediate on macOS, what dispatches the syscall is the value inx16. The0x80convention on macOS dates back to Apple's BSD heritage on x86 (int 0x80); when the platform moved to ARM64, the immediate was preserved out of inertia. Linux ARM64 chosesvc #0because there is no historical reason for any other value on a fresh ABI.
Linux ARM64 only
- Linux AArch64 has no
opensyscall.openat(56) is the replacement, withAT_FDCWD(-100) as the first argument. - Error detection returns a negative value, not a carry flag.
cmp x0, #0; b.ltreplaces macOS'sb.cs. .globalis required for any symbol referenced across translation units. Appleldis lenient about missing declarations; GNUldrejects. We declare every entry-point symbol (_main→main,_rt_*) at column 0. Only labels at column 0 may be declared; attempting to.globala data symbol or a label line containing:lo12:causes the assembler to choke.
Linux x86-64 only
- GNU
asrejects//as a comment. Our x86-64 emission uses#. [r12 + r14 + rcx]has three registers. x86-64 addressing allows at most two. Uselea r15, [r12 + r14]to flatten, then[r15 + rcx].- Intel syntax is opted into by
.intel_syntax noprefixat the top of every.sfile. Every subsequent line must match; mixing AT&T (%rax) with Intel (rax) anywhere in the same file breaks the assembler. - RIP-relative addressing is the idiomatic way to reference data in position-independent code:
lea rax, [rip + symbol].
Platform detection
At the top of intercalc.sh:
_OS=$(uname -s | tr '[:upper:]' '[:lower:]')
_ARCH=$(uname -m)
case "${_OS}_${_ARCH}" in
darwin_arm64) _INTERCAL_PLATFORM=macos_arm64 ;;
linux_x86_64) _INTERCAL_PLATFORM=linux_x86_64 ;;
linux_aarch64) _INTERCAL_PLATFORM=linux_arm64 ;;
*) _INTERCAL_PLATFORM=macos_arm64 ;;
esac
The fallback to macOS ARM64 is a development convenience; a user on an unsupported platform sees a build error when cc -x assembler - refuses the output. setup_platform.sh prints the detected platform and confirms the three inputs (runtime, syslib, codegen) exist.
Cross-platform testing from macOS
To reproduce a Linux CI failure from a macOS development machine, run tests/cross_test.sh:
zsh tests/cross_test.sh linux_x86_64
zsh tests/cross_test.sh linux_arm64 --image ubuntu:24.04
The script spins up a Docker container for the requested platform, installs zsh and gcc, mounts the repository, and runs the relevant test suite inside. It is slower than a native run (~3 minutes for the full suite on a Docker x86-64 VM), but much faster than waiting for CI and, critically, reproducible locally.
Exercises
b.cson macOS vsb.lton Linux. Construct a one-line INTERCAL program whose generated code exercises this conditional. Trace why the platforms chose different conventions historically.- The
sedpipeline has a substitutionmov x3, #0x1002 → mov x3, #0x22. Find every place in the macOS runtime where0x1002appears. What would happen if the substitution matched inside a comment? - Suppose we want to add Windows ARM64 (COFF, different syscall model). Decide whether to go the post-hoc translation route or write a fresh codegen backend, and justify the choice in one paragraph.
- The x86-64 backend emits Intel syntax. Could we instead emit AT&T syntax without rewriting the codegen? What, mechanically, would that require?
- Run
tests/cross_test.sh linux_x86_64locally. Compare the wall-clock time oftests/run_tests.shinside the container to a native macOS run. What fraction of the slowdown is Docker overhead, and what fraction is the x86-64 emulation?
Next reading
- runtime.md: the per-platform runtime routines that this chapter's differences manifest in.
- testing-and-workflow.md: how the CI job configures each platform.
AGENTS.mdsections "Multi-platform porting guide" and "Assembly pitfalls by platform", the authoritative versions of the tables and pitfalls summarised here.
Self-hosting
A compiler is self-hosting when it can compile its own source. The goal of this repository is to reach that state for INTERCAL: an INTERCAL compiler whose source is an INTERCAL program, compiled by an older copy of itself, producing an executable that can in turn compile the same source. This chapter explains how the project gets there, what "fixpoint" means in practice, and what stage we are at today.
The bootstrap problem
A brand-new language has no compiler until somebody builds one, and the first compiler cannot be written in that language because nothing exists to compile it. The standard resolutions are:
- Write the first compiler in another language, say C or shell. Use it to compile a compiler written in the new language.
- Find an older version of the new language whose compiler already exists, extend it, and bootstrap by recompiling the extensions.
Our approach is option (1), executed in three phases, with the deliberate choice of shell as the bootstrap language.
Phase 1. The shell bootstrap
src/bootstrap/intercalc.sh is a complete INTERCAL compiler written in zsh. It reads .i from stdin, emits ARM64 or x86-64 assembly, concatenates that with the runtime and (optionally) the syslib, and invokes cc -x assembler - to produce a binary. It runs to roughly 2100 lines and handles the full language, every statement type, every operator, all four variable prefixes, arrays, abstention, COME FROM, the politeness rule, and the 16 runtime error codes.
This is what gives us the "primordial spark" (chispa primigenea): the first INTERCAL compiler that exists at all. Everything that follows builds on its output.
Phase 2. The self-hosted MVP
src/compiler/compiler.i is an INTERCAL program whose job is, today, extremely modest: read a source file via Label 666, classify it by content hash, emit the pre-generated assembly for that specific program, and exit. It is 43 lines of INTERCAL and, functionally, a template dispatcher.
The repository also ships src/compiler/templates/<platform>/<testname>.s: one pre-compiled assembly file per test program per platform. The MVP's "compilation" is:
- Read argv[1] (the source file name).
- Read its contents into the reserved
,65535buffer. - Compute a content hash (delegated to the wrapper).
- Look up the matching template.
- Write the template to stdout.
The wrapper script intercal then concatenates the runtime, the syslib, and the emitted template into the final binary.
This is trivially not a real compiler. What it is, is proof that the end-to-end self-hosted pipeline works: a .i program (compiler.i) was compiled by intercalc.sh, the resulting binary reads another .i file via the Label 666 syscalls, and produces assembly that builds a second binary identical to what the bootstrap would have built. Every component. Label 666, argv access, the reserved ,65535 buffer, the read and write syscalls, the exit code path, is exercised.
The template-dispatch shape matters for one additional reason: it lets us run the self-hosted compiler in CI across every test program, without needing the real lexer and parser to exist yet. The self-hosted MVP passes 25/25 tests on all three platforms. That coverage is the guarantee that the runtime and the INTERCAL language features used by compiler.i are already rock solid.
Phase 4. The evolving compiler
src/compiler/stage3.i is where the template dispatcher is being replaced, incrementally, by a real compiler. As of substage 3.2.a, the file has grown to ~110 lines and can:
- Read argv[1] into
,65535. - Record the source's byte count in
.20. - Read the first byte (
,65535 SUB #1) into.21. - Read the second byte into
.27. - Read the last byte at index
.20into.22. - Compute four branchless byte-equality probes against ASCII
D,O,P,A(.23,.24,.25,.26). - Combine the first two probes into a 2-character keyword detector for
"DO"(.29). - Print all of these (count, first byte, last byte, four probes, is_DO) as Roman numerals.
The branchless-equality pattern is documented in docs/intercal_patterns.md as "conditional ADD without a branch": subtract via 1010, pack any set bit to LSB via select-from-self, flip via mingle+XOR+select. About fifteen statements per equality test, but no abstain dance, no unwind, no branch. The approach was chosen after three attempts to use loops with conditional break ran into a structural blocker, see the next paragraph.
The roadmap from here, matching the stages in AGENTS.md, is:
- Lexer: scan
,65535forDO,PLEASE,DON'T, counting statements and recording boundaries in parallel arrays,11–,18. - Parser: classify each statement, parse expressions into a tree using arrays
,20–,23and;20. - Semantic analysis: politeness check, label uniqueness, COME FROM resolution.
- Minimal codegen: emit assembly for
GIVE UPonly, exercising the full pipeline-to-binary assembly. - Incremental codegen: one statement type at a time, each with a dedicated regression test.
- Fixpoint: compile
stage3.iwith itself, verify generation-to-generation output stability.
Each sub-stage is committed as a separate piece with a failing test, a passing implementation, and green CI across all three platforms. The TDD workflow documented in AGENTS.md is what makes this a viable plan rather than a multi-month debugging session.
The fixpoint test
A compiler is self-hosted in a meaningful way only when running it on its own source is a stable operation: the output does not change if you do it again. The test we will eventually run is:
# Generation 1: compile compiler.i with the bootstrap
zsh src/bootstrap/intercalc.sh < src/compiler/compiler.i > gen1
# Generation 2: compile compiler.i with gen1
./gen1 src/compiler/compiler.i > gen2.s
cat runtime.s syslib_native.s gen2.s | cc -x assembler - -o gen2
# Generation 3: compile compiler.i with gen2
./gen2 src/compiler/compiler.i > gen3.s
# Fixpoint: gen2.s and gen3.s must be byte-identical
diff -q gen2.s gen3.s
If gen2.s = gen3.s, the compiler has reached a fixpoint: it now produces the same output for itself whether compiled by the bootstrap or by its own previous generation. That is the precise definition of self-hosting used in this project and described in bootstrap.sh.
Note that gen1 does not need to equal gen2. The bootstrap compiler and the self-hosted compiler can emit slightly different assembly (different register allocations, different operand ordering). What matters is that the self-hosted compiler is internally consistent: once it is the one in charge, its output stabilises immediately.
Why a third generation is useful
Two generations are enough to prove correctness, in the sense that gen2 could compile gen3 again and produce gen3 again. A third generation catches a different class of bug: suppose gen1 had a subtle miscompilation that happened to produce a correct compiler gen2, but gen2 itself mishandled some feature only used inside its own source. Then gen2(compiler.i) ≠ gen1(compiler.i), and we would expect gen3 to differ from gen2. Comparing three generations makes this detectable.
Historically, the three-stage bootstrap is also how gcc validates itself. The third stage exists not because two is wrong, but because three is cheap insurance.
Why shell for the bootstrap, and not C or Rust
The bootstrap language does not affect the final compiler, only the initial act of bringing one into existence. Three factors pushed us toward shell:
- Universality: every supported target (macOS, Linux ARM64, Linux x86-64) has zsh. No toolchain bootstrap is required before the compiler bootstrap.
- Introspectability: adding
set -xreveals the pipeline in full. Every phase is a function. Every emitted line of assembly is aprintcall. - Appropriateness: INTERCAL is itself 1970s-era baroque. A 1970s-era shell, with tricky quoting and awk-adjacent pipelines, is a fair match.
The third of these is half-serious. The first two are decisive. A C bootstrap would need a make system, headers, a build toolchain, and cross-compilation configuration per platform. A Rust bootstrap would need a modern rustup setup on every CI runner. zsh needs none of that.
The documented fallback, if the shell version ever becomes unmaintainable, is to make the bootstrap emit Rust source that the rust compiler lowers to native code. We have not needed that.
What self-hosting does not mean
It is tempting to conflate "self-hosting" with "production-ready" or "optimised". Neither is implied:
- Self-hosting is a purely mechanical property. A buggy compiler that reliably produces a buggy copy of itself is still self-hosting.
- The self-hosted compiler is allowed to be slow and unoptimised, provided it terminates. Speed is a separate concern.
- Self-hosting is not a guarantee that the language is Turing-complete, only that the specific program
compiler.iis expressible.
In our case we care about self-hosting for the same reason every historical language implementation did: it is the cleanest demonstration that the language is complete enough to express its own translation.
Trusting Trust
Ken Thompson's 1984 Turing Award lecture, Reflections on Trusting Trust, set out a class of attack that is unique to self-hosting compilers. Roughly: a malicious compiler can be modified to recognise when it is compiling its own source, reinsert a backdoor into the new compiler binary, and propagate that backdoor through every future generation, even after the malicious code has been removed from the source. The attack is invisible to source-level inspection because the malicious behaviour lives only in the binary that compiles the next binary.
Our compiler is a tiny, hand-readable program with no production users; a serious Trusting Trust attack on it would not be worth anyone's effort. The lesson is conceptual rather than operational: once a compiler can compile itself, the source is no longer the only thing you have to trust. You also have to trust the binary that compiled the source, and the binary that compiled that, and so on back to the chispa primigenea.
The standard countermeasure, Diverse Double-Compiling (DDC) by David A. Wheeler (2005, formalised in his 2009 PhD), is to compile the same source with two independent compilers and verify that their outputs agree. If two unrelated compilers produce byte-equivalent binaries from the same INTERCAL source, both would have to share the backdoor for the attack to survive. For us, the practical analogue is the differential test we already run: pure-INTERCAL syslib compiled by intercalc.sh versus native syslib hand-written in assembly. The two paths are independent enough that a Trusting Trust attack on one would have to be replicated by a hand attacker on the other.
This is also why we keep the bootstrap compiler readable and small. A two-thousand-line zsh script is not malice-proof, but it is auditable in an afternoon, which is the most defensible position a small language implementation can occupy.
Exercises
- Read
bootstrap.sh. At what step does it assumecompiler.iis a real compiler rather than the template-dispatch MVP? What heuristic does it use to decide? - Given that
gen1andgen2can differ legitimately, why does the fixpoint test insist ongen2 = gen3? Give an example wheregen1 = gen2 = gen3would be impossible for a correct compiler. - Today's
stage3.ireads the source file and prints three bytes. Describe the smallest extension that would make it distinguish aDOfrom aPLEASE DOstatement. Estimate the number of INTERCAL lines required. - Could the bootstrap be written in Python 3 instead of zsh? What would change in the CI configuration? What would not change?
- The
--pure-syslibflag swaps the syslib at the entry point of each compilation. Would you use--pure-syslibfor the self-hosting fixpoint test? Why or why not?
Next reading
- map-of-the-compiler.md: the exact layout of
src/compiler/and how the MVP and stage3 files relate. - testing-and-workflow.md: the four test suites, differential testing, and the TDD contract that keeps stage3 on the rails.
- platforms.md: why self-hosting has to work identically on three platforms and what enforces that.
Testing and workflow
A compiler is a program whose output is another program. That gives it an inconveniently large surface area: a bug can live in the lexer, the parser, the semantic analyser, the code generator, the runtime, the syslib, or the glue between any two of those. A single mistake can pass compilation unchecked and fire only at runtime on a specific platform with a specific input. Testing is therefore not optional; it is the primary mechanism by which this project asserts that anything works.
What follows: the four test suites, the TDD contract that governs changes, how differential testing between the bootstrap and the self-hosted compiler is arranged, and the pre-commit / pre-push / CI cadence that enforces everything.
The four test suites
| Suite | File | Scope | Count |
|---|---|---|---|
| Bootstrap | tests/run_tests.sh | Full language, via intercalc.sh | 33 |
| Pure syslib | tests/test_syslib_pure.sh | Pure vs native syslib equivalence | 3 |
| Self-hosted MVP | tests/run_self_tests.sh | Template-dispatch compiler.i end-to-end | 25 |
| Evolving | tests/run_stage3_tests.sh | stage3.i diagnostics | 4 |
The four together comprise 65 tests, and the count grows as each new compiler feature acquires its regression test. They run in sequence on every push, on every platform: three platforms × 65 tests = 195 distinct test executions per CI run, give or take a handful of platform-skipped cases.
CI also exercises the bootstrap suite a second time with INTERCAL_SYSLIB=cache to verify that the cached pure-syslib path produces correct binaries, bringing the per-platform total higher in practice.
A separate tools/bench.sh script measures compile and link times across representative programs, with --json output and a --compare baseline.json mode for tracking regressions across commits. It is not part of the test suites themselves; treat it as the project's lightweight performance dashboard.
run_tests.sh: the ground truth
This suite is the source of truth. Each entry is an INTERCAL program under tests/test_<name>.i with an expected output (inline or in a sibling file). The runner compiles the program with intercalc.sh, executes it, captures stdout, and compares to the expected value. Failures surface with the actual vs expected diff.
The tests are grouped by what they exercise:
- Language primitives:
test_variables.i,test_nested_expr.i. - I/O:
test_hello.i,test_read_out_num.i,test_read_out_multi.i,test_overbar.i,test_write_in.i. - Control flow:
test_control.i,test_come_from.i,test_forget.i,test_give_up.i. - State management:
test_stash.i,test_ignore_remember.i,test_abstain.i,test_abstain_gerund.i. - Arithmetic via syslib:
test_syslib.i,test_divide.i,test_multiply.i,test_multidim_array.i. - Politeness:
test_errors_rude.i,test_errors_polite.i: each expects a specific ICL error on stderr. - Runtime errors:
test_error_e123.i,test_error_e621.i,test_error_e633.i: each must terminate with the matching ICL code. - Label 666:
test_syscall_readself.i: the program reads its own source via argv[0] and Label 666, then prints metrics about it.
A new language feature or codegen path requires a new entry. A bug fix requires a reproducer that fails before the fix and passes after. These rules are binding; see "TDD contract" below.
test_syslib_pure.sh: differential testing
The pure-vs-native syslib split (see syslib.md) is the basis of our strongest differential test. Three programs, add, multiply, divide, are compiled twice, once with intercalc.sh (native syslib) and once with intercalc.sh --pure-syslib (syslib expressed in INTERCAL and fed through the full pipeline). Both binaries are run, and their outputs are compared byte for byte.
Any divergence is a fail. The failure modes this catches include:
- A native assembly routine that silently disagrees with its INTERCAL reference (wrong algorithm, missing edge case).
- A compiler change that mishandles some INTERCAL construct used by the pure syslib but not by the test programs.
- A runtime change (e.g. to
_rt_mingleor_rt_select) that affects only one of the two paths.
Differential testing is cheap and high-value because the two implementations are independent. A bug that hides in both, a miscompilation of the shared runtime operator primitives, survives this test but fails the bootstrap suite.
run_self_tests.sh: self-hosted MVP
This suite runs the same 25 INTERCAL programs as run_tests.sh but compiles them with the self-hosted intercal wrapper instead of the bootstrap script. Because the MVP's "compilation" is template dispatch, the test harness confirms three things simultaneously:
- The pre-generated assembly template for each program is correct (i.e. it is byte-for-byte what the bootstrap produces today).
- The wrapper correctly identifies the input program by content hash and selects the right template.
- The self-hosted compiler binary itself,
intercal_core, produced by compilingsrc/compiler/compiler.iwith the bootstrap, correctly reads its argv, opens the source file, reads it via Label 666, and writes the template to stdout.
Drift is caught through the template integrity manifest (src/compiler/templates/manifest.txt, SHA-256 checksums) and verified by tools/verify_manifest.sh before the tests run. If anybody changes an INTERCAL test program or an intercalc.sh codegen detail, the template must be regenerated and re-manifested; otherwise the manifest check fails.
run_stage3_tests.sh: the evolving compiler
Three programs today, and growing. They exercise the diagnostic instrumentation in src/compiler/stage3.i: byte count, first byte, last byte, and will grow as the evolving compiler acquires a real lexer, parser, and codegen. Each new sub-stage adds one or two tests before the implementation lands (the TDD red-green cadence is strict here).
The TDD contract
The project's AGENTS.md is explicit: before modifying the compiler, the syslib, or the runtime, add or extend a test that captures the expected behaviour, and verify it fails before you write code and passes after. This is not a suggestion; it is the project's working protocol.
Three categories of change, and the corresponding tests:
- A new language feature or codegen path → a new
tests/test_<name>.iwith expected output, registered intests/run_tests.sh. - A bug fix → the smallest reproducer that fails in the current state, committed separately or in the same commit as the fix.
- A self-hosted compiler extension → a new entry in
tests/run_stage3_tests.shthat fails against the current stage3 binary and passes after the implementation.
Exceptions are enumerated and narrow: documentation-only changes, CI workflow edits, renames that do not affect behaviour, formatting. Any exception is called out in the commit message with a one-line justification.
Pre-commit, pre-push, CI
Three layers of verification, increasingly expensive and increasingly thorough. They exist because fast feedback is more valuable than complete feedback.
Pre-commit (~30 seconds)
Installed via tools/install_hooks.sh. Runs tools/verify_manifest.sh and tests/run_tests.sh if anything under src/, tests/, tools/, intercal, bootstrap.sh, or setup_platform.sh is staged. Documentation-only commits (like this one) are skipped.
Fast enough to run on every commit. Catches about 90 percent of issues before they reach the tree.
Pre-push (~1–2 minutes)
Runs all four suites: bootstrap, pure syslib, self-hosted MVP, stage3. Rebuilds intercal_core and stage3_bin from scratch so tests aren't coloured by stale binaries. A pre-push failure means the push is aborted.
This is the last line of defence before CI takes over. It is slower than pre-commit but still runs locally in the time it takes to drink half a coffee.
Continuous integration (~15 minutes)
.github/workflows/ci.yml runs on every push and every pull request. Three jobs, one per platform, each executing the full pre-push sequence. The platforms are:
macos-14for macOS ARM64.ubuntu-24.04-armfor Linux ARM64.ubuntu-latestfor Linux x86-64.
A regression that is platform-specific, different syscall convention, different assembler syntax, lands in exactly the job that catches it. All three must be green for the branch to be mergeable.
Release validation
.github/workflows/release.yml builds 9 artifacts (.zip, .tar.gz, .deb, .rpm across three platforms) on every version tag. A separate release-smoke.yml installs each artifact in a clean container and runs the test suite, confirming that the packaged binary actually works on a user's machine. This catches packaging bugs that would otherwise ship to users.
Writing a new test
Six steps, in order, for a new INTERCAL feature:
- Create
tests/test_<feature>.iwith a minimal program that exercises the feature. - Write the expected output as a literal string in
tests/run_tests.sh, or as a sibling.expectedfile if the output is multi-line. - Register the test by adding a line to the
_run_testcalls intests/run_tests.sh. - Run
zsh tests/run_tests.sh --filter <feature>. The test should fail (red). - Implement the feature in
intercalc.sh. - Re-run. The test should pass (green).
The --filter, --verbose, and --keep flags on the runner speed up the iterate-and-inspect loop. --keep preserves failed-test artifacts under /tmp/intercal_failures/ so you can re-run cc by hand.
Docker cross-platform reproduction
The tests/cross_test.sh harness spins up a Docker container for a chosen target platform, mounts the repository, and runs the suite inside. Use it whenever a Linux-only bug needs reproducing from a macOS machine:
zsh tests/cross_test.sh linux_x86_64
zsh tests/cross_test.sh linux_arm64 --image ubuntu:24.04
The containers install zsh and gcc from the distro, mount the repo read-write (so any test output they produce is visible from the host), and run the full four-suite stack. A five-second docker info preamble verifies that Docker is actually running before the slower setup begins.
Exercises
- Read
tests/run_tests.shand list the five flags it supports. For each flag, describe one situation in which it saves time. - Write an INTERCAL test that would catch a bug in
codegen_assignthat swaps the 32-bit overflow check with the ignore-flag check. Why is it important that the test catches both orderings? - The pure-vs-native syslib test uses only three programs. Construct a fourth program whose inclusion would materially broaden coverage, and explain what class of bug it would catch that the existing three miss.
- Pre-commit skips the test suite for documentation-only changes. Argue for or against extending the same skip to
.github/workflow edits. - Compare the bootstrap suite running locally to the same suite running inside
tests/cross_test.sh linux_x86_64. What portion of the slowdown is x86-64 emulation on ARM64, and how could you measure that independently?
Next reading
- platforms.md: the per-platform syscall and syntax details that CI exercises.
- self-hosting.md: the fixpoint test that will eventually join the test suites.
AGENTS.md: the authoritative TDD contract and commit discipline.
Tests directory tour
The tests/ directory holds the regression suites that keep the compiler honest. Each test_<name>.i is a small INTERCAL program with an expected output (or expected ICL___I error code); the harness runners compare actual against expected and fail loudly on any divergence.
This chapter is a one-paragraph-per-test reference so a contributor can find the right existing test before adding a new one.
For the test infrastructure (runners, suites, CI) see testing-and-workflow.md.
Language primitives
test_variables.i: assigns to a scalar and reads it back. The smallest meaningful proof-of-life for the assign + READ OUT path.test_nested_expr.i: a nested expression with sparks and rabbit-ears. Verifies the parser respects alternation and the codegen produces correct mingle / select sequences.test_32bit_arith.i: exercises 32-bit syslib labels (1500, 1530) with:Nvariables. Catches regressions in the 32-bit codegen that 16-bit tests miss.
Control flow
test_control.i: basic NEXT / RESUME pair. The smallest subroutine call.test_come_from.i: exercisesCOME FROM. Confirms the static back-edge is emitted and the targeted statement does not fall through.test_forget.i:FORGETpops NEXT-stack frames without transferring. Used in loop patterns to prevent stack growth.test_give_up.i: single-statementDO GIVE UP. The minimum legal program. Also exercises the politeness-rule's 5-statement floor (with one statement and zeroPLEASE, the program would otherwise failICL079I).
State management
test_stash.i: STASH and RETRIEVE round-trip. Confirms the per-variable stash stack works end-to-end.test_ignore_remember.i:IGNOREmakes a variable read-only;REMEMBERreverses it. Verifies the per-variable ignore-flag check is emitted at every store.test_abstain.i:ABSTAIN FROM (label)deactivates a specific statement;REINSTATEreverses. Verifies the_stmt_flagsbyte is loaded and tested at every statement entry.test_abstain_gerund.i:ABSTAIN FROM CALCULATINGdeactivates all assignments. Exercises the gerund-name resolution and the bulk flag-update codegen.
Arithmetic via syslib
test_syslib.i: basic addition through label 1000.test_multiply.i: multiplication through label 1030.test_divide.i: division through label 1040.test_multidim_array.i: 2D array dimensioned withBY, then per-element access. Covers the linear-index calculation incodegen_array_ref.
I/O
test_hello.i: printsHello, World!via the Turing Text Model. The canonical TTM exercise. See walkthrough-hello.md for the full trace.test_read_out_num.i: single scalar output as a Roman numeral. Exercises_rt_write_roman.test_read_out_multi.i: multiple scalars in a singleREAD OUTstatement. Verifies the parser handles variable lists.test_overbar.i: output of values above 4000, exercising the overbar (vinculum) notation in_rt_write_roman.test_write_in.i: read a number from stdin in spelled-out English digit names. Exercises_rt_write_in_scalar.
Politeness errors
test_errors_rude.i: a program with too fewPLEASEs. Expected to fail compilation withICL079I. The runner asserts the error fires and the binary is not produced.test_errors_polite.i: too manyPLEASEs. Expected to fail withICL099I.
Runtime errors
test_error_e123.i: recursive NEXT withoutFORGETuntil the 80-deep stack overflows. Expected to fireICL123Iat runtime.test_error_e182.i: duplicate label. Compile-time errorICL182I.test_error_e240.i: array dimensioned to zero. Runtime errorICL240I.test_error_e241.i: out-of-bounds array subscript. Runtime errorICL241I.test_error_e275.i: assignment of a 32-bit value to a 16-bit slot. Runtime errorICL275I.test_error_e436.i: RETRIEVE with no preceding STASH. Runtime errorICL436I.test_error_e621.i:RESUME #0. Runtime errorICL621I.test_error_e632.i:RESUMEwhen the NEXT stack is empty. Runtime errorICL632I.test_error_e633.i: fall off the end of the program withoutGIVE UP. Runtime errorICL633I.
Probabilities
test_probability_zero.i:%0modifier; the statement is dead code. Verifies the compiler emits the random-roll check correctly and the body never executes when the threshold is zero.
Label 666
test_syscall_readself.i: opens its own source file via syscall 1, reads the first byte via syscall 2, prints it as a Roman numeral. The end-to-end exercise of Label 666 plus,65535plus argv access.
How to add a new test
The TDD workflow lives in AGENTS.md. The mechanical recipe:
- Create
tests/test_<feature>.iwith the minimal INTERCAL program that exercises the new behaviour. - Open
tests/run_tests.shand add a_run_test(or_run_error_test) line at the appropriate place. - Set the expected output as a literal string, or write
tests/test_<feature>.expectedfor multi-line output. - Run
zsh tests/run_tests.sh --filter <feature>. The test should fail (red). - Implement the feature in
intercalc.sh(and runtime / syslib if needed). - Run again. The test should pass (green).
- Run the full suite. Nothing else should regress.
For a self-hosted compiler change, repeat the cycle in tests/run_self_tests.sh or tests/run_stage3_tests.sh. Templates may need regenerating via tools/gen_manifest.sh.
Cross-suite test parity
The bootstrap suite (run_tests.sh) and the self-hosted MVP suite (run_self_tests.sh) cover the same set of test programs by design, every program that the bootstrap can compile has a pre-generated template that the MVP can dispatch to. When you add a new bootstrap test, you should also add (or accept that you cannot yet add) the matching self-hosted entry. The stage3 suite is independent: it tests the evolving compiler's small range of supported features only.
Exercises
- Run a single test:
zsh tests/run_tests.sh --filter come_from. What is the expected output? Compare with the actual output by inspection. - Modify
tests/test_hello.ito print "Hello," followed by a different name. Compute the new TTM deltas with the encoder from turing-text-model.md, update the test, and run. - The runtime-error tests share a pattern: each fails deliberately with a specific
ICL___Icode. Construct the smallest INTERCAL program that firesICL129I(NEXT to unknown label, now compile-time). Why does the test set not currently include it? test_syscall_readself.ireads its own source. Trace which Label 666 syscalls fire, in which order, and what the expected output looks like.- The 30 bootstrap tests are not exhaustive. INTERCAL has surface that no test covers. Pick one (e.g.
WRITE IN ,1for an array, or%50probability) and write a test for it.
Next reading
- testing-and-workflow.md: the runners and the TDD discipline that makes the suite useful.
- debugging.md: what to do when a test fails.
- your-first-contribution.md: the broader walkthrough of which a test addition is one step.
Tools tour
The tools/ directory holds the supporting scripts that surround the compiler: benchmarks, linters, manifests, hooks, the pipeline introspector, and the reproducible-build helper. None of them are required to build INTERCAL programs (intercalc.sh does that on its own), but each addresses a real maintenance need.
This chapter is a one-paragraph-per-tool reference for what every script does, when to use it, and what flags it accepts.
build_syslib.sh, warm the pure-syslib cache
tools/build_syslib.sh
Pre-compiles src/syslib/syslib.i for the current platform and writes the result into the user's cache directory at $XDG_CACHE_HOME/intercal/syslib-<platform>-<hash>.s (default $HOME/.cache/intercal/). The cache key is the SHA-256 of syslib.i, so the file auto-invalidates whenever the syslib changes.
After running this once, every subsequent compilation with INTERCAL_SYSLIB=cache skips the 30–100-second penalty of recompiling the pure syslib. Run in CI / release pipelines so end users do not pay the cold-cache cost. If you never use INTERCAL_SYSLIB=cache, you can ignore this script entirely; native (the default) does not touch the cache.
bench.sh, performance dashboard
tools/bench.sh # default tabular output
tools/bench.sh --json # JSON, one record per benchmark
tools/bench.sh --json > before.json # save a baseline
tools/bench.sh --compare before.json # diff the current run against a baseline
Runs a fixed set of compile-and-run benchmarks: bootstrap compile of a single-statement program, bootstrap compile of hello world, full bootstrap test suite, self-hosted-core build, stage3 build, full self-hosted test suite. Each is timed (wall, user, system) by zsh's time builtin. The JSON form is structured so you can jq it; the compare mode prints percentage deltas. Use it when you have made a compiler change you suspect might have a performance impact, or when you want to track compile-time evolution across releases.
gen_manifest.sh, regenerate the template SHA-256 manifest
tools/gen_manifest.sh
Walks every .s file under src/compiler/templates/, computes its SHA-256, writes the result to src/compiler/templates/manifest.txt. Run this once whenever you change one or more templates (because the bootstrap codegen for that test program changed). The manifest is committed alongside the templates so that integrity can be verified later.
The script handles the platform difference between shasum (BSD/macOS) and sha256sum (GNU/Linux) automatically. It produces deterministic output: same input templates produce a byte-identical manifest.
verify_manifest.sh, verify the template manifest
tools/verify_manifest.sh
Verify that every template referenced in manifest.txt exists, that no templates exist that the manifest does not list, and that every recorded SHA-256 matches its file. Exit code zero on success, non-zero on any drift. Run automatically by the pre-commit hook and by CI before the test suites; intended to catch the case where somebody edits a template without regenerating the manifest.
install_hooks.sh, opt into the project's git hooks
sh tools/install_hooks.sh
Configures core.hooksPath to .githooks/ in the local clone. After running, every commit triggers verify_manifest.sh plus a fast bootstrap test run; every push triggers all four test suites. Undo with git config --unset core.hooksPath. Run this once after cloning the repo and before your first commit.
lint_assembly.sh, platform-aware lint for .s files
tools/lint_assembly.sh src/runtime/macos_arm64.s
find src/compiler/templates -name '*.s' | xargs -I{} tools/lint_assembly.sh {}
Static checks tailored to each target platform: macOS ARM64 wants _ prefixes on exported symbols, @PAGE/@PAGEOFF relocations, svc #0x80 for syscalls; Linux ARM64 wants no underscore prefix, :lo12: relocations, svc #0; Linux x86-64 wants # comments rather than //, no three-register addressing, Intel syntax. The platform is auto-detected from the file path or can be passed explicitly. Useful when you have hand-written or modified assembly and want to verify it before running the full test suite.
lint_intercal.sh, static checks for INTERCAL source
tools/lint_intercal.sh tests/test_hello.i
find tests -name 'test_*.i' | xargs tools/lint_intercal.sh
Reports the politeness ratio, flags labels in the syslib reserved range, warns on RESUME with potential zero, warns on missing GIVE UP. Output format is path:line: level: message. Exit zero if there are no errors (warnings still allowed); exit one if any error is found.
A .i file can opt out of specific checks with a magic comment: DON'T NOTE LINT-SKIP: politeness labels resume. Supported tokens are politeness, labels, resume, and all. Use all to silence the linter entirely on a file that is intentionally unusual.
pipeline_dump.sh, introspect each phase of compilation
tools/pipeline_dump.sh tests/test_hello.i
tools/pipeline_dump.sh program.i --platform linux_x86_64
tools/pipeline_dump.sh program.i --out /tmp/dump
Writes a directory containing every intermediate stage: the source as-is, the whitespace-normalised source, the statement list, the politeness count, the program-only assembly, the platform runtime, and the combined assembly that goes to cc. Useful for explaining the pipeline to a newcomer or when debugging a codegen issue that is easier to diagnose by reading the intermediate output rather than the final binary.
The --out flag lets you redirect the dump to a specific directory. The default /tmp/intercal_dump is wiped between runs.
rewrite_uuid.py, deterministic Mach-O LC_UUID
tools/rewrite_uuid.py path/to/binary
Rewrites the LC_UUID load command in a Mach-O binary with a SHA-256-derived UUID computed from the binary itself (with the UUID field zeroed during the hash). This makes the binary's identity bytes reproducible across compilation runs. The script handles the structural details of Mach-O, magic check, nfat/ncmds parsing, finding the right load command, and leaves the rest of the binary untouched.
Caveat: rewriting the UUID invalidates any embedded ad-hoc code signature. Apple Silicon requires that compiled executables be code-signed (even ad-hoc), so the typical sequence is: build → rewrite_uuid → re-sign with codesign -fs -. The release pipeline does this automatically.
The script is Python rather than zsh because the Mach-O parsing is structural enough that string-manipulation in shell would be more error-prone than running a small struct-parser. It is the only Python dependency in the repository, and it runs with no third-party packages, only the stdlib.
When to reach for which tool
| Situation | Tool |
|---|---|
| Wrote a new INTERCAL program | lint_intercal.sh |
Modified intercalc.sh and want to inspect output | pipeline_dump.sh |
Modified a runtime or syslib .s file | lint_assembly.sh |
Modified one or more templates/*.s | gen_manifest.sh, then verify_manifest.sh |
| Suspect a performance regression | bench.sh --compare against a saved baseline |
| Cloned the repo for the first time | install_hooks.sh |
| Want a reproducible Mach-O binary | rewrite_uuid.py (called by the release pipeline) |
Exercises
- Run
tools/bench.sh --jsonand inspect the output. Which benchmark is the slowest? Why? - Take a passing test program, edit it slightly, and run
tools/lint_intercal.shon the result. What does the linter say? Does the politeness ratio change as expected? - Read
tools/rewrite_uuid.py(about 100 lines). Identify the load-command magic forLC_UUIDand the size of its body. What other load commands does Mach-O define that we might one day need to handle? - The
bench.shbenchmarks includebootstrap_simple(compiletests/test_give_up.i). What fraction of that time iscc -x assembler -versus the rest of the pipeline? - Write a small INTERCAL program that intentionally violates two distinct lint rules. Verify that
lint_intercal.shreports both, and that the magic commentDON'T NOTE LINT-SKIP: allsilences them.
Next reading
- debugging.md: uses
pipeline_dump.shandbench.shextensively. - testing-and-workflow.md: uses
verify_manifest.shin pre-commit, runs the test suites thatbench.shmeasures. - executables-and-linking.md: context for
rewrite_uuid.pyand the LC_UUID load command.
Debugging the compiler
A compiler bug manifests as a difference between what you wrote and what the binary does. Because our pipeline is short and largely side-effect-free, diagnosing that difference is usually a matter of following the bug from symptom to phase to specific line. This chapter collects the techniques we actually use.
The symptom taxonomy
Every compiler bug we have hit in this project falls into one of these buckets:
- Compile-time crash. The compiler prints an unexpected error, or fails silently. Either the lexer, the politeness check, or the label resolver is upset.
- Link-time failure.
cc -x assembler -rejects the generated assembly. The codegen or the platform translation is producing invalid assembly. - Runtime error (ICL). The binary runs and exits with an
ICLnnnImessage. The runtime is behaving as designed; the bug is in the user program or in the code that should have prevented this condition at compile time. - Runtime crash (SIGSEGV). The binary dies violently, usually inside the runtime. The codegen emitted something that looks right but violates an assembly invariant.
- Wrong output. The binary runs, exits cleanly, and prints the wrong answer. The hardest category, because everything else "works". Either the codegen mis-evaluated an expression, a runtime routine miscomputed a result, or a state bit (abstain, ignore) was mishandled.
Each requires different instrumentation.
Compile-time crashes
When intercalc.sh itself fails, the fastest path is:
- Re-run with
zsh -x src/bootstrap/intercalc.sh < program.i > /dev/null 2>trace. Every line executed is logged totrace. - Find the last executed function before the crash.
- Inspect the relevant arrays at that point with
print -l ${stmt_type[@]}(or equivalent).
The most common compile-time bug is a tokeniser misclassification: a statement whose body contains unexpected content is classified as UNKNOWN and the codegen emits bl _rt_error_E000. You catch this by listing stmt_type and seeing the unexpected UNKNOWN.
The second most common is a politeness miscount: we thought we had 1/5 but have 1/6 because a DON'T NOTE wasn't counted. List stmt_polite and sum.
Link-time failures
When cc -x assembler - rejects the output, the relevant information is on stderr. Strategy:
- Reproduce with
INTERCAL_ASM_ONLY=1 zsh src/bootstrap/intercalc.sh < program.i > failing.s. Now you have the assembly as a file. cc -x assembler -c failing.s -o /dev/nullisolates the assembler error without running the linker.- Read the error: GNU
asand Appleasdiffer in their messages. GNU is usually more specific (line 42: Error: junk at end of line, first unrecognized character is ...). - Open
failing.sat the reported line. The generated assembly includes line-directive-like comments that match thecodegen_*function that emitted each block; use those to navigate back intointercalc.sh.
Platform-specific assembler errors almost always point at one of the pitfalls listed in platforms.md: wrong comment delimiter, wrong relocation syntax, three-register addressing, forgotten .global. Match the error against that table first.
Runtime ICL errors
ICL errors fire when a runtime-detected condition is met. The error codes are enumerated in runtime.md. Some of them are legitimate user-program bugs (ICL275I on a 32-bit value being stored into a 16-bit slot), some indicate a compiler bug (ICL123I NEXT stack overflow when the program has no obvious loop), and some are spec-compliance failures (ICL633I for a program missing its GIVE UP).
The debug workflow:
- Note which ICL code fired.
- Read the codegen for the statement type that triggers that particular ICL. For example, ICL275I is emitted by
codegen_assignfor scalars; the check iscmp w0, #65535; b.hi _rt_error_E275. - Trace backwards from the failing statement: what RHS expression produced the oversized value?
- If the answer is "nothing should have produced this value", the bug is in the runtime or in the expression evaluator. Keep going.
A useful crutch: modify the source program to precede the suspect statement with DO READ OUT .N for the scalar in question. Roman-numeral output of an intermediate value reveals the arithmetic step where the error originates.
Runtime crashes
SIGSEGV in the compiled binary is usually one of:
- The codegen emitted an addressing expression that the assembler accepted but the CPU rejects (exceedingly rare, three-register addressing on x86-64 is usually caught by the assembler).
- The runtime mis-manages the stack: a saved register is not restored, or a stack-local buffer was sized incorrectly.
- The codegen overwrote a callee-saved register without saving it.
The fastest diagnosis tool is lldb or gdb:
lldb ./failing
(lldb) run
(lldb) bt
The backtrace reveals the fault address and the call chain. Match the fault address against the disassembly (otool -tv ./failing on macOS, objdump -d ./failing on Linux). The bug is usually the instruction or two before the fault, not the fault itself.
The Linux x86-64 Label 666 open/write bug described in memory/bugs_learned.md is a representative case. A local on-stack buffer for a C string collided with a previously-stored alloc_size, because both used the same [rbp-32] slot. The symptom was SIGSEGV on ret in _rt_sys666_open. The fix was to move alloc_size into a callee-saved register (r14). The diagnosis came from reading the disassembly alongside the runtime source and spotting the shared slot.
Wrong output
The hardest category. The binary compiles, runs, exits, and prints the wrong answer. Nothing flagged anything.
Strategy in order of escalation:
- Compare the output to the expected. How big is the diff, one byte, one line, one word? One byte usually means an arithmetic off-by-one or a TTM tape miscalculation. Longer suggests a control-flow divergence.
- Reproduce with the smallest possible input. Delete statements until the divergence no longer reproduces; the last statement whose deletion fixes it is the one the bug lives in.
- Compile the reduced reproducer with
INTERCAL_ASM_ONLY=1and read the emitted assembly for that statement. Does it match your mental model of what the codegen should produce? - If it does, the bug is in the runtime routine the codegen called. Open the corresponding
_rt_*routine in the platform assembly file and read it. - If it doesn't, the bug is in the codegen. Work back from the mismatched assembly to the codegen function that produced it, and from there to the input state of the statement at that point in the pipeline.
An underused technique for wrong-output bugs: the differential test against --pure-syslib. If the bug disappears when switching to the pure syslib, the native syslib is the culprit. If the bug persists, the runtime or the compiler itself is implicated. Running both forms of the same program and comparing outputs is cheap and sharply diagnostic.
Platform-specific bugs
A bug that reproduces on one platform and not another is almost always one of:
- A syscall number mismatch.
- A calling convention difference (argument passing, preserved registers).
- An assembler syntax that our codegen emits in macOS form and the Linux translation did not fully convert.
The Docker-based reproducer tests/cross_test.sh is the primary tool here:
zsh tests/cross_test.sh linux_arm64
zsh tests/cross_test.sh linux_x86_64
From a macOS development machine, those commands reproduce the Linux CI job byte-for-byte, locally, in ~3 minutes. Any bug that shows up in CI and not on your laptop is reproducible this way.
Bisecting across commits
When a previously-green test starts failing, git bisect is almost always the right tool:
git bisect start
git bisect bad HEAD
git bisect good <last known good commit>
git bisect run zsh tests/run_tests.sh --filter <test_name>
git bisect run automates the bisect loop, running the filter-test at each commit and classifying as good or bad. Typical bisect depth for this repo's history is 6–8 steps, a few minutes total.
A caveat: the template manifest (src/compiler/templates/manifest.txt) is updated in lock-step with template regeneration. A bisect that lands on a commit mid-rebuild of a template may see verify_manifest.sh fail independently of the test. Use --skip to step past such commits.
Pipeline dump
tools/pipeline_dump.sh is a convenience wrapper:
tools/pipeline_dump.sh tests/test_hello.i
It prints each intermediate stage of compilation for the given program: the tokenised statement list, the generated assembly, and (optionally) the linked binary's disassembly. Useful for explaining the pipeline to somebody else, less useful as a debugging tool because INTERCAL_ASM_ONLY=1 already gives you the one stage you usually want.
For statement-level structural analysis, the compiler exposes a --diagnose flag:
zsh src/bootstrap/intercalc.sh --diagnose < tests/test_hello.i
This prints the tokenised statement table, type, polite flag, negation, label, body, without invoking the codegen. Useful when you want to confirm that the lexer is classifying statements the way you expect.
For IR-shaped views of the program, the compiler also ships --emit-cfg and --emit-3addr. The first prints basic blocks plus edges (the same shape LLVM IR, MIR, CLIF and the rest expose). The second prints a flat three-address listing (GIMPLE-shaped). Both are inspection-only and skip codegen:
zsh src/bootstrap/intercalc.sh --emit-cfg < tests/test_come_from.i
zsh src/bootstrap/intercalc.sh --emit-3addr < tests/test_hello.i
These are the cheapest way to see how the compiler models a particular program. Pair them with the relevant chapter in Part VII (LLVM, GCC, rustc, Go, ...) when learning what a CFG or three-address IR looks like in production.
For performance regressions, tools/bench.sh measures compile and link timings on representative programs:
tools/bench.sh # tabular output
tools/bench.sh --json > before.json # save baseline
# ... make a change ...
tools/bench.sh --compare before.json # diff vs baseline
Lint checks
tools/lint_intercal.sh runs basic sanity checks against .i files: politeness balance, obvious typos in verb keywords, unreferenced labels. tools/lint_assembly.sh scans .s files for known platform pitfalls (three-register x86 addressing, misplaced // in x86 source, etc.). Both are invoked in CI but can be run locally:
zsh tools/lint_intercal.sh src/compiler/*.i
zsh tools/lint_assembly.sh src/runtime/*.s
A lint failure is not definitive proof of a bug, but it is a strong hint.
Memory: keeping the bug history
The private memory/bugs_learned.md file, per developer, records critical bugs and what we learned from them. The existing entries cover the major regressions: the syslib prepend-vs-append issue, the DON'T tokenisation bug, the Linux x86-64 stack-slot collision.
New bugs worth documenting are those whose fix is non-obvious from the diff, usually a root-cause analysis deeper than "we forgot to handle case X". Updating memory/bugs_learned.md after debugging a hard bug is one of the few routine maintenance habits the project has.
Exercises
- Deliberately break
intercalc.shby changing the politeness ratio bounds from (1/5, 1/3) to (1/4, 1/3). Which tests fail? Reproduce the failure withzsh tests/run_tests.sh --verbose. - Write an INTERCAL program that fires ICL123I (NEXT stack overflow). How many NEXT statements do you need at minimum?
- Break
_rt_minglein the macOS ARM64 runtime by changing one instruction. Runzsh tests/run_tests.sh. Which tests fail first? What does the failure mode tell you about how many tests exercise mingle? - Use
git bisect runto identify the commit where the Linux x86-64 Label 666 open/write bug was fixed. (Check the commit log to find a plausible endpoint; don't rely on your memory.) - Run
tools/lint_intercal.sh src/compiler/stage3.i. Does it flag anything? If so, is the flag a real problem?
Error message design
A compiler's error messages shape its usability more than almost any other surface. A correct compiler with hostile diagnostics is an unfriendly tool; an inaccurate compiler with helpful messages is at least debuggable. INTERCAL puts the bar somewhere unusual: the format of error messages is part of the language's deliberate joke (codes like ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE), but the format does not relieve us of the obligation to make them helpful.
What our error messages look like, how they have improved since the project began, and where they fall short of what modern compiler diagnostics deliver.
The ICL convention
Every compile-time and runtime error fires a message of the form ICLnnnI MESSAGE TEXT, where nnn is a three-digit decimal code. The convention dates to the 1972 INTERCAL manual and has been preserved by every subsequent implementation. The codes are part of the language's specification, ICL079I is the rude-program error in C-INTERCAL, in CLC-INTERCAL, and in ours.
The text is uppercase by tradition. PROGRAMMER IS INSUFFICIENTLY POLITE is the spec text; substitutions are not allowed. This is a constraint our diagnostics inherit and that we honour.
What our error messages contain today
A typical compile-time error, fired by die_compile:
ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE
ON THE WAY TO STATEMENT 7 (LABEL (200), SOURCE LINE 12)
Three pieces:
- The numeric code and uppercase message text from the spec.
- The statement number where the error fired.
- The label (if any) of that statement, plus the source line number.
The second and third pieces are project-specific; they did not exist a few months ago. die_compile was extended to take an optional statement-index argument, and many call sites now pass it. The result is a diagnostic that points at some location in the source, not a Rust-grade caret, but enough that a programmer can find the offending line.
A runtime error, fired by _rt_error_E*:
ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
Just the code and message; no source location, because the runtime does not have access to the source file. A programmer hits ICL123I and has to grep for NEXT statements to find the loop.
What modern compilers do
The state of the art for compiler error messages is, by widespread agreement, what Rust's rustc started doing around 2016 and what Elm did before it. The Rust diagnostic redesign was led by Niko Matsakis, Yehuda Katz, Aaron Turon, Alex Crichton, and Sophia Turner. Three principles emerged:
- Spans, not lines. Every diagnostic carries a span (start byte, end byte, file). The message points at the smallest range that signifies the issue. A wrong type does not blame the whole expression; it blames the operand.
- Multiple labels per diagnostic. A primary span gets the main label; secondary spans get supporting labels ("variable defined here", "expected type required by this signature"). The reader sees several locations at once.
- Suggestions. When the compiler can plausibly guess the fix ("did you mean
&instead of&&?"), it offers a concrete edit, often as a code-actionable snippet that an IDE can apply with one keystroke. - Plain language. Even the technical messages are written in sentences.
expected type \u32`, found type `String`` reads naturally; the compiler does not assume the reader has internalised the term-rewriting formalism.
Each of these principles is a research direction, and Rust's actual implementation took years. The infrastructure (rustc_errors::DiagCtxt, the span_* methods, the JSON-emitter for tooling) is substantial.
How our diagnostics compare
We are short of Rust on every axis:
- Spans. We have a statement number and a source line, but not a column or a byte offset. The unit of localisation is the whole statement.
- Multiple labels. Our diagnostics are single-label only. ICL182I (duplicate label) names the duplicate, but does not also point at the original definition.
- Suggestions. We never suggest a fix. The user has to read the message text and reason about the cause.
- Plain language. The spec mandates baroque uppercase text.
PROGRAMMER IS INSUFFICIENTLY POLITEis a faithful rendering, but it is also unhelpful to somebody who does not already know the politeness rule. We compensate by linking from the docs (this book) to the meaning.
The gap is reasonable for our use case. We have no IDE integration, no JSON emitter, no users for whom diagnostic latency is critical. The current diagnostics are enough to debug compile failures from the command line.
Improvements that would be cheap
Several improvements would not require a full rewrite:
- Column number on the source line. The lexer's
\x01separator already tracks statement boundaries; extending it to record byte offsets would let us producesource.i:12:34references. - Multi-label ICL182I. When firing the duplicate-label error, also report the index of the previous statement that used the same label. The information is in
label_to_stmtalready; we just do not print it. - Suggestions for typos. Each statement that classified as
UNKNOWNcould be compared against the list of known verbs with edit-distance one or two. A typoedDO READ OUT .1(say,DO REED OUT .1) could be flagged with a "did you mean READ?" suggestion. - Source line printing. When firing an error, print the full source line and a caret pointing at the statement boundary.
intercalc.shwould need to keep the original source string around for this to work, which it already does (it is inSOURCE).
The cost of each is low; the cost of a full Rust-style diagnostic infrastructure is high. We should pick the cheap improvements and stop.
Improvements that would be expensive
- Spans through the parser. Tracking byte spans for every expression node would require restructuring the parallel-array AST to carry source positions. Not impossible, but invasive.
- JSON emitter for tooling. Useful only if there were tools that consumed it. We have none.
- i18n. The error messages are in English (uppercase). Translating them is a large effort with no clear audience; INTERCAL programmers are global but small.
These are not on the roadmap.
How die_compile was extended
Originally die_compile took two arguments: code and message. Adding the third (statement index for context) was a single-commit change:
die_compile() {
local code=$1
local msg=$2
local ctx_idx="${3:-}"
if [[ -z "$ctx_idx" && -n "${i:-}" && "$i" =~ '^[0-9]+$' ]]; then
ctx_idx="$i"
fi
echo "ICL${code}I ${msg}" >&2
if [[ -n "$ctx_idx" && -n "${stmt_type[$ctx_idx]:-}" ]]; then
local lbl="${stmt_label[$ctx_idx]:-}"
local line="${stmt_source_line[$ctx_idx]:-?}"
if [[ -n "$lbl" ]]; then
echo " ON THE WAY TO STATEMENT $ctx_idx (LABEL ($lbl), SOURCE LINE $line)" >&2
else
echo " ON THE WAY TO STATEMENT $ctx_idx (SOURCE LINE $line)" >&2
fi
fi
exit 1
}
The context-detection heuristic, if no third arg is passed, look for an i variable in the caller's scope, lets old call sites keep working without modification while new ones get the context for free. It is a small example of the kind of incremental usability work that a compiler benefits from.
The runtime side
Runtime errors do not have access to the source file, so they cannot print source lines. They could, in principle, print the statement number that fired the error, the codegen knows which statement is being executed at the call site. This would require emitting the statement index as a data argument to every _rt_error_* call, which doubles the size of error-emitting code. We have not done it.
A useful intermediate would be a --debug flag that emits per-statement labels into the binary and a runtime hook that prints the active statement on error. The cost is binary size and a small startup penalty; the benefit is much better runtime diagnostics. Worth considering for a future release.
Exercises
- Construct a program that fires
ICL182I(duplicate label). What information does the current diagnostic give you? What would a multi-label version look like? - Run
intercalc.sh --diagnoseontests/test_hello.i. The output is a different kind of diagnostic, informational rather than error. Compare its format to the error format. What design choices differ? - The lexer collapses whitespace and tracks no source positions. If we wanted line:column references in diagnostics, what data would
tokenizeneed to record per statement? - Pick one of the cheap improvements listed above (e.g. typo suggestions for unknown verbs). Sketch the implementation in zsh. How many lines?
- Compare
ICL079I PROGRAMMER IS INSUFFICIENTLY POLITEwith what Rust would say for an analogous offence (e.g. a#[deny(missing_docs)]violation). Which is more helpful? Which is more memorable?
Next reading
- debugging.md: how to use the current diagnostics in practice.
- semantic-analysis.md: where most compile-time errors fire from.
- runtime.md: the runtime-error catalogue.
How a C or Lisp compiler would differ
Most readers approaching this repository have built or studied a compiler for some other language: C, Java, Python, Lisp, perhaps a small functional language for a course. This chapter sets our INTERCAL implementation alongside what those readers expect, phase by phase, so the design choices we have made become legible by contrast.
The two reference points are deliberately chosen:
- C represents an imperative, statically typed, machine-oriented language. Its compiler design is the canonical case in most textbooks.
- Lisp represents a functional, dynamically typed, expression-oriented language. Its compiler design forces a different set of decisions.
Both are well documented elsewhere; this chapter does not try to teach either. It catalogues the differences from our implementation and explains why we chose what we chose.
Lexing
A C lexer has to handle:
- String literals with escape sequences, multi-line continuations, and (historically) trigraphs.
- Numeric literals in three bases (decimal, octal, hexadecimal) plus floating-point.
- A preprocessor that runs before lexing proper, expanding
#include,#define, and conditional compilation. - Wide characters and Unicode source identifiers (in modern C).
- The famous lexer hack for distinguishing
T * x(multiplication) fromT * x(declaringxas pointer toT), which requires the lexer to know which identifiers are typedef names.
A Lisp lexer is by contrast almost trivial:
- Parentheses, atoms, numbers. That is most of it.
- Quoted strings exist but the syntax is uniform.
- The reader macro system lets the user extend the lexer at runtime, which sounds dramatic but in practice only adds a handful of cases.
Our INTERCAL lexer falls between the two, closer to Lisp:
- No string literals. Constants are decimal integers only.
- No preprocessor. No conditional compilation. No includes.
- One lexer hack:
DON'Tmust be one token, notDO+N'T. This is dispatched by a single peek-ahead branch. - Whitespace is collapsed during reading; case is folded.
The C lexer's cost (the typedef hack, the preprocessor's macro expansion, the float-literal grammar) does not apply to us. The Lisp lexer's flexibility (reader macros) does not apply either, because we do not need it. We get a lexer that is simpler than a C lexer and more case-driven than a Lisp lexer, but architecturally closer to either than to a hypothetical "modern" lexer with Unicode and string interpolation.
Parsing
C grammar has notorious ambiguities:
- Operator precedence.
*p++parses as*(p++), not(*p)++. Sixteen levels of precedence. - The dangling-else problem: in
if (a) if (b) c; else d;, whichifdoes theelsebelong to? - Function pointer declarations whose syntax mirrors the call form.
- Compound literals.
- The previously-mentioned typedef ambiguity.
A C parser is typically LALR(1) (yacc/bison) or hand-written recursive descent with substantial lookahead. Either way it is hundreds of productions and several thousand lines.
Lisp's parser, in turn, is a read loop:
read():
consume whitespace
if next is '(': read list of read() until matching ')'
else if next is digit: read number
else: read symbol
That is the whole parser. There is no precedence to resolve, because every expression is already explicitly grouped by parentheses. There is no dangling else, because there is no else.
INTERCAL's parser sits with Lisp's: we have no precedence either, because every expression is explicitly grouped by sparks ' or rabbit-ears ". The recursive-descent parser has fifteen productions and runs in ~190 lines. Like Lisp, our grammar is LL(1); like Lisp, our parser corresponds line-for-line with the grammar.
The cost we pay for this simplicity is the same cost Lisp pays: programmers have to type more grouping characters. INTERCAL programmers also have to alternate the two grouping types, which is a constraint Lisp does not impose.
Type checking
C's type system is the main reason a C compiler has a substantial semantic-analysis phase:
- Implicit type promotions:
int + charproducesint, with thecharwidened. - Pointer arithmetic:
p + 1wherepisT *advances bysizeof(T)bytes. - Function-call type checking: arguments must match parameter types, or be promotable to them.
const,volatile,restrictqualifiers.- Aggregate types: structs, unions, arrays.
Lisp at the standard end of the spectrum has no compile-time types at all. Every value carries a runtime tag, and operators dispatch on that tag. The compiler's "type checking" reduces to "is this a syntactically valid Lisp expression", which the parser has already answered.
INTERCAL has four types: onespot (16-bit), twospot (32-bit), tail array (16-bit elements), hybrid array (32-bit elements). They are syntactically identifiable by the variable prefix. Type checking reduces to:
- Is the assignment target's prefix consistent with the LHS expression's width?
- Is the array subscript count correct for the array's dimensionality?
- Is the value being stored within the target's range (16-bit slots reject values > 65535)?
The first is a compile-time check buried in codegen_assign. The second is a runtime check (we do not track array dimensionality through expressions statically). The third is a runtime overflow check that fires ICL275I.
So our type system sits between C's and Lisp's: more structure than Lisp but vastly less than C. The compile-time checking is correspondingly modest.
Intermediate representation
A modern C compiler has a multi-stage IR pipeline:
- After parsing: AST.
- Lowering pass: AST to high-level IR (e.g. Clang's
clang::Stmttree → MLIR or LLVM IR). - Multiple optimisation passes on the IR: SSA construction, CSE, GVN, dead-code elimination, loop transformations, register allocation.
- Lowering to target machine instructions.
LLVM IR alone has ~60 instruction opcodes, three integer types beyond the platform native width, vector types, structured types, and a notion of blocks-with-arguments for SSA φ-functions. The IR is the central data structure of the compiler.
A Lisp compiler typically uses bytecode as its IR. SBCL goes further and has a CPS-based IR called IR1 plus a register-allocated lower IR called IR2. The IR is also where dynamic-language-specific optimisations happen: type inference, inlining of known primitives, dispatch elimination.
Our compiler has no IR. We go from AST to assembly directly, one statement at a time. This is the choice that distinguishes us most sharply from both C and Lisp implementations.
The reasons we make it work without an IR are documented in middle-end-and-optimisation.md: one source language, no optimisation pressure, small enough programs that the cost of recompiling everything dominates anyway. A C compiler designer would be aghast at the omission; a Lisp compiler designer would point out that a small Lisp compiler can also skip the IR (early Lisp compilers did) and that the choice scales.
Code generation
C compilers emit:
- Detailed prologues and epilogues per function: save callee-saved registers, allocate stack space, set up frame pointer (optionally).
- Calls following the platform calling convention, with argument promotion and aggregate handling.
- Function-pointer call sites (indirect calls through register).
- Branch-predicted control flow with hint instructions where the architecture supports them.
- Per-architecture instruction-scheduling decisions (which our compiler defers entirely to the assembler).
Lisp compilers emit:
- A single, large dispatch loop that walks the bytecode and executes each operation.
- Calls into a runtime that does most of the heavy lifting (allocation, GC, type dispatch).
- Substantial memory traffic compared to C, because every value is potentially heap-allocated.
INTERCAL compilers like ours emit:
- One labelled block per source statement, with abstain-flag and probability checks at the top.
bl/callto a small set of runtime routines (_rt_mingle,_rt_select,_rt_write_roman, etc.).- Per-platform syscall sequences for I/O and process control.
Our emitted code looks closer to a tail-end C compiler's output than to a Lisp compiler's. We do not have a dispatch loop; we have direct branches. We do not heap-allocate per-operation; we use fixed BSS slots.
Memory model
C's memory model is a contract between the compiler and the programmer. Every variable lives at a specific address. The programmer can take addresses of variables, do arithmetic on them, and read or write through them. The compiler is responsible for making sure that "what looks like a write to a variable" actually reaches that variable's address (subject to some optimisation latitude, the as-if rule).
Lisp's memory model is opaque to the programmer. Every value is allocated on a heap (with the exception of fixnums and a few other immediate types in some implementations). A garbage collector reclaims memory periodically. The programmer cannot take addresses or do arithmetic on them.
INTERCAL's memory model is somewhere between the two:
- Scalars (
.N,:N) live in fixed BSS slots. The programmer cannot take their address but the compiler exposes them through symbolic references. - Arrays (
,N,;N) are heap-allocated by the runtime viammap. The compiler stores the pointer in a fixed slot. The programmer cannot manipulate the pointer directly but can grow and shrink the array via dimensioning. - Stash stacks (per-variable LIFO) and the NEXT stack are runtime-managed structures the programmer can grow but not directly access.
- The reserved
,65535array is a runtime-controlled buffer that the programmer agrees not to touch outside Label 666 syscalls.
There is no garbage collection. There is no free. Once an array is dimensioned, the runtime never reclaims its storage. This works because INTERCAL programs allocate arrays sparingly and the OS reclaims everything at process exit.
Runtime services
C's runtime is the C standard library: malloc, free, printf, file I/O, math, string handling. Most of it is dynamically linked to every C program.
Lisp's runtime is much larger: garbage collector, type-tag dispatch, symbol table, condition system, eval (in many implementations), readline, debugger. A Lisp runtime is typically several megabytes.
Our runtime is a few hundred lines of platform-specific assembly per platform. It implements:
- Mingle, select, the unary operators.
- Roman numeral output.
- English digit-name input.
- Turing Text Model array I/O.
- mmap allocation.
- The NEXT stack helper.
- 16 error-exit routines.
- 8 Label 666 syscall handlers.
A C program could embed the same set of services in well under 10 KB. A Lisp program could not, even the smallest Lisp runtime needs a garbage collector. We sit at the C end of the runtime-size spectrum.
Self-hosting
C compilers are routinely self-hosted: GCC and Clang both compile themselves. The mechanics are well understood and the bootstrap process is documented in their respective build instructions.
Lisp compilers are typically self-hosted too: SBCL, CMUCL, and many smaller Lisps compile themselves. The Lisp tradition explicitly emphasises this, a Lisp implementation that cannot bootstrap itself is rare.
INTERCAL has not, to public knowledge, ever been self-hosted. C-INTERCAL is written in C; CLC-INTERCAL is written in Perl. Our project's ambition to write compiler.i in INTERCAL (and reach a 3-generation fixpoint) is the first such attempt. Whether it succeeds is open; the current state is documented in self-hosting.md.
Performance
A modern C compiler's output is within ~2× of hand-written assembly for most workloads. The optimisation pipeline is what does this.
A modern Lisp compiler's output is typically 2–10× slower than equivalent C, depending on the program. The slowdown comes from runtime type dispatch, allocation pressure, and missed inlining opportunities.
Our compiler's output is many orders of magnitude slower than C, because we do no optimisation at all and call into the runtime for every operator. This is acceptable for our purposes (no production users) but would be a fatal flaw for a real implementation.
A future version of the compiler with a real IR and a few optimisation passes (constant folding, peephole, primitive inlining) could probably get within 5× of equivalent C. Whether the effort is worth it depends on whether anybody ever wants to run an INTERCAL program fast.
Why this comparison matters
The language a compiler targets shapes every decision the compiler designer makes. C's complexity forces an elaborate front end and a substantial type checker. Lisp's flexibility forces an elaborate runtime and a lighter front end. INTERCAL's deliberate primitive-but-complete shape forces a tiny front end, a tiny back end, and a runtime that is small in code but large in conceptual responsibility.
A reader who expects a C-compiler-shaped implementation will be surprised by how little code we have. A reader who expects a Lisp-compiler-shaped implementation will be surprised by how primitive our runtime is. Both surprises are deliberate. The compiler is shaped exactly for the language it targets; departures from textbook shape come from the language, not from designer whim.
Next reading
- overview.md: what we are.
- middle-end-and-optimisation.md: what we deliberately do not have.
- further-reading.md: books that walk through C and Lisp compilers in their own right.
INTERCAL among the esoteric languages
INTERCAL is the oldest member of a small but persistent genre: the esoteric programming language (esolang). An esolang is designed not for production use but to make a point, usually about minimalism, parody, conceptual difficulty, or computational theory. INTERCAL invented the genre in 1972; the second wave arrived in the early 1990s; the genre is still active today.
What follows places INTERCAL alongside the other prominent esolangs and identifies what each contributes.
Brainfuck (1993)
Designed by Urban Müller, Brainfuck has eight commands: > < + - [ ] , .. It exposes a Turing-machine view of computation: a tape of cells, a data pointer, the four pointer-and-cell operations, and balanced bracket loops. A complete Brainfuck compiler fits in 240 bytes. Müller's original target, and implementations exist for almost every architecture.
Brainfuck's design philosophy is minimalism: how few primitives can you have and still be Turing-complete? The answer is six (the I/O can be omitted in a strict mathematical sense), and Brainfuck is an exhibit of that fact. Its I/O is byte-stream-oriented and convention-free.
INTERCAL contrasts with Brainfuck in every direction. Where Brainfuck has eight one-character commands, INTERCAL has dozens of multi-word verbs. Where Brainfuck eliminates almost all syntactic structure, INTERCAL adds extra structure (politeness, alternating brackets) on top of conventional procedural form. Brainfuck makes a point by minimising; INTERCAL makes a point by parodying.
Befunge (1993)
Chris Pressey designed Befunge as a two-dimensional language: code is laid out on a grid, and the instruction pointer can move in any of four cardinal directions. Branches are physical changes of direction. The language has stack-based arithmetic and Reverse Polish Notation expressions.
Befunge's contribution is spatial structure. Where Brainfuck makes computation linear and minimal, Befunge makes it geometric. A Befunge program is read as a 2D diagram, not a sequence of statements.
INTERCAL has no spatial structure at all, its programs are top-to-bottom statement lists. The two languages share the genre but explore different axes of unconventionality.
Malbolge (1998)
Ben Olmstead designed Malbolge to be as hard to program in as possible. Named after the eighth circle of hell in Dante's Inferno, it self-modifies its instructions on every step in a way that is very nearly impossible to reason about manually. The first "Hello, World!" in Malbolge took two years to produce, and it was generated by a search program rather than written by hand.
Malbolge's contribution is adversarial design. Where INTERCAL is hard to read because of its parodic features, Malbolge is hard to write at all because of its operational semantics. INTERCAL's difficulty is at the surface; Malbolge's difficulty is at the substrate.
Shakespeare Programming Language (2001)
Karl Hasselström and Jon Åslund's Shakespeare expresses programs as Shakespearean plays. Variables are characters, statements are dialogue lines, control flow is acts and scenes. A correct program reads as a coherent (if absurd) play.
Shakespeare's contribution is literary mimicry. The language extends INTERCAL's parodic intent, make programming look like something else, to literary form rather than just to syntactic form. Many similar languages followed (Chef, Whitespace, ArnoldC), but Shakespeare set the template.
INTERCAL parodies the conventions of programming-language design itself; Shakespeare parodies the boundary between programming and literature.
Whitespace (2003)
Edwin Brady and Chris Morris designed Whitespace to use only spaces, tabs, and newlines as significant tokens; every other character is ignored. This means a Whitespace program looks like an empty file or like an unformatted text document, but it is in fact a complete program.
Whitespace's contribution is invisibility. The language's source is, in any text editor, indistinguishable from blank space. The only way to read a Whitespace program is to render whitespace explicitly. INTERCAL's source is at least textually visible; Whitespace makes invisibility into a feature.
Where INTERCAL fits
INTERCAL is the oldest esolang, predating the genre by about twenty years. Brainfuck, Befunge, Malbolge, and Shakespeare are all from the 1990s and 2000s; they had INTERCAL as a precedent. The Esolang community wiki lists INTERCAL as the proto-example whenever someone asks "what is an esoteric language?".
Several traits make INTERCAL distinct within the genre:
| Feature | INTERCAL | Brainfuck | Befunge | Malbolge | Shakespeare |
|---|---|---|---|---|---|
| Year | 1972 | 1993 | 1993 | 1998 | 2001 |
| Design tone | Parody | Minimalism | Geometric | Adversarial | Literary |
| Instruction count | ~14 verbs | 8 commands | ~20 | 8 | ~30 forms |
| Variables | Numbered, typed | Tape cells | Stack-only | Self-modifying | Named characters |
| Control flow | NEXT/RESUME/COME FROM | Brackets | 2D direction | Self-modify | Acts and scenes |
| I/O | Roman+TTM | Byte stream | Byte stream | Byte stream | Numeric |
| Self-hosted? | Attempted (this project) | Yes (many) | Yes (rare) | No (probably impossible) | Not seriously |
| Compile-time check | Politeness | None | None | None | Verse rules |
The politeness rule is unique. The Turing Text Model is unique. The full named-symbol palette (sparks, rabbit-ears, tail, hybrid, big money, etc.) is unique. The combination of a strict 1972 specification with a small but persistent maintainer community is unique. INTERCAL has more conceptual surface than Brainfuck, less than Shakespeare, and a different orientation from any of them.
Why INTERCAL has aged well
Most early esolangs are no longer maintained. INTERCAL is. Three reasons:
- It is short enough to specify in a few dozen pages, but rich enough to admit non-trivial implementations.
- Its parodic posture has not dated. The conventions it ridicules are still recognisable today.
- The maintainer community is small but persistent: three serious implementations (C-INTERCAL, CLC-INTERCAL, this one) have kept it in working condition since 1990.
Brainfuck and Befunge are similarly persistent. Malbolge and Whitespace less so, they made their point and the point was made. Shakespeare survives mostly as a teaching example.
What INTERCAL is not
It is not the most minimal esolang (Brainfuck is). It is not the hardest (Malbolge is). It is not the most literary (Shakespeare is). It is not the most novel in execution model (Befunge is). What it is, is the first and the most conceptually elaborate parody, the language that established the genre's conventions: parody as design intent, deliberately inconvenient features, a complete spec, a small maintainer community.
This is a useful position, and the reason the language is worth implementing fifty-plus years after its first compiler. Understanding INTERCAL is understanding the genre.
Further reading
The Esolang community maintains a comprehensive wiki at https://esolangs.org/. The 2014 talk by blinry, Esoteric Programming Languages, surveys the genre with examples; slides are linked in further-reading.md. Hillel Wayne's Brief Introduction to Esoteric Languages (https://www.hillelwayne.com/talks/esolangs/) is a more recent treatment.
For INTERCAL specifically, the resources in further-reading.md point to the original 1972 manual, the C-INTERCAL distribution, and the CLC-INTERCAL site.
Exercises
- Identify three features INTERCAL has that no other esolang in the table above shares. Are they superficial or load-bearing for the language's identity?
- Brainfuck is famously easy to compile (240 bytes for the original). Why is INTERCAL so much harder?
- The Shakespeare Programming Language uses character names as variables. Could INTERCAL be reformulated to use named variables instead of numbered ones? What would change in the spec?
- Malbolge has resisted self-hosting because its semantics are operationally adversarial. INTERCAL's barriers to self-hosting are different. List them.
- Suppose you wanted to design a new esolang in 2026. Which of INTERCAL's design choices would you copy, and which would you avoid?
Next reading
- what-is-intercal.md: INTERCAL on its own terms.
- history-and-context.md: INTERCAL's place in the broader history of programming languages.
- further-reading.md: surveys of the genre.
Language design philosophy: INTERCAL against the canon
C. A. R. Hoare's 1973 keynote Hints on Programming Language Design is the canonical short statement of how to design a programming language well. Hoare lays out five principles (simplicity, security, fast translation, efficient code, and readability) and argues that languages should be evaluated against them.
INTERCAL was published one year before Hoare's lecture and sets out, with what was probably playful awareness, to violate every one of his principles deliberately. Reading the two documents side by side is one of the best ways to understand what INTERCAL is doing and why.
Hoare's five principles
From the 1973 paper, summarised:
- Simplicity. The language and its compiler should be small enough that a competent programmer can hold both in their head. Features should compose orthogonally; corner cases should be eliminated rather than enumerated.
- Security. The compiler should reject programs whose meaning is not well-defined. Type errors, range errors, and uses-before-definition should fail to compile rather than running and misbehaving.
- Fast translation. A compiler should be able to translate a program faster than the programmer can read it. Long compile times are a barrier to the iterate-and-test cycle.
- Efficient code. The translation should produce executables that run reasonably fast. A factor-of-three slowdown over hand-written assembly is acceptable; a factor of a hundred is not.
- Readability. The source should be readable by somebody other than the author. Identifiers, control flow, and data flow should be evident on first reading.
Hoare elaborates each principle and shows how violations produce real costs, debugging time, security holes, productivity losses.
INTERCAL against the principles
Simplicity (violated, on purpose)
INTERCAL has fourteen statement types, four variable namespaces, two grouping characters that must alternate, and a politeness rule that operates on the whole program. The grammar is small but the semantics are not orthogonal: the same READ OUT does completely different things on a scalar versus an array, and the Turing Text Model algorithm is not derivable from any simpler principle. A competent programmer can hold the spec in their head, but only after deliberate study; the language does not yield to a casual reading.
The violation is deliberate. Simplicity in Hoare's sense, orthogonal features, would defeat the parodic intent.
Security (variably honoured)
INTERCAL's compile-time security is limited to the politeness rule, the label uniqueness check, and (now) the spark/rabbit-ears nesting check. Everything else is a runtime error. A program that overflows a 16-bit slot, indexes past an array, or RESUMEs an empty NEXT stack will compile cleanly and fail at runtime.
This is partly a constraint of the language (INTERCAL allows abstention, so most checks have to be runtime) and partly a deliberate parodic choice (security in Hoare's sense would require typing, which INTERCAL refuses).
Fast translation (mixed)
The bootstrap compiler runs in milliseconds for ordinary programs. The pure-syslib path takes 30 seconds because syslib.i is 9000 lines of INTERCAL that must be tokenised, parsed and emitted; the cache mode (see syslib.md) brings it back to milliseconds after one warming. By Hoare's standard, native and cache modes pass; pure-syslib does not.
This is not a parodic violation, just an artefact of expressing a syslib in the language itself. Cache mode is Hoare-compliant.
Efficient code (violated, by indifference)
We have no production users for whom runtime performance matters. Compiled INTERCAL programs are many orders of magnitude slower than equivalent C, because every operator is a runtime call and there is no register allocator. Hoare's principle is violated by indifference, not by intent.
For a language that takes itself seriously this would be unacceptable. For INTERCAL it is irrelevant.
Readability (violated, on purpose)
DO ,1 SUB #4 <- #0 is readable in the sense that a careful reader can derive its meaning, but not in the sense Hoare meant, the meaning is not evident on first reading. The Turing Text Model output makes a sequence of constants look like a string only after one knows the encoding. The politeness rule encourages PLEASE to appear at distributed positions for compliance reasons rather than for emphasis.
This is the principle INTERCAL violates most enthusiastically. Reading INTERCAL is the reward of having learned INTERCAL; it does not give itself away.
Why a deliberately bad language is interesting
Hoare's principles are correct for production languages. INTERCAL is not a production language. Its value is exactly that it occupies the design space opposite the principles, and by doing so makes them more visible. A reader of INTERCAL learns by contrast what each of simplicity, security, readability buys for the languages that respect it.
This framing, design as parody, is older than INTERCAL but INTERCAL was the first programming language to embrace it explicitly. The wave of esoteric languages that followed (Brainfuck, Befunge, Malbolge, Shakespeare, Whitespace) each picked one of Hoare's principles to violate even more aggressively than INTERCAL did. Brainfuck violates expressiveness. Malbolge violates predictability. Shakespeare violates the boundary between code and prose. None of them is useful for production work; all of them sharpen the reader's sense of what production languages are doing.
Niklaus Wirth's perspective
Wirth is the closest thing to a counterpoint within the language-design canon. His Pascal (1970), Modula-2 (1978), and Oberon (1987) progression is a study in stripping a language down, each successor has fewer features than its predecessor, and each is designed to compile in one pass. Wirth's principle could be summarised as "a language is finished when there is nothing left to take away".
INTERCAL violates this principle by accumulating idiosyncrasies. Every revision of the spec adds features (COME FROM was added by C-INTERCAL in 1990; Label 666 by CLC-INTERCAL; quantum operators by CLC-INTERCAL). Each addition is in the spirit of the original, more deliberate inconvenience, but the overall trajectory is one of accretion rather than reduction.
This is not failure relative to Wirth; it is genre divergence. Wirth designs production languages that aim for elegance through subtraction. INTERCAL designers aim for parody through accretion. Both can be right because they are answering different questions.
What INTERCAL teaches that the canon does not
Reading Hoare and Wirth in isolation produces a particular kind of language designer: one who optimises for what compilers do well. INTERCAL adds a complementary lesson: the things compilers can be forced to do badly. The politeness rule teaches that compile-time predicates can be arbitrary properties of the whole program. The Turing Text Model teaches that I/O semantics can be functionally complete and operationally absurd at the same time. COME FROM teaches that control flow primitives can be designed to make programs harder, not easier, to read.
A language designer who reads only the canon ends up with one set of answers. A designer who also reads INTERCAL has a wider hypothesis space, including hypotheses they will deliberately reject, which is what hypothesis spaces are for.
Where INTERCAL stops being parody
Some features of INTERCAL would be reasonable in a production language:
- The four variable namespaces with explicit prefix sigils (
.:,;) are clearer than the implicit type system of older Fortran or BASIC. - The cleanly separated 16-bit and 32-bit numeric types avoid C's promotion rules.
- The strict spark/rabbit-ears alternation is a real solution to the precedence-inference problem, it forces the programmer to be explicit, which is sometimes what you want.
These were not necessarily intended seriously, but they could be lifted out of the parody and put into a serious language. Whether anyone will is a separate question.
Exercises
- Read Hoare's 1973 paper (linked in further-reading.md). Pick one principle and find an INTERCAL feature that violates it more egregiously than the examples above.
- Wirth's Oberon-2 has fewer than 30 reserved words and compiles in one pass. INTERCAL has roughly 25 reserved words. Where is the difference in the programs the two languages express?
- Construct a small INTERCAL program that satisfies Hoare's principle of readability, one that an unprepared reader could understand in one minute. How short does it have to be?
- The deliberate-anti-design genre that INTERCAL launched has dozens of members today. Is there a Hoare principle that no esolang has yet violated?
- The spark/rabbit-ears alternation rule, transplanted into a serious language, would make expressions verbose but unambiguous. Sketch what a serious language with this rule would look like. Would anybody use it?
Next reading
- history-and-context.md: INTERCAL's place in the broader history of language design.
- esolangs-context.md: the genre INTERCAL launched.
- further-reading.md: Hoare, Wirth, and the canonical literature on language design.
History and context
The INTERCAL language, the compilers that have implemented it, and the design choices that brought us here. The historical and comparative context that the technical chapters assume but do not spell out.
INTERCAL, 1972
The language was designed on 26 May 1972 by Donald R. Woods and James M. Lyon at Princeton University. The original reference manual, The INTERCAL Programming Language Reference Manual (1973), was the first formal specification; the more widely-circulated revision is The INTERCAL Programming Language Revised Reference Manual. The manual's tone is a parody of the technical writing conventions of the era, but the language it specifies is a complete, Turing-complete programming language with deliberate and consistent semantics.
The design brief stated explicitly that the new language should have nothing in common with any major language of the time. The languages the designers wanted to differ from, named in the manual itself, include FORTRAN, BASIC, COBOL, ALGOL, SNOBOL, SPITBOL, FOCAL, SOLVE, TEACH, APL, LISP, and PL/I. INTERCAL's defining design choice is therefore to avoid every feature then fashionable: no keywords shared with any other language (no IF, no GOTO, no WHILE); grouping with two alternating bracket types instead of nested parentheses; arithmetic only through bitwise operators; politeness as a compile-time check. The result is a language that is Turing-complete, specifiable in a few dozen pages, and pleasant to read after one gets over the first hour.
The earliest implementation, written by Woods and Lyon, was a compiler in SPITBOL (a SNOBOL4 dialect) targeting an IBM System/360 at Princeton. It was used by a small Princeton community in the early 1970s. The original sources are not publicly available today, but the manual that documented its acceptance has been digitised and circulates online.
C-INTERCAL (ick), 1990
Eric S. Raymond rewrote and extended INTERCAL in C in 1990, producing a more portable implementation under the name C-INTERCAL (often abbreviated ick, from the compiler binary's name). The C-INTERCAL distribution added several extensions to INTERCAL-72:
- The
COME FROMstatement, now considered canonical INTERCAL despite being absent from the 1972 manual. - External function calls via the
-eflag. - A test suite, release tooling, and documentation.
C-INTERCAL is still the reference implementation. Raymond's documentation at http://catb.org/~esr/intercal/ remains the clearest exposition of the language's pragmatic semantics, and many programmers learn INTERCAL through his version first.
Our compiler is clean-room: it has been written without reading C-INTERCAL's source or copying fragments of its documentation. The language reference in AGENTS.md and the grammar in appendix-grammar.md were written from first principles against the INTERCAL-72 manual.
CLC-INTERCAL
CLC-INTERCAL, maintained by Claudio Calvelli, is a later implementation in Perl with further extensions: quantum computing primitives, an object system, Baudot-coded text I/O, and a syscall mechanism via a reserved label called 666. The CLC-INTERCAL project is hosted at https://uilebheist.srht.site/.
Label 666 is the feature of CLC-INTERCAL we borrowed most directly. Its parameter-passing convention, "call by vague resemblance to the last assignment", is idiosyncratic and obscurely documented (see 666.md). Our version of Label 666 uses a simpler fixed-register convention: .1 as syscall number, .2/.3/.4 as parameters and results, and ,65535 as the data buffer. This is not CLC-INTERCAL compatible, and we make that clear to any reader.
The decision to adopt something Label-666-shaped rather than inventing a new mechanism was driven by the fact that 666 is already mentally associated with "syscall gate" for anybody familiar with CLC-INTERCAL. Using it for the same purpose, even with a different calling convention, reduces confusion.
Why write another INTERCAL compiler
Three existing implementations are described above. A fourth is therefore not strictly necessary. The reasons we built this one anyway:
-
Educational. None of the existing implementations were designed to be read as compiler construction tutorials. C-INTERCAL is pragmatic C from 1990 with three decades of accretion; CLC-INTERCAL is Perl. The INTERCAL-72 original is lost to most developers. A small, clean, single-language-per-file implementation in a working codebase serves a role the others do not.
-
Self-hosting in pure INTERCAL. To our knowledge, no historical INTERCAL compiler has been self-hosted in INTERCAL. C-INTERCAL is written in C; CLC-INTERCAL is written in Perl. The attempt to express the full compiler in INTERCAL is, partly, an exercise in whether INTERCAL is practically (not just theoretically) capable of such a program.
-
Native-binary output on modern platforms. Both C-INTERCAL and CLC-INTERCAL transpile to C and rely on
ccto produce the final binary. We wanted to see what a direct-to-assembly path looks like for a language this small. Skipping C as an intermediate removed a dependency and forced us to confront the platform differences directly. -
Own the clean-room implementation. A from-scratch compiler for a specified language, written without reference to any existing implementation, is a clean starting point for whatever extensions or experiments we want to try.
Comparative notes
A short catalogue of how our design decisions differ from other INTERCAL implementations and, more broadly, from the C compilers most readers will be familiar with.
Transpilation vs direct emission
C-INTERCAL emits C; CLC-INTERCAL emits Perl; we emit ARM64 or x86-64 assembly. The transpilation path trades one layer of complexity (dealing with machine code) for another (dealing with the target language's constraints). In practice, transpiling to C is the less risky choice. C compilers are well-tested, but it forces the INTERCAL implementer to match INTERCAL's semantics to C's, and some mismatches are awkward (C's signed-overflow undefined behaviour versus INTERCAL's unsigned wrap semantics).
Operator implementation
All three implementations implement mingle and select as subroutines in the runtime. The difference is how the subroutine is called: C-INTERCAL inlines them as C function calls, CLC-INTERCAL as Perl subroutines, and we as bl _rt_mingle / bl _rt_select native calls. The semantics are identical.
Syslib
C-INTERCAL ships a pure-INTERCAL syslib called syslib.i, analogous to ours. CLC-INTERCAL has a similar library but with different label conventions. Our src/syslib/syslib.i was written clean-room, but the label numbering follows the INTERCAL-72 convention (1000–1999 reserved, specific labels for add/sub/mul/div) because that is the specification.
Self-hosting ambition
C-INTERCAL and CLC-INTERCAL do not aim to be self-hosted. Our project does. That forces several specific design decisions:
- The Label 666 syscall mechanism must exist in the compiler's output, because the self-hosted compiler needs to read files at runtime (no
argc/argvparsing in pure INTERCAL). ,65535must be reserved. Any program we ever compile cannot use that array, because the self-hosted compiler does.- The compiler's output must match the bootstrap's output for the same inputs, at least up to observable program behaviour. If the two compilers produce different binaries, the fixpoint test cannot converge.
Extensions
We deliberately avoid most extensions:
- No MAYBE / backtracking.
- No computed COME FROM.
- No threading via multiple COME FROMs to the same label.
- No Wimpmode (decimal I/O).
- No TriINTERCAL (base 3).
The rationale is to keep the core language surface small enough that compiler.i can realistically be built in INTERCAL. Every extension we add is another codegen function to write in INTERCAL, and at the current pace of stage3 development every kilobyte of INTERCAL source is expensive.
How a C compiler would handle the same tasks
A reader familiar with C compilers might find it useful to know what the INTERCAL compiler does differently, and why.
Lexing
A C lexer has to handle strings, character constants, escape sequences, preprocessor directives, numeric literals in three bases, and trigraphs. Our lexer handles none of those, no strings, no literals other than decimal, no preprocessor. On the other hand, we handle DON'T as a single token, which no C lexer has to deal with.
Parsing
A C parser is LL(k)-untractable in several places; most C compilers use hand-written recursive descent with unbounded lookahead or occasional LR(1) tables (yacc/bison style). Our parser is LL(1) because INTERCAL's expression grammar has no operator precedence: every operator must be explicitly grouped, so there is no ambiguity to resolve.
C's type system is the main reason C compilers have a dedicated semantic analysis phase. INTERCAL has four types (onespot, twospot, tail, hybrid) and no type inference; the type of every expression is fixed by its root node. There is almost no type-checking for us to do.
Code generation
C compilers emit one instruction per source token is a pointer-poor model. Modern C compilers emit SSA IR, run 20+ optimisation passes, and only then lower to target instructions. Our compiler emits ~10 instructions per INTERCAL statement, directly, without optimisation.
The cost of our approach is that the emitted assembly is not optimal: we call _rt_mingle even when the operands are constants we could fold. The benefit is that the codegen is transparent. You can read codegen_assign and see, line by line, what assembly will come out.
Runtime
C's runtime is largely the C library: malloc, printf, file I/O, and so on. Our runtime is much smaller because INTERCAL asks for less: Roman-numeral output, Turing-tape arrays, mingle, select, unary operators, plus the Label 666 syscalls. A C runtime for an INTERCAL-sized program would be at least 100KB; ours is ~40KB per platform.
How a Lisp compiler would handle the same tasks
Lisp compilers present a useful contrast because they invert several of the assumptions a C-style compiler makes.
Lexing and parsing
Lisp's syntax is so simple that lexing and parsing fuse into a single read function. Parentheses, symbols, and numbers; nothing else. Our lexer is more involved than a Lisp lexer but has exactly the same shape: token-by-token consumption with a small switch.
Semantic analysis
A Lisp-with-macros compiler has to handle macro expansion as part of semantic analysis: the program is transformed by user-defined rewrites before any codegen happens. We have nothing comparable. INTERCAL has no macros, and the closest thing we have to compile-time expansion is the gerund resolution in ABSTAIN FROM CALCULATING.
Runtime
Lisp runtimes universally include a garbage collector. Ours does not: INTERCAL allocates arrays once via _rt_mmap and never frees them. For the programs we run this is acceptable; for a Lisp program it would not be.
Where this project sits in the compiler-construction literature
There are, roughly, four genres of compiler-construction text:
- Theory first. The Dragon Book, Appel's Modern Compiler Implementation. Full formal treatment of grammars, parsing tables, IR, optimisation.
- Hands-on build. Crafting Interpreters, Thain's Introduction to Compilers, Crenshaw's Let's Build a Compiler. Take the reader through a complete compiler, one phase at a time.
- Technique catalogues. Cooper & Torczon's Engineering a Compiler, Muchnick's Advanced Compiler Design. Surveys of modern techniques, with deep treatment of specific optimisations.
- Case studies. Project-specific writeups, the CHICKEN Scheme implementation notes, the Go compiler internals talks, the LLVM documentation.
This repository's docs/ directory belongs to genre (4), with elements of genre (2). It is a case study of a small self-hosting compiler, narrated phase by phase, with exercises and cross-references to the classical literature for the reader who wants depth beyond what we provide here.
The design choice to remain small, no IR, no optimisation, hand-written runtime, is what makes this case-study role feasible. A full modern compiler could not be documented this way; it is too big. INTERCAL, and this compiler specifically, are small enough.
Design rationale: an FAQ
The questions anybody seeing this compiler for the first time will reasonably ask, with short answers that point at the deeper chapters for readers who want more.
Why write an INTERCAL compiler in 2026?
Because INTERCAL is the right size to be a complete teaching example. A full C compiler is too big to read through in a weekend; a pure regex engine is too small to illustrate more than a couple of phases. INTERCAL sits in the sweet spot: it has a lexer, a parser, a semantic-analysis phase, a code generator, a runtime, and a system library, and every one of those pieces fits in a few hundred lines.
See overview.md.
Why no intermediate representation?
Adding an IR pays off when you have multiple source languages, multiple target backends, or want to run many optimisation passes. We have one source language (INTERCAL), two backends that share most of their structure (ARM64 and x86-64), and no performance pressure. An IR would be more work to build and maintain than the direct codegen it would replace.
See middle-end-and-optimisation.md.
Why zsh for the bootstrap?
Three reasons. First, universality: every system we target has zsh, so a bootstrap-from-scratch requires no extra toolchain. Second, transparency: the entire compiler is one file, and adding set -x dumps every phase. Third, appropriateness: INTERCAL is a 1970s-era language and zsh is a 1970s-era language-adjacent tool, which pairs well enough to feel deliberate.
See self-hosting.md.
Why not transpile to C like C-INTERCAL does?
Transpiling to C trades one complexity (emitting assembly) for another (matching INTERCAL semantics to C semantics). Some mismatches are awkward, signed overflow is undefined in C but must wrap in INTERCAL, and the dependency on a C compiler adds a hidden layer where bugs can hide. Direct-to-assembly removes that layer and lets us see exactly what runs.
See code-generation.md.
Why not use a parser generator like Bison?
INTERCAL's grammar is LL(1) with ~15 productions. A Bison grammar file plus the generated parser is more code, not less, than a hand-written recursive-descent parser. The hand-written version is transparent: you can point at any production in the grammar and the corresponding function in intercalc.sh. A generated parser obscures this.
See parser-theory.md.
Why maintain two syslibs (pure INTERCAL and native assembly)?
The pure-INTERCAL syslib (9065 lines) is slow but is the authoritative specification of what each arithmetic routine does. The native assembly syslib (~300 lines per platform) is fast but translation-dependent. Running both implementations on the same inputs and diffing is a strong correctness test, it catches any bug that exists in only one of them.
A third path bridges the two: INTERCAL_SYSLIB=cache pre-compiles the pure-INTERCAL syslib once per content hash and reuses the resulting .s artifact, giving native-like compile time with pure-syslib semantics. tools/build_syslib.sh warms the cache on first use.
See syslib.md and testing-and-workflow.md.
Why Label 666 for syscalls?
Because INTERCAL-the-language has no syscall mechanism, and our self-hosted compiler cannot exist without one. Label 666 is the minimum extension that makes syscalls possible: one reserved label, a fixed-register convention for parameters, and a set of explicit syscall numbers. The name 666 is a deliberate nod to CLC-INTERCAL, which uses the same label for the same purpose (though with a different calling convention).
See label-666-intro.md and 666.md.
Why not just use CLC-INTERCAL's Label 666 as-is?
CLC-INTERCAL's Label 666 uses a parameter convention called "call by vague resemblance to the last assignment": the parameters live in whichever register was last assigned to in the program. This is deliberately obscure (consistent with INTERCAL's aesthetic) but hard to reason about. Our version uses fixed registers .1 through .4. We lose binary compatibility with CLC-INTERCAL but gain a debuggable syscall mechanism.
See 666.md.
Why self-host at all?
Self-hosting is the cleanest demonstration that a language is complete enough to express its own translation. Every compiler that reaches the fixpoint state (where the Nth-generation self-compile equals the (N+1)th) provides its own authoritative specification: the language is whatever the compiler understands. For INTERCAL specifically, self-hosting has never been done before; this project is trying.
See self-hosting.md.
Why a template-dispatch MVP before a real self-hosted compiler?
Because writing a full compiler in INTERCAL is estimated at 5000–15000 lines and months of work. We did not want to spend that effort before validating that the end-to-end self-hosted pipeline (Label 666, argv access, the reserved ,65535 buffer) could work at all. The template-dispatch MVP is ~40 lines of INTERCAL that proves the plumbing is viable; real compiler work follows in stage3.i.
See self-hosting.md.
Why tests/run_tests.sh, tests/run_self_tests.sh, and two more? Four suites?
Each suite tests a different layer of the stack. run_tests.sh validates the bootstrap compiler. test_syslib_pure.sh runs the pure-vs-native differential test. run_self_tests.sh validates the self-hosted MVP against the bootstrap. run_stage3_tests.sh validates the evolving real compiler. The layering is what lets us change a low-level component (say, a codegen function) and know exactly which suite would catch a regression.
Why TDD instead of writing code and then adding tests?
Because the cost of a miscompilation is high and often invisible. A bug that passes the existing tests but miscompiles one real-world INTERCAL construct might not surface until somebody writes a program using that construct. TDD, writing the test first, forces us to articulate what the new behaviour should be before writing code, which in turn catches wrong specifications at design time rather than at runtime.
See AGENTS.md, "TDD workflow".
Why split the code generation between intercalc.sh and codegen_x86_64.sh?
ARM64 (macOS and Linux) shares almost all of its emitted assembly: small differences in syscall numbers, relocation syntax and entry-point names are patched with a sed post-processing step. x86-64 is a different architecture, so it needs a full codegen rewrite. Rather than one monolithic codegen with conditionals at every emission, we have one base codegen for ARM64 and a complete override for x86-64. Zsh's last-function-wins semantics makes the override trivial.
See platforms.md.
Why reserve ,65535 exclusively for Label 666?
Every Label 666 syscall that needs buffer data (open's filename, read's contents, argv's arguments) needs a well-known memory region. Reserving a specific array makes the interface portable between the compiler and the runtime without invention. The choice of 65535 (the largest 16-bit array index) keeps the reserved slot far from anything a normal program would use.
See label-666-intro.md.
Why use cc -x assembler - rather than writing our own assembler?
Writing an assembler for Mach-O or ELF is a nontrivial project in its own right, and the system cc already does it correctly. The tradeoff is a dependency on cc, which is present on every system we target. We pay that dependency cost in exchange for not having to implement instruction encoding, relocation handling, and executable-format packaging.
See executables-and-linking.md.
Why three platforms and not just one?
Because a compiler that only works on one platform has not proved anything about its portability. The three-platform matrix (macOS ARM64, Linux ARM64, Linux x86-64) forces us to think about every platform-specific corner case at implementation time rather than when somebody later tries to port. The CI cost (three jobs instead of one) is worth the design pressure.
See platforms.md.
Why not support Windows?
Windows is on the roadmap but not yet implemented. The PE/COFF executable format, the Microsoft calling convention (different from System V AMD64), and the Win32 API rather than Unix syscalls all require substantial new code. We chose to stabilise the Unix targets first; Windows will follow.
Why pre-generate test templates rather than actually compiling them?
Because the self-hosted MVP is not yet a real compiler. It is a template dispatcher. For the 25 test programs we care about, we have pre-generated the exact assembly the bootstrap compiler would produce, and the MVP's job is just to recognise each program and emit its matching template. When stage3.i becomes a real compiler, the templates become a cross-check (MVP output should match stage3 output), not the source of truth.
See self-hosting.md.
Why not merge the bootstrap and the self-hosted compilers?
The bootstrap compiler (intercalc.sh, zsh) and the self-hosted compiler (stage3.i, INTERCAL) are two different programs because they are written in two different languages. They are expected to produce the same outputs for the same inputs once stage3.i is complete. Until then, they are parallel, and the bootstrap remains the reference. After the fixpoint is reached, intercalc.sh becomes mostly historical, a primordial spark that is no longer used except when somebody bootstraps from scratch.
See self-hosting.md.
Why enforce the politeness rule?
Because the language specification requires it. The politeness rule, between 1/5 and 1/3 of statements must use PLEASE: is INTERCAL's signature compile-time check. A compiler that silently ignores it is not really compiling INTERCAL.
Practically, the rule is also our only opportunity to fire a compile-time error. Every other check in the INTERCAL error catalogue is a runtime condition.
See semantic-analysis.md.
Why no optimisations?
We have no production users for whom performance matters. Every optimisation pass is additional code surface that can introduce miscompilations. Until either compile time or runtime becomes a real bottleneck, adding optimisations is negative-value work. The "middle end" chapter explains where the low-hanging fruit is, if we ever decide to harvest it.
See middle-end-and-optimisation.md.
Why put so much content in docs/ instead of in the code comments?
Because the audience for this project includes readers who want to understand how compilers work without necessarily modifying this one. Those readers should be able to read connected prose. Inline comments serve a different purpose, quick tips for somebody modifying the code, and cannot substitute for a narrative explanation of why the code is shaped the way it is.
See the root README.md of docs/ for the three reading paths.
Why keep AGENTS.md in the repo root instead of under docs/?
Because AGENTS.md is the authoritative contributor contract, not narrative documentation. It is symlinked to CLAUDE.md because AI tools look for CLAUDE.md. Moving it under docs/ would break the convention and add indirection for both human and AI readers.
See ai-collaboration.md.
Why "chispa primigenea" and not "primordial spark" in the code?
Bilingual developers, primarily Spanish. The Spanish phrase is in the code and in some commit messages as a project-specific signature. The English translation appears in the docs wherever a reader without Spanish would need to understand the reference.
Anything else?
If you have a question the docs do not answer, open an issue or a PR. Answers added to this FAQ are encouraged.
Next reading
- overview.md: the technical overview.
- what-is-intercal.md: the plain-English introduction to the language.
- further-reading.md: external resources.
Your first contribution
This chapter walks a new collaborator through landing their first change on this project. It assumes you have cloned the repository and can build and test it (see getting-started.md). The target is a small, well-scoped change that exercises the entire workflow, branch, write a test, implement, run tests locally, commit, push, without requiring deep understanding of any single component.
We will pick one specific example: adding a new error message to the runtime. This change is realistic, touches both the runtime assembly and the test suite, and produces something useful that the project would actually want.
The change, in plain English
The runtime today fires errors for many conditions: ICL275I for assigning a 32-bit value to a 16-bit slot, ICL123I for a NEXT stack overflow, and so on. Suppose we want to add a new error for a hypothetical condition that is not yet detected, say, ICL888I for "PROGRAM CONTAINS A FIXME THAT SHOULD HAVE BEEN ADDRESSED BY NOW". This is a deliberately fictitious error; the point is to practise the mechanics.
The steps:
- Create a branch.
- Write a failing test that expects
ICL888Ion stderr. - Add the error message to the runtime.
- Add a codegen path that emits the error.
- Run the tests locally.
- Commit and push.
- (Optionally) open a pull request.
Step 1: Create a branch
git checkout -b my-first-contribution
Branch names in this project are informal. Something descriptive is enough.
Step 2: Write the failing test
We need an INTERCAL program that triggers ICL888I. Since there is no trigger yet, the test will fail.
Create tests/test_error_e888.i:
DO FIXME
DO GIVE UP
The exact contents depend on what FIXME is supposed to mean. For now, assume we will teach the compiler to recognise FIXME as a keyword that emits a runtime error unconditionally.
Register the test by adding a line near the bottom of tests/run_tests.sh:
_run_error_test "error_e888" "ICL888I"
The _run_error_test helper is already defined in the runner; it compiles the program, runs it, and asserts that the specified ICL code appears on stderr.
Now run the suite:
zsh tests/run_tests.sh --filter error_e888
The test should fail. The compiler does not know what FIXME means, so it will classify DO FIXME as an UNKNOWN statement, which emits _rt_error_E000 (not E888). You will see:
FAIL error_e888 (expected ICL888I, got ICL000I)
Good. Failing test in hand, we can proceed.
Step 3: Add the error message to the runtime
Open src/runtime/macos_arm64.s. Find the block of _rt_error_* routines (around line 369). They all look like:
_rt_error_E123:
adrp x1, _errmsg_123@PAGE
add x1, x1, _errmsg_123@PAGEOFF
mov x2, #54 ; message length in bytes
mov x0, #2 ; fd 2 (stderr)
mov x16, #4 ; write syscall
svc #0x80
mov x0, #1 ; exit status 1
mov x16, #1 ; exit syscall
svc #0x80
Add a new block:
_rt_error_E888:
adrp x1, _errmsg_888@PAGE
add x1, x1, _errmsg_888@PAGEOFF
mov x2, #MESSAGE_LENGTH
mov x0, #2
mov x16, #4
svc #0x80
mov x0, #1
mov x16, #1
svc #0x80
Where MESSAGE_LENGTH is the length of your new error string. Let's use:
ICL888I PROGRAM CONTAINS A FIXME\n
Count the bytes, including the newline: 35.
Find the block of _errmsg_* definitions in the .data section (near the bottom of the file). Add:
_errmsg_888: .ascii "ICL888I PROGRAM CONTAINS A FIXME\n"
Repeat this change in src/runtime/linux_arm64.s and src/runtime/linux_x86_64.s. Note that Linux ARM64 uses svc #0, mov x8, #93 for exit and mov x8, #64 for write; x86-64 uses entirely different syntax. See platforms.md for the syntactic differences. The three files must stay in sync.
Step 4: Add the codegen path
Open src/bootstrap/intercalc.sh and find the tokenize() function. Add recognition of the FIXME keyword (around the existing statement-type detection logic):
elif [[ "$body" == "FIXME" || "$body" == FIXME* ]]; then
stmt_type[stmt_count]="FIXME"
stmt_body[stmt_count]="$body"
Then find codegen_statement and add a case for FIXME:
FIXME) emit " bl _rt_error_E888" ;;
The x86-64 backend in src/bootstrap/codegen_x86_64.sh does not need changes for this particular case because the bl instruction is architecture-specific, but the x86-64 backend does need to emit call _rt_error_E888 instead. Find codegen_x86_64.sh's equivalent dispatch and add the override.
Step 5: Run the tests locally
zsh tests/run_tests.sh --filter error_e888
Expected: PASS error_e888 (runtime error 888).
Then run the full suite to make sure nothing else broke:
zsh tests/run_tests.sh
If any test that previously passed now fails, your change has unintended consequences. Common causes:
- A token that was previously valid (
FIXMEas a variable name, say) now matches your new keyword. Unlikely for this specific word, but real for more ordinary keywords. - The runtime
.datasection alignment was broken by inserting a new message at the wrong byte offset. Review the Mach-O / ELF section directives.
Iterate until the full suite is green.
Step 6: Commit
git add tests/test_error_e888.i tests/run_tests.sh src/runtime/*.s src/bootstrap/intercalc.sh src/bootstrap/codegen_x86_64.sh
git commit -m "Add ICL888I runtime error for FIXME statements
Introduces a new runtime error code 888 fired when a program contains
a FIXME statement. Motivation: give programmers a way to explicitly
mark incomplete work so the compiler enforces addressing it at runtime
rather than silently accepting.
Co-Authored-By: Your Name <[email protected]>
"
Commit messages in this project describe the why, not the what. A diff shows what changed; the message should explain the motivation.
The project's pre-commit hook will now run: it will verify the template manifest (no changes there, should pass) and run the bootstrap test suite. If the tests are green, the commit succeeds.
Step 7: Push
git push -u origin my-first-contribution
The pre-push hook will run all four test suites before pushing to the remote. Depending on your machine, this takes 1–2 minutes. If any suite fails, the push is aborted; fix and try again.
Once the push succeeds, you can open a pull request on GitHub targeting main.
What you just did
You touched every layer of the project:
- A test that articulates the expected new behaviour.
- The runtime assembly, in three platform variants.
- The compiler's tokeniser and codegen.
- The test runner registration.
That pattern, test first, touch every affected file, iterate until green, is the workflow the project expects for any non-trivial change. Smaller changes follow the same pattern with fewer files.
Common stumbling blocks
- The three runtime files drift out of sync. If
src/runtime/macos_arm64.sgets a new error but the Linux files do not, CI will pass on macOS and fail on Linux. Always edit all three (or explicitly skip the Linux ones with a TODO if the feature is genuinely macOS-specific, which is rare). - The pre-commit hook's template-manifest check fails. This happens if you touched
src/compiler/templates/without regenerating the manifest viazsh tools/gen_manifest.sh. Usually a signal that you changed something you didn't intend to. - The test runner's assertion pattern misfires. If your error message contains special regex characters or Roman numerals that also match other error codes, the runner may match the wrong string. Debug with
zsh tests/run_tests.sh --verbose --filter your_testto see the raw output.
Where to go next
- For changes to the front end (lexer, parser, semantic analysis), start with lexing-and-parsing.md and semantic-analysis.md.
- For changes to the back end (codegen, runtime, syslib), start with code-generation.md and runtime.md.
- For changes to the self-hosted compiler (
compiler.i,stage3.i), start with self-hosting.md and be especially careful about the TDD rule. - For changes to the testing infrastructure, start with testing-and-workflow.md.
- For AI-assisted work specifically, see ai-collaboration.md and
AGENTS.md.
Welcome aboard.
Working on this repository with an AI agent
This chapter is for the human who wants to use an AI coding assistant on this repository, and for the AI agent itself. The primary guide for any contributor, human or AI, is AGENTS.md in the repository root. That file is the authoritative contract: how to run tests, how to structure commits, what the TDD workflow looks like, which language pitfalls apply to which platform. What follows here is the shorter, compiler-specific briefing that assumes AGENTS.md will be consulted whenever specifics are needed.
Why this matters
This project's design is unusual along several dimensions that AI agents, trained on conventional codebases, tend to get wrong:
- The source language is INTERCAL. Pattern-matching against C, Python, or Rust idioms produces misleading suggestions.
- The bootstrap compiler is a single zsh script (about 2100 lines today, growing as compile-time checks and optimisations are added), not a Python or Rust program. Agents often try to introduce tooling from other ecosystems.
- There is no intermediate representation. Agents trained on LLVM-style architectures often suggest adding one.
- The platform differences are syntactic, not semantic. An agent that sees "ARM64 assembly" and assumes it can be copy-pasted from a Linux source to a macOS source will break things.
- The self-hosting goal is a fixpoint, not a feature flag. An agent that makes a change that breaks the bootstrap compiler has broken everything downstream.
The right mental model is closer to a 1970s compiler than to a modern LLVM front-end. The shortcuts a modern toolchain provides are not available, and when they are proposed they usually produce subtle breakage.
The non-negotiable rules
From AGENTS.md, summarised:
- Before modifying the compiler, syslib, or runtime, add a failing test that captures the intended behaviour.
- Run
zsh tests/run_tests.shlocally before every commit. For self-hosted changes runzsh tests/run_self_tests.shtoo. - One sub-stage per commit during stage3 development; each commit is green on all three platforms.
- Never edit
CLAUDE.mddirectly, it is a symlink toAGENTS.md. - Never skip git hooks (
--no-verify) without explicit permission. - Never commit broken code. If a commit fails tests, fix it or revert; do not amend a broken commit's predecessor.
- Never delegate understanding to a sub-agent. Sub-agents are for parallel research, not for one-off edits to
intercalc.shor the runtime assembly.
These rules exist because past violations have caused real regressions. The TDD rule in particular is the project's primary defence against the class of bugs that are easy to write and hard to reproduce.
What an agent is good for here
- Broad searches across the codebase (find every place
,65535is written, find every_rt_error_*call site, enumerate all TODOs). - Parallel research (platform-specific assembly pitfalls vs cross-platform pitfalls, differential-testing techniques vs traditional golden-output testing).
- Drafting documentation, the kind of editorial work this directory represents. The prose-style rules an agent should apply when writing for
docs/are listed inAGENTS.mdunder "Documentation prose style"; follow them from the start so a later style pass is not needed. - Proposing test cases from a natural-language description of a bug.
- Reviewing a diff for consistency with the rest of the codebase.
What an agent is not good for here
- Editing
intercalc.sh, anycodegen_*function, or the runtime assembly files without a human reviewing the diff line by line. The cost of a miscompilation is one or more platforms failing CI after a push; the cost of a subtle miscompilation is undetected and potentially intermittent. - Editing
compiler.iorstage3.iwithout a matching failing-then-passing test. The risk of introducing a regression that only surfaces during the fixpoint test is high. - Running tests. Tests are run by the human so the output is visible. An agent claiming "all tests pass" without showing the actual output is a stated outcome, not a verified one.
- Making commits. The human commits so that the commit message and staged files are reviewed before they become permanent.
How to brief an agent effectively
The pattern that works, based on the experience documented in AGENTS.md and the memory files:
- State the problem in one or two sentences, citing the relevant source files and line numbers.
- Describe what you have already tried and ruled out.
- List the constraints the agent must respect (platform compatibility, byte-exact output vs bootstrap, the TDD rule).
- Ask for something concrete: a diff, a test, a paragraph of prose, a list of files to inspect.
- Set a response-length bound if the output should be compact.
A poorly briefed agent produces generic, middle-of-the-road answers. A well-briefed agent produces targeted work.
Useful memory patterns
The repository's memory/ directory (private to each user) stores per-user notes that persist across sessions. The general convention established in this project:
memory/project_status.md: what is done, what is next, phase tracking.memory/architecture.md: the current compiler architecture, per-platform.memory/bugs_learned.md: critical bugs and the lessons from them.
These files are not committed to the repository, by design. They hold the agent's running understanding of the project, which would be noise for another human reading the history.
The TODO.md at the repository root is different: it is a working notes file between Claude sessions, committed to the tree. It is intentionally informal.
Repository-specific vocabulary for agent prompts
Words that mean specific things in this project and should not be interpreted through their general software-engineering meaning:
- Bootstrap: the shell-script compiler
src/bootstrap/intercalc.sh, the chispa primigenea. Not the CI concept, not the OS-loading concept. - Self-hosted: compiled by
intercal_core, itself produced fromsrc/compiler/compiler.i. Specifically not the bootstrap path. - Fixpoint: the property that gen2 and gen3 of the self-hosting process produce byte-identical assembly.
- Template: a pre-generated assembly file under
src/compiler/templates/. Not a Jinja template or a C++ template. - Runtime: the hand-written platform-specific assembly under
src/runtime/. Not a Python runtime, not the JVM. - Pure syslib: the INTERCAL-language implementation of labels 1000–1999 in
src/syslib/syslib.i. The--pure-syslibflag makes the compiler use it instead of the native assembly version.
The commit message convention
From the last ten commits on main:
Phase N.M Stage X.Y: short descriptionfor planned-roadmap work.docs: subjectfor documentation-only changes.Fix <area>: short descriptionfor bug fixes.- Body describes the why rather than the what, since the diff covers the what.
- Every commit ends with the Co-Authored-By line for the AI that participated.
Agents drafting commit messages should match this style.
When to ask the human for confirmation
Auto-mode or not, some actions warrant a pause:
- Any
git push --force,git reset --hard,rm -rf, or operation that destroys uncommitted work. - Any change to
release.yml,ci.yml, or.githooks/that alters the project's quality gates. - Any change that modifies the template manifest without a matching change to the templates themselves.
- Any deletion of a test case or a
.ifixture. - Any change to
LICENSE,CODE_OF_CONDUCT.md, orSECURITY.md.
The rule of thumb from AGENTS.md: the cost of pausing is low; the cost of an unwanted destructive action is high.
Reading order for a fresh agent session
AGENTS.md: the contract.README.md: what the repository is and how to build it.docs/overview.md: why it is shaped this way.docs/map-of-the-compiler.md: where to find things.- The phase chapters, as needed for the task at hand.
An agent that starts with the first three files and consults the rest on demand is operating correctly.
From INTERCAL to real compilers
The previous chapters built up a complete picture of one small compiler. This chapter is the bridge from that picture to the much larger one a contributor to LLVM, rustc, GCC, Go, GHC, OCaml, Cranelift, Zig, Swift, or V8 has to hold in their head. The aim is to make the transfer as cheap as possible: most of the conceptual work has already been done.
If you have read Parts I through V of this book, the table below names what you already know in production-compiler vocabulary, and what you do not yet.
What you already know
| Concept in this book | Same concept in production compilers |
|---|---|
Lexer (tokenize in intercalc.sh) | Clang's clang/lib/Lex, rustc's rustc_lexer, GCC's per-frontend lexer, Go's cmd/compile/internal/syntax, GHC's compiler/GHC/Parser/Lexer.x |
Parser (parse_expr, hand-written recursive descent) | All compilers in this Part use hand-written recursive descent. rustc's rustc_parse, Clang's Parser, GCC's per-language parsers, Go's syntax.Parser, OCaml's Menhir-generated parser. |
| AST in parallel arrays | LLVM does not have a long-lived AST. rustc has rustc_ast, then HIR, then THIR. GCC has GENERIC. Swift's AST is rich and evolves through phases. GHC's HsSyn is parametrised by phase. |
| Semantic analysis (politeness, label checks, COME FROM resolution) | rustc's rustc_resolve + rustc_hir_typeck; Clang's Sema; GCC's tree-level type checks; OCaml's Hindley-Milner inferencer; GHC's OutsideIn(X); Zig's Sema. |
| Code generation (direct ARM64/x86-64 emission) | LLVM's IR + LLVM backends; rustc's rustc_codegen_llvm lowering MIR; GCC's RTL → assembly; Go's SSA + per-arch lowering; OCaml's hand-written native backend; Swift's SIL + IRGen + LLVM. |
Runtime (_rt_* functions) | libc + per-language runtime: libstdc++, libcxx, Rust's core/std, GCC's libgcc, Go's runtime (with GC + scheduler), GHC's RTS (with GC + STG machine), OCaml's runtime, Swift's runtime, V8's heap + scheduler. |
| System library (labels 1000–1999) | The "intrinsics" each compiler ships: __builtin_* in GCC and Clang, core::intrinsics::* in rustc, internal/runtime in Go, GHC primops, OCaml primitives. |
Constant folding (eval_const) | LLVM's InstSimplify, rustc's interpret/MIR const-eval (miri), GCC's tree-level folder, Go's .rules rewrites, GHC's simplifier. |
Dead-flag elimination (compute_flag_checks) | Generic dead-code elimination on SSA / GIMPLE / MIR. |
| Peephole pass | Same pass exists at multiple levels in each compiler. |
| Self-hosting (3-generation fixpoint) | rustc bootstraps in three stages; OCaml has done so continuously since 1985; Zig went stage1 (C++) → stage2 (Zig); Go went 6g/8g (C) → cmd/compile (Go) in 2015. |
| Differential testing (pure vs native syslib) | LLVM has fuzzers (libFuzzer, csmith integration); rustc has crater runs; GCC has its testsuite plus randomised testing; Go has fuzzing built in. |
Reproducible builds (tools/rewrite_uuid.py, SOURCE_DATE_EPOCH) | All major compilers work with reproducible-builds.org and embed deterministic outputs. |
| Trusting Trust (DDC reflection) | The same threat model. LLVM, GCC, Go, OCaml have all begun publishing reproducible self-builds for this reason. |
The first column is a chapter or two of this book. The second column is the rest of your career in compiler engineering, but it is the same conceptual skill.
Distinguishing features per compiler
Each compiler in Part VII has a defining feature that other compilers do not have, or have only at much smaller scale:
| Compiler | Defining feature(s) you learn here |
|---|---|
| LLVM | Modular pass infrastructure, single SSA IR, TableGen, MLIR generalisation |
| GCC | Three-IR stack (GENERIC/GIMPLE/RTL), mature LTO, machine descriptions, plugin system, mailing-list culture |
| rustc | Borrow checker on MIR, query-based incremental compilation, alternative codegen backends (Cranelift/GCC), four-IR stack |
| Go | Self-contained (no LLVM), declarative .rules DSL, escape analysis for stack/heap, fast compile times as design goal |
| GHC | Four IRs with formal semantics, lazy evaluation runtime (STG), type classes via dictionary passing, Cmm portable assembly |
| OCaml | Hindley-Milner type inference (the canonical implementation), functor module system, dual bytecode + native backends, unbroken bootstrap chain since 1985 |
| Cranelift | Backend-as-library, ISLE declarative DSL, regalloc2 SSA-based linear scan, "fast compile" as explicit goal |
| Zig | Comptime as unifying primitive, Sema as the largest phase, stage1→stage2 self-hosting parallel to ours, multiple self-hosted backends |
| Swift | SIL as semantic IR (ARC, generics, witness tables explicit), Mandatory vs Performance pass distinction, ARC optimisation |
| V8 | Tiered JIT, sea-of-nodes IR, speculation + deoptimisation, hidden classes for JS dynamic objects |
A reader who picks one and goes deep gets a skill set that transfers to compilers in the same family. A reader who reads several gets a sense of the design space.
Comparison table across all ten
| Aspect | LLVM | GCC | rustc | Go | GHC | OCaml | Cranelift | Zig | Swift | V8 |
|---|---|---|---|---|---|---|---|---|---|---|
| IR levels | 1 | 3 | 4 | 2 | 4 | 5 | 1 | 2 | 2 (+LLVM) | 3 (BC, Maglev SSA, SoN) |
| Backend | Self | Self | LLVM | Self | NCG or LLVM | Self | Self | LLVM or self | LLVM | Self (per tier) |
| Compilation model | AOT | AOT | AOT | AOT | AOT | AOT + bytecode | AOT/JIT | AOT | AOT | JIT (4 tiers) |
| GC | No (host) | No (host) | No (compile-time) | Yes | Yes | Yes | No | No | Yes (ARC) | Yes (Orinoco) |
| Self-hosted | C++ (no) | C++ (no) | Rust (yes) | Go (yes) | Haskell (yes) | OCaml (yes, since 1985) | Rust (no, library) | Zig (yes, since 2022) | C++ (no) | C++ (no) |
| Codebase size | ~10M C++ | ~15M mixed | ~3M Rust | ~50K Go | ~700K Haskell+C | ~200K OCaml | ~50K Rust | ~500K Zig | ~3M C++ | ~3M C++ |
| Build time | ~30 min | ~1 hour | ~1 hour | minutes | ~30 min | minutes | seconds | ~30 min | hours | ~1 hour |
| Frontends | Many | Many | Rust only | Go only | Haskell only | OCaml only | None (library) | Zig only | Swift only | JS + WASM |
| Targets | 50+ | 50+ | LLVM's | 15+ | x86-64, ARM64, +others | x86-64, ARM64, +others | x86-64, ARM64, RISC-V, s390x | LLVM's + 4 self | LLVM's | x86-64, ARM64 |
| Distinguishing IR feature | LLVM IR (typed SSA, opaque ptrs) | RTL (machine-level) | MIR (CFG with explicit drops) | SSA + .rules | Core (System FC), STG | Lambda + Cmm | CLIF (block params, not phis) | ZIR + AIR | SIL (ARC explicit) | TurboFan SoN |
Reading across the rows, you can see the design clusters:
- LLVM, GCC, Go, OCaml, Cranelift, Zig (when self-hosted backend), V8 all build their own backends. rustc and Swift use LLVM. GHC has both options.
- LLVM and rustc share LLVM IR; OCaml, Go, GHC's NCG, V8 have their own; Cranelift's CLIF is a portable middle ground.
- GC is in Go, GHC, OCaml, V8 (Orinoco), Swift (ARC). rustc's borrow checker eliminates the need. LLVM and GCC delegate to the host language.
- JIT is V8 alone among the ten. The other nine are AOT.
What you do not yet know, and where to learn it
A production compiler differs from this one in degree on most axes. A few axes deserve named follow-up reading.
Modern intermediate representations
Our compiler has no IR. Production compilers have at least one and often several. The big concepts you will meet:
- SSA form (Static Single Assignment): every variable is assigned exactly once. We touched this in middle-end-and-optimisation.md. The Cytron et al. (1991) paper is the canonical reference.
- Control-Flow Graph: the program as a graph of basic blocks. Most analyses operate on the CFG, not on tree-shaped IR.
- Dataflow analysis: figuring out what is true at every program point, computed iteratively until a fixpoint. Constant propagation and dead-code elimination both use it.
- Type systems: most production languages are typed. Type checking is a different kind of work from anything our INTERCAL compiler does.
- Sea of nodes: an alternative IR where control and data flow are unified into a single graph. Used by V8's TurboFan and HotSpot's C2. Cliff Click 1995.
For the first three, Cooper and Torczon's Engineering a Compiler (3rd edition) is a thorough modern reference; Appel's Modern Compiler Implementation is the academic counterpart. For type systems specifically, Pierce's Types and Programming Languages. All are listed in further-reading.md.
Optimisation pipelines
Our compiler has a handful of small optimisations. Real compilers have hundreds, organised into pipelines that run them in carefully chosen orders, often several times each.
The classical optimisations to read about: dead-code elimination, common subexpression elimination, global value numbering, loop-invariant code motion, induction-variable simplification, scalar replacement of aggregates, function inlining, partial redundancy elimination. Each has its own paper or two.
The meta-question of pass ordering ("which order should we run optimisations in, and how often") is itself an active research area. The Cornell course CS 6120 (linked from further-reading.md) is the best free entry point.
Backend code generation
Our backend is a per-statement template. A production backend selects target instructions from an IR-level description, schedules them to use the pipeline efficiently, and allocates physical registers under tight constraints.
The major topics: instruction selection (greedy, BURS-style, or DAG-based), instruction scheduling (list scheduling, software pipelining), register allocation (graph colouring per Chaitin, linear scan, second-chance bin packing, SSA-based as in regalloc2).
LLVM's lib/CodeGen/ directory is the most readable production-grade implementation. GCC's RTL machinery is older and more opaque. Cranelift's regalloc2 is the most legible modern register allocator. OCaml's linear-scan implementation is the most pedagogically friendly.
Type systems
Almost every production compiler has a richer type system than INTERCAL's "spot, twospot, tail, hybrid". Modern type systems include polymorphism, subtyping, traits or interfaces, lifetime tracking (in rustc), effect tracking (in some research compilers), gradual typing (some Python tools).
The research literature is enormous. Pierce's Types and Programming Languages is the standard textbook. For specific systems:
- Rust ownership and lifetimes: the rustc-dev-guide chapters on Borrow Checking and the Polonius RFC.
- Haskell's System FC and constraint-based inference: Vytiniotis et al. 2011 on OutsideIn(X).
- Swift's constraint solver: Apple's documentation plus the Lattner papers on SIL.
- OCaml's Hindley-Milner: Didier Rémy's "Using, Understanding, and Unraveling the OCaml Language" (free PDF).
- Zig's comptime + types-as-values: Andrew Kelley's blog posts.
Concurrency, incremental compilation, IDE integration
A compiler that runs only as a batch job is a 1980s compiler. Modern compilers integrate with IDEs (via the Language Server Protocol or per-vendor protocols), respond to single-keystroke edits incrementally, and parallelise themselves across cores.
These concerns are mostly invisible in our INTERCAL compiler because the compiler runs in milliseconds and nobody types in INTERCAL inside an IDE. They will be the bulk of the work you see in production-compiler PRs.
The rustc-dev-guide chapter on Queries and Salsa is the best free explanation of how a modern compiler structures itself for incremental compilation.
Memory management strategies
Different compilers handle memory differently:
- No GC, type-system-managed: Rust (ownership + lifetimes).
- No GC, manual: C, C++, Zig (allocator-aware standard library).
- Reference counting, compile-time-inserted: Swift (ARC).
- Generational GC: Go, OCaml, GHC, V8.
- Concurrent GC: Go, V8 (concurrent marker), GHC (optional concurrent collector).
Each strategy comes with a runtime, a compiler-runtime contract (write barriers, safepoints, root-walking), and a particular set of tradeoffs (latency vs throughput, complexity vs predictability).
For a deep treatment, The Garbage Collection Handbook by Jones, Hosking, and Moss is the canonical reference. The shorter summary is in each compiler's runtime documentation.
JIT compilation
V8 is the only JIT in this Part. The world of JITs includes HotSpot (Java), LuaJIT, .NET CLR, JavaScript Core (Safari's), SpiderMonkey (Firefox's), GraalVM (Polyglot). Each has its own set of tiers, IRs, and design choices.
Key concepts: tiered compilation, on-stack replacement, inline caches, hidden classes (or the equivalent for non-JS dynamic languages), speculation + deoptimisation.
LLVM's ORC is its JIT subsystem; rustc has no JIT. GCC has JIT support via libgccjit. The closest analog to V8 outside V8 itself is HotSpot's C2 (which uses the same sea-of-nodes IR Cliff Click invented for both).
A reading plan from here
For somebody who wants to land a first patch on a production compiler within a couple of months:
- Pick one of the ten compilers in this Part. The selection criteria below help.
- Read the corresponding overview chapter.
- Read the project's own developer guide (rustc-dev-guide, GCC's gccint manual, LLVM docs, GHC commentary, etc.).
- Build the project locally. Allow a couple of hours.
- Find a "good first issue" or equivalent label. Read the issue, reproduce it, attempt a fix.
- Submit a PR or patch following the project's conventions.
A couple of months is a realistic timeline for a first patch. The first patch is the hardest. The book in your hands has done its job if reading the production compiler's source is no longer intimidating, just larger.
Selection criteria
If you have no preference, here is a rough ranking by approachability:
- Easiest to onboard: rustc (rustc-dev-guide is excellent), Cranelift (small codebase, welcoming community), Go (good docs, fast iteration).
- Most valuable for general compiler skills: LLVM (you will encounter it everywhere), Go (clean SSA backend with declarative rules).
- Deepest theoretical content: GHC (formal IRs, type theory), OCaml (Hindley-Milner, classical compiler design).
- Most distinctive niches: V8 (only JIT here), Swift (only SIL here), Zig (only comptime here).
- Industry adoption: LLVM, GCC, Go, rustc, V8 are all in production use at scale.
- Academic adoption: GHC, OCaml are the most studied in compiler-research papers.
What our INTERCAL compiler will never teach you
A few things this book deliberately does not cover. They become relevant only at production scale.
- Garbage collection. INTERCAL does not allocate. Every modern dynamic language compiler does. The standard reference is The Garbage Collection Handbook (Jones, Hosking, Moss).
- JIT compilation. Our compiler runs ahead of time only. JITs are most relevant in V8, HotSpot, LuaJIT, the .NET CLR. LLVM's ORC is its JIT subsystem; rustc has no JIT.
- Profile-guided optimisation. PGO collects runtime profiles and feeds them back into the next compilation to inform optimisation decisions. LLVM, GCC, Go, Swift all support it.
- Link-time optimisation. LTO defers some optimisations until the linker has visibility across translation units. LLVM (ThinLTO), GCC (lto1), and Swift (CMO) all support it.
- Polyhedral optimisation, vectorisation, autoparallelisation. Heavyweight numerical optimisations relevant to HPC. Polly (in LLVM) and Graphite (in GCC) are the open-source representatives.
- Lazy evaluation runtime. Specific to GHC (and a handful of research languages). Our compiler is strict.
- Speculation and deoptimisation. JIT-specific. Only V8 in this Part.
Each of these is its own subfield. A reader who has finished this book and wants to dive into one of them has the conceptual background to read the relevant Wikipedia page, follow the references, and go from there.
A skill ladder, week by week
The reading plan above answers "what". This section answers "what does my first month actually look like". Treat the schedule as a guide, not a contract. Some weeks compress; others stretch.
Week 1: vocabulary acquisition. Read this book's Parts I-V if you have not already. Run through the exercises in getting-started.md. Compile a few of tests/test_*.i and trace the output back to the source through intercalc.sh. By the end of the week you should be able to point at any line in intercalc.sh and say which phase of compilation it belongs to. The goal is fluency in the vocabulary: lexer, parser, semantic analysis, codegen, runtime.
Week 2: pick a target and build it. Choose one of the ten production compilers. Build the project from source as documented in contributing-to-production-compilers.md. Set aside a full day; it will take longer than you expect. Run the project's test suite. Verify your build can compile a hello-world in the project's source language. The goal is having a development environment that works.
Week 3: read your way around. Pick the corresponding overview chapter (llvm-overview.md, gcc-overview.md, rustc-overview.md, go-overview.md, ghc-overview.md, ocaml-overview.md, cranelift-overview.md, zig-overview.md, swift-overview.md, or v8-overview.md). Then read the project's own developer guide (rustc-dev-guide, gccint, LLVM docs, GHC Commentary). The goal is internal-vocabulary fluency: when you read "MIR" or "STG" or "SIL", you know what is meant.
Week 4: read source until something feels obvious. Pick a small subsystem and read it line by line until you understand it. Good first targets per project: a single LLVM pass under llvm/lib/Transforms/Scalar/; a single GIMPLE pass in GCC; a single MIR transform in rustc; a single SSA pass under cmd/compile/internal/ssa/ in Go; a single mandatory SIL pass in Swift; the regalloc2 spill heuristic in Cranelift; one Sema function in Zig. The goal is the moment when reading a function in the project's source feels like reading any other code, not like deciphering a foreign language.
Weeks 5-6: small contribution. Find a good first issue (or equivalent label) that touches the subsystem you read. Reproduce the bug locally. Write a failing test (every project requires this). Implement the fix. Run the test suite. Open the PR (or send the patch). Iterate on review feedback. The goal is your first merged change.
The whole sequence is six weeks of part-time work. Some people compress it to two; others stretch to six months. Either is fine.
Mental-model shifts
Moving from this compiler's codebase to a production compiler requires several mental shifts. Naming them up front shortens the adjustment period.
From "every line is comprehensible" to "you only ever see the part you are working on". Our intercalc.sh is 2,000 lines. You can read it in a sitting. LLVM, GCC, rustc are millions of lines. Nobody reads them top to bottom. Production-compiler work is "find the file, understand the function, leave the rest unread". The skill is locating the file fast. Project-internal documentation, dev guides, and git log for the area you care about are how you do this.
From "no IR" to "many IRs". Our compiler turns the parse tree directly into assembly. Every production compiler has at least one IR; some have four (rustc, GHC). Each IR has a purpose: name resolution, type checking, optimisation, codegen. Tracking which IR you are looking at, and what it does and does not contain, is a constant low-grade effort. Asking "is this MIR or HIR?" should be a reflex.
From "shell script glue" to "library architecture". Our compiler is a shell script with assembly templates. Production compilers are libraries with stable internal APIs, plugin points, and pass managers that orchestrate hundreds of transformations. The infrastructure is itself the bulk of the code; the actual transformations are often shorter. Reading "the architecture" is reading the pass manager, the IR builders, the analysis caches, the diagnostic system. The transformations sit on top.
From "one platform per build" to "every build is a target choice". We compile on macOS ARM64 or Linux ARM64 or Linux x86-64; the choice is the platform we are running on. Production compilers cross-compile by construction. Every build picks a target triple. Backends are selected per target. Calling conventions, ABIs, and instruction set details parameterise everything. A change that "works on my machine" can break on a target you have never personally seen.
From "we test functionality" to "we test invariants". Our tests run a compiled program and check stdout. Production compilers also do this, but layered on top of invariant tests: the IR after this pass is well-formed; the SSA invariants hold; the type checker accepts known-good programs and rejects known-bad; the borrow checker satisfies the formal properties of NLL. The bulk of the test infrastructure is invariant checking, not end-to-end functional testing. Adding a new pass means adding new invariant tests.
From "I understand every error" to "this error came from a system I have not seen". When something fails in our compiler, you can trace it to a specific zsh function in 20 minutes. In production compilers, failures cross subsystem boundaries. A bug in instruction selection might surface as a misoptimised loop reported by a user who is debugging their game. Diagnostic tools (LLVM's --debug-only=, rustc's -Z flags, Go's -d=ssa/<phase>=N) become essential. Learning the diagnostic surface is a project of its own.
From "the language is small" to "the language has a 30-year history". INTERCAL has fifteen statement types and four data types. C++ has hundreds of features, decades of accreted decisions, and ABI commitments to thirty years of binaries. The conservatism of production compilers reflects this. A change that "looks obvious" might break a kernel module compiled in 2010. The review process is calibrated for this risk.
Concrete bridges per compiler
Each compiler has specific exercises that bridge from "I read the chapter" to "I can edit the source". The exercises below are deliberately small. Each is doable in an afternoon if you know where to look. None requires submitting a patch.
LLVM bridge exercise
Goal: write your first LLVM pass.
- Build LLVM and Clang locally (see contributing-to-production-compilers.md).
- Pick
llvm/lib/Transforms/Utils/HelloPass.cpp(or the equivalent template) and study it. - Write a pass that counts the number of
addinstructions per function and prints the count. - Run it on
clang -O0 -c -emit-llvmoutput for a small C file. - Verify the count matches what
opt -print-instructionsreports.
The point is not the pass itself; it is the loop "edit C++, rebuild, run, iterate". By the time you have done this, you have absorbed the LLVM build system, the pass-manager API, the IR walking idioms, and the diagnostic flags. Future passes are variations on the same loop.
The closest analog in our compiler: writing a new function in intercalc.sh that walks stmt_* arrays and prints something. Same shape, different language.
Cranelift bridge exercise
Goal: write your first ISLE rule.
- Build Cranelift (
cargo build -p cranelift-codegen). - Open
cranelift/codegen/src/isa/x64/lower.isleand read existing rules until they feel familiar. - Pick a small operation (say,
iadd) and add a rule that recognises a specific pattern (e.g., adding zero) and rewrites it to a no-op. - Add a filetest in
cranelift/filetests/filetests/runtests/i32-add.clifthat triggers the rule. - Run
cargo test -p cranelift-filetestsand watch your rule fire.
The point is that ISLE is declarative: a pattern plus a result. Once one rule lands, every other rule is the same mental shape. Production-grade work in Cranelift is mostly adding such rules and refining heuristics.
The closest analog in our compiler: adding a constant-folding case in eval_const. Same shape (pattern: input form → output form), different syntax.
Go bridge exercise
Goal: write your first SSA optimisation rule.
- Build Go from source (
./make.bash). - Open
src/cmd/compile/internal/ssa/gen/generic.rulesand read the first 200 lines. - Add a rule that simplifies a pattern (start with something like
(Mul64 x (Const64 [1])) => x). - Run
go run gen/*.goto regenerate the rule-handler Go code. - Build the compiler and run
go test -run TestSSAto verify nothing breaks. - Compile a small program that triggers your pattern and dump SSA with
-gcflags='-d=ssa/opt=2'to see the rewrite happen.
Go's .rules files are conceptually the same as ISLE. The dialect differs but the shape is identical.
The closest analog in our compiler: adding a rule to the (currently small) peephole_optimize. We do peephole on emitted assembly text rather than on SSA, but the "match a pattern, rewrite it" idea is the same.
rustc bridge exercise
Goal: write your first MIR transformation.
- Build rustc (
./x.py build). - Open
compiler/rustc_mir_transform/src/simplify.rsand read it. - Pick a tiny structural simplification (e.g., remove unreachable blocks). Either improve an existing pass or write a new one in the same directory.
- Wire it into the pipeline in
compiler/rustc_mir_transform/src/lib.rs. - Add a regression test under
tests/codegen/that exercises the change. - Run
./x.py test tests/codegenand./x.py test tests/ui.
rustc's MIR transforms are straightforward Rust. The barrier is build time (the bootstrap), not the code itself.
The closest analog in our compiler: adding a new pass to the main() function in intercalc.sh. Same idea (transform after parsing, before codegen), production scale.
GHC bridge exercise
Goal: add a Core simplifier rule.
- Build GHC (
hadrian/build). - Open
compiler/GHC/Core/Opt/Simplify.hsand surrounding files. - Find an existing rule and read it carefully. The simplifier has hundreds; pick one that is small and self-contained.
- Write a regression test in
testsuite/tests/simplify/that exercises a simplification GHC currently does. - Run
hadrian/build test --only=simplify.
The simplifier is the heart of GHC's optimiser. Once one rule is comprehensible, the rest become tractable.
The closest analog in our compiler: eval_const constant-folding. Conceptually a tiny simplifier, operating on a tiny expression language.
OCaml bridge exercise
Goal: trace type inference on a tricky program.
- Build OCaml (
./configure && make). - Open
typing/typecore.ml. Findtype_expression. - Compile a small program with
-dtypedtreeto see the typed AST OCaml produced. Find an expression and trace it throughtype_expression. - Now write a program that triggers a polymorphic generalisation (e.g.,
let id x = x in ...). Trace through the level mechanism intyping/btype.ml. - Add a comment to the source explaining what you found.
OCaml's type checker is the canonical Hindley-Milner implementation. Reading it is reading the algorithm.
The closest analog in our compiler: check_politeness and check_labels. Conceptually they do the same kind of work (analyse properties of the parsed program), at a much simpler level.
Zig bridge exercise
Goal: trace one comptime evaluation through Sema.
- Build Zig.
- Write a tiny comptime function:
fn double(comptime x: u32) u32 { return x * 2; }. - Compile with
-femit-zirto see the ZIR. - Open
src/Sema.zigand find wheredoubleis called: search for the relevant operation handler. - Add a
std.debug.printcall inside Sema's handler formuland rebuild Zig. - Recompile your test program. You should see the print fire when the comptime call evaluates
2 * 2.
The point is that comptime is just Sema interpreting the IR. Once you have done one trace, the rest of Sema is the same kind of code.
The closest analog in our compiler: eval_const. We do a tiny version of Zig's comptime: walk the parse tree, evaluate sub-expressions where all operands are constant.
Swift bridge exercise
Goal: trace a SIL optimisation pass.
- Build Swift (allocate hours and ~50 GB).
- Compile a small Swift file with
-emit-siland look at the output. - Pick an optimisation (e.g.,
lib/SILOptimizer/Transforms/SimplifyCFG.cpp). Read the pass. - Modify a Swift program until you can see the pass change SIL output. Add a
// CHECK:comment for FileCheck. - Add the regression test under
test/SILOptimizer/.
Swift's SIL is the most semantically rich IR in this Part. Reading SIL output for a generic function with protocol witnesses is a course in itself.
The closest analog in our compiler: nothing direct. We have no IR. The lesson is conceptual: production IRs preserve language semantics, and passes operate on those semantics.
V8 bridge exercise
Goal: see speculation in action.
- Build V8 (
fetch v8 && cd v8 && gn gen out/x64.optdebug && ninja -C out/x64.optdebug). - Run d8 (the standalone V8 shell) on a script that has a hot loop with a polymorphic property access.
- Watch with
--trace-opt --trace-deopt. - Modify the script to break the IC's assumption (suddenly write a different shape). Watch the deoptimisation fire.
- Adjust the script until it exercises tier promotion: Ignition → Sparkplug → Maglev → TurboFan.
The point is to internalise that speculation is a compiler-runtime contract. The optimiser bets; the runtime collects the bet or pays out.
The closest analog in our compiler: nothing. AOT compilers do not speculate. The lesson is purely conceptual.
GCC bridge exercise
Goal: read one GIMPLE pass deeply.
- Build GCC (
./configure --enable-languages=c && make). - Open
gcc/tree-ssa-dce.cc. Read it. - Compile a small C program with
-fdump-tree-alland find the dead-code-elimination dump. - Modify the C source until you can see DCE remove a specific statement.
- Trace the removal in the GIMPLE dump.
The point is to learn how dumps tie source code to the IR. Once you can read GIMPLE dumps, every later GIMPLE pass is approachable.
The closest analog in our compiler: compute_flag_checks. We do a similar dataflow (per-statement analysis of "is this flag ever touched") with the result removing dead code.
What to read while building
A reading list ordered by when you are likely to need each item.
While picking a target compiler: each per-compiler chapter in this Part. They are deliberately self-contained.
While building the project: the project's developer guide. rustc-dev-guide is the gold standard; LLVM has the docs at https://llvm.org/docs/; GCC has gccint; GHC has the Commentary; Go has the in-source READMEs.
While reading source: the relevant overview chapter (in this book) plus the project's IR specification. LangRef.rst for LLVM. The MIR specification in rustc-dev-guide. The GHC Commentary's Core chapter. The SIL.md file in the Swift repo.
While writing your first patch: the project's coding style guide and contribution guide. Not optional. Production compilers reject patches that violate style on first review. Save yourself the back-and-forth.
For the long run: a textbook. Engineering a Compiler (Cooper and Torczon, 3rd edition 2023) is the modern reference. Modern Compiler Implementation in ML (Appel) is the academic counterpart. Read alongside the source as you encounter concepts in the wild.
Exit criteria for a first patch
You are ready to submit a first patch when:
- You can build the compiler in under five minutes from a clean tree (assuming a warm
ccache/incremental cache). - You can run the test suite for the area you are touching.
- You have read at least three previous patches in the same area, observed how they were structured, and learned the conventions.
- You can explain, in two sentences, what your patch does and what test would fail without it.
- You have a regression test that fails on
mainand passes with your patch. - You have read the project's contribution guide for the specific area.
If any of these are not yet true, you are still in the preparation phase. Do not rush. The cost of a thoroughly-prepared first patch is a week. The cost of an under-prepared first patch is a month of review thread, a withdrawn contribution, and a bruised relationship with the maintainers.
Cross-references to advanced techniques
The chapters that follow this one go much deeper into specific compiler techniques:
- techniques-we-use.md: every advanced technique present in this compiler, explained in production-compiler vocabulary. If you understand our
eval_const, you understand a slice of LLVM'sInstCombine. If you understand ourcompute_flag_checks, you understand a slice of GCC's tree-level DCE. The chapter names the correspondences. - techniques-we-lack.md: every advanced technique missing from this compiler, organised by phase. SSA construction, register allocation, garbage collection, JIT speculation, polyhedral optimisation. The chapter is a roadmap of the design space, with pointers into each production compiler that exemplifies a technique.
- improvement-proposals.md: twenty concrete proposals (eight Tier 1 quick wins, seven Tier 2 medium investments, five Tier 3 major undertakings) for which Part VII and Part VIII techniques to bring back to our compiler. Each proposal carries its own algorithm sketch, where in the codebase it would live, effort estimate, dependencies, test strategy, risks, educational value, and references.
Treat the four chapters (this one plus the other three) as the bridge in four layers: this one for the conceptual map, "we use" for "what you already know in production-compiler vocabulary", "we lack" for "what to read next", "improvement-proposals" for "what to actually do".
After the first patch: the medium term
The skill ladder above tops out at landing your first PR. Production-compiler engineering is a much longer game. The medium-term picture, organised by ambition.
The "ten patches" plateau
Most contributors plateau here. You have landed a handful of changes, are subscribed to the right mailing lists or labels, the maintainers know your name. Your changes are typically incremental: a missing pattern in instruction selection, a small correctness fix in a pass, an improvement to a diagnostic message. The work is satisfying and the cadence is sustainable.
The skill being honed at this stage is navigating the codebase quickly. By patch ten, you should be able to find any subsystem you have not yet touched in under five minutes via a combination of grep, mailing-list archives, git log -p, and the project's developer documentation. You should also have a rough mental map of who owns what, which areas welcome refactoring and which to leave alone, and what the maintainers' aesthetic preferences are (does this project like long names or short ones; does it run linters strictly; does the review process tolerate large diffs).
How to deepen at this stage: read other contributors' patches, especially the ones that get extended review discussions. The friction in the discussion is where the project's values surface. A patch that gets immediate approval taught you what was correct; a patch that took ten rounds of review taught you what is contentious.
The "owns a subsystem" plateau
A handful of contributors per project go further. They become the de facto owner of a subsystem: regalloc2 in Cranelift, the borrow checker in rustc, the inliner in LLVM, the constraint solver in Swift. The role is not formal in most projects (LLVM has no "owner" titles); the recognition emerges from sustained contribution.
The skill at this stage is system-level design. Reviews you give are no longer "this looks right"; they are "this changes the contract between the inliner and the optimiser; have you considered the case where the inlined function has effects?". Patches you write are not bug fixes; they are architecture changes that might span thousands of lines and require coordinating with several other subsystems.
How to reach this stage: pick a subsystem that is undersupported and adopt it. The path is not glamorous; you are reading old code, fixing technical debt, writing tests for things nobody tested, documenting things nobody documented. Two years of patient work in one subsystem usually produces ownership-level expertise; one year is rare.
The "designs a feature" plateau
A few contributors design new compiler features end to end: a new optimiser pass that did not exist; a new IR layer; a new type-system extension. This is rare and high-stakes; it requires alignment with the project's leadership, not just the code reviewers.
The skill at this stage is organisational design. You write an RFC. You convince several maintainers it is worth doing. You implement a prototype. You adjust based on review. You shepherd the feature to stable. The work is mostly meetings and writing, less coding.
How to reach this stage: be one of the recognised owners of a related subsystem first. The trust required to land a major design comes from years of credibility. Some projects have a more open process (Rust's RFC procedure, GHC's Haskell Foundation tech proposal); others are more closed (Apple drives Swift evolution from inside).
Maintaining a fork
A specific senior task that comes up often: maintaining a fork of a production compiler.
Reasons companies fork:
- Vendor patches: a chip vendor adds optimisations specific to their target before they are upstream.
- Stability lock-in: a downstream project pins to a known-good revision and backports critical fixes.
- Feature divergence: a product needs functionality not aligned with upstream priorities (e.g., heavy compile-time configuration).
- License-driven divergence: less common, mostly historical.
Notable forks in production:
- Apple maintains a fork of LLVM/Clang for Xcode, with patches that go upstream eventually but lag main.
- Google maintains internal LLVM/Clang forks, partly for stability and partly for security tooling.
- Many embedded vendors fork GCC for specific instruction-set extensions.
- Mozilla forked rustc briefly during the 2018 edition transition.
The skills involved:
- Cherry-picking upstream commits cleanly.
git cherry-pick -xto record provenance. - Conflict resolution when downstream patches and upstream changes touch the same files.
- Re-baseline strategy: how often do you rebase the fork on upstream
main? Yearly? Per-LLVM-release? Continuous? - Test infrastructure: a fork needs its own CI, often inheriting upstream test counts plus fork-specific tests.
- Communication with upstream: aim to land patches upstream over time so the fork shrinks.
For our INTERCAL compiler the analog is small but real: when somebody packages our compiler in a Linux distro, they are effectively maintaining a fork (with a delta of distro-specific build flags). The principles transfer.
Reading: Chromium's "How we maintain a fork of LLVM" blog posts; Apple's tracked fork in their public llvm-project mirror; GCC's vendor branches.
Backporting
A subset of fork-maintenance: bringing fixes from one branch to another. Production compilers have multiple branches in flight: main, release/X.Y for the current stable, release/X.Y-1 for the previous. A regression in stable means cherry-picking the fix from main to the release branch.
Conventions vary:
- LLVM has
release/<X>.xbranches with[X.x]prefixed PRs for backports. - rustc has stable, beta, and nightly. Most fixes land in nightly; some are explicitly nominated for backport via the
beta-nominatedandstable-nominatedlabels. - GHC has
ghc-X.Y-stablebranches. - Go's release process backports critical fixes to the previous two minor versions.
The trade-off: backporting a fix improves the stable release, but every backport is a divergence from main and a risk of new regressions. Maintainers are conservative.
For our INTERCAL compiler: we have one branch (main) and tags (v0.1.0). The lesson transfers if the project ever ships maintenance releases.
Designing new optimisations
Designing an optimisation that has not been built before is the most senior compiler-engineering task. Most production compilers have a hundred optimisations; the rare twentieth-or-so addition is a serious project.
The shape of the work:
- Identify a class of programs that are slower than they should be. Either by reading benchmarks (SPEC, PolyBench), profiling production code, or noticing a pattern that repeats in user-reported issues.
- Hypothesise an optimisation. The hypothesis must be both correct (preserves observable behaviour) and profitable (saves time or space measurably).
- Build a prototype. Single-pass implementation, narrow scope. Run on a small benchmark suite.
- Measure carefully. Optimisations almost always trade compile time for runtime. The trade-off must be net positive on representative code.
- Generalise. Handle all the edge cases the prototype skipped. Add tests for each.
- Submit. Expect deep review; the project's senior engineers will have opinions about whether your optimisation belongs in the canonical pipeline, with what cost model, in what phase order.
Examples of recent optimisation additions and the work they entailed:
- LLVM's LoopVectorize: years of incremental additions starting around 2013. Major rewrites multiple times. The current code is the work of dozens of contributors over a decade.
- rustc's GenericSpecialization improvements: ongoing for years, with each release tightening the specialiser.
- Cranelift's egraph optimiser: introduced in 2022 by Chris Fallin, replacing several smaller optimisers with one e-graph-based pass.
- Go's PGO support: introduced in Go 1.21, refined incrementally.
The lesson: senior optimisation work is a multi-year arc, not a single PR.
Influencing language design
The deepest level. The compiler is the language's implementation; whoever owns the compiler also influences the language. In open-source projects, this influence is usually shared with a language-design committee or a benevolent dictator.
How influence is exercised:
- Publishing RFCs (Rust's RFC repo, Swift's evolution repo, Haskell's prime track).
- Implementing experimental features behind unstable feature gates (rustc's
#![feature(...)], GHC's{-# LANGUAGE ... #-}). - Engaging in design discussions on the language's primary forum (rust-lang discourse, swift-evolution mailing list, haskell.org committee).
- Authoring papers that propose new features with prototypes (common in OCaml and Haskell history).
For somebody on this path, the compiler is the medium for a language-design conversation. The commits become arguments in the discussion. Effectiveness comes from the commits being correct, well-reviewed, and demonstrating the proposed feature works in practice.
For our INTERCAL compiler: the language is fixed by the 1972 specification. We do not get to influence INTERCAL. The lesson is conceptual: in projects where language design is alive, the compiler is the front line.
Long-term reading
A reading list for somebody who has reached the "owns a subsystem" stage and wants to deepen:
- Engineering a Compiler (Cooper and Torczon, 3rd edition 2023). The modern textbook reference.
- Modern Compiler Implementation in ML (Andrew Appel). The academic counterpart, goes deeper on type theory.
- Optimizing Compilers for Modern Architectures (Allen and Kennedy 2001). The reference for loop optimisation and vectorisation.
- The Garbage Collection Handbook (Jones, Hosking, Moss, 2nd edition 2023). The reference for runtime memory management.
- Advanced Compiler Design and Implementation (Muchnick 1997). Pre-SSA but still the reference for many classical algorithms.
- Types and Programming Languages (Pierce 2002). Type-system theory.
- Practical Foundations for Programming Languages (Harper, 2nd edition 2016). The deeper theoretical grounding.
Plus, depending on specialisation:
- Compiling with Continuations (Appel 1992) for functional-language back ends.
- Hacker's Delight (Warren 2nd ed.) for low-level bit manipulation, branchless code.
- Linkers and Loaders (Levine 1999) for the post-codegen world.
- Computer Architecture: A Quantitative Approach (Hennessy and Patterson 6th ed.) for the target side.
- Programming Language Pragmatics (Scott 4th ed.) for survey-level breadth.
Plus, conference proceedings:
- PLDI (Programming Language Design and Implementation) annually.
- POPL (Principles of Programming Languages).
- CC (Compiler Construction).
- CGO (Code Generation and Optimization).
- ICFP for functional-language work.
- OOPSLA for object-oriented and dynamic-language work.
Most major compiler features were proposed in one of these venues before being engineered into production. Reading current proceedings is reading where the next decade's compilers will go.
Compiler engineering specialisations in 2026
"Compiler engineer" is one job title hiding ten distinct careers. The skills overlap; the day-to-day work, target codebases, and hiring pipelines do not. A reader picking a track benefits from naming the choice early.
Frontend engineer
Lexers, parsers, name resolution, type checking, diagnostics. The work is closest to the early chapters of this book. A frontend engineer at Apple writes Clang's Sema; at rustc, the borrow checker and trait solver; at TypeScript, the structural-typing inference; at Swift, the constraint solver. Diagnostics quality is half the work; an unhelpful error message is a bug. Prerequisites: parsing, type theory, language semantics. Pierce's Types and Programming Languages is the standard text. Apple, Microsoft (TypeScript, C#), Mozilla, JetBrains (Kotlin) and the Rust project hire here.
Optimiser engineer
The middle end: SSA, dataflow, loop analyses, vectorisation, inlining, partial redundancy elimination. The work is reading benchmarks, hypothesising transformations, prototyping passes, fighting compile-time regressions. Optimiser engineers tend to congregate at LLVM (Apple, Google, ARM), GCC (Red Hat, SUSE, AdaCore), rustc, Go, and GHC. Prerequisites: SSA construction, dataflow analysis, the classical optimisation literature. Cooper and Torczon, then Muchnick.
Backend engineer
Instruction selection, register allocation, instruction scheduling, machine descriptions, calling conventions. The work parameterises by ISA: x86-64, ARM64, RISC-V, GPU dialects, custom accelerators. Vendor work dominates here. NVIDIA, AMD, Intel, ARM, Qualcomm, Apple Silicon all run large backend teams. Embedded vendors maintain GCC and LLVM forks for niche targets. Prerequisites: computer architecture (Hennessy and Patterson), the target's ISA reference, register allocation papers (Chaitin, Poletto-Sarkar, Wimmer linear scan, regalloc2 SSA-based).
Runtime engineer
Garbage collectors, schedulers, linkers, dynamic loaders, ABIs, exception handling. The runtime is half the language's behaviour at execution time. Go's GC team, V8's Orinoco, GHC's RTS, OCaml's runtime, .NET's CoreCLR, the JVM (Oracle, Azul, Amazon Corretto), Swift's ARC and concurrency runtime are all runtime engineering. Prerequisites: The Garbage Collection Handbook, knowledge of the target OS's memory model, lock-free programming.
ML compiler engineer
The fastest-growing track. Take a neural network expressed in PyTorch or JAX, lower it through MLIR or a custom IR, fuse operations, tile for the target's memory hierarchy, generate kernels for GPU, TPU, or NPU. The toolchains are XLA, TVM, IREE, Triton, Mojo, the Modular stack. NVIDIA, Google, Meta, Apple, Modular, Anthropic, OpenAI, Cerebras, Tenstorrent, AWS Annapurna, Groq, Graphcore, Qualcomm AI all hire heavily. Compensation is the highest in the field. Prerequisites: linear algebra, GPU programming (CUDA or its analogues), MLIR, plus standard compiler skills. The combination of compiler and ML background is rare; either alone is not enough.
GPU compiler engineer
Adjacent to ML compilers but distinct. The work is shader compilation (Vulkan, Metal, DirectX), CUDA backend, ROCm, ray-tracing intrinsics, warp-level optimisation. NVIDIA's NVPTX backend in LLVM, AMD's ROCm, Apple's Metal, Intel's compute stack. Prerequisites: SIMT execution, the target GPU's microarchitecture, divergence analysis, register pressure under massive parallelism.
Security and sanitizer engineer
ASan, MSan, UBSan, TSan, LSan, CFI, ShadowCallStack, fuzzing harnesses, hardening transformations. Compilers as the last line of defence. Google's sanitizer team, Apple's PAC and CFI work, Microsoft's CFG and CET enablement. Constant-time codegen for cryptography sits here too: the Clangover attack of 2024 showed that a compiler can turn constant-time source into secret-dependent machine code, opening cryptographic implementations to timing side-channels. Prerequisites: knowledge of common vulnerability classes, dynamic analysis instrumentation, the target's hardware-security features.
HLS engineer
High-Level Synthesis: compiling C, C++, or domain-specific languages to FPGA bitstreams. Xilinx (now AMD) Vivado HLS, Intel HLS, Cadence Stratus. The IR pipeline ends at hardware, not software. Smaller community than software compilers, but well-paid and aging slowly. Prerequisites: digital logic, Verilog or VHDL, polyhedral analysis for loop transformations.
Language designer
The track with the fewest jobs but the longest reach. Designs evolution proposals, drives RFC processes, shepherds feature acceptance. Most language designers are also senior compiler engineers; the job rarely exists in isolation. Apple drives Swift evolution from inside; Rust has an open RFC process; Haskell's GHC Steering Committee gates language extensions; the Go team is small and centralised. Prerequisites: years of credibility on the implementation side, plus writing skill.
Compiler verification engineer
Formal proofs that a compiler preserves semantics. CompCert (the verified C compiler) qualified for DO-178C avionics certification in March 2026. CakeML for ML. The CertiCoq line of work for Coq. The track is small but growing as safety-critical and cryptographic deployment forces more rigorous guarantees. Prerequisites: a proof assistant (Coq/Rocq, Lean, Isabelle), operational semantics, the published verification literature. Most jobs here are in research labs (INRIA, MPI-SWS) or at companies with regulated safety profiles (AbsInt, Galois, Adelard).
Industry hiring landscape
The CompilerJobs directory (mgaudet.github.io/CompilerJobs) tracks more than 200 organisations with compiler teams. The headline employers in 2026:
- Apple: Clang, LLVM, Swift, GPU compilers, JavaScriptCore. Multiple sites.
- Google: Go, V8, Dart, MLIR, Tink, internal LLVM forks for production.
- Meta: PyTorch compiler, HHVM, Cinder (Python), HipHop, BOLT, internal LLVM contributions.
- Microsoft: MSVC, C#, F#, TypeScript, the Rust compiler, Python acceleration.
- NVIDIA: PTX backend, Triton, MLIR, CUDA toolchain, deep-learning compilers. Listings open through 2026 for LLVM and MLIR engineers, with deep-learning compiler salaries quoted at 144k to 270k base for senior roles.
- AMD: ROCm, Vivado HLS, internal LLVM work, GPU codegen.
- Intel: oneAPI, ISPC, GPU compiler, classical x86 backend tuning.
- ARM: LLVM/GCC backend tuning for Neoverse and Cortex, autovectorisation.
- Qualcomm: NPU compiler stack, deep-learning toolchains, LLVM downstream.
- Mozilla: SpiderMonkey, contributions to Rust.
- Bytecode Alliance: Wasmtime, Cranelift, the WebAssembly Component Model. Cranelift is the entry-point recommendation for new compiler engineers in this Part because the codebase is small and the maintainers are welcoming.
- Modular: Mojo, MAX. ML-compiler-first company.
- Anthropic: language and compiler work supporting model serving and infrastructure.
- Cerebras, Tenstorrent, Groq, Graphcore, SambaNova: ML accelerator compilers.
- AWS Annapurna: Inferentia and Trainium toolchains.
- Jane Street: OxCaml, the internal OCaml fork.
- Embedded vendors: STMicro, NXP, Renesas, Espressif. Mostly GCC, increasingly LLVM.
Role expectations layer roughly:
- Entry-level / new grad: a CS degree (bachelor or master), an open-source contribution to a compiler or runtime project, comfort with C++ or Rust, and the textbook material from one of Engineering a Compiler, Modern Compiler Implementation, or a graduate course. Internships are the dominant pipeline; NVIDIA and Apple run large compiler-internship programmes, and most of the senior engineers came in that way. Total compensation in the US ranges roughly 130k to 200k for new-grad compiler roles at FAANG-tier companies, with stock and bonuses pushing the higher number.
- Mid-level (3 to 7 years): independent ownership of a subsystem (one inliner, one register allocator, one ISA backend), a track record of shipped patches reviewed by maintainers, and the ability to write design documents that hold up to scrutiny. Compensation 200k to 350k at established compilers companies, with a long tail higher at ML-compiler startups.
- Senior and staff: cross-subsystem design ownership, RFC authorship, the ability to mentor mid-level engineers and hold the codebase's invariants in their head. The job is mostly review, design, and dispute resolution. Compensation 350k to 700k+ at FAANG, with ML-compiler equity packages occasionally outpacing the rest.
The ratio of open positions to qualified candidates remains skewed toward demand. Compiler engineering is one of the few subfields where senior hires routinely command above-market offers because the supply of people who have shipped a working IR pass is small.
Reading academic papers effectively
Compiler engineering is one of the few industrial fields where the production code and the research literature share authors. A patch in LLVM's loop vectoriser is often the implementation of a recent paper. The skill of reading papers fluently pays back through the rest of the career.
The conferences worth tracking
- PLDI (Programming Language Design and Implementation): the flagship venue, annual. PLDI 2026 is in Boulder, Colorado, June 17 to 19. Compiler optimisations, IR designs, and implementation results dominate.
- POPL (Principles of Programming Languages): more theoretical, type systems, semantics, verification. POPL 2026 is in Rennes, France.
- OOPSLA: object-oriented, dynamic-language, GC and runtime work. Part of the SPLASH umbrella.
- CC (Compiler Construction): smaller, more focused on compiler-engineering papers without the theoretical heft.
- CGO (Code Generation and Optimization): backend, register allocation, instruction selection, profile-guided work. CGO 2026 is in Sydney, co-located with HPCA, PPoPP, and CC.
- ASPLOS: architectural support for programming languages and operating systems. The cross-cut between hardware and compilers.
- MICRO: microarchitecture. Less PL-focused but where many backend ideas originate.
- ICFP: functional programming. The natural home for GHC and OCaml work, plus type-system advances.
The PACMPL series (dl.acm.org/journal/pacmpl) publishes accepted papers from PLDI, POPL, ICFP, and OOPSLA in open-access form. ACM SIGPLAN sponsors the major venues; member access is cheap relative to the value.
How to skim a paper
The standard technique, attributed to S. Keshav, is the three-pass approach. The first pass takes ten minutes: read the title, abstract, introduction, section headings, conclusions, and skim the references. After this pass you should know what the paper claims, what kind of paper it is (theoretical, engineering, or empirical), and whether it is worth a second pass.
The second pass takes an hour. Read the paper end to end, pay attention to figures and tables, mark passages you do not understand. After the second pass you should be able to summarise the main thrust of the paper and its supporting evidence to somebody else.
The third pass takes several hours and is for papers you intend to implement or build on. Reconstruct the paper as if you were the author. Where would you have made different choices? What did the authors leave unsaid? At the end of the third pass you should be able to identify the paper's strengths and weaknesses and notice the assumptions the authors made implicitly.
For a working compiler engineer, most papers stop at the first pass. A handful per year merit the second; one or two a year the third.
Finding the implementation
Modern compiler papers usually come with code. The artifact-evaluation tracks at PLDI, POPL, OOPSLA and CGO publish reproducibility badges, and the artifacts themselves often live on GitHub or Zenodo. The conference's papers track lists each accepted paper with a separate "Artifact Available" badge; the badge links to the repository.
Outside the artifact track, search GitHub for the paper title or the authors' names. Production compiler patches often cite the paper number directly in the commit message; git log --grep="paper title" against LLVM, rustc, or GHC frequently finds the implementation. The Cliff Click sea-of-nodes paper, the Cytron SSA paper, the Chaitin register-allocation paper all have multiple implementations findable this way.
When the artifact does not run as advertised (a frequent outcome), the paper itself is usually still readable. The skill of reading the algorithm and reimplementing it from scratch is what most compiler-engineering work demands.
Open problems in compiler research circa 2026
Five or six themes dominate the current research landscape. Reading work in any of them is a credible specialisation.
AI-driven compiler optimisation
Meta released the LLM Compiler in 2024, a model trained on 546 billion tokens of LLVM IR and assembly, achieving 77% of the optimisation benefit of full autotuning search. Compiler-R1 and Reasoning Compiler, both from NeurIPS 2025, push reinforcement-learning agents into the pass-selection problem. The open question is whether LLM-driven optimisation can be made correct enough to ship in production toolchains; current systems generate incorrect code on large inputs frequently enough that human review or formal verification is required. The cross-pollination with verified-compiler research is active.
Verified runtime systems
CompCert verifies the compiler. The runtime it links against is conventional C. Recent work pushes verification into the runtime: verified GC (CertiKOS line, the Iris-based work), verified concurrency primitives, verified memory allocators. The motivation is that an unverified runtime undermines the verified compiler's guarantees. CompCert 3.17, released February 2026, integrates with the Rocq proof assistant; Cornell researchers used clightgen to formally verify a modular-inverse implementation in libsecp256k1, the cryptographic library underpinning Bitcoin.
Heterogeneous compute
CPUs, GPUs, TPUs, NPUs, FPGAs, and accelerators all coexist in modern systems. The compiler problem is taking a single high-level program and lowering it to multiple targets, partitioning work across them, and managing the data movement. MLIR is the platform of record; the open problems are how to express partitioning policies, how to schedule across heterogeneous memory hierarchies, and how to handle dynamic shape information without hand-tuning per target. ONNX Runtime, Apache TVM, IREE, and Modular MAX all sit in this space.
Energy-efficient codegen
The IEEE study "Program energy efficiency: the impact of language, compiler, and implementation choices" remains the canonical empirical reference. Distributed Green Compiler approaches save 30 to 40% of clock cycles via scheduling adjustments; EnerJ-style approximate computing can save up to 90% on permissive workloads. The open question is how to expose energy as a first-class optimisation objective alongside speed and code size. Most production compilers still treat it as a side-effect of speed optimisation.
Post-quantum cryptography compilation
NIST standardised Kyber, Dilithium, and SPHINCS+ between 2022 and 2024; deployment is now under way. The compiler problem is generating constant-time code for the new algorithms. The KyberSlash attack of late 2023 and the Clangover attack of 2024 both showed that compiler optimisations break constant-time guarantees written in source. liboqs (the Open Quantum Safe project) is the open-source reference implementation; production deployment requires careful coordination between the cryptographic implementation and the compiler. Active research targets compile-time verification that constant-time properties survive optimisation.
Formally-verified ABIs
The C ABI is specified informally per platform. Mismatches cause real bugs (the recent zlib 1.3 ABI break, the historical libstdc++ ABI churn). Recent work formalises ABIs at the level of register usage, alignment, exception unwinding, and TLS access. The CompCert qualification for avionics included a partial ABI formalisation. The open problem is unifying these per-vendor formalisations into a verified contract that linkers and dynamic loaders honour.
Persistent-memory codegen
Intel Optane shipped, then was discontinued; the persistent-memory programming model survives in CXL-attached storage and battery-backed DRAM. The compiler problem is reasoning about durability boundaries: which writes have committed to persistent storage, which have not, where to insert flush and fence instructions. PMDK and the C++ persistent memory programming model are the production targets.
War stories from production transitions
A handful of historical cases hold most of the lessons compiler engineers need. The patterns repeat.
Python 2 to 3 (2008 to 2020, twelve years)
The transition was announced with Python 3.0 in 2008 and effectively completed when Python 2.7 lost upstream support in January 2020. Twelve years from announcement to completion. The official rollout assumed the community would migrate quickly given automated tooling (2to3); the reality involved years of dual-version compatibility shims (six, __future__ imports), a long period of community uncertainty over whether Python 3 was the future, and large industrial codebases (Dropbox, Instagram) carrying the migration cost late into the 2010s. Guido van Rossum's own 2018 retrospective acknowledged that Dropbox's migration was still under way a decade after Python 3.0 shipped. Lesson: a migration that breaks every working program at the language-syntax level cannot be hurried by tooling alone. The community must be convinced and supported with libraries that work on both versions long enough for the dependency graph to migrate.
Go's compatibility promise (2012 to ongoing)
Go 1, released in March 2012, included an explicit compatibility promise: programs that compile against the Go 1 specification will continue to compile and run unchanged. Twelve years later the promise has held. The 2023 GODEBUG mechanism (Go 1.21) extends this further: subtle behavioural changes that the Go 1 promise permits are gated behind GODEBUG settings that programs can opt out of, with each setting maintained for at least two years and four releases. The result is that Go upgrades are routinely boring, which the team treats as the highest design virtue. Lesson: backward compatibility is not free; it requires a process for handling the genuine breaking changes that arise (security fixes, specification clarifications) without abandoning the promise. GODEBUG is the engineering mechanism that makes the philosophy work.
Rust 2018 edition (2018 onwards, ongoing)
Rust introduced the edition mechanism in 2018 to allow non-source-compatible language changes (new keywords, syntax shifts) without forking the ecosystem. Each crate declares its edition; editions interoperate at the compiled-library level. Migration is via cargo fix --edition, which mechanically rewrites code where it can. The 2018 edition migration shipped largely successfully, but the postmortems documented real friction: doctests are not auto-migrated, idiom lints sometimes give wrong suggestions, macros can generate code that does not work in the new edition, and corner cases requiring manual edits were common. The Rust team explicitly acknowledged that organisational project-management around editions needed improvement. Subsequent editions (2021, 2024) refined the process. Lesson: the edition mechanism is genuine progress over the Python 2/3 model, but only if migration tooling is honest about its limitations and the project commits to keeping editions interoperable indefinitely. Rust did both.
Swift 5 ABI stability (2019)
Swift 5 declared ABI stability on Apple platforms in March 2019. Before Swift 5, every app embedded the Swift standard library inside its bundle, because the runtime made no compatibility guarantee across compiler versions. After Swift 5, the runtime ships in the OS, app bundles shrank, and binary frameworks built with Swift 5.1 work in any project using Swift 5.1 or later (with the build settings configured for distribution). Module stability followed in Swift 5.1. Lesson: ABI stability is a one-way commitment with a long preparation phase. Apple spent years documenting the runtime layout, polishing the standard library, and writing the ABI Stability Manifesto before flipping the switch. The reward is permanent; the preparation is multi-year. Compilers that do not commit to ABI stability (rustc most prominently) cite the Swift example as the cost of doing it right.
C++ modules (2019 to ongoing)
C++20 standardised modules in 2019. Six years later, adoption is still partial: a 2024 community survey found only 29% of respondents allowing modules in their projects. Tooling support across GCC, Clang, and MSVC remains inconsistent; build-system integration with CMake, Bazel, and Meson is fragmented; third-party libraries lag because users lag because libraries lag. By 2026 the major compilers can build module-using code, but the chicken-and-egg problem persists. Lesson: language-level features that change the build model (rather than just the source language) face an ecosystem-coordination problem that is qualitatively different from migrating syntax. The C++ committee can standardise; only build-system maintainers can deploy.
GCC's switch to C++ (2008 to 2012)
GCC was implemented in C until version 4.8. The transition to C++ as an implementation language was announced in 2008, completed in 2012, and has been the status quo since. The move was contentious; long-time GCC contributors objected to the dependency on a more complex language. The benefits proved modest in performance (1 to 2% compile-time reduction on hash-table conversions) but significant in maintainability and contributor growth. Lesson: a compiler's own implementation language is a long-running political question, not just a technical one. The conversation took four years; the retroactive judgement is broadly that the move was correct, but the process taught GCC's leadership how to coordinate divisive changes through a community of long-tenured contributors.
The recurring pattern across all these stories: every successful transition combined three ingredients. A clear technical mechanism for migration (cargo fix, GODEBUG, ABI stability manifesto). A long timeline measured in years, not releases. And a credible commitment from project leadership to sustain the migration through to completion. Transitions that lacked any one of these (the early Python 3 rollout, C++ modules so far) accumulated cost without paying off.
Closing
The skill of reading a compiler is a smaller skill than the skill of writing one from scratch. This book has tried to teach both, by writing one from scratch and explaining each piece in plain enough language that the same vocabulary works on a much larger codebase.
The ten chapters of LLVM, GCC, rustc, Go, GHC, OCaml, Cranelift, Zig, Swift, and V8 are the bridge. Cross any one of them when you are ready.
LLVM, in shape
LLVM is the modular compiler infrastructure that powers Clang, Swift, Rust (by default), Julia, Crystal, and a long tail of language frontends and analysis tools. If you have used clang to compile C, you have used LLVM. The codebase lives at https://github.com/llvm/llvm-project.
This chapter is an orientation map. Enough to walk into the LLVM source tree and know what each directory is for, what to read first, and how the architecture maps to the smaller compiler in this repository.
The single most useful framing of LLVM is: it is not a compiler. It is a kit of compiler parts, with one IR connecting them, and a discipline that anything which speaks LLVM IR can be plugged in. Clang, rustc, Swift, and the rest are consumers of the kit, each contributing their own frontend and consuming the IR plus backends LLVM provides.
Three phases, one IR
LLVM organises a compiler into three phases connected by a single intermediate representation called LLVM IR.
- A frontend turns source code into LLVM IR. Clang is the C/C++/Objective-C frontend. The Rust compiler uses LLVM as a backend; its frontend produces a Rust-specific IR called MIR, which the Rust codegen layer then lowers to LLVM IR.
- A middle end runs optimisation passes on LLVM IR. The IR is the same regardless of source language, so the optimisations apply to every frontend.
- A backend lowers LLVM IR to machine code for a specific target (x86-64, ARM64, RISC-V, GPU, WebAssembly).
The big architectural idea is that a frontend and a backend never have to know about each other. Adding a new language means writing a frontend that emits LLVM IR. Adding a new processor means writing a backend that consumes it. Every existing optimisation comes for free.
In our compiler, the three phases collapse onto one host. The frontend, middle end (such as it is), and backend all live in intercalc.sh, and the IR is ad hoc: a parse tree in parallel arrays, used once and thrown away. LLVM trades that simplicity for the modularity that makes it usable across hundreds of language and target combinations.
What LLVM IR looks like
LLVM IR is a typed, low-level, SSA-form language that resembles a portable assembly. A trivial example:
define i32 @add(i32 %a, i32 %b) {
%r = add i32 %a, %b
ret i32 %r
}
The same IR can be printed as text (.ll), serialised as a binary bitcode file (.bc), or held in memory as a C++ object graph. About sixty instruction opcodes cover the ground from loads and stores through arithmetic, control flow, and aggregate manipulation. SSA form (each variable is assigned exactly once) makes most optimisation passes simpler to write.
Our INTERCAL compiler has nothing like this. Every statement becomes assembly directly, with no IR step in between. middle-end-and-optimisation.md explains why we made that choice and what it costs us.
LLVM IR in more detail
LLVM IR has a hierarchical structure:
- Module: a translation unit. One file in, one Module out. Contains functions, global variables, type declarations, metadata.
- Function: a single function. Contains basic blocks, parameter list, return type, attributes, debug info.
- BasicBlock: a maximal sequence of instructions with a single entry point and a single exit point (terminator). A function is a directed graph of BasicBlocks.
- Instruction: an SSA operation, with operands (other Values) and a result Value (or void).
- Value: anything that can be referenced as an operand. Includes Instructions, Constants, function arguments, basic block addresses, etc.
Types in LLVM IR are explicit:
- Integers
i1,i8,i16,i32,i64,i128, with signedness expressed by the operation rather than the type. - Floating-point:
half,float,double,fp128, and a few platform-specific exotics. ptr(opaque pointer, since LLVM 15; before that, typed pointers likei32*carried the pointee type).- Aggregate types: arrays
[N x T], structs{T1, T2, ...}, vectors<N x T>. - Function types
T (Args). - Metadata
!Nfor non-semantic information attached to instructions.
The opaque pointer transition is itself a useful piece of LLVM history. Until LLVM 15, pointers carried their pointee type, which seemed natural but was the source of many bugs (loads would type-mismatch with stores in subtle ways during optimisation). The IR was changed to make pointers untyped; loads and stores carry their type explicitly. The transition took years and required rewriting many optimisation passes.
Memory model: LLVM IR has a memory model based on C/C++11. Loads and stores can be marked atomic with an ordering (relaxed, acquire, release, acquire-release, sequentially-consistent). Non-atomic accesses can race; atomic accesses cannot.
SSA with a twist: LLVM IR uses explicit alloca instructions in function entry blocks plus load/store to model variables that have addresses. This avoids requiring the frontend to insert phi nodes for normal local variables. The mem2reg pass promotes alloca'd locals to SSA registers when possible, eliminating the loads and stores. This is a famous trick: frontends emit "easy" IR, the optimiser cleans it up.
The pass manager
LLVM optimisations are organised as a pipeline of passes, each a class that takes an IR module (or function, or basic block) and rewrites it. The pass manager runs them in a configured order. Some examples:
- Constant folding (we do a tiny version of this in
eval_const). - Dead-code elimination (we have a dedicated form for the abstain flag).
- Common subexpression elimination, loop-invariant code motion, induction-variable simplification, register promotion of stack slots.
- Inlining, scalar replacement of aggregates, sparse conditional constant propagation, global value numbering.
- Vectorisation, loop unrolling, auto-vectorisation.
LLVM has had two pass managers in its history. The Legacy Pass Manager (LPM) was the original, used until LLVM 13. The New Pass Manager (NPM) was developed in parallel since 2015 and became default in 2021. Both still ship; LPM is being phased out.
The differences matter for somebody reading or writing LLVM passes:
- LPM: passes inherit from
FunctionPass,ModulePass,LoopPass, etc. Order and analysis dependencies are declared viagetAnalysisUsage. - NPM: passes are mixin classes implementing
run(Function&, FunctionAnalysisManager&)and friends. Analysis caching is more explicit. Pipeline construction is more flexible (aPassBuilderproduces the pipeline programmatically).
A typical pipeline at -O2 runs roughly 200 passes, in carefully chosen order, often with several passes repeated. The default pipeline is built in llvm/lib/Passes/PassBuilderPipelines.cpp. For somebody learning the optimiser, reading that file is the fastest way to see what production really runs.
The phases of the pipeline:
- Early simplification:
mem2reg,simplifyCFG,instcombine. Cleans the frontend's output. - Canonicalisation: bring code into a normalised form so later passes can pattern-match.
- Scalar optimisations: CSE, GVN, SCCP, DCE. The classical optimisations.
- Loop optimisations: LICM, indvar simplification, loop unrolling, loop vectorisation.
- Inlining + interprocedural: function inlining, argument promotion, dead-argument elimination.
- Late simplification: clean up after inlining.
- Vectorisation: SLP and loop vectorisers.
- Lowering: prepare for backend.
Each phase has multiple passes; the order within a phase is itself a topic. Adding a new optimisation usually means inserting it in the right place, which depends on what the surrounding passes need to see.
A new pass is a few hundred lines of C++ that subclasses one of the pass base classes and overrides runOnFunction or its newer pass-manager equivalent. Reading an existing pass is the standard way to learn how to write one. llvm/lib/Transforms/Scalar/ is a good directory to browse for short, self-contained examples. ADCE.cpp (Aggressive Dead Code Elimination), ConstantHoisting.cpp, GVN.cpp, SimplifyCFG.cpp are all approachable.
Backends: SelectionDAG and GlobalISel
LLVM has two complete backend infrastructures, coexisting:
SelectionDAG is the original. Pipeline: LLVM IR → SelectionDAG → SelectionDAG (legalised) → SelectionDAG (combined) → MachineInstr → MCInst → object file.
The DAG is a directed acyclic graph representation of one basic block at a time. Pattern-matching during selection picks instructions from the target's instruction set, with patterns specified in TableGen. Multiple per-target passes (legalize, combine, select) progressively narrow the DAG until everything maps to a target instruction.
SelectionDAG is the way most older LLVM backends do instruction selection. The downside: per-block scope limits the optimisations possible during selection, and global decisions (register allocation, instruction scheduling) happen on the post-DAG MachineInstr representation.
GlobalISel is the newer infrastructure, started around 2016. Pipeline: LLVM IR → MIR (Machine IR, generic) → MIR (legalised) → MIR (regbank-selected) → MIR (instruction-selected) → object.
GlobalISel works on Machine IR (an SSA-form IR with target-generic operations) throughout. Each pass is explicit (not a phase of the DAG). The result is more uniform across targets and amenable to global optimisations during selection.
Adoption: AArch64 uses GlobalISel by default at -O0 only; SelectionDAG remains the default at higher optimisation levels. x86-64 and others are gradually transitioning. Some targets still use only SelectionDAG.
For a reader, the contrast between the two is illuminating. SelectionDAG is older and has more accumulated wisdom; GlobalISel is newer and has cleaner architecture. Both are still in production. The transition is a multi-year effort.
TableGen
A unique LLVM technology: TableGen is a domain-specific language for describing target machines. It is used for instruction definitions, register sets, calling conventions, instruction scheduling, and pattern-matching rules.
A TableGen instruction definition looks like:
def ADD32rr : I<0x01, MRMDestReg, (outs GR32:$dst),
(ins GR32:$src1, GR32:$src2),
"add{l}\t{$src2, $dst|$dst, $src2}",
[(set GR32:$dst, (add GR32:$src1, GR32:$src2))]>;
That is the x86 ADD32rr (32-bit register-to-register add) instruction. The fields name encoding bits, operand classes, assembly text, and a SelectionDAG pattern. The TableGen compiler reads files like this and produces C++ that LLVM links.
TableGen is large. The x86 backend's TableGen sources alone are ~50,000 lines describing every x86 instruction LLVM supports. Reading TableGen is its own skill; the syntax is dense and the resolution rules are non-obvious. The benefit is that the same description drives instruction selection, encoding, scheduling, disassembly, and assembly parsing. A single source of truth for "what does this CPU do".
For a reader, TableGen is one of LLVM's distinctive features. The same idea is reinvented elsewhere (Cranelift's ISLE, Go's .rules files, GCC's machine descriptions) but TableGen is the most baroque and the most complete.
Register allocators
LLVM ships multiple register allocators, selectable per build:
- greedy (default): the production allocator, sophisticated, written for code quality.
- basic: simpler, mostly historical.
- fast: very fast, low quality, used in
-O0debug builds. - PBQP: a partitioned-Boolean-quadratic-programming allocator, more research than production.
The greedy allocator is the heart of -O2 codegen. Algorithm sketch: prioritise live ranges by spill cost; for each, try to assign a register; if conflicts arise, split the range or spill it. The algorithm is not pure graph-colouring (Chaitin's classical formulation); it is "register allocation as a sequence of decisions ordered by priority".
For a reader who wants to learn register allocation, the LLVM greedy allocator is large (>10,000 lines) and dense. Cranelift's regalloc2 is more legible; OCaml's linear-scan is the simplest production example. Reading them in that order is a good progression.
MC layer
The MC layer (llvm/lib/MC) handles low-level encoding and decoding of instructions. It is what turns MachineInstr into bytes (or assembly text), and what parses assembly text back into MachineInstr.
Why a separate layer? Because there are many places where instruction-level work happens: the assembler (llvm-mc), the disassembler, the inline assembler in Clang, the JIT (which encodes instructions directly to memory), the integrated assembler (which emits object code from LLVM directly without going through as).
The MC layer is a clean abstraction over "instruction in bytes vs instruction in text vs instruction as a structured object", with each consumer parameterising what it needs.
MLIR: the IR generalised
MLIR (Multi-Level IR) was added to the LLVM project in 2019 and is now the centre of LLVM's research and ML-systems work. It is a framework for describing IRs, with multiple "dialects" coexisting in the same module.
The key ideas:
- A dialect is a namespace of operations. The
arithdialect hasarith.addi,arith.mulf. Theaffinedialect hasaffine.for,affine.if. Thelinalgdialect has high-level linear-algebra operations. Each dialect has its own semantics. - Dialects can be lowered into other dialects.
linalglowers toaffine,affinelowers toscf,scflowers to standard control flow, eventually everything lowers to LLVM dialect, which is one-to-one with LLVM IR. - The same MLIR module can simultaneously contain multiple dialects, each capturing the right level of abstraction for the part of the program it describes.
Production users in 2024-2026:
- TensorFlow/XLA: tensor-algebra compilation, the original MLIR motivation.
- Mojo (Modular's AI language): AOT compilation through MLIR all the way down.
- Clang IR (CIR): experimental MLIR-level representation of Clang's AST. The long-term play is for some Clang front-end work to operate on CIR rather than directly on the AST.
- Flang: the Fortran frontend uses MLIR for its high-level IR (FIR dialect) and lowers to LLVM IR.
- IREE: ML compiler that targets multiple backends through MLIR.
- CUDA Tile: NVIDIA's tile-based GPU compilation.
The most-influential built-in dialects: arith, memref, affine, scf, func, gpu, tosa, linalg, and llvm (the last is one-to-one with LLVM IR). The 2026 EuroLLVM round tables surfaced a series of design discussions on assembly/ISA-level dialects, MLIR canonicalisation, EmitC (lowering MLIR to readable C source), and early-exit semantics for regions, all of which point at MLIR being increasingly used for very low-level work that LLVM IR alone could not represent cleanly.
A new ABI library started landing in 2026 with ABITypeMapper and ABIRewriteContext as dialect-agnostic bridges to LLVM's lowering. The motivation: ABI-correct lowering is target-specific complex code that has been duplicated across frontends; the new library centralises it.
For a reader, MLIR is the next step beyond "IR design". It generalises the idea of "lower from one IR to another" into a framework, parametrising both the source and target IRs. The dialect and lowering machinery is a useful study even if you do not immediately need to use MLIR. The most accessible entry point is the official MLIR tutorial on building a Toy language.
Subprojects
The LLVM project (llvm-project) is now a monorepo containing multiple related subprojects:
- llvm/: the IR, optimiser, backends, MC layer.
- clang/: C/C++/Objective-C/CUDA/HIP/HLSL frontend.
- clang-tools-extra/: clang-tidy, clang-format, clang-include-fixer.
- lld/: the LLVM linker, drop-in replacement for ld with much better speed.
- lldb/: the LLVM debugger.
- compiler-rt/: runtime libraries (sanitisers, profile, builtins).
- libcxx/: C++ standard library.
- libcxxabi/: low-level C++ runtime support.
- libunwind/: stack unwinding.
- mlir/: Multi-Level IR.
- flang/: Fortran frontend.
- polly/: polyhedral loop optimiser.
- bolt/: Binary OptimisaTion (post-link binary optimiser; profile-guided basic-block reordering for already-compiled binaries).
- openmp/: OpenMP runtime.
- libc/: an experimental LLVM-based libc.
- cross-project-tests/: integration tests across subprojects.
Each subproject is a candidate for its own chapter in a more ambitious treatment. For our purposes, knowing they exist and what they do is enough.
Repo layout, briefly
The main directories in llvm-project:
clang/ The C/C++/Objective-C frontend
llvm/ The middle end and backends
lib/IR/ The IR data structures
lib/Transforms/ Optimisation passes (Scalar, IPO, Vectorize, ...)
lib/CodeGen/ Target-independent backend infrastructure
lib/Target/<arch>/ Per-target backend (X86, AArch64, RISCV, AMDGPU, ...)
lib/Analysis/ Analyses passes use (alias, scalar evolution, ...)
lib/MC/ Instruction-level encoding/decoding
lib/Passes/ Pipeline construction
docs/ User-facing documentation
utils/TableGen/ The TableGen compiler
lld/ The LLVM linker
lldb/ The LLVM debugger
mlir/ Multi-Level IR
flang/ The Fortran frontend
polly/ Polyhedral loop optimisations
bolt/ Post-link binary optimiser
libcxx/, libc/ Runtime libraries
Most of what a beginner cares about is in llvm/lib/Transforms/ (passes), llvm/lib/Target/ (backends), and clang/lib/ (the C++ frontend). The docs/ directory has a reference for every feature; llvm/docs/LangRef.rst is the IR specification.
How LLVM compares to our INTERCAL compiler
| Aspect | INTERCAL compiler (this repo) | LLVM |
|---|---|---|
| IR | None (parse tree only) | LLVM IR, SSA-form, typed |
| Frontends | One (INTERCAL) | Many (Clang, rustc, Swift, ...) |
| Backends | Two (ARM64, x86-64) | Many (X86, AArch64, RISC-V, GPU, WASM, ...) |
| Optimisations | Constant folding, dead-flag elimination, peephole | Hundreds of passes |
| Codebase size | ~2000 lines zsh + a few thousand lines assembly | ~35 million lines total monorepo (~10M C++ source proper) |
| Build | cc -x assembler - | CMake + ninja, ~30 minutes |
The right way to read this table is not "INTERCAL is small, LLVM is big" but "everything LLVM does, our INTERCAL compiler also does, just at orders of magnitude less effort, with orders of magnitude less to optimise". The same conceptual machinery is in both.
If you only read five files
When approaching LLVM for the first time, the following five give the broadest grounding:
llvm/lib/Passes/PassBuilder.cpp: the new pass manager, the entry point that constructs the optimisation pipeline.llvm/include/llvm/IR/Instructions.h: the IR vocabulary as C++ classes.mlir/lib/IR/Operation.cppplusmlir/include/mlir/IR/OpDefinition.h: the MLIR operation model.bolt/lib/Rewrite/RewriteInstance.cpp: the BOLT post-link optimiser's pipeline entry.clang/lib/Sema/SemaExpr.cpp: where most user-visible Clang diagnostics live.
Common contributor gotchas
Avoidable first-PR mistakes that come up frequently in LLVM review:
- Forgetting to update one of the parallel builder/visitor enums when adding a new Instruction.
- Mismatched
LLVM_ENABLE_PROJECTSversusLLVM_ENABLE_RUNTIMESfor compiler-rt and libcxx. - Assuming MLIR ops auto-roundtrip; you must add
assemblyFormator a custom parser. - BOLT requires
-Wl,-q(relocations preserved) at link time; without it BOLT cannot operate. opt -O2no longer accepts the legacy pass manager flags. Use-passes='...'syntax with the new PM.
Area specialists in 2025-2026
Following these contributors' commits and blog posts is a fast education in their respective subsystems:
- Nikita Popov (middle-end, InstCombine).
- Florian Hahn (LoopVectorize, VPlan).
- Mehdi Amini (MLIR).
- Maksim Panchenko and Amir Ayupov (BOLT).
- Aaron Ballman (Clang Sema).
- Fangrui Song / MaskRay (lld, ELF, linker matters).
Diagnostic flags worth knowing
Beyond -print-after-all:
opt -passes='print<...>'for analysis dumps.--print-changed=quiet: only show passes that change IR.llvm-reduce: the modern replacement forbugpoint. Reduces a failing test case to a minimal reproducer.--debug-only=<pass>(requires-DLLVM_ENABLE_ASSERTIONS=ON).clang -mllvm -opt-bisect-limit=N: binary searching miscompiles.MLIRContext::disableMultithreading(): makes MLIR crashes deterministic.
For MLIR specifically: mlir-opt --mlir-print-ir-after-all --mlir-print-ir-before-all --mlir-disable-threading.
How to read LLVM source for the first time
A short order of attack:
- Read
llvm/docs/LangRef.rstto learn the IR vocabulary. Roughly the same effort as reading our appendix-grammar.md. - Browse
llvm/lib/Transforms/Scalar/for a small pass likeADCE.cpp(Aggressive Dead Code Elimination) orConstantHoisting.cpp. Each is a self-contained ~500-line file. - Read one of the per-target backends.
llvm/lib/Target/RISCV/is comparatively new and concise. - For Clang, start with
clang/lib/Parse/Parser.cppto see a real recursive-descent parser at production scale. A pleasant continuity with our parser-theory.md. - For the pass manager, read
llvm/lib/Passes/PassBuilderPipelines.cppto see what-O2actually does. - For TableGen, pick a small target description like
llvm/lib/Target/RISCV/RISCV.tdand trace a simple instruction definition.
How to contribute
Since late 2023, LLVM uses GitHub PRs as the recommended tool. Phabricator went read-only in October 2023 and the server was shut down in October 2024. The contributing flow:
git clone https://github.com/llvm/llvm-project
cd llvm-project
git checkout -b my-fix
# ... edit, test ...
git push fork my-fix
# open PR on GitHub
Reviewers are subscribed by area; tag the right ones based on the file paths you touched. Every patch needs at least one approval before merge. Style is enforced by clang-format. Tests live in llvm/test/ (lit-based, FileCheck-driven) or clang/test/ etc.
Beginner-friendly issues are tagged good first issue on https://github.com/llvm/llvm-project/issues. Categories:
- Documentation patches.
- Small optimiser bugs (often missing patterns in
InstCombineorSimplifyCFG). - Missing diagnostics or improved diagnostics in Clang.
- TableGen rule additions (target-specific instruction selection).
- Simple test additions.
LLVM has a Discourse forum at https://discourse.llvm.org/ where new contributors ask questions and architecture discussions happen.
Where to go next
- The official Getting Started with LLVM page if you want to build LLVM locally.
- The Architecture of Open Source Applications: LLVM, an essay by Chris Lattner, the original LLVM author. Ten pages, very readable, complements this chapter.
- The LLVM Developer Meetings (twice yearly, on YouTube) for talks on every part of the project.
- LLVM Weekly newsletter at https://llvmweekly.org/ for the active development cadence.
- "Engineering a Compiler" by Cooper and Torczon for the textbook treatment of what LLVM does.
- contributing-to-production-compilers.md for how to land a first patch.
- cranelift-overview.md for the deliberate counterpoint to LLVM.
- gcc-overview.md and rustc-overview.md for the two compilers most beginners will reach for next.
GCC, in shape
GCC is the GNU Compiler Collection, the original free-software compiler suite. It has compiled most of the Linux kernel, most of the GNU userland, and a sizeable fraction of every Unix-shaped piece of software for thirty-five years. Its source lives at https://gcc.gnu.org/git.html (mirrored on GitHub at https://github.com/gcc-mirror/gcc).
LLVM is the modular newcomer. GCC is the older system that was already there, and its design is correspondingly different. The single most important difference: GCC uses three intermediate representations stacked on top of each other, not one.
The three IRs
A C source file goes through this pipeline inside GCC:
source → AST → GENERIC → GIMPLE → RTL → assembly
Each arrow is a translation pass, sometimes a sequence of them. Each box on the left is more abstract; each box on the right is closer to the target machine.
- GENERIC is the language-independent abstract syntax tree. The frontend (C, C++, Fortran, Ada, Go, D, Rust-via-gccrs) produces GENERIC trees that capture the program's shape and types. GENERIC is still recognisably what the user wrote: scopes, expressions, declarations.
- GIMPLE is a three-address form derived from GENERIC. Every expression is broken down into operations of at most three operands, and control flow is normalised. This is where most language-independent optimisations happen: constant propagation, dead-code elimination, loop transformations, vectorisation, link-time optimisation. GIMPLE itself has multiple sub-forms (high gimple, low gimple) that progressively expose more of the eventual machine model.
- RTL (Register Transfer Language) is GCC's low-level IR. It is much closer to the actual instruction set and is where instruction selection, register allocation, and scheduling happen. RTL describes individual machine operations with precise side-effect information, drawn from each target's
.mdmachine description file.
Compare with LLVM, which has only LLVM IR between frontends and backends. GCC's choice means more translation steps, but also more places to apply optimisations at the right level of abstraction.
GENERIC in detail
GENERIC is GCC's language-independent tree-form IR. Each node is a tree, a tagged union represented at the C level as a pointer with type tag bits.
What GENERIC captures:
- Declarations (variables, functions, types, namespaces).
- Expressions (binary, unary, calls, references, conversions).
- Statements (compound, if, loops, returns).
- Types (integer, floating, pointer, struct, function, ...).
- Scopes and bindings.
The shape preserves the source-level structure. A C if (a < b) x++; else y++; becomes a COND_EXPR node with three children. A C++ template instantiation produces GENERIC trees for the instantiation.
What is unusual: GENERIC is the same data structure regardless of source language. All of C, C++, Fortran, Ada, Go, D produce GENERIC. Each frontend may extend the node set with language-specific nodes, but the core tree representation is shared. This is part of what enables language interoperability in GCC: the runtime FFI layers can be expressed in GENERIC.
Because GENERIC stays close to the source, it is not optimised aggressively. Most algorithmic work happens after lowering to GIMPLE.
GIMPLE in detail
GIMPLE is GCC's three-address IR. The lowering from GENERIC to GIMPLE is called "gimplification" and happens in gcc/gimplify.cc. The job of gimplification: take the structured tree representation and break it into simple statements with at most three operands.
GIMPLE has three sub-forms:
- High GIMPLE: structured control flow (compound statements, if/else, loops) is preserved. Easier to transform without losing source-level reasoning.
- Low GIMPLE: control flow is lowered to gotos and conditional gotos; structured constructs are gone. Closer to the eventual control-flow graph.
- SSA GIMPLE: variables are renamed so each definition is unique. Phi nodes appear at control-flow joins. This is where most optimisations operate.
GIMPLE statements are simpler than GENERIC nodes: an assignment t = a + b * c decomposes into tmp = b * c; t = a + tmp. The result is a flat list of three-address operations within each function.
Conversion to SSA: GCC's algorithm is a variant of Cytron-style iterated dominance frontiers, but with refinements specific to GIMPLE (handling memory references, partial updates, variable scoping). The implementation lives in gcc/tree-into-ssa.cc.
GIMPLE optimisation passes
The list of GIMPLE-level optimisations in GCC is enormous. Around 250 passes are defined in gcc/passes.def, organised into a pipeline.
The categories:
- Tree-SSA passes: operate on SSA-form GIMPLE. CCP (constant propagation), DSE (dead store elimination), DCE (dead code elimination), DOM (dominator-based optimisations), VRP (value range propagation), reassoc (associative reordering), forwprop (forward propagation), backprop (backward propagation), TER (temporary expression replacement).
- Loop optimisations: LIM (loop-invariant motion), unroll, ivcanon (induction variable canonicalisation), vect (vectoriser), parloops (auto-parallelisation), graphite (polyhedral, optional).
- Inter-procedural (IPA): cross-function passes.
- Lowering passes: progressively lower abstractions (e.g.,
expand_omp_forfor OpenMP loops).
Reading a single GIMPLE pass is approachable. Reading the whole pipeline is a long-term project.
IPA: inter-procedural analysis
What distinguishes GCC's middle-end is the depth of inter-procedural analysis. IPA passes see the entire program (or a large chunk of it via LTO) and reason across function boundaries:
- inline: function inlining. Heuristic-driven, cost-modelled, with feedback from later passes.
- cp (constant propagation across calls): if a function is always called with the same constant argument, propagate it.
- devirt (devirtualisation): determine which virtual function call resolves to which concrete callee, replace indirect calls with direct ones.
- icf (identical code folding): merge functions with identical machine code.
- pure-const: classify functions as pure (no side effects) or const (no observable behaviour beyond return value), enabling further optimisations at call sites.
- sra (scalar replacement of aggregates): split a struct argument into separate scalar arguments when only some fields are used.
- fnsplit: split a function into hot and cold parts to improve inlining decisions.
- WHOPR (Whole-Program Optimisation): the LTO pipeline. Partitions the program for parallel optimisation, runs IPA across all partitions, merges results.
LTO in GCC predates LLVM's by years. The relevant flag is -flto. The pipeline is sufficiently mature that GCC LTO is the default for many production Linux distros.
For a reader, IPA is the area most clearly distinguishing GCC from LLVM. LLVM has IPA passes (lib/Transforms/IPO/) but the framework is less developed; GCC's IPA infrastructure has decades of polish.
RTL in detail
After GIMPLE optimisation, GCC lowers to RTL: Register Transfer Language. This is the low-level IR.
An RTL expression looks like:
(set (reg:SI 100) (plus:SI (reg:SI 101) (const_int 1)))
Read aloud: "set the 32-bit register 100 to the sum of register 101 and the constant 1". The Lisp-like syntax is original; RTL was modelled on a 1980s register-transfer notation.
RTL has two phases:
- Pre-reload RTL: uses pseudo-registers (virtual registers, unbounded numbering). Optimisations like CSE, GVN, jump optimisation, loop optimisation operate here.
- Post-reload RTL: physical registers assigned. Spill code inserted. Closer to assembly.
The transition is driven by register allocation. Until 2013, GCC used a pass called "reload" that rewrote pre-reload RTL to post-reload RTL by allocating registers and inserting spills. Reload was complicated and a frequent source of bugs. In 2013, GCC introduced LRA (Local Register Allocator) as a simpler replacement. LRA is the default register allocator now.
RTL passes in roughly the order they run:
- expand: GIMPLE to RTL, the initial conversion.
- cse: common subexpression elimination on RTL.
- combine: combine multiple RTL instructions into one when the target supports it. The famous "combiner" pass.
- mode-switching: insert mode changes (e.g., x87 floating-point control word).
- regmove: move pseudo-registers to make register allocation easier.
- ira/lra: register allocation.
- postreload: post-allocation cleanup.
- machine-reorg: per-target reorganisation (e.g., delay slot filling on architectures that have them).
- final: emit assembly.
For a reader, RTL is harder to read than LLVM IR. The Lisp-like syntax is unfamiliar; the side-effect semantics are subtle (RTL expressions describe what happens, with explicit sets, but also implicit modifications via attributes); the per-pass mutations are intricate.
The reward for reading RTL: GCC can describe target-specific behaviour at this layer in ways LLVM IR does not naturally support. Conditional execution on ARM, predicated execution on Itanium, x86's complex addressing modes: all are first-class in RTL.
Machine descriptions (.md files)
Each target architecture has a gcc/config/<arch>/ directory containing a machine description: a Lisp-like text file (.md) that names every instruction the architecture supports.
A machine description entry:
(define_insn "addsi3"
[(set (match_operand:SI 0 "register_operand" "=r")
(plus:SI (match_operand:SI 1 "register_operand" "%r")
(match_operand:SI 2 "register_operand" "r")))]
""
"add %0,%1,%2")
The addsi3 rule matches: a set of an SI (32-bit integer) register operand to the sum of two SI register operands. When matched, it emits add %0,%1,%2 as assembly.
Machine descriptions also encode:
- Operand predicates: what kinds of operands are valid for an instruction (register, memory, immediate).
- Operand constraints: which physical registers, address forms, immediate ranges are valid.
- Insn attributes: type (load, store, alu, ...), latency, pipeline stage. Used for scheduling.
- Peephole patterns: late-stage rewrites of one instruction sequence to another.
The .md format is older than TableGen and somewhat simpler. A complete machine description for a target is tens of thousands of lines, but each individual rule is a few lines.
For a reader, machine descriptions are the GCC alternative to TableGen. They capture the same information (instruction definitions, operand classes, scheduling) in a different syntax. Reading a small .md file (e.g., for an embedded target) is a quick way to learn the format.
Frontends
GCC supports several frontends, each living in its own subdirectory:
gcc/c-family/ Shared C/C++/ObjC infrastructure
gcc/c/ C frontend
gcc/cp/ C++ frontend
gcc/fortran/ Fortran (gfortran)
gcc/ada/ Ada (GNAT)
gcc/d/ D
gcc/go/ Go (gccgo)
gcc/rust/ Rust (gccrs, in active development)
gcc/m2/ Modula-2 (added in GCC 13)
Each frontend parses its language and emits GENERIC trees. From that point onwards the pipeline is shared. A bug fix in GIMPLE-level dead-code elimination benefits every frontend simultaneously.
A few frontends deserve attention:
- gccgo: an alternative Go frontend that uses GCC's optimiser instead of the standard
gccompiler's SSA backend. Slower to compile, sometimes produces faster code, supports architecturesgcdoes not. The Go ecosystem effectively maintains two production compilers. - gccrs (GCC Rust): an in-progress Rust frontend in GCC. Motivation: certifications and safety-critical environments where rustc/LLVM cannot be used. Active development through 2024-2026, included in the GCC distribution since GCC 13. The Polonius borrow-check library, originally developed by the rustc project, was integrated into gccrs for GCC 15. In rustc itself, Polonius is opt-in and still being stabilised; the production borrow checker remains NLL.
- GNAT (Ada): the most complete free-software Ada compiler. Used for high-integrity software (avionics, defence). The GCC Ada frontend is the only practically viable Ada implementation outside proprietary tools.
- gfortran: the most widely used free Fortran compiler. Numerical computing in Linux and HPC environments depends heavily on it.
For a reader, the frontend diversity is a teachable point. GCC supports more languages than any other compiler in this Part, and the languages span generations and paradigms (Ada from 1983, Fortran with FORTRAN-77 origins, modern Rust, the languages in between). The shared GENERIC representation is what makes that possible.
libgcc, libstdc++, libsanitizer
GCC ships with several runtime libraries:
- libgcc: the low-level runtime support. Provides functions the compiler emits calls to, even for "freestanding" environments. Examples: 64-bit integer arithmetic on 32-bit targets, soft-float emulation, exception unwinding, stack overflow checks.
- libstdc++: the GNU C++ standard library. The reference implementation of the standard.
- libsanitizer: the runtime support for AddressSanitizer, ThreadSanitizer, UndefinedBehaviorSanitizer, and others. Shared with LLVM's compiler-rt.
- libgomp: OpenMP runtime.
- libitm: transactional memory runtime.
The libsanitizer share with LLVM is interesting: GCC and LLVM both emit calls into the same sanitizer runtime, with the runtime implementing the actual checking and reporting. The compiler-side instrumentation is independent; the runtime is shared. This is a mostly cooperative relationship between the two projects.
libgccjit and JIT users
libgccjit is GCC's JIT API, a C-callable library for emitting code at runtime. As of GCC 11+ it is past alpha and ABI-stable. Active production users include the Ravi (Lua-derived language) JIT, an experimental Octave JIT, the Coconut JIT, and the rustc-codegen-gcc backend (which uses libgccjit even for AOT despite the name). Bindings exist for Python, Perl, and Rust.
For a learner, libgccjit is the smaller alternative to LLVM's ORC for embedding GCC's optimiser as a JIT. It reuses GCC's middle-end (GIMPLE passes, IPA, RTL) and emits machine code directly to memory.
Reload and LRA
GCC 4.8 (2013) introduced LRA (Local Register Allocator) as a planned successor to the older "reload" pass. In 2025 GCC 15 was the last release where the old reload code was still available; LRA is now the only register allocator going into GCC 16 and onwards. The migration was decade-long; the old reload pass had accumulated complexity that LRA simplifies dramatically.
For a contributor, the lesson is that production register allocators rewrite themselves in place over years, with the old and new coexisting before the old is finally removed. LLVM had a similar arc with greedy replacing the linear-scan-on-MachineInstr allocator, though more incrementally.
New frontends in GCC 15-16
GCC 16's frontend list (alongside the long-standing C, C++, Fortran, Ada, Go, D, Modula-2, Objective-C, Rust-via-gccrs):
- COBOL: a new frontend, in tree.
- Algol 68: continued maturation.
- Modula-2: in-tree since GCC 13.1, healthy and maintained.
The GCC Steering Committee formally widened the door for new language frontends in 2025. The result was COBOL and Algol 68 alongside the older work on Rust.
gccrs status update (GCC 15-16)
gccrs (the GCC Rust frontend) had a productive 2025 cycle. GCC 15.1 (April 2025) merged about 145 gccrs patches; the headline was integration of the Polonius borrow checker. Through 2025, gccrs reached real-code milestones: try blocks, while let loops, and a working SipHash implementation pulled from core. Funding from Open Source Security Inc. extends through GCC 16.1 stage 1.
gccrs is not expected to be production-ready in GCC 16 but is now a credible non-LLVM Rust path. The parallel route (using rustc with rustc_codegen_gcc to reach GCC's backends) is a different project; see rustc-overview.md.
Plugins
GCC has a formal plugin system. Plugins can:
- Add new passes to the pipeline.
- Add new attributes interpretable by code generators.
- Provide custom diagnostics.
- Hook into compilation events (e.g., post-pass).
Plugins are GPL-licenced (the plugin_is_GPL_compatible symbol must be defined in every plugin), but using a plugin does not GPL-contaminate the user's source code. The licensing distinction is documented in the GCC documentation.
Examples of plugins in production:
- MELT: Modular Extension Language Tool, a Lisp-like DSL for GCC plugins.
- GCC plugins for the Linux kernel:
randstruct(randomises struct field layout),structleak(zeroes out leaked structures),stackleak(clears stack leftover).
For a reader, the plugin system is a clean way to extend GCC without forking. The same is technically possible in LLVM but not as formally supported.
How GCC compares to LLVM
The big architectural distinction is one IR versus many. LLVM optimises everything in LLVM IR; GCC optimises some things at the GIMPLE level (where the program is still abstract) and others at the RTL level (where machine model matters). The result is similar end-to-end, but the locus of work is different.
A few practical consequences:
- GCC's GIMPLE-level passes are often easier to write than the equivalent LLVM passes because GIMPLE is closer to the source.
- GCC's RTL handles target-specific concerns at a layer LLVM puts inside its backends. Reading a GCC backend means reading a
.mdfile; reading an LLVM backend means reading a TableGen file plus C++. - LLVM's pass manager and modular library design make it easier to embed in tools (linters, static analysers, incremental builds). GCC is more monolithic.
- GCC has stronger support for some legacy languages (Fortran, Ada) and target architectures.
- GCC's IPA infrastructure is more mature than LLVM's, and LTO is more battle-tested.
Neither is "better". They are different points in the design space.
How GCC compares to our INTERCAL compiler
| Aspect | INTERCAL compiler | GCC |
|---|---|---|
| IR levels | 1 (parse tree, transient) | 3 (GENERIC → GIMPLE → RTL) |
| Frontends | 1 (INTERCAL) | 8+ (C, C++, Fortran, Ada, Go, D, Rust-via-gccrs, Modula-2) |
| Backends | 2 (ARM64, x86-64) | 50+ (everything from x86-64 to obscure embedded chips) |
| Optimisation | a few local passes | hundreds of GIMPLE and RTL passes |
| Codebase | ~2000 lines zsh + assembly | ~15 million lines, mostly C++ |
| Build | cc -x assembler - | autoconf + make, ~hours |
Same shape, different scale. Same conceptual phases, more layers of optimisation, more frontends, more backends.
If you only read five files
For getting oriented in GCC:
gcc/passes.def: the pass pipeline. Reading this top to bottom gives you the map of GCC.gcc/gimple.handgcc/gimple.cc: the GIMPLE data structures.gcc/tree-ssa.cc: the SSA transformations on GIMPLE.gcc/lra.ccplusgcc/lra-constraints.cc: register allocation.gcc/rust/rust-session-manager.cc: gccrs's frontend driver if you intend to work on Rust support.
Common contributor gotchas
- Copyright assignment to the FSF (or DCO sign-off) is mandatory; PRs without it will be returned.
- ChangeLog entries are expected.
contrib/mklogexists for that; do not write them by hand. -fdump-tree-all-details-graphproduces graphviz, not the same as-fdump-tree-all.- LRA's reload constraints fail silently as "unable to find a register to spill" when you forget to mark a clobber. The fix is almost always in
*.mdconstraints. - gccrs must compile against trunk libgccjit and matches a specific Rust edition. Mismatched
--enable-languages=rustbuilds quietly skip it.
Area specialists
- Richard Biener: middle-end, tree-ssa.
- Jakub Jelinek: release manager, OpenMP.
- Vladimir Makarov: LRA, IRA.
- Jeff Law: RTL.
- Arthur Cohen and Philip Herron: gccrs leads.
- David Malcolm: analyzer, diagnostics.
Diagnostic flags worth knowing
-fdump-passes: list all passes that ran.-fdump-tree-all-details-blocks-vops: very verbose tree dumps.-fdump-rtl-all-slim,-fdump-ipa-all,-fdump-tree-evrp.-da: alias for-fdump-rtl-all.-S -dp: annotate generated assembly with RTL insn IDs.-fdbg-cnt=<pass>:N: bisect a regression at the granularity of a specific pass.
To bypass the driver, run cc1 directly: cc1 -quiet -fdump-tree-all foo.c. To debug an internal-error: gdb cc1, set a breakpoint at internal_error, then bt and p debug_tree(t).
Reading GCC source for the first time
A practical order:
- Read
gcc/doc/gccint.texi(the gccint manual), specifically the chapters on GENERIC, GIMPLE, and RTL. Roughly equivalent to reading appendix-grammar.md, code-generation.md, and calling-conventions.md in this book. - Browse
gcc/tree-cfg.ccfor a sense of how GIMPLE control-flow graphs are built. ~1500 lines, well-commented. - Read one of the GIMPLE optimisation passes.
gcc/tree-ssa-dce.cc(dead-code elimination on SSA) is a good candidate. - Read
gcc/passes.defto see the entire pass pipeline at once. Each line names a pass; the order is the order they run in. - For backends,
gcc/config/aarch64/aarch64.mdis a relatively modern machine description and is more readable than older ones. - For LRA,
gcc/lra-constraints.ccis the heart of register allocation.
Mailing-list contribution flow
GCC's review culture is different from GitHub-PR projects. Patches are sent as email to [email protected]:
git format-patch -1 HEAD # produce a .patch file
# write a description, ChangeLog entry
git send-email [email protected] --to=<reviewer>@... <patchfile>
A maintainer responds. Typical responses: "OK to commit", "needs revision: [comments]", or further questions. Iteration happens in the email thread.
Once the patch is approved, the contributor commits it themselves with their own attribution (or the maintainer commits on their behalf, depending on access). The commit must include a ChangeLog entry.
GCC also has Bugzilla at https://gcc.gnu.org/bugzilla/ for issue tracking. The mailing list is for patches and discussion; Bugzilla is for bugs.
The cadence is slower than GitHub. Build patience into expectations: a small patch might take a week to land; a non-trivial one, a month or more.
For a reader, the GCC contribution flow is a window into pre-GitHub open-source culture. The mailing list, the patch-by-email convention, the ChangeLog discipline: all predate (and outlast) the rise of pull-request workflows.
Where to go next
- The GCC Internals manual is the canonical reference; treat the rest of this chapter as orientation.
- The GCC Summit proceedings (older, 2003-2010) for retrospective views on architectural decisions.
- "An Introduction to GCC" by Brian J. Gough, free at https://nongnu.askapache.com/gcc-intro/, for the user-facing perspective.
- contributing-to-production-compilers.md for how to interact with the GCC mailing-list-driven review process, which differs from LLVM's GitHub-PR model.
- llvm-overview.md and rustc-overview.md for the alternatives.
rustc, in shape
rustc is the Rust compiler. The source lives at https://github.com/rust-lang/rust. The authoritative companion document for anyone reading or modifying the compiler is the rustc-dev-guide, which the rest of this chapter assumes you will eventually read.
rustc is interesting as a third reference point because it has neither LLVM's single IR nor GCC's three. It has four: HIR, THIR, MIR, and (via codegen) LLVM IR. Each layer exists to make a specific job easier.
The pipeline, end to end
Rust source goes through this sequence:
source
→ tokens (lexer)
→ AST (parser)
→ HIR (lowering, after macro expansion and name resolution)
→ THIR (lowering, after type checking)
→ MIR (lowering, for borrow checking and optimisation)
→ LLVM IR (codegen)
→ machine code (LLVM)
Six lowering steps, four named IRs. Each is the right shape for the work that happens at that level.
What each IR is for
AST is what the user wrote. Macros are not yet expanded. Names are not yet resolved. The parser produces it; almost nothing else touches it.
HIR (High-level Intermediate Representation) is the AST after macro expansion, name resolution, and minor desugaring. Lifetimes that the user elided are now explicit. HIR is what most compiler passes see during type checking. It is still close enough to the source that error messages can point at sensible spans.
THIR (Typed High-level IR) is HIR after type checking. Method calls are resolved to specific function references, autoref/autoderef coercions are inserted, overloaded operators are replaced with explicit calls. THIR exists as a stepping stone: it is fully typed but still tree-shaped, which makes it the right starting point for building MIR.
MIR (Mid-level IR) is the most distinctive piece of rustc's design. MIR is a control-flow graph in basic blocks, each containing simple typed statements with explicit drops, moves, and references. This is where Rust's borrow checker runs. Borrow checking on MIR (rather than on HIR or AST) is what made non-lexical lifetimes possible. MIR is also the IR for a growing set of compiler-internal optimisations, constant evaluation, and the recent const-generic and dataflow analyses.
LLVM IR is what rustc emits when it is finally ready to hand off to the LLVM backend. The codegen layer (rustc_codegen_llvm) walks MIR and emits LLVM IR. There are alternative codegen backends: rustc_codegen_cranelift for fast debug builds, and rustc_codegen_gcc for using GCC as the backend instead of LLVM.
Why so many IRs
Each lowering removes ambiguity that was useful at a higher level but inconvenient at a lower one.
- AST → HIR removes macros and name ambiguities. A pass at HIR level does not have to worry about whether
vec!is a macro or a function call. - HIR → THIR removes type ambiguities. A pass at THIR level does not have to re-do trait resolution.
- THIR → MIR turns the tree into a control-flow graph. A pass at MIR level can use dataflow algorithms naturally. The borrow checker, in particular, is much easier to express on MIR than on HIR.
- MIR → LLVM IR removes Rust-specific concerns (drop semantics, panics, generics). LLVM does not need to know about lifetimes or traits.
Compare this with LLVM (one IR for everything) and GCC (three IRs at different levels of abstraction). rustc sits closer to GCC's school of thought than to LLVM's, but with more semantic information preserved at each level.
The borrow checker on MIR
The borrow checker (rustc_borrowck) is rustc's most distinctive piece. It runs on MIR, after type checking and after MIR construction. Its job: reject programs that would create undefined behaviour by violating Rust's ownership and borrowing rules, and accept everything else.
The history is worth knowing:
- Pre-2018: lexical borrow checker on HIR (in
rustc_borrowck's old form). Borrows lived for the entire enclosing lexical scope. Infamously rejected programs that "felt" correct, like splitting a struct into two disjoint borrows. - 2018: NLL (Non-Lexical Lifetimes) on MIR. Borrows live for as long as needed, computed via dataflow. Many previously-rejected programs become valid. The "NLL" name is historical; the system is now just "the borrow checker".
- In progress (2024-2026): Polonius, originally a Datalog reformulation of the borrow checker, currently being rewritten as a "Polonius alpha" location-sensitive analysis that is a strict superset of NLL. It accepts the NLL "problem case 3" and lending iterators that NLL rejects. The 2026 project goal is to stabilise Polonius alpha behind a feature gate; the team will accept 10-20% borrow-checking compile-time overhead for the expressiveness gains. NLL remains the production default; gccrs uses a separate Polonius integration as its production borrow checker since GCC 15.
How NLL works in outline:
- For each borrow in the function, compute the region (set of MIR points) where the borrow must remain valid.
- For each variable, compute the liveness information: at which points the variable is live (its value will be used).
- Check that no two conflicting borrows overlap in their regions.
- Check that moves out of variables happen only when no borrows of those variables are live.
The algorithm is dataflow on the MIR control-flow graph. The implementation in rustc_borrowck is around 50,000 lines, including diagnostics, but the algorithmic core is much smaller.
Polonius (in progress) reformulates this as Datalog rules:
borrow_alive(L, P) :- borrow_introduced(L, P).
borrow_alive(L, Q) :- borrow_alive(L, P), edge(P, Q), !borrow_killed(L, Q).
error :- borrow_alive(L, P), conflicting_access(L, P).
The advantage: the rules are declarative, easier to extend, easier to reason about. The Polonius engine then computes the fixpoint. The transition to Polonius has been gradual, with Polonius results currently used for some warnings while NLL drives the actual error reporting.
For a reader, the borrow checker is one of the most concrete examples of a non-trivial static analysis applied to a practical problem. Reading the high-level overview in the rustc-dev-guide and then the implementation gives a full picture.
The trait solver
The trait solver (rustc_trait_selection, gradually being replaced by a new solver) is rustc's other distinctive analysis. Its job: given a trait constraint like T: Eq or Vec<T>: Iterator, find the implementation (or implementations) that satisfy it.
The hard cases:
- Multiple impls: a type might satisfy a trait in multiple ways. Coherence rules (one impl per (type, trait) pair) prevent this in user code, but compiler-internal reasoning sometimes encounters non-deterministic states.
- Higher-ranked traits:
for<'a> Fn(&'a u32) -> &'a u32requires reasoning about all lifetimes simultaneously. - Associated types:
<T as Iterator>::Itemis a type that depends on which impl is chosen. - Specialisation (unstable): a more specific impl can override a less specific one. Coherence rules become more complex.
- GATs (Generic Associated Types): trait associated types parameterised by lifetimes or types. New as of 2022.
The old solver is imperative: a loop tries impls one at a time, with backtracking and special-cased handling. The new solver (started 2022, work in progress through 2026) is based on a proof tree: explicit goal-seeking with structured search and improved error reporting.
For a reader, the trait solver is the closest production analog to a Prolog-style logical inference engine. The trade-offs (completeness vs decidability, expressiveness vs error-message clarity) are studies in their own right.
The query system
rustc's compilation is structured as a graph of queries. Each query is a function from input to output that the compiler can ask for and that gets cached. Examples:
tcx.type_of(def_id): what is the type of this definition?tcx.borrowck(def_id): borrowcheck this function.tcx.optimized_mir(def_id): produce the optimised MIR for this function.
When a query is asked for the first time, rustc computes it and caches the result. Subsequent calls return the cached value. The query system also tracks dependencies: query A depends on query B if computing A asks for B.
Why this matters: incremental compilation. When a file changes, rustc invalidates only the queries whose dependencies changed. Unchanged queries reuse cached results. The result is incremental builds that touch only what is necessary, not the full pipeline.
The query system is implemented in rustc_query_system. The approach is influenced by the Salsa library (used by rust-analyzer), though the rustc implementation is older.
For a reader, the query system is the cleanest production example of "compiler architected as memoising graph". Modern languages targeting fast iteration (Java's javac, Kotlin's compiler, TypeScript's tsc) have moved to similar designs.
Crates inside rustc
The rustc compiler is a Cargo monorepo with many crates. The full list:
rustc_lexer/ Token-level scanning (also used by rustfmt, rust-analyzer)
rustc_parse/ Parser (recursive descent, ~30K lines)
rustc_ast/ AST data structures
rustc_expand/ Macro expansion (declarative + procedural)
rustc_resolve/ Name resolution
rustc_hir/ HIR data structures
rustc_hir_pretty/ HIR pretty-printer
rustc_hir_typeck/ Type checking on HIR (expression-level)
rustc_trait_selection/ Trait solver (old)
rustc_next_trait_solver/ Trait solver (new, in progress)
rustc_mir_build/ THIR → MIR construction
rustc_borrowck/ Borrow checker on MIR
rustc_const_eval/ Constant evaluation (miri-based)
rustc_mir_transform/ MIR-level optimisations
rustc_codegen_ssa/ Codegen scaffolding (backend-independent)
rustc_codegen_llvm/ LLVM backend
rustc_codegen_cranelift/ Cranelift backend (separate repo, integrated)
rustc_codegen_gcc/ GCC backend (separate repo, integrated)
rustc_driver/ CLI driver, the entry point
rustc_session/ Compilation-session state
rustc_query_system/ Query infrastructure
rustc_query_impl/ Query implementations (generated)
rustc_metadata/ Crate metadata format and reading
rustc_save_analysis/ Save-analysis data (for IDEs)
rustc_target/ Target descriptions
... Plus 50+ more
The crate boundaries are real: each crate compiles independently, depends on the others through stable interfaces, and has its own README. The compiler/rustc_*/README.md files are the entry points for new contributors looking at a particular area.
Alternative codegen backends
rustc supports multiple backends, selectable per build:
- rustc_codegen_llvm: production default. LLVM backend.
- rustc_codegen_cranelift: fast debug-mode codegen. Roughly 2-3x faster than LLVM for debug builds.
- rustc_codegen_gcc: experimental GCC backend. Uses GCC's optimiser instead of LLVM. Useful for targets where LLVM is weak or where GCC's mature LTO matters.
The backends share rustc_codegen_ssa, the scaffolding crate. Each backend implements a trait that defines what it means to "lower MIR to machine code". The shared trait is large (~50 methods) but well-defined; new backends can be added in a focused way.
For a reader, the multi-backend story is rustc's strongest argument for its design. Where Swift is "swift + LLVM", rustc is "rustc + (LLVM | Cranelift | GCC)". The flexibility is partly because MIR is far enough from LLVM IR that the lowering is non-trivial; the lowering is replaceable.
miri as a standalone tool
miri (rustc_const_eval) is the MIR interpreter that powers const fn evaluation in rustc. It also runs as a standalone tool (cargo miri) for detecting undefined behaviour in Rust code.
What miri does standalone: interpret a program's MIR rather than executing the compiled binary, with strict checks for UB. Detects:
- Memory safety violations (use after free, double free, out-of-bounds access).
- Type confusion (transmuting incompatible types).
- Uninitialised memory reads.
- Dangling references.
- Race conditions (with the
experimental-data-race-detectorflag).
miri is much slower than running compiled code (~100x), but catches subtle bugs that escape testing on optimised builds. It is the standard tool for Rust unsafe-code review.
The shared engine: when rustc evaluates a const fn, it runs miri internally on the function's MIR. When the user runs cargo miri, it runs miri on the whole program's MIR. The same interpreter handles both cases.
For a reader, miri is the most concrete example of "abstract interpretation as a tool". The engine is well-engineered (handles memory provenance, allocator semantics, interior mutability) and worth studying as a production interpreter.
Bootstrap stages
rustc bootstraps in three required stages plus an optional fixpoint stage:
- Stage 0: rustc beta from the previous release. Used to build stage 1.
- Stage 1: rustc compiled by stage 0, using the current source. The result is a working compiler but with some limitations.
- Stage 2: rustc compiled by stage 1. This is the production-equivalent compiler. The most thoroughly tested.
- Stage 3 (optional): rustc compiled by stage 2. Used to verify that stage 2 reproduces itself (the fixpoint check).
The stages are conceptually equivalent to our 3-generation fixpoint, just with the addition of the beta-version starting point.
The build orchestration: x.py build is a Python wrapper that handles the multi-stage build. x.py test, x.py check, x.py doc are the related commands. Reading the bootstrap documentation in the rustc-dev-guide is the right preparation for working on rustc itself.
Ecosystem in the same monorepo
rust-lang/rust is unusual in being a single repository for the language ecosystem:
- library/{core,alloc,std,test}: the standard library.
- src/tools/cargo: the build tool.
- src/tools/rustfmt: the formatter.
- src/tools/clippy: the linter.
- src/tools/rust-analyzer: the LSP server (mirrored from a separate repo).
- src/tools/miri: standalone miri.
- src/tools/rustdoc: the documentation tool.
- src/tools/error_index_generator: generates error code documentation.
The decision to keep these together (rather than as separate repos) is part of the project's "everything in lock-step" philosophy. Changes that span the language and the tools can be landed atomically. The cost: huge repository, slow CI.
For a reader, the monorepo structure means that learning rustc means learning more than the compiler. Cargo, rustdoc, the standard library: all are part of the same project, with the same review process.
How rustc compares to LLVM and GCC
| Aspect | rustc | LLVM (used by Clang) | GCC |
|---|---|---|---|
| Frontend language | Rust only | Many (Clang, Swift, Julia, ...) | Many (C, C++, Fortran, Ada, ...) |
| IR layers | 4 (HIR, THIR, MIR, LLVM IR) | 1 (LLVM IR) | 3 (GENERIC, GIMPLE, RTL) |
| Distinctive analyses | Borrow checker on MIR | None Rust-specific | None Rust-specific |
| Backends | LLVM (default), Cranelift, GCC | Many | Many |
| Implementation language | Rust (self-hosted) | C++ | C and C++ |
| Codebase | ~3 million lines Rust | ~10 million lines C++ | ~15 million lines mixed |
| Incremental compilation | Query-based, mature | None at compiler level | None at compiler level |
rustc is an unusual case: it is itself self-hosted (the compiler is written in Rust), like our INTERCAL ambition. rustc bootstrapped through OCaml; it now compiles itself in three stages, the first of which uses a previous stable rustc.
How rustc compares to our INTERCAL compiler
The INTERCAL compiler bootstraps the same way rustc does. zsh plays the role OCaml played for early Rust. After self-hosting, both projects can build themselves.
The differences are scale and the existence of an IR pipeline. rustc has four levels of IR; our compiler has none. rustc has a borrow checker and a type system; we have four numeric types and the politeness rule. rustc emits LLVM IR; we emit ARM64 or x86-64 assembly directly.
The conceptual map is the same. Lex, parse, check, lower, emit. Reading rustc with the vocabulary from this book in mind, you will see the same shape, just with each phase greatly enlarged and each IR level made explicit.
If you only read five files
For getting your bearings in rustc's source:
compiler/rustc_driver_impl/src/lib.rs: the driver. Shows the phase pipeline end to end.compiler/rustc_middle/src/query/mod.rs: the query DAG. Every cacheable computation lives here.compiler/rustc_borrowck/src/lib.rs: the borrow checker entry point.compiler/rustc_next_trait_solver/src/solve/mod.rs: the new trait solver.compiler/rustc_codegen_ssa/src/back/write.rs: the codegen back-end shared layer between the LLVM, Cranelift, and GCC backends.
Common contributor gotchas
./x.py checkbefore./x.py buildsaves hours.- Adding a new query requires touching
rustc_middle/src/query/mod.rsAND implementing the provider; the macro errors are cryptic. tcx.lifetimeof inferred regions is meaningless outside the borrow checker.- UI tests need exact stderr; run
./x.py test --blessto update expected outputs. - Using
-Znext-solver=globallymay hide bugs that only show withcoherencemode. - Do not add
tracing::info!in hot query paths; usedebug!and run withRUSTC_LOG.
Area specialists
- lcnr: next solver, NLL.
- compiler-errors: trait solver, diagnostics.
- Nilstrieb: parser, span machinery.
- oli-obk: const eval, opaque types.
- petrochenkov: resolver, macros.
- Mark Rousskov: perf infrastructure.
- Zalathar: coverage, rollups.
Notable recent PRs to read
- PR #145244 (lcnr): "non-defining uses of opaques in borrowck". Demonstrates how opaque-type subtlety surfaces in borrow checking.
- PR #140306: specialization in the new solver.
- PR #126614: next-solver uplift.
Diagnostic flags worth knowing
-Zdump-mir=all,-Zdump-mir-graphviz: MIR snapshots.-Zverbose-internals,-Zprint-type-sizes: type-system inspection.-Zself-profileplussummarize: per-query timing.-Zthreads=1: deterministic ICE reproduction.RUSTC_LOG=rustc_borrowck=debug: scoped tracing.RUSTC_BACKTRACE=full: see where an ICE was raised.-Ztrack-diagnostics: trace which compiler code emitted each diagnostic.
For nightly-regression bisection: cargo bisect-rustc. For incremental-compilation issues: -Zincremental-verify-ich.
Reading the rustc-dev-guide
The rustc-dev-guide is the single most useful document for understanding rustc. It is maintained alongside the compiler, kept in sync with the source, and explicitly written for new contributors. A reasonable order:
- Overview of the Compiler: the front-to-back tour.
- The HIR, The THIR, The MIR: the IR descriptions.
- Type Checking and Trait Solving: the conceptual core of the type system.
- Borrow Checking and Drop elaboration: the Rust-specific bits.
- Code Generation: how MIR becomes LLVM IR and then machine code.
- Queries and the query system: how incremental compilation works.
After this book and the dev guide, you have the vocabulary to start opening compiler issues and reading the code that fixes them.
How to contribute
GitHub PRs to https://github.com/rust-lang/rust. Every PR needs an r=<reviewer> comment from a designated reviewer; bors is the merge bot. Mentored issues come with a designated r?@<reviewer> already assigned.
Beginner-friendly issues:
E-easyandE-mentorlabels: explicitly identified for new contributors.A-diagnostics: diagnostic-message improvements, often small and high-value.A-clippy: lints in the Clippy linter.A-rustdoc: rustdoc improvements.A-incr-comp: incremental compilation improvements (smaller scope, bounded).
Build:
git clone https://github.com/rust-lang/rust
cd rust
cp config.example.toml config.toml
# edit config.toml: set profile = "compiler"
./x.py build
The first build is slow (an hour or so) because of the multi-stage bootstrap. Incremental builds of single crates take seconds.
Where to go next
- The rustc-dev-guide is the single most important document.
- The Rustonomicon at https://doc.rust-lang.org/nomicon/ for unsafe Rust details that the compiler enforces.
- "Stupid Stupid xargs" by Niko Matsakis (and other Niko blog posts at https://smallcultfollowing.com/babysteps/) for the design history of the borrow checker.
- contributing-to-production-compilers.md for how to land a first patch on rustc.
- llvm-overview.md for the backend rustc uses by default.
- cranelift-overview.md for the alternative debug backend.
- gcc-overview.md for the alternative production backend (
rustc_codegen_gcc). - from-intercal-to-real-compilers.md for the bridge from this book's content to production-compiler work.
Go (gc), in shape
The Go compiler, conventionally called gc (short for "Go compiler", unrelated to garbage collection), is the reference implementation of Go. Source lives at https://github.com/golang/go in src/cmd/compile. Unlike Clang or rustc, gc does not lean on LLVM, GCC, or any other backend. Frontend, middle end, backend, linker, runtime: all of it is Go, all of it is in the same repository, all of it builds itself.
That self-contained quality is the first thing to take in. Around 600,000 lines of Go cover the compiler proper (cmd/compile), with another 50,000 for the linker (cmd/link). Roughly half the compiler is generated from declarative SSA rewrite rules; the hand-written portion is about half that. There is no external dependency at compile time and no libc dependency at run time. The compiler decides stack vs heap allocation through escape analysis. The runtime ships its own scheduler for goroutines and its own concurrent garbage collector. The linker emits binaries for any of fifteen-odd targets without needing a system toolchain installed.
For a reader of this book, Go is the most direct counterpart to our INTERCAL compiler at production scale: zsh and assembly here, Go and Go assembly there, the same self-contained spirit.
Pipeline, end to end
Go source goes through this sequence:
source program.go
→ tokens cmd/compile/internal/syntax (lexer)
→ AST (syntax) cmd/compile/internal/syntax (parser)
→ AST (ir) cmd/compile/internal/noder
→ typed AST cmd/compile/internal/types2
→ AST after walk cmd/compile/internal/walk
→ SSA cmd/compile/internal/ssa
→ machine code cmd/compile/internal/ssa (lowering)
→ object file cmd/compile/internal/obj
→ executable cmd/link
Eight stages, two ASTs, one SSA IR, one object format, and one linker. Each stage is a Go package that operates on the data structures of the next.
The lexer and parser are hand-written and live in cmd/compile/internal/syntax. They produce a syntactic AST that captures the program shape. The noder then translates that AST into the older ir package's representation, which is what the rest of the compiler historically expected.
Type checking happens in cmd/compile/internal/types2, a recent (Go 1.18+) reusable type checker that doubles as the type checker for go/types and tools like gopls. Generics support landed alongside types2. The output is a fully typed ir AST.
walk is the lowering pass. It rewrites high-level Go constructs into smaller primitives the SSA backend can handle. Range loops become explicit for loops. Channel sends and receives become calls into the runtime. Map operations become hash-table calls. defer becomes setup plus runtime registration. Slice literals become allocations plus stores. Most of the magical-looking Go syntax disappears here.
The output of walk is then converted to SSA function-by-function. The SSA backend optimises and lowers to machine code for the target. Codegen emits a Go-specific object format, not ELF/Mach-O directly, which is then consumed by cmd/link together with all other compiled packages and runtime code to produce the final executable.
SSA with declarative rewrite rules
The SSA backend was added in Go 1.7 (2016) by Keith Randall and replaced the older 6g/8g code generators. It is the most distinctive part of the compiler.
The IR is conventional SSA: each value has a single definition, basic blocks form a control-flow graph, function arguments are block parameters of the entry block. What is unconventional is how optimisations are written.
Each architecture has a gen/<arch>Ops.go file that lists every SSA opcode the architecture supports. Each architecture also has a gen/<arch>.rules file that rewrites generic SSA into architecture-specific SSA, plus optimisation rules that fire at the right point in the pipeline.
A rule looks like this:
(Add64 (Const64 [c]) (Const64 [d])) => (Const64 [c+d])
(Add64 x (Const64 [0])) => x
(Add64 (Const64 [c]) x) && c < 0 => (Sub64 x (Const64 [-c]))
The left side is a pattern over SSA nodes. The right side is the rewrite. Optional Go-language guards (&& condition) gate the rule. The whole .rules file is compiled to Go by cmd/compile/internal/ssa/gen/rulegen.go during the build, producing a function the SSA pipeline calls in each rewrite phase.
This is rare in production compilers. LLVM has TableGen for instruction selection but pass-level optimisations are conventional C++. Cranelift has ISLE for lowering but optimisations are also Rust. Go has .rules for both, in the same syntax. Reading generic.rules (~3500 lines, architecture-independent simplifications) is one of the most pleasant ways to learn what a SSA-form optimiser actually does.
The phases of the SSA pipeline live in cmd/compile/internal/ssa/compile.go. A typical Go function passes through about fifty named phases:
early phielim,early copyelim: clean up the SSA constructionopt: applygeneric.rulesrewrites until fixpointdse(dead store elimination),cse(common subexpression elimination)prove: range analysis based on assertions and bounds checksnilcheckelim: remove redundant nil checkslate opt,loopRotate,late copyelimlower: apply<arch>.rulesto translate generic SSA to architecture-specific SSAlateLower: more architecture-specific cleanupregalloc: linear-scan-style register allocation on SSAloop rotate,stackframe,trimgenssa: emit machine instructions
You can dump any phase with go build -gcflags='-d=ssa/<phase>=<level>' program.go. Higher levels print more detail. Reading SSA dumps for a small program (start with go build -gcflags='-d=ssa/opt=2' program.go) is the fastest way to learn the pipeline.
Escape analysis
Go is a garbage-collected language, but the compiler tries to allocate on the stack whenever it safely can. The decision lives in cmd/compile/internal/escape.
The algorithm is a dataflow analysis over function summaries. Each variable is treated as a node in a graph. Edges represent "can the value of A flow into B". A variable escapes if a path exists from it to:
- the function's return value
- a global variable
- a heap-allocated structure
- the receiver of a method that may store it
Variables that do not escape are allocated on the stack. Variables that escape are allocated on the heap and become GC roots.
The lessons embedded here are subtle. Taking the address of a local variable does not by itself force heap allocation; only escaping the address does. Returning a pointer to a local typically forces heap allocation, but inlining can sometimes prove escape stays local and the allocation moves back to the stack of the caller. Closures capture variables; whether they escape depends on whether the closure itself escapes.
The contrast with Rust is illuminating. Rust solves the same problem at type level via the borrow checker: lifetimes are part of the type, escape is a compile error, no GC needed. Go solves it at IR level: escape is a runtime concept (heap-vs-stack), and what cannot be proven non-escaping defaults to the heap. Both are correct, both work, both teach the same underlying problem from opposite angles.
Reading both, side by side, gives a contributor a real intuition for how language design pushes complexity around: Rust pushes it to the type system, Go pushes it to the GC plus escape analyser. INTERCAL would push it nowhere because INTERCAL has no closures and no pointers, but the conceptual lesson transfers.
Profile-guided optimisation (PGO)
PGO went GA in Go 1.21 (2023) and is fully production-ready by Go 1.24. Compiling with -pgo=auto consumes a default.pgo next to main, drives devirtualisation and inlining choices, and reports 2-14% gains on representative benchmarks. The Uber case study (spring 2025) reported roughly 24,000 cores saved across their largest services. Go 1.25 brings PGO further into the default toolchain. Remaining rough edges in 2026: profile freshness, build determinism, CI integration.
Generics: GCShape stenciling
Go's generics use a hybrid called GCShape stenciling with a dictionary. The compiler emits one body per distinct GC shape (size, alignment, pointer mask) rather than per concrete type. Each call passes a dictionary of run-time type info that the body uses for type-dependent operations. This is a deliberate compromise between full monomorphisation (bigger binaries, faster code; rustc's choice) and pure dictionary passing (smaller binaries, slower code; GHC's choice).
The dictionary indirection has a measurable cost: PlanetScale's 2022 post (still cited in 2025 discussion) showed that for cases like map keys with method calls, GCShape can be slower than equivalent non-generic code. There is no movement toward full monomorphisation.
Garbage collector evolution: Green Tea
Go's GC is concurrent and not generational, the same shape since Go 1.5. Recent work, however, is significant: Green Tea GC ships in Go 1.25 behind GOEXPERIMENT=greenteagc and is slated to become the default in Go 1.26.
The classic tri-color abstraction (white/gray/black) is preserved. The unit of work changes: older Go GC traced individual objects on a shared work queue; Green Tea traces at span granularity, with two bits per object (gray and black) on each span, and the shared work queue holding spans, not objects. Marking a span sweeps its objects in batches, which improves cache locality and parallel scan throughput. Reported wins are around 10% less GC time on typical workloads, up to 35-40% on allocation-heavy ones. Some workloads see no benefit (the DoltHub team reported neutral results), which is why the 1.25 default is opt-in.
Inlining
The inliner lives in cmd/compile/internal/inline. It is budget-based: each function carries a "complexity score" computed from its AST, and the inliner inlines callees while their score fits the caller's remaining budget.
Inlining matters in Go because so much of the standard library and so much of generic code is short. Without inlining, generic containers, the iteration protocol, and most runtime helpers would carry call overhead that competing languages elide.
The inliner has accumulated a few sophisticated tricks:
- mid-stack inlining (Go 1.12+): inline a function even if it itself calls something not inlined
- profile-guided inlining (Go 1.20+): use PGO data to bias the inliner toward hot call sites
- unified inliner (Go 1.20+): replaces the old "inline before walk" + "mid-stack inline after walk" split
A reader who wants to understand Go performance reads the inliner. A reader who wants to understand Rust performance reads rustc_mir_transform/inline. The algorithms are similar but the decisions are not, because Rust's monomorphisation already specialises generics aggressively before inlining can be considered.
Runtime cooperation
The compiler does not stand alone; it cooperates with the runtime in several places. This cooperation is invisible from outside but central to the design.
Write barriers: the GC needs to know when a pointer in the heap is overwritten so it can update the marker state. The compiler inserts barrier calls at every pointer write that could be tracked. Walk handles part of this; ssa lowers it.
Stack growth: goroutines start with tiny stacks (2KB) that grow as needed by copying. The compiler emits a stack-check prologue at every function entry. If the stack would overflow, the prologue calls into runtime.morestack, which allocates a larger stack, copies the frame, and resumes.
Preemption: sysmon and the GC need to interrupt running goroutines at safe points. The compiler emits "safe point" annotations in machine code that runtime knows how to find for stack scanning and async preemption (Go 1.14+).
Schedule yield: certain operations (channel send/receive on a full/empty channel, select, network I/O) yield to the scheduler. The compiler turns these into runtime calls that may park the goroutine.
defer and recover: defer statements push a deferred call onto a per-goroutine stack at the point of declaration; the function epilogue (or a panic walk) pops and executes them. The compiler chooses between three implementations depending on shape: heap-allocated, stack-allocated, and open-coded (Go 1.14+, the cheapest, used when defers are statically determinable).
These are the places to look when learning how a compiler-runtime contract is structured. The compiler emits machine code that knows about runtime invariants; the runtime relies on the compiler to maintain them. Bugs in either side manifest as crashes that look like the other side's fault.
Linker and object format
Go has its own linker (cmd/link) and its own object format. The format is described in cmd/internal/goobj. It is not ELF, not Mach-O, not COFF: it is a Go-specific intermediate that the linker reads and turns into the target executable format.
The linker handles:
- symbol resolution across packages
- dead-code elimination at link time (functions not reachable are dropped)
- DWARF generation for debugging
- buildinfo embedding (the
runtime.buildVersionstring and friends) - type metadata for reflection (the
_typeandinterfacetypestructures) - target-specific ELF/Mach-O/PE/Wasm emission
Reading cmd/link is one way to learn linkers without diving into LLD or GNU ld. It is much smaller (~80,000 lines) and the abstractions are tighter because there is one frontend and one runtime. It is, in effect, a self-contained linker textbook.
Cross-compilation
GOOS and GOARCH environment variables select the target. Setting GOOS=linux GOARCH=arm64 go build produces a Linux ARM64 binary on macOS without any cross-toolchain installation. There is no --target flag, no Clang -target=arm64-linux-gnu style; it is in the build invocation itself.
This works because the compiler has every supported backend compiled in, the linker can emit every supported format, and the runtime is included as Go source for every target. Targets supported as of Go 1.22+ include: linux/{amd64,arm64,arm,386,riscv64,mips64,ppc64,s390x,loong64}, darwin/{amd64,arm64}, windows/{amd64,arm64,386}, freebsd, openbsd, netbsd, dragonfly, plan9, solaris, illumos, aix, ios, android, js/wasm, wasip1.
For somebody coming from a C/C++ world where cross-compiling is a recurring pain (sysroot, libc choice, header copies, libstdc++), Go's approach is striking. The price is that adding a new target means writing a Go-side backend, not piggy-backing on LLVM. The benefit is that everyone gets cross-compilation as a natural property of using the language.
Bootstrap
gc is self-hosted. To build it from source you need an older Go to bootstrap. The chain:
- Pre-1.5: the compiler was written in C as
6c/8c/5cand translated to6g/8g/5gfor Go targets. - Go 1.5: a semi-automated translation rewrote the compiler in Go. From this point on, Go itself was needed to build Go.
- Since Go 1.22 the bootstrap rule is "Go 1.N requires Go 1.M, where M is N-2 rounded down to even", so Go 1.22-1.23 require Go 1.20.x and Go 1.24+ require Go 1.22.x. When bootstrapping from older sources, you chain through previous releases (Go 1.4 from C, then a 1.17.13 binary, then forward).
gccgo is a separate frontend in GCC that uses GCC's optimiser instead of gc's SSA. It is slower to compile, occasionally produces faster code, and is the way to use Go on architectures gc does not support. The Go ecosystem effectively maintains two production compilers, used in different niches.
Repo layout
src/cmd/compile/internal/
syntax/ Lexer + parser, syntactic AST
noder/ Syntactic AST → ir AST
types2/ Type checker
ir/ "Old" AST (typed, used by walk and through SSA construction)
walk/ Lowering of high-level constructs
escape/ Escape analysis
inline/ Inliner
ssa/ SSA backend
gen/ Op definitions and rewrite rules per architecture
ssagen/ AST → SSA conversion
<arch>/ Per-architecture glue (amd64, arm64, riscv64, ...)
base/ Compiler-wide configuration and command-line flags
typecheck/ Old typechecker (legacy, gradually superseded by types2)
src/cmd/link/ Linker
src/cmd/asm/ Assembler (Go's assembly dialect, not GNU)
src/cmd/internal/goobj/ Object format
src/cmd/internal/obj/<arch>/ Per-architecture instruction encoding
src/runtime/ Runtime: scheduler, GC, channels, defer, panic
src/runtime/mgc*.go Garbage collector implementation
src/runtime/proc.go Scheduler
src/runtime/netpoll*.go Network poller (epoll/kqueue/IOCP)
src/runtime/sys_*_*.s Per-OS, per-arch syscall stubs
The Go assembler dialect deserves a footnote. Go's assembler is not GNU as. It uses a Plan 9-derived syntax where each architecture is described in terms of pseudo-registers and pseudo-instructions that the assembler lowers to native ones. Reading runtime/asm_amd64.s for the first time is a small culture shock; the conventions are documented at https://go.dev/doc/asm.
Comparison with other compilers
| Aspect | gc | LLVM (Clang) | rustc | INTERCAL compiler |
|---|---|---|---|---|
| IR levels | 2 (ir AST + SSA) | 1 (LLVM IR) | 4 (HIR/THIR/MIR/LLVM IR) | 0 (parse tree only) |
| Backend | Self (gen+rules) | LLVM | LLVM (default) | Self (templates) |
| Linker | Self (cmd/link) | LLD or system ld | LLD or system ld | system cc as driver |
| Optimisations | ~50 SSA passes, declarative rules | ~200 passes, C++ classes | MIR transforms + LLVM passes | constant fold, peephole, dead-flag |
| Self-hosted | Yes | No (C++) | Yes (Rust) | Yes (INTERCAL via stage3) |
| Cross-compile | Built-in via GOOS/GOARCH | --target with sysroot | --target with sysroot | macOS arm64, Linux arm64+x86-64 |
| Codebase | ~50K Go (compile) + ~80K Go (link) | ~10M C++ | ~3M Rust | ~2K zsh + assembly |
| Compile speed | Very fast (package parallel) | Slow (single-threaded per TU) | Slow (heavy IR) | Instant |
The shape Go shares with our INTERCAL compiler is "do it yourself, top to bottom". Go does it at production scale; we do it at toy scale. The decision points are the same: own backend or borrow LLVM, own linker or invoke cc, own runtime or rely on libc.
If you only read five files
For getting oriented in Go's compiler source:
src/cmd/compile/README.md: the project's own short orientation.src/cmd/compile/internal/ssa/_gen/genericOps.goand_gen/AMD64.rules: the generic IR ops and a per-arch lowering rule file.src/cmd/compile/internal/ssa/rewrite.go: how rules are matched and applied.src/cmd/compile/internal/escape/escape.go: escape analysis.src/runtime/proc.go: the runtime that the compiler emits cooperation calls into (write barriers, stack growth, preemption).
Common contributor gotchas
- Editing
*.ruleswithout re-runninggo generateincmd/compile/internal/ssaproduces no effect. Easy to think your change is wrong when really the generated code is stale. - Rule order matters; more-specific rules go first.
- Escape analysis is summary-based and per-package; recursion on calls is approximated.
//go:nosplitfunctions cannot allocate; the compiler will sometimes silently move heap-allocs off if you misuse it.- Runtime cooperation hooks (
runtime.morestack,writebarrier) are inserted by the compiler ingenssa.go. Do not assume the asm matches the SSA literally.
Area specialists
- Keith Randall: SSA backend, originator.
- Cherry Mui: linker, runtime.
- Matthew Dempsky (mdempsky): escape analysis, frontend types2.
- Austin Clements: runtime, GC cooperation.
- David Chase: SSA, regalloc.
Diagnostic flags worth knowing
GOSSAFUNC=Foo go build: dump SSA HTML for functionFoo.-gcflags='-m=2': escape and inlining details (level 3 is even more verbose).-gcflags='-d=ssa/<phase>/debug=1': trace a specific SSA phase.-gcflags='-d=checkptr=2': instrumented pointer checks.-gcflags='-S -L': assembly with source-line annotations.GODEBUG=gctrace=1,allocfreetrace=1: runtime-side tracing.-gcflags='-d=ssa/<pass>/off=1': bisect rule changes by disabling one phase.
For runtime-cooperation issues: GODEBUG=asyncpreemptoff=1 isolates whether new safe-point work is at fault.
Reading order
For a contributor who wants to land a first patch on Go in roughly a month:
- Read the Go programming language tutorial at https://go.dev/tour/ if you do not already know Go.
- Read the rustc-overview equivalent for Go, the README in
src/cmd/compile. Short and orienting. - Browse
src/cmd/compile/internal/syntax/parser.go. A real, hand-written, recursive-descent parser at production scale. ~3000 lines, excellent reading. - Open
src/cmd/compile/internal/ssa/gen/generic.rules. Read the first 200 lines until the patterns become natural. This is where most algebraic simplification lives. - Pick a phase from
compile.goand read its source.dse.go(dead store elimination) is short and self-contained. - For runtime, read
runtime/proc.gofor the scheduler,runtime/mgcmark.gofor the GC marker,runtime/netpoll_epoll.gofor the network poller.
How to contribute
Go uses Gerrit, not GitHub PRs. The flow:
git clone https://go.googlesource.com/go
cd go
git config remote.origin.review https://go-review.googlesource.com
git codereview change # creates a branch + commit
# ...edit, test...
git codereview mail # sends to Gerrit for review
The git-codereview plugin is a wrapper documented at https://go.dev/doc/contribute. Reviews happen on go-review.googlesource.com. Each change needs at least one approval (+2) from a maintainer.
Beginner-friendly issues are tagged Help Wanted and NeedsInvestigation on https://github.com/golang/go/issues. Particularly approachable categories: SSA optimisation rules in .rules files (declarative, easy to test), runtime small bugs, standard-library improvements, vet checks, error-message fixes.
Tests use Go's own testing framework. The test/ directory at the repo root holds end-to-end tests that exercise the compiler on small Go programs. Each new optimisation rule should come with a test in test/ that exercises the pattern.
Where to go next
- The Go internals series at https://internals-for-interns.com/posts/understanding-go-runtime/ walks the runtime piece by piece. Pairs naturally with our runtime.md, where the same questions ("what does the runtime have to do that the language can't?") come up at INTERCAL scale.
- Sazak's Go internals series at https://sazak.io/series/go-internals covers the SSA backend and walk pass in detail.
- The community-maintained https://github.com/emluque/golang-internals-resources indexes most extant Go internals material.
- Russ Cox's blog at https://research.swtch.com/ contains many of the original design notes for the Go compiler and runtime.
- llvm-overview.md and cranelift-overview.md for backends that take other approaches.
- contributing-to-production-compilers.md for a side-by-side comparison of contribution flows across the compilers in this Part.
GHC (Haskell), in shape
The Glasgow Haskell Compiler is the reference implementation of Haskell. Source at https://gitlab.haskell.org/ghc/ghc. It is the compiler in this Part with the most distinctive shape: four intermediate representations, each with formal semantics, and a runtime that implements lazy evaluation rather than eager. None of the other compilers here have either property at the same depth.
GHC matters in a book about compilers because its IRs are designed objects in a way most production IRs are not. Core is a tiny lambda-calculus, perhaps ten constructors, with a published formal semantics. STG is a simpler abstract machine model for lazy evaluation. Cmm is portable assembly with garbage-collection cooperation built in. Each was the subject of one or more papers by Simon Peyton Jones and his collaborators. Reading the GHC source means reading those papers turned into engineering, which is rare in production compilers.
The runtime story is just as distinctive. Lazy evaluation forces a particular runtime architecture: thunks, sharing, weak head normal forms, a stack discipline different from eager-evaluation languages. The Haskell runtime ("the RTS") has accumulated decades of work on this. None of the eager-language runtimes in this Part has the equivalent.
For a reader, GHC is the compiler that pushes the IR concept to its strongest form. If the LLVM chapter teaches you that an IR can be a portable assembly, the GHC chapter teaches you that an IR can also be a typed lambda calculus with a published semantics, lowered through several stages each of which preserves type and meaning.
The pipeline
Haskell source goes through more lowering steps than any other compiler in this Part:
source Foo.hs
→ tokens compiler/GHC/Parser/Lexer.x
→ HsSyn (parsed) compiler/GHC/Hs (phase GhcPs)
→ HsSyn (renamed) compiler/GHC/Rename, phase GhcRn
→ HsSyn (typechecked) compiler/GHC/Tc, phase GhcTc
→ Core compiler/GHC/HsToCore (the desugarer)
→ Core (after Simplifier) compiler/GHC/Core/Opt
→ STG compiler/GHC/CoreToStg
→ Cmm compiler/GHC/StgToCmm
→ assembly or LLVM IR compiler/GHC/CmmToAsm or compiler/GHC/Driver/Backend/Llvm
→ object via system as compiler/GHC/Linker
→ executable via system linker
Six lowering steps producing four intermediate representations. The shape: front-end, several IR layers, back-end.
The frontend (HsSyn through Core) is what is unusual. HsSyn is the AST and is parametrised by a "phase" type so the same data structure represents the program at different stages of frontend processing. Core is the typed lambda calculus. STG and Cmm are progressively lower abstractions that preserve enough semantic information for the runtime to do its job.
HsSyn: the phased AST
HsSyn (compiler/GHC/Hs/) is GHC's source AST. The signature data type is called HsExpr, parameterised by a pass parameter:
data HsExpr (p :: Pass) = HsVar (XVar p) (LIdP p)
| HsLit (XLit p) Lit
| HsApp (XApp p) (LHsExpr p) (LHsExpr p)
| ...
The XVar p, XLit p, XApp p fields are extension points. For each constructor, the type-family XVar pulls in a different type depending on whether p is GhcPs (parsed), GhcRn (renamed), or GhcTc (typechecked).
This is the "Trees that Grow" pattern (Najd and Peyton Jones, 2017). The same data structure changes shape gradually as the compilation phase progresses. A typed AST has type info at each node; a renamed AST has resolved names; a parsed AST has neither. The same recursive walks work on all three forms because the constructor names are stable; only the extension fields differ.
The pattern is GHC-specific in production compilers (rustc has separate AST/HIR/THIR types for each stage; Swift has one richly-typed AST evolved in place). Haskell as a language is good enough at type-level programming to make the Trees-that-Grow pattern feasible; in less type-rich languages it is not natural.
Renaming: scope and qualification
The renamer (compiler/GHC/Rename/) resolves names. Every identifier in the source has potentially many bindings (defined here, imported from there, qualified differently); the renamer picks the right one, or reports an error.
Why renaming is its own phase rather than merged with type checking: because Haskell has open imports (import Data.List, brings everything in), qualified imports, hiding clauses, name shadowing rules, and several layers of namespaces (term-level vs type-level vs class-level). A separate phase makes the rules tractable.
After renaming, the AST is GhcRn. Each name is a unique identifier ("name") rather than a textual binding. Subsequent phases never need to worry about scope.
Type checking: OutsideIn(X) and constraint-based inference
The type checker (compiler/GHC/Tc/) is the compiler's most sophisticated frontend phase. It implements OutsideIn(X), a constraint-based inference algorithm parameterised over a theory X of type-equality reasoning.
How it works in outline:
- Walk the AST, generating constraints (equalities, class memberships, subsumptions).
- Solve the constraints, simplifying and resolving until a fixpoint.
- For each
let-bound function, generalise: any free type variable not appearing in the surrounding environment becomes universally quantified. - The "X" is the theory plug-in: GADT equalities, type families (functions at type level), kind polymorphism, etc.
The data structures are intricate. Type, Kind, TyCon (type constructors), TyVar (type variables), Coercion (evidence of type equality), Class, DFun (dictionary function for an instance). Each is shared with Core, because Core needs to represent the same types after type checking.
Type-class resolution: class Eq a where (==) :: a -> a -> Bool is the user-level definition. The type checker turns this into a record type plus a function dispatching through that record. An instance like instance Eq Int where ... becomes a value of that record type. A use of == at type Int finds the right instance and elaborates the call to pass the dictionary explicitly. By the time we reach Core, type classes are gone; only dictionary passing remains.
GADTs and type families: these are where the OutsideIn algorithm earns its keep. A pattern match on a GADT constructor refines the local type; the constraint solver tracks this. Type families are functions at type level whose reductions are themselves constraints. The X-theory plug-in handles these uniformly with ordinary equalities.
For a reader who wants to learn type-system implementation, GHC's type checker is the deepest treatment available in production. It is also dense; the Trees-that-Grow encoding plus the constraint solver plus the rich data structures combine to a learning curve. The corresponding chapter in the GHC documentation is the right preparation.
Core: System FC, the centre of the compiler
Once type checking is done, the desugarer (compiler/GHC/HsToCore/) translates HsSyn to Core. Core is the most important IR in GHC. It is a typed lambda calculus, called System FC ("System F with Coercions"), a variant of Girard-Reynolds System F augmented with type-equality coercions to support GADTs and type families.
Core is small. The data type for expressions is roughly:
data Expr b = Var Id
| Lit Literal
| App (Expr b) (Arg b)
| Lam b (Expr b)
| Let (Bind b) (Expr b)
| Case (Expr b) b Type [Alt b]
| Cast (Expr b) Coercion
| Tick (Tickish Id) (Expr b)
| Type Type
| Coercion Coercion
Ten constructors. That is the entire core language. Everything Haskell expresses gets desugared into trees built from these ten.
What makes this powerful:
- Typed: every Core expression has a type. After every pass, you can run
Core Lintto verify that types remain consistent. - Total (or as close as a non-total language can be): the language itself is a calculus with reduction rules. Optimisations are reductions plus rewrites that preserve meaning.
- Sufficient: every Haskell program desugars to Core. There is nothing in the source language that requires a different IR.
- Coercion-bearing: GADT equalities and type-family applications generate
Castexpressions with explicit coercion evidence. The runtime never inspects coercions; they are erased before code generation. But the type checker uses them to encode the proof that the equality holds.
The simplifier (compiler/GHC/Core/Opt/Simplify/) is the optimisation engine. It performs:
- Inlining: based on the function's "unfolding" (Core source) and a set of heuristics. Aggressive: GHC inlines much more than most compilers.
- Beta reduction:
(\x -> e1) e2becomese1[x := e2]. - Case-of-case:
case (case e of ...) of ...becomescase e of ...after rewriting alternatives. Often unblocks further simplifications. - Let-floating: moves
let-bindings outside of functions or inwards as needed for sharing or evaluation order. - Eta-expansion:
fbecomes\x -> f xwhen an argument shape is needed. - Constant folding for primitive operations.
- RULES application: user-declared rewrite rules from
{-# RULES "name" forall x. f x = g x #-}are applied during simplification.
All of these run within a single fixpoint loop: the simplifier does not have separate passes for each optimisation; it does one walk that applies them all and iterates until stable. In production GHC, the simplifier runs multiple times in the pipeline, between other passes.
The relevance for somebody learning compilers: Core plus its simplifier is the cleanest production example of optimising a typed language. Each pass is a meaning-preserving rewrite. The IR is small enough to understand fully; the optimiser is sophisticated enough to teach modern techniques.
Strictness analysis and worker/wrapper
Two GHC-specific optimisations deserve their own attention because they are central to making Haskell fast.
Strictness analysis (compiler/GHC/Core/Opt/DmdAnal.hs): Haskell is lazy by default, but many functions are strict in some of their arguments (always evaluate them). The compiler analyses each function to determine which arguments are demanded and how (head-normal-form, fully evaluated, etc.). The result is a "demand signature" attached to each function.
The analysis is dataflow over Core, computing for each variable the "demand" that the function places on it. The lattice is rich (lazy, used once, used once strictly, strict and unboxed, etc.). The result enables the next optimisation.
Worker/wrapper transformation: with strictness information in hand, the compiler splits functions into two parts:
- The worker takes unboxed (raw) values and does the actual computation.
- The wrapper takes boxed (heap-allocated) values, unboxes them where appropriate, calls the worker, and reboxes the result.
The wrapper is small and gets inlined everywhere; the worker is the real work. After enough simplification, the boxes/unboxes around the worker often cancel out with operations elsewhere, leaving direct unboxed calls. This is the difference between "Haskell allocates everything" and "Haskell allocates only when it has to".
For a reader, strictness analysis is the cleanest example of a non-trivial dataflow analysis on a typed lambda calculus. It is also the optimisation that makes lazy evaluation practical in a production language; without it, the constant factor would be unfavourable.
STG: the abstract machine for laziness
After Core simplification ends, Core is translated to STG (Spineless Tagless G-machine, Peyton Jones 1992). STG is closer to the runtime than Core: it makes evaluation explicit, allocations explicit, and the abstract machine model concrete.
The STG syntax is even smaller than Core. From compiler/GHC/Stg/Syntax.hs:
data StgExpr = StgApp Id [StgArg]
| StgLit Literal
| StgConApp DataCon [StgArg] [Type]
| StgOpApp StgOp [StgArg] Type
| StgCase StgExpr ...
| StgLet (StgBinding) StgExpr
| StgLetNoEscape (StgBinding) StgExpr
| StgTick (Tickish Id) StgExpr
The names match Core but the semantics are different. StgApp f args is "apply function f to args"; in Core App was "form a tree"; in STG it is "perform an application". StgLet introduces a thunk on the heap; the let-bound value is allocated as a closure with code pointer plus free variables.
The "spineless" part: there is no AST spine of nested applications; applications are saturated where possible (all arguments at once), so allocations are minimised. The "tagless" part: closures in the heap don't carry a tag distinguishing thunks from values from constructors; the code pointer at the start of the closure dictates how to interpret it, and the interpreter (or generated code) jumps to that pointer to evaluate.
This design decision is the centre of GHC's evaluation model. A thunk and an evaluated value have the same shape in the heap; evaluation just means jumping to the code pointer, which (for a thunk) computes the value and updates the code pointer to be a "return this value" stub, and (for an already-evaluated value) jumps straight to the consumer.
The architectural simplicity buys a lot: no need for tags, no need for evaluators that switch on tag, sharing happens automatically through the in-place update.
For a reader, STG is the most distinctive piece of GHC's design and the hardest to compare to anything else. The Spineless Tagless G-machine paper from 1992 is required reading.
Cmm: portable assembly with cooperative GC
After STG, GHC translates to Cmm (compiler/GHC/Cmm/). Cmm is GHC's portable assembly. The lineage: it descends from C-- (Peyton Jones, Ramsey, and Reig, 1999), a portable assembly designed to support garbage-collected languages.
What Cmm has that LLVM IR does not:
- Calling-convention awareness for the language's GC: every Cmm procedure declares which of its arguments and live variables are GC-managed pointers. The runtime can scan these without disassembling the code.
- Stack management primitives: explicit stack-frame layout, stack pointer manipulation, stack overflow checks. The Haskell runtime is cooperative with the compiler about stack use.
- First-class globals: globally-shared registers like
Sp(stack pointer),Hp(heap pointer) are syntactically distinguished. - Multiple return: Cmm procedures can return multiple values directly to multiple destinations, avoiding allocation.
Cmm passes (in compiler/GHC/Cmm/Opt/):
- Stack layout (allocate slots for live variables across calls)
- Sinking (move computations to where they are used)
- Constant folding
- Common-block elimination
- Dead-code elimination
These passes are conventional but operate on a representation that knows about garbage collection, which conventional optimisers do not. Reading Cmm passes is a way to see what optimisation looks like when GC cooperation is a first-class concern.
NCG and the LLVM exit
After Cmm passes, GHC has two backends:
- NCG (Native Code Generator): compiler/GHC/CmmToAsm/. GHC's own backend, hand-written per architecture (x86-64, AArch64, PowerPC, RISC-V are supported in various states). Each backend is small relative to LLVM: roughly the order of ten thousand lines per architecture. The default for most platforms.
- LLVM: compiler/GHC/Driver/Backend/. Translate Cmm to LLVM IR, hand off to LLVM. Produces faster code in some cases (~5-15% improvement on numeric code), slower compile times.
The choice is per-build: ghc -fllvm selects LLVM, default is NCG. The NCG is small, fast to run, and produces reasonable code. LLVM is the production choice for tightly-optimised numeric Haskell.
Why does NCG exist alongside an LLVM option? Compile speed (NCG is much faster), distribution simplicity (no LLVM dependency), and platform support (NCG works on platforms where bringing up an LLVM target is its own project).
The runtime (RTS)
rts/ is GHC's runtime system, on the order of a hundred thousand lines of C plus assembly. It is the largest non-Haskell part of GHC.
What it provides:
- Garbage collector: generational, copying for the young generation, mark-compact for the older. An optional concurrent variant exists for low-pause applications.
- Thread scheduler: Haskell threads are green threads (M:N over OS threads). The RTS schedules them, handling context switches in user space.
- Sparks: speculative parallel evaluation.
par a bcreates a "spark" fora, allowing the runtime to evaluate it on another thread if available; otherwiseais just lazy as usual. - STM (Software Transactional Memory): transactional memory primitives, with the runtime managing log-based concurrency.
- Bytecode interpreter: GHCi (the interactive interpreter) executes bytecode directly; the bytecode interpreter is part of the RTS.
- FFI: bridges to C libraries, both calling C from Haskell and being called from C.
The GC deserves a footnote. Generational copying with a minor GC tuned for very fast allocation is the right design for a language that allocates as much as Haskell does. Every thunk is an allocation. Every list cons is an allocation. Every closure is an allocation. The minor GC must keep up with this. Most Haskell programs spend more time in the GC than in any non-trivial part of the program; tuning the GC is a routine performance activity.
For a reader, the RTS is the part of GHC most worth studying for understanding what a runtime has to provide for a high-level language. The contrast with Go's runtime (which has goroutines and a GC but no thunks) and with Rust's runtime (which has neither, beyond the stack and OS facilities) is sharp.
Concurrent (non-moving) garbage collector
GHC 8.10 (2020) added an optional concurrent mark-and-sweep collector for the old generation. By 2026 it is the standard low-latency option for Haskell production deployments. Real-world adopters (Mercury, Pusher, the IOG team) report sub-millisecond pauses on large heaps at the cost of slightly higher CPU on a spare core. There is no public 2025-2026 set of benchmarks superseding Ben Gamari's original numbers; ongoing work in 2025 has been around finalisers and weak references rather than a redesign.
A common production gotcha: -with-rtsopts=-N (use all cores) is poor as a library default because it grabs every core whether the consuming program wants that or not. Stack tracks an open issue (commercialhaskell/stack#680) about this.
JavaScript backend
GHC has a JavaScript backend, still labelled "technology preview" in the GHC 9.14 user's guide and not shipped in bindists. Users must build a cross-compiler. The 2025 discussion focused on output size; compiled bundles are large compared to GHCJS (the older, separate Haskell-to-JS compiler).
For somebody studying compilers, the GHC JS backend is interesting because it is a non-LLVM, non-NCG path: GHC's pipeline goes Cmm → JavaScript directly, treating JS as the target machine. Reading compiler/GHC/StgToJS/ shows what that lowering looks like.
Plugin ecosystem
GHC's plugin system supports plugins at several levels: parser plugins, renamer plugins, typechecker plugins, Core plugins, Cmm plugins. The most consequential plugin in production is Liquid Haskell, which adds refinement types to Haskell. Tweag's March 2025 release was a structural milestone: Liquid Haskell now consumes GHC's post-typecheck AST directly instead of re-parsing and re-typechecking the module. A GSoC 2025 project added qualified-import and alias resolution.
Repo layout
compiler/
GHC/
Hs/ Source AST (HsSyn) with phased extension fields
Parser/ Lexer (Alex) and parser (Happy)
Rename/ Name resolution
Tc/ Type checker (OutsideIn algorithm, constraint solver)
HsToCore/ Desugaring HsSyn → Core
Core/ Core IR + simplifier
Opt/ Optimisations (simplifier, demand analysis, etc.)
CoreToStg/ Core → STG
Stg/ STG IR
StgToCmm/ STG → Cmm
Cmm/ Cmm IR + passes
CmmToAsm/ NCG (Native Code Generator)
Driver/ Top-level compiler driver, backend selection
rts/ Runtime system in C + assembly
libraries/ Standard library packages (base, ghc-prim, etc.)
testsuite/ Test programs
docs/users_guide/ User-facing documentation
docs/comm/ "Commentary": developer documentation
The docs/comm/ (commentary) directory is the developer documentation, sometimes outdated, but the only narrative explanation of many internals.
Comparison with other compilers
| Aspect | GHC | rustc | OCaml |
|---|---|---|---|
| IRs | HsSyn, Core, STG, Cmm | HIR, THIR, MIR, LLVM IR | Parsetree, Typedtree, Lambda, Cmm, Mach |
| Type system | HM + System F + classes + GADTs + families | HM-derived + traits + lifetimes | HM + functors + GADTs |
| Evaluation | Lazy (call-by-need) | Eager | Eager |
| Backend | NCG (default) or LLVM | LLVM | Self-hosted per-arch |
| Runtime | RTS with GC, scheduler, STM, sparks | Minimal (libstd, no GC) | C runtime with GC, exceptions |
| Self-hosted | Yes | Yes | Yes |
| Distinguishing piece | Lazy evaluation runtime | Borrow checker | Functor module system |
GHC stands out on every row. Lazy evaluation alone changes everything: how arguments are passed, what allocation patterns look like, what optimisations matter, what the runtime has to do.
If you only read five files
For getting oriented in GHC source:
compiler/GHC/Driver/Pipeline.hs: the orchestrator.compiler/GHC/Core/Opt/Simplify/Iteration.hs: the simplifier rewrite engine, the heart of the optimiser.compiler/GHC/Core/Opt/DmdAnal.hs: demand analysis.compiler/GHC/Stg/Lift.hspluscompiler/GHC/StgToCmm.hs: STG and the lowering to Cmm.rts/Schedule.cplusrts/sm/Storage.c: the runtime system.
Common contributor gotchas
Note [...]is GHC's design-document convention. Every cross-cutting decision has aNote; grep is the only index. Adding code that crosses one of these boundaries usually means writing or referencing the relevant Note.- Demand-analysis fixpoints can blow compile time. Watch
-ddump-stranalfor divergent results. - The simplifier runs to a fixpoint, with a phase number. Rules are gated by phase:
{-# RULES "name" [2] forall x. f x = g x #-}only fires in phase 2 and earlier. - RTS code is split between threaded/non-threaded variants compiled with different
#defines. Edits toSchedule.cmust build both ways. - "Shouldn't happen" panics expect you to add a Note explaining the invariant.
Area specialists
- Simon Peyton Jones: simplifier, types.
- Sebastian Graf: demand analysis, Cmm.
- Matthew Pickering: eventlog, ticky tooling.
- Ben Gamari: RTS, releases.
- Andreas Klebinger: codegen, regalloc.
- Cheng Shao: Wasm backend.
- Rodrigo Mesquita: linker.
Diagnostic flags worth knowing
-ddump-simpl-iterations,-ddump-stranal,-ddump-cse: per-phase Core dumps.-ddump-stg-final,-ddump-cmm-from-stg: STG and Cmm dumps.-ddump-asm-stats: assembly statistics.-dverbose-core2core: trace Core-to-Core passes.-dcore-lint,-dstg-lint,-dcmm-lint: per-IR sanity checkers. Always enable when developing new passes.-tickyplus+RTS -rticky.html -RTSpluseventlog2html: per-closure execution profile.
For RTS issues: +RTS -Ds -Da -DG -RTS enables debug-build trace output; requires building with --enable-debug-build.
Reading order
A practical path:
- Read the GHC user guide for context on the language and tooling.
- Read the GHC Commentary, the developer documentation.
- Browse
compiler/GHC/Hs/Expr.hsto see HsSyn. - Read
compiler/GHC/Core/Syntax.hs(or the equivalent) for Core. Ten constructors, easy to absorb. - Read "Implementing Lazy Functional Languages on Stock Hardware: The Spineless Tagless G-Machine" (Peyton Jones 1992) before diving into STG code.
- Read
compiler/GHC/Cmm/Syntax.hsfor Cmm. - Read
compiler/GHC/Core/Opt/Simplify/Iteration.hsto see the simplifier. - For runtime,
rts/sm/Storage.cis the heap manager,rts/sm/GC.cis the major collector.
How to contribute
GHC uses GitLab merge requests at https://gitlab.haskell.org/ghc/ghc. The community is active, with weekly devops calls, open mailing lists, and a strong tradition of academic-paper-followed-by-implementation. The contribution guide is in MAINTAINERS.md.
Beginner-friendly categories:
- Error message improvements: GHC has been investing in user-facing diagnostics; small additions are welcome.
- Library additions to
base(the standard library) following the Core Libraries Committee's process. - Documentation in
docs/. - Simplifier or demand-analysis improvements: each one is a small PR, with rich opportunities.
Build:
git clone https://gitlab.haskell.org/ghc/ghc
cd ghc
./boot
./configure
hadrian/build
Build time is significant (~30 minutes from scratch). Bootstrapping requires an older GHC, downloadable via ghcup. Hadrian has been the only supported build system since GHC 9.6 (2023); the legacy Make-based build was removed.
Where to go next
- "The Implementation of Functional Programming Languages" by Simon Peyton Jones (1987), free PDF at https://www.microsoft.com/en-us/research/publication/the-implementation-of-functional-programming-languages/. Older but still relevant on lazy evaluation and graph reduction.
- "Implementing Lazy Functional Languages on Stock Hardware: The Spineless Tagless G-Machine" (Peyton Jones 1992), the canonical STG reference.
- "Modern Compiler Implementation in ML" by Andrew Appel; the ML-flavoured cousin to the Haskell story.
- The GHC Commentary at https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary.
- "OutsideIn(X): Modular type inference with local assumptions" (Vytiniotis et al. 2011) for the type-checker algorithm.
- ocaml-overview.md for the other major ML-family compiler.
- rustc-overview.md for the type-system descendant that took different decisions.
OCaml, in shape
OCaml is the production member of the ML family of languages, descendant of Caml Special Light, descendant of Caml Light, descendant of Caml, descendant of LCF/ML. The compiler lives at https://github.com/ocaml/ocaml. It is small by production-compiler standards, around 200,000 lines, and has been continuously self-bootstrapped for roughly 35 years through an unbroken chain of source releases. That continuity is itself the lesson: a self-hosting compiler can persist for decades without the bootstrap chain ever breaking, if the project takes care to ship a bootstrap binary alongside source.
OCaml deserves a chapter for three independent reasons. It is the canonical implementation of Hindley-Milner type inference, the algorithm that underlies the type systems of Haskell, Rust (in part), Swift (in part), Scala, and most modern statically-typed functional languages. Its module system with functors is a piece of language design that has not been adopted at the same depth by anyone else in this Part. And it pairs a native compiler with a bytecode compiler that share the same frontend, demonstrating in 200,000 lines what tiered compilation looks like at the design level rather than the JIT level.
For a reader of this book, OCaml is the production parallel to "what if our compiler had a real type system and a real module system but stayed small". It is also genealogically connected to rustc: rustc was first bootstrapped through OCaml (rustboot, 2010-2011), and many of rustc's design instincts trace back to OCaml habits.
The pipeline
OCaml has two output paths from a shared frontend:
source program.ml
→ tokens parsing/lexer.mll (ocamllex)
→ Parsetree parsing/parser.mly (Menhir/ocamlyacc)
→ Typedtree typing/
→ Lambda lambda/translmod.ml + bytecomp/translcore.ml
→ bytecode bytecomp/bytegen.ml (ocamlc path)
→ Closure asmcomp/closure.ml (ocamlopt path)
→ Cmm asmcomp/cmmgen.ml
→ Mach (per-arch) asmcomp/<arch>/selection.ml
→ Linear asmcomp/linearize.ml
→ assembly asmcomp/<arch>/emit.mlp
The two paths share everything up to and including Lambda. The bytecode path then turns Lambda into a stack-based bytecode for the OCaml virtual machine (ocamlrun). The native path performs closure conversion, lowers to Cmm, picks instructions per architecture (Mach), linearises (Linear), and emits assembly.
ocamlc is the bytecode compiler; ocamlopt is the native compiler. Both produce executables, but with different runtime characteristics: bytecode runs through a portable VM; native compiles to platform-specific machine code. Both compilers are themselves OCaml programs; the bootstrap problem is solved by shipping a bytecode boot/ocamlc in the repository.
Hindley-Milner in production
OCaml's type checker is the canonical Hindley-Milner inferencer in production. The code lives in typing/. The key module is typing/typecore.ml, which implements the inference algorithm.
The algorithm, in outline, is Algorithm W. Each expression has a type variable; the algorithm walks the AST, generating substitutions that unify type variables with concrete types. When a let-bound expression has a polymorphic type, the algorithm generalises: free type variables in the expression's type that are not free in the surrounding environment become quantified. When the polymorphic value is used, the type is instantiated by replacing the quantified variables with fresh type variables, and inference continues.
What looks simple in the textbook becomes work in production:
- Level-based generalisation: a naive algorithm runs in O(n²) on programs with deep
let-nesting. OCaml uses a level-based scheme (Didier Rémy's invention) that tracks the binding depth of each type variable and generalises lazily. - Recursive types: occurs check prevents infinite types, except where the language deliberately allows them (
-rectypes). - Polymorphic mutability: the value restriction (Wright 1995) constrains where polymorphism can be generalised in the presence of mutable references. OCaml implements a refined form of the value restriction that allows more programs than the strict one.
- GADTs: handled as locally abstract types with equation-based reasoning. Adds significant complexity to inference.
- First-class modules: modules can be packed into runtime values (
(module M : S)) and used as expressions, with their type system contribution preserved. - Object types: structural subtyping with row variables and unification under row constraints.
Reading typing/typecore.ml line by line is one of the most productive ways to learn type inference. Roughly 4,000 lines, dense but readable, and it implements a feature set that is broader than most academic presentations cover.
The genealogical link to rustc is visible here: rustc's type checker also descends from Hindley-Milner, with significant departures (bidirectional inference, trait dispatch, lifetimes). But the family resemblance shows in the data structures: type variables, levels, unification, generalisation, instantiation. A reader who has read OCaml's type checker will recognise the moves in rustc's, even if the encoding differs.
The module system with functors
Modules are the part of OCaml that has the least direct counterpart in this Part. Other compilers have namespaces, classes, traits, packages: OCaml has signatures, structures, and functors.
A signature describes what a module provides:
module type S = sig
type t
val zero : t
val add : t -> t -> t
end
A structure implements a signature:
module IntS : S = struct
type t = int
let zero = 0
let add x y = x + y
end
A functor takes a module and produces a module:
module MakeMonoid (M : S) = struct
let sum = List.fold_left M.add M.zero
end
module IntSum = MakeMonoid (IntS)
This is parametric modules: a function from modules to modules, applied at compile time. The MakeMonoid functor is a definition; MakeMonoid (IntS) is an application that produces a new module.
What this gives you that namespaces or classes do not:
- Type abstraction at module boundary:
type tin the signature is opaque from outside the module unless explicitly exposed. - Parametric reuse: write the data structure or algorithm once over a signature; instantiate it for every type that satisfies the signature.
- Functor composition: functors take functors as arguments, producing module pipelines.
- First-class modules: a module can be packaged as a runtime value, passed to a function, returned, stored in a list. Compile-time abstraction crosses into runtime.
The compiler implementation lives mostly in typing/mtype.ml (module types), typing/includecore.ml (signature matching), and typing/typemod.ml (module typing). Reading these gives you a feel for what a non-trivial module system looks like at the implementation level. Significantly more complex than Rust's module system; significantly less complex than ML-with-functors theoretical accounts make it sound.
For a reader, the practical lesson is that module-level abstraction is a different kind of thing from value-level abstraction (functions) and type-level abstraction (generics, type classes). Modules sit at a third level. Most languages collapse module-level into one of the other two; OCaml keeps it separate, and the result is unusually expressive.
Lambda and the dual-target frontend
After type checking, the typed AST is lowered to Lambda, an untyped lambda calculus IR. The types are erased at this point: Lambda does not carry them.
Why erase? Because both the bytecode and the native backends consume Lambda, and neither needs the source-level type structure. Type erasure simplifies the IR and lets the same data structure flow into two very different backends.
Lambda has:
- Variables, applications, lambdas, lets, sequences
- Primitive operations (arithmetic, comparison, allocation)
- Pattern-match compilation (more on this below)
- Exception handling primitives (try/raise)
- Module-level operations (load, store, structure access)
The Lambda layer is also where some early optimisations happen: constant folding, simple inlining, dead-code elimination, basic CSE. Nothing aggressive, but enough to clean up the immediate output of type checking.
Pattern matching: OCaml is a pattern-matching language, and pattern matches in the source AST are compiled to decision trees in Lambda. The compilation is the textbook problem from Maranget's papers ("Compiling Pattern Matching to Good Decision Trees", JFP 2008), implemented in lambda/matching.ml. It is one of the more sophisticated parts of the compiler and is worth reading on its own, separate from the rest of OCaml internals.
The bytecode path: ocamlc
ocamlc lowers Lambda to bytecode, a stack-based instruction set executed by ocamlrun. The bytecode VM design descends from the ZINC machine (Leroy 1990), simplified.
Key VM characteristics:
- Stack-based: most operations consume operands from the stack and push results.
- Accumulator register: one designated register for the "current" value, an optimisation over pure stack design.
- Compact: each instruction is one byte for the opcode plus 0-2 bytes of operand. A program fits in much less space than its native equivalent.
- Fast to start: no compilation to machine code, no linker, no relocation. The VM loads the bytecode and runs.
Why ship a bytecode compiler at all in 2026, when native is faster? Several reasons:
- Portability: the bytecode runs on any platform with a
ocamlrun; the binary is the same. - Bootstrap:
boot/ocamlcis the bootstrap binary in the repo. Bytecode is platform-independent, so the bootstrap binary works on every target. - Compile speed:
ocamlcis faster thanocamlopt, useful for development cycles. - Debug: the bytecode debugger (
ocamldebug) works on bytecode programs; debugging native programs is harder in OCaml's ecosystem.
For a reader, this is one of the cleanest examples of "the same language compiled two ways for different tradeoffs". The decisions feel familiar: use bytecode for fast iteration and ship-anywhere portability, use native for production speed.
The native path: ocamlopt
The native pipeline takes Lambda through closure conversion, Cmm lowering, instruction selection, register allocation, and assembly emission.
Closure conversion (asmcomp/closure.ml): turns nested functions into top-level functions plus explicit closure data. A free variable in an inner function becomes a field of the closure record.
Cmm (asmcomp/cmm.ml): a portable assembly IR. Instructions are arithmetic, memory, control flow, calls, allocation. Cmm is conceptually similar to the Cmm in GHC (and shares the lineage from C-- by Peyton Jones), though the implementations are independent. Cmm is target-independent; the same Cmm can be compiled for any supported architecture.
Mach (asmcomp/mach.ml): a per-architecture intermediate that captures the target's instructions plus pseudo-registers. The Cmm-to-Mach lowering picks instructions; the result is Mach.
Liveness and register allocation (asmcomp/liveness.ml, asmcomp/regalloc.ml, asmcomp/linscan.ml): OCaml ships two native register allocators. The default is a graph-colouring allocator (Chaitin-Briggs flavour). An optional linear-scan allocator, the classical Poletto-Sarkar algorithm from "Linear Scan Register Allocation" (1999), is opt-in via -linscan (since OCaml 4.06) and lives in asmcomp/linscan.ml. The linear-scan implementation is small (~330 lines) and notably readable. It is one of the best educational references for register allocation in any production compiler.
Linear (asmcomp/linear.ml): the Mach is then linearised, exploring control flow and producing a flat instruction sequence.
Emission (asmcomp/<arch>/emit.mlp): the linear instructions are formatted as assembly text for the target. The .mlp extension is for files preprocessed by cpp; the architecture-specific assembly syntax differs between as (GNU) and Apple's assembler, and the preprocessor handles those differences.
Assembling and linking: OCaml invokes the system assembler (as) and linker (ld or cc -o), like our INTERCAL compiler. There is no LLVM, no LLD; the entire native backend is OCaml code that emits text the system tools consume.
The native backend supports amd64, arm64, riscv, power, s390x, with i386 and a few others retired or deprecated. Each is roughly 1,000 lines. The contrast with LLVM's per-target backends (tens of thousands of lines each) is stark; the price is that OCaml's optimiser is much less aggressive.
The runtime
runtime/ is the C-language runtime that supports both bytecode and native programs. Around 30,000 lines of C plus assembly for context switching.
What it provides:
- Garbage collector: generational mark-sweep with incremental GC of the major heap. The minor heap is a copying collector. The major heap uses mark-sweep with optional compaction. Designed for low pause time given the era (2.0+ added incremental, 4.0+ added concurrent finalisation, 5.0+ added multicore).
- Exceptions: implemented via stack unwinding through OCaml frames. Each
trysets a handler frame;raisewalks the stack until a handler matches. - FFI:
externaldeclarations connect OCaml functions to C implementations via a small set of conventions. The C side uses thecaml_*API for allocation and value access. - Multicore (OCaml 5.0+, 2022):
Domainfor parallelism, effects for capability-style concurrency.
The OCaml 5.0 multicore project deserves a footnote. It took about a decade of design work and a major runtime rewrite. The result is parallel OCaml without breaking source compatibility; the same programs run on 4.x and 5.x, but multicore programs use the new Domain API. The relevant lesson is that retrofitting concurrency to a runtime that assumed single-threaded was a serious undertaking, comparable in scale to the JIT additions in V8 or Sparkplug.
The unbroken bootstrap chain
The ML language family traces back to LCF/ML (Edinburgh, 1970s). The Caml lineage is:
- ~1987: Caml (Ascánder Suárez at INRIA), the first Caml implementation, in Lisp.
- 1990: Caml Light (Xavier Leroy and Damien Doligez), bytecode VM, the first widely-used Caml.
- 1995: Caml Special Light, added a native compiler.
- 1996: OCaml 1.0, the unified release that succeeds Caml Special Light.
- continuously since: each release built by the previous.
The mechanism: boot/ocamlc is a bytecode binary committed to the repository. It is the previous release's bytecode compiler, capable of compiling the current source. Each release updates boot/ocamlc only after a successful self-build.
This is the textbook implementation of "Trusting Trust" considerations applied at production scale. A malicious modification of the OCaml source would have to also modify the boot binary in a self-consistent way; the scrutiny on OCaml releases (and the existence of independent rebuilds) makes that hard to do silently.
For our INTERCAL compiler, the boot binary equivalent is intercalc.sh (the zsh script, plus the runtime and syslib it depends on). The chain is: intercalc.sh compiles compiler.i to produce intercal_core, which compiles itself, fixpoint test. The same shape, smaller scale, less scrutiny.
The Caml family chain has been unbroken for roughly 35 years (depending on whether you count from Caml Light's 1990 bytecode self-hosting or earlier prototypes). That is a useful number to remember when thinking about how long a self-hosted compiler can persist.
OCaml 5 in production
Multicore OCaml, released as OCaml 5.0 in December 2022, has crossed into production by 2026. Notable adopters:
- Jane Street completed its production switch to the multicore runtime. Their internal OxCaml fork (an experimental "OCaml oxidised") is the testbed for new Flambda 2 capabilities.
- Docker Desktop is rolling out direct-style Eio-based code, reaching "hundreds of millions of users" per Anil Madhavapeddy's ICFP 2025 notes.
Pitfalls reported from real adoption:
- GC pacing changed under the new runtime; latency regressions need tuning.
Unix.forksemantics with parallel domains remain a sharp edge.- Effect handlers have an "unhandled effect" trap when escaping a Domain.
OCaml 5.3 (January 2025) re-enabled statmemprof with multicore awareness. PR #12309 introduced dedicated syntax for deep handlers (pattern-matching style), reducing the boilerplate that made handlers feel research-y in 5.0-5.2.
Flambda 2
Flambda 2 is the optional middle-end optimiser for OCaml's native backend. By 2026 it is Jane Street's sole optimiser; the original Flambda and Closure passes are no longer in their pipeline. Flambda 2 supports both the OCaml 4 and OCaml 5 runtimes; OCaml 4 support is scheduled for removal in autumn 2025.
It is selectable in OCaml 5.4.0 beta 2 via the standard flambda2 switch (e.g., opam switch create 5.4.0+beta2+flambda2).
The OxCaml fork is where new Flambda 2 capabilities are tested before upstreaming. The compilation pipeline differs in several places (loop optimisation, unboxing, inlining heuristics) but the rest of the compiler is upstream-compatible.
Platform tooling
The OCaml platform (the curated set of canonical tooling) had a productive 2025-2026 cycle:
- Dune 3.21.0 added OxCaml support and copy-on-write file operations.
- Merlin 5.6.1-504 improved signature help and fixed completion for inlined record labels.
- OCaml-LSP 1.25.0 added
.mlxfile support with diagnostics, code actions, and formatting viaocamlformat-mlx. - opam 2.5.0 is up to 70% faster on
opam updateoperations. - Relocatable OCaml landed in late 2025, letting opam clone switches instead of rebuilding them. First available in OCaml 5.5 alpha.
For somebody learning the OCaml ecosystem, this tooling is the visible surface. The compiler's stability over decades means the tooling is what changes year to year.
Repo layout
parsing/ Lexer, parser, AST, Parsetree
typing/ Type checker, environment, module typing
typecore.ml Expression-level inference
typemod.ml Module-level inference
includecore.ml Signature matching
lambda/ Lambda IR, pattern-match compilation, early opts
bytecomp/ Lambda → Bytecode
asmcomp/ Lambda → Closure → Cmm → Mach → assembly
closure.ml Closure conversion
cmm.ml, cmmgen.ml Cmm IR and generation
<arch>/ Per-architecture
linscan.ml Linear-scan register allocator
middle_end/ Optional middle-end (Flambda 1 and 2 inliners)
runtime/ C runtime (GC, exceptions, FFI)
stdlib/ Standard library
boot/ Bootstrap bytecode binaries
testsuite/ Tests
Makefile.config Build configuration
configure Configure script
The middle_end/ directory is where Flambda lives. Flambda is OCaml's optional optimising middle-end, off by default in standard releases (Flambda 1) and enabled with --enable-flambda. Flambda 2 is in development. Both perform inlining, simplification, and unboxing on a Flambda-specific IR sandwiched between Lambda and the rest of the pipeline. Most production OCaml builds do not use Flambda; it is a research project at this point.
Comparison with other compilers in this Part
| Aspect | OCaml | rustc | GHC |
|---|---|---|---|
| Type system family | Hindley-Milner with extensions | HM + ownership + traits | HM + System F + classes + GADTs |
| Module system | Functors (parametric modules) | Crates + traits | Modules but flat |
| IRs | Parsetree, Typedtree, Lambda, Cmm, Mach, Linear | AST, HIR, THIR, MIR, LLVM IR | HsSyn, Core, STG, Cmm |
| Backend | Self-hosted per-arch | LLVM (default) | NCG or LLVM |
| Bytecode target | Yes (ocamlc) | No | No (GHCi has bytecode but for interactive only) |
| Self-bootstrapped | Yes (1985+) | Yes (via OCaml originally, then via LLVM) | Yes |
| GC | Generational mark-sweep | None | Generational copying |
| Codebase | ~200K lines OCaml | ~3M Rust | ~700K Haskell + C |
The shape closest to ours: OCaml's split between bytecode (small, portable, fast to start) and native (larger, target-specific, faster) maps onto our intercalc.sh (bytecode-equivalent: portable shell, slow but ubiquitous) and compiler.i (native-equivalent: targets specific platforms via Label 666). The analogy is loose but the idea is the same.
The shape closest to rustc: type inference, module-level abstraction, immutable-by-default semantics. Reading OCaml after rustc is reading a smaller cousin.
If you only read five files
For getting oriented in OCaml's compiler source:
parsing/parsetree.mli: the AST type, the foundation of every later transformation.typing/typecore.ml: the expression type-checker. ~4,000 lines of dense Hindley-Milner.lambda/lambda.mlandlambda/translcore.ml: Typedtree to Lambda lowering.asmcomp/cmmgen.ml: Lambda to Cmm.asmcomp/asmgen.ml: the native pipeline driver.
For Flambda 2: middle_end/flambda2/simplify/simplify_expr.ml in the ocaml-flambda fork.
Common contributor gotchas
- The type-checker mutates
Btype.cleanup_abbrevlevels. Do not snapshot a type withoutgeneralize/instancepairing or you will leak metavariables. Lambda.lambdais untyped; all GADT info is lost. Do not try to recover it.- Native and bytecode backends share the frontend but diverge at Cmm/Bytegen. A behavioural difference is usually a Cmm bug.
- The standard library is compiled with bootstrapping rules in
stdlib/Makefile. Edits need amake coldstartcycle. - PRs that touch the type checker need the maintainers' agreement; the team is small and conservative. Discuss before implementing.
Area specialists
- Xavier Leroy: whole compiler, release manager.
- Gabriel Scherer: type system, frontend.
- Florian Angeletti: errors, modules.
- Pierre Chambart, Vincent Laviron, Guillaume Bury: Flambda 2.
- Damien Doligez: runtime.
- KC Sivaramakrishnan: multicore runtime.
- Nathanaëlle Courant: Flambda 2 collaborator.
Diagnostic flags worth knowing
-dparsetree,-dtypedtree: frontend dumps.-dlambda,-drawlambda: Lambda IR before and after early simplification.-dclambda: Closure IR (after closure conversion).-dcmm,-dlinear,-dsel,-dreload,-dlive,-dspill,-dscheduling: native-pipeline dumps.OCAMLPARAM=_,dump-into-file=1: route dumps to files instead of stderr.- For Flambda 2:
-dflambdaand-dflambda-let-stage.
For bootstrapping: boot/ocamlc is the bytecode compiler used while the build is broken. When frontend changes break the stdlib build, regenerate via make promote after the new compiler is bootstrapped.
Reading order
A practical path for somebody with some functional-programming background:
- Read Real World OCaml for the language. Free online.
- Read
parsing/parser.mlyfor the grammar. - Read
typing/typecore.mlslowly. This is the big one, the canonical Hindley-Milner inferencer. - Read
lambda/matching.mlfor pattern-match compilation. Self-contained, beautiful. - Read
asmcomp/linscan.mlfor register allocation. Short and pedagogical. - Read
runtime/major_gc.cfor the major heap GC.
How to contribute
GitHub PRs to https://github.com/ocaml/ocaml. The project is INRIA-led with a dedicated set of maintainers. Code review is rigorous and code style is conservative. The CONTRIBUTING.md in the repo describes the flow.
Beginner-friendly categories:
- Standard library improvements:
stdlib/is broad and many functions are improvable. - Small bug fixes in less-touched parts of the compiler.
- Documentation: the manual is extensive but the compiler internals have very little.
- Testsuite additions, especially for less-tested features.
Build:
git clone https://github.com/ocaml/ocaml
cd ocaml
./configure
make
make tests
The build is fast (~5 minutes on a modern machine) compared to LLVM or Swift. The test suite is comprehensive.
Where to go next
- The OCaml manual at https://ocaml.org/manual.
- Real World OCaml by Yaron Minsky, Anil Madhavapeddy, and Jason Hickey, free at https://dev.realworldocaml.org/.
- Xavier Leroy's papers on the OCaml compiler at https://xavierleroy.org/publi/.
- "The ZINC Experiment: An Economical Implementation of the ML Language" (Leroy 1990) for the bytecode VM design.
- "Linear Scan Register Allocation" (Poletto and Sarkar 1999) for the regalloc.
- rustc-overview.md for the genealogically-related compiler.
- ghc-overview.md for the other major ML-family production compiler.
Cranelift, in shape
Cranelift is the deliberate counterpoint to LLVM: a code-generation library, written in Rust, designed for fast generation rather than aggressive optimisation. Source lives at https://github.com/bytecodealliance/wasmtime under cranelift/. It is not a complete compiler. There is no frontend, no parser, no linker. It takes its own intermediate representation as input and produces machine code or object files as output. Embedders write the frontend.
The reason to read about it in this book is that it inverts the LLVM defaults. LLVM is "as much optimisation as you can afford"; Cranelift is "as little optimisation as you can get away with, and as fast as possible". Both are correct answers to different questions. A reader who only knows LLVM will treat its tradeoffs as natural law; reading Cranelift is the easiest way to see those tradeoffs as choices.
About 50,000 lines of Rust cover x86-64, AArch64, RISC-V 64-bit, and s390x targets. By comparison, LLVM is roughly 200 times that. The size difference is not because Cranelift is half-finished; it is because Cranelift is doing less by design.
Who uses it
Cranelift began in 2016 as cretonne, started by Dan Gohman as a standalone code-generation library. It was later experimentally adopted by Mozilla's SpiderMonkey as a WebAssembly backend (2018-2020) but was removed before shipping in Firefox. It is now developed under the Bytecode Alliance. The major consumers:
- Wasmtime: the reference WebAssembly runtime. Cranelift compiles each WASM module on first use. Compile time matters because users wait for it.
- rustc as an alternative debug-mode codegen backend, enabled with
-Zcodegen-backend=cranelift. Speeds debug builds by 2-3x because Cranelift is much faster to run than LLVM. - Wasmer: another WASM runtime, supports Cranelift among multiple backends.
- Lucet (archived): Fastly's edge-WASM runtime, originally Cranelift-based; Fastly migrated to Wasmtime.
The pattern is that Cranelift wins where compile time per function dominates total time: JIT scenarios, ahead-of-time compilation of many small functions, debug builds where iteration speed matters more than emitted code quality.
CLIF: Cranelift's IR
CLIF (Cranelift Intermediate Format) is the IR. It is SSA-form, typed, organised into basic blocks. The instruction set has roughly 200 opcodes covering integer and floating-point arithmetic, memory access, vector operations, control flow, and ABI-related operations.
A small CLIF function looks like this:
function %add(i32, i32) -> i32 {
block0(v0: i32, v1: i32):
v2 = iadd v0, v1
return v2
}
Three things to notice. First, function arguments are block parameters of block0, the entry block, not separate parameters of the function as in LLVM. Second, control-flow joins use block parameters everywhere, not phi nodes. A block can be jumped to from multiple predecessors with different argument values; the receiving block names them as its parameters. Third, types are part of every value definition; CLIF has no implicit promotions.
Block parameters instead of phi nodes is one of the design decisions worth pausing on. LLVM and most other SSA-form IRs use phi instructions at the start of each block to merge values from predecessors. Cranelift represents the same information as block arguments. The two are isomorphic, but block-arguments form is easier to reason about for some algorithms and easier to maintain through transformations: there are no special "phi must come first" rules, no need to update phi inputs separately when adding a predecessor edge, no risk of breaking SSA by inserting code before phis.
This is the same design choice MLIR made (block arguments in MLIR's SSA dialects), and the same one Webkit's B3 made. It is a quiet but real architectural difference from the LLVM lineage.
SSA construction on the fly
Frontends do not build CLIF directly; they use cranelift_frontend::FunctionBuilder. This API maintains SSA form incrementally as the frontend emits instructions, using the algorithm from Braun et al., "Simple and Efficient Construction of Static Single Assignment Form" (CC 2013).
The Braun algorithm avoids the explicit dominance-frontier computation that classical SSA construction (Cytron 1991) requires. Instead, it lazily inserts block parameters whenever a variable read needs a value the current block does not have, walking predecessors as needed and inserting parameters on the fly.
The practical consequence: a frontend can emit CLIF top-down without computing dominators or planning where phi-nodes belong. The SSA structure emerges as a side effect of the build. This is much friendlier than LLVM's typical pattern of "emit allocas, store/load to model variables, run mem2reg later".
For a contributor, this means the frontend code is short and direct. For a reader, it is a different intuition for SSA construction than the textbook algorithm.
Optimisation passes (the deliberately small list)
Cranelift's optimiser is intentionally minimal. The passes that run by default:
- Simple constant folding
- Simple dead-code elimination
- Branch threading (jump-to-jump elimination)
- Simple CSE (common subexpression elimination)
- Egraph-based simplification (
cranelift_codegen::opts/, in production): a single pass that combines GVN, simplification, and limited rewriting through an e-graph data structure
What is missing, by design: aggressive inlining, loop optimisations, vectorisation, polyhedral, profile-guided. Cranelift is not the place to do those; LLVM is.
The egraph rewriter is the most distinctive recent addition. The 2026 design write-up by Chris Fallin, "The acyclic e-graph: Cranelift's mid-end optimizer", is the canonical reference. Cranelift uses an acyclic variant of the standard e-graph data structure: this avoids the saturation explosion that classical e-graphs (egg, equality saturation) can hit, while keeping the engineering benefits. The optimiser is on by default, and ISLE rewrite rules drive it. As of 2026, around seventeen contributors have added or tweaked rules over the last three years; the codebase is small enough that adding a single rule is a focused contribution.
E-graphs (equivalence graphs) are a data structure where each node represents an equivalence class of values, and rewrites add to the class without losing the original form. After applying rewrites, an "extraction" phase picks the cheapest representative from each class. Cranelift's implementation is tailored for SSA. The whole thing is a single pass that does the work of several conventional passes.
Reading cranelift/codegen/src/opts/ is a way to learn about e-graphs without diving into the academic egg library. It is a production e-graph applied to a real backend.
Three execution tiers in Wasmtime
A 2024-2025 development worth highlighting: Wasmtime now ships three execution backends instead of just Cranelift.
- Cranelift: the optimising backend covered above. Default for production hot code.
- Winch: a single-pass baseline compiler, 15-20x faster compile time than Cranelift, 1.1-1.5x slower runtime. The answer for serverless cold-start workloads where compile time dominates.
- Pulley: a portable bytecode interpreter that runs on platforms without a Cranelift backend, including security-restricted environments where the W^X (write-xor-execute) constraint forbids JIT. Pulley reuses CLIF and the mid-end, then emits Pulley bytecode instead of native code.
The three-tier story is itself a teaching moment. The same compiler infrastructure (CLIF, ISLE, the mid-end optimiser) feeds three different output styles, each tuned for a different deployment scenario. The split is the right reflection of "compile-time vs run-time vs portability" trade-offs.
ISA support and recent additions
By 2026, Cranelift supports as full backends:
- x86-64
- AArch64
- RISC-V (RV64GC)
- IBM z/Architecture (s390x)
Plus the Pulley portable bytecode target. New ISA work clusters around RISC-V vector extensions and ISLE rewrites for SIMD lowering on x86-64.
Component model and WASI
A nearby (not-Cranelift but worth knowing about) development: WASI Preview 2 stabilised in 2024 and the Component Model shipped through 2025. Wasmtime is the reference implementation. Wasmtime 37.0 added experimental map<K,V> support and an opt-in wasip3 flag for Preview 3 (async components). Browser support is still in W3C process Phase 2/3.
For Cranelift specifically, the Component Model means the compiler is now compiling component-typed WebAssembly, not just plain WebAssembly. The component-vs-module distinction propagates through the compilation pipeline.
Lowering via ISLE
Once optimisation is done, Cranelift lowers CLIF to architecture-specific instructions. The lowering is described in ISLE (Instruction Selection Lowering Expressions), a domain-specific language for pattern-matching rewrites.
An ISLE rule looks like this:
(rule (lower (has_type $I32 (iadd x y)))
(x64_add $OperandSize.Size32 x y))
The left side is a CLIF pattern. The right side is a machine-instruction expression. ISLE compiles to Rust by cranelift-isle, which is itself a small standalone tool.
ISLE is conceptually similar to LLVM's TableGen, GHC's pattern matcher, and Go's .rules files. Each project has reinvented the same idea: a declarative DSL for instruction selection rules, compiled into the host language. ISLE is by far the smallest and most readable of the four. The grammar fits in a page; the compiler is roughly 5,000 lines of Rust.
For a contributor who wants to add a new instruction selection rule, the workflow is: edit cranelift/codegen/src/isa/<arch>/lower.isle, add a test in cranelift/filetests/, run cargo test. No C++, no Tablegen-generated code to debug, no manual phi insertion. The friction is genuinely low.
VCode: post-lowering, pre-regalloc
After ISLE lowering, the IR is no longer CLIF; it is VCode, a representation of architecture-specific instructions with virtual registers. VCode lives in cranelift/codegen/src/machinst/.
VCode is designed for the register allocator to consume. It has:
- ordered instructions with explicit operand kinds (use, def, mod)
- explicit virtual register numbers
- block layout with terminators
- spill/reload slots reserved by the allocator
The split between CLIF and VCode is a clean boundary: CLIF for portable optimisations, VCode for architecture-specific concerns. LLVM has a similar split between LLVM IR and MachineInstr; Cranelift's VCode is lighter and more uniform across architectures.
regalloc2
Register allocation is delegated to the regalloc2 crate, a separate library used by Cranelift and potentially by other backends. The crate exposes a function-level allocator interface: input is a SSA function in a regalloc2-specific IR, output is the same function with virtual registers replaced by physical ones, plus spill/reload code.
The algorithm is a SSA-based backtracking allocator, ported and generalised from SpiderMonkey's IonMonkey allocator. Live ranges are grouped into "bundles"; bundles are pulled from a priority queue, attempting to assign a physical register to each. When a conflict arises, the allocator can evict a lower-spill-weight bundle and reassign it, or split the conflicting range and retry. This is fundamentally different from a linear-scan algorithm, which never revisits decisions.
The result is allocation that is roughly comparable in quality to LLVM's greedy allocator but several times faster to run. For Cranelift's use case, that tradeoff is right.
regalloc2 is independently published with a design document (doc/DESIGN.md in the repo) and was introduced in Chris Fallin's blog post "Cranelift, Part 4: A New Register Allocator" (cfallin.org, 2022). It is a self-contained way to learn modern register allocation. It is one of the most legible production register allocators available.
Object emission and JIT
Cranelift can produce object files (for AOT compilation) or executable code in memory (for JIT). The crates split is:
cranelift_module: trait definitions for declaring functions, data, and resolving symbols.cranelift_object: implementsModulefor AOT, output is a real ELF/Mach-O/COFF file via theobjectcrate.cranelift_jit: implementsModulefor JIT, allocates memory pages withmmap, emits code into them, marks them executable.
The same cranelift_module interface drives both. An embedder writes a frontend that emits CLIF and calls Module::define_function; whether the result is a file or in-memory code depends on which Module impl is used.
For a learner, this is a clean illustration of the API design: AOT and JIT differ only at the boundary, not in the compiler proper. LLVM's MCJIT and ORC architectures had to grow into a similar shape but the seams show.
Comparison with LLVM (the central comparison)
| Aspect | Cranelift | LLVM |
|---|---|---|
| Lines of code | ~50,000 Rust | ~10,000,000 C++ |
| Build time of compiler | ~30 s from scratch | ~30 minutes |
| Targets | x86-64, AArch64, RISC-V 64, s390x | 50+ |
| Optimisation depth | Minimal (egraph + a handful of passes) | Hundreds of passes, deep |
| Compile time per function | ~10 ms typical | 100 ms - 1 s typical |
| Code quality vs LLVM | 0.7-0.85x speedup baseline | 1.0x baseline |
| Instruction selection DSL | ISLE | TableGen |
| Register allocator | regalloc2 (backtracking, SSA-based, Ion-derived) | Greedy, basic, fast (selectable) |
| IR | CLIF (SSA, block params, ~200 ops) | LLVM IR (SSA, phi nodes, ~60 core ops + intrinsics) |
| API style | Embed-as-library from day 1 | Embed-as-library, retrofitted |
The right reading of this table is not that Cranelift is "worse" than LLVM. It is that Cranelift made different choices and lives in a different niche. For a JIT compiling untrusted WASM modules in the hot path of every request, "10ms per function" matters more than "5% better generated code". For a release build of a Linux distro, the priorities flip and LLVM wins.
This is a frequent shape in compiler engineering: the same mature problem (instruction selection, register allocation) admits multiple production-quality answers, each optimised for a different use case. Reading both Cranelift and LLVM in the same week is the fastest way to internalise that.
Repo layout
cranelift/
codegen/ The backend proper
src/ir/ CLIF data structures
src/machinst/ VCode + machinst infrastructure
src/isa/<arch>/ Per-architecture lowering
lower.isle ISLE rules for that architecture
src/opts/ Optimisation passes (egraph, etc.)
src/regalloc/ Glue to regalloc2
frontend/ FunctionBuilder API for IR construction
object/ AOT output via the `object` crate
jit/ JIT output to executable memory
module/ Module abstraction shared by AOT and JIT
isle/ ISLE compiler (a separate tool)
filetests/ Filetest framework + per-feature tests
reader/, parser/ CLIF text format parser (for testing)
docs/ Internal documentation
The rest of the wasmtime repo (the runtime, the WASM frontend, etc.) sits next to cranelift/ but is logically separate.
If you only read five files
For getting oriented in Cranelift source:
cranelift/codegen/src/ir/dfg.rs: the data-flow graph IR.cranelift/codegen/src/egraph.rspluscranelift/codegen/src/opts/*.isle: aegraph and the rewrite rules.cranelift/codegen/src/isa/x64/lower.isle: the x86-64 lowering rules.cranelift/codegen/src/machinst/lower.rsplus the regalloc2 entry incranelift/codegen/src/regalloc/mod.rs.pulley/src/interp.rs: the Pulley portable bytecode interpreter.
Common contributor gotchas
- The aegraph is acyclic and built once. You cannot mutate IR after egraph construction.
- ISLE rules are pattern-matched bottom-up; more specific patterns must be marked with priorities or you get nondeterministic selection.
- regalloc2 expects vregs in SSA. Any post-SSA pass that introduces a non-SSA def silently miscompiles.
- Pulley shares ISA-shaped lowering with native back-ends. An instruction missing in
pulley_shared/abi.rsfalls back to a slow path. cargo test -p cranelift-codegendoes not run filetests. Usecargo run -p cranelift-tools -- test.
Area specialists
- Chris Fallin: founder of regalloc2 and aegraph.
- Nick Fitzgerald: Wasmtime, fuzzing.
- Trevor Elliott: ISLE, x64.
- Jamey Sharp: verifier, security.
- Alex Crichton: Wasmtime overall, Pulley.
- Anton Kirilov: AArch64.
Notable recent reads
- PR #10709 (cfallin): "fix invalid regalloc constraints on try-call with empty handler list" demonstrates a representative regalloc-validation interaction.
- Pulley performance issue #10102 thread.
- Fallin's 2026-04-09 aegraph blog post.
Diagnostic flags worth knowing
--set enable_verifier=true: verify IR after each pass.CRANELIFT_DEBUG_REGALLOC=1: dump regalloc decisions.--set regalloc_checker=true: runtime-side regalloc validation. Catches a large fraction of regalloc bugs at runtime.wasmtime --emit-clif=dir/: dump CLIF before each pass.cargo run -p cranelift-tools -- compile --target x86_64 --print foo.clif: drive Cranelift on a.cliffile directly.RUST_LOG=cranelift_codegen::isa=trace: scoped tracing.--set enable_pcc=true: proof-carrying code mode (experimental).
For miscompiles: write a .clif filetest first (run, compile, optimize), then debug with clif-util.
Reading order
A practical path for a reader:
- Read
docs/ir.mdanddocs/isle.mdin the repo. Short, well-written, concrete. - Walk through
cranelift/codegen/src/ir/instructions.rsto see the CLIF instruction set. - Read
cranelift/codegen/src/isa/x64/lower.islefor x86-64 instruction selection rules. The patterns are explicit and the right side is the assembly. - Read
regalloc2's README and the linked paper if you want to understand allocation. - Read
cranelift/codegen/src/opts/'s egraph implementation if you are curious about optimisation.
How to contribute
GitHub PRs to https://github.com/bytecodealliance/wasmtime. The community is small and welcoming. The Bytecode Alliance is the umbrella; review happens via GitHub. Code style: rustfmt, idiomatic Rust, no unsafe outside small well-justified spots.
Beginner-friendly categories:
- ISLE rule additions or refinements: each rule is small, testable in isolation, and immediately useful.
- regalloc2 improvements: the codebase is small enough that a careful contributor can land changes quickly.
- CLIF instruction additions: when a missing operation prevents a frontend from emitting efficient code.
- Documentation:
docs/is incomplete in places.
The core maintainers (Chris Fallin, Andrew Brown, and others) are responsive and willing to mentor. Compared to LLVM's volume of contributors, Cranelift is small enough that you will likely get review from someone who has read every line of the file you are changing.
Where to go next
- Cranelift documentation in https://github.com/bytecodealliance/wasmtime/tree/main/cranelift/docs.
- Chris Fallin's blog at https://cfallin.org/ for design notes on regalloc2 and ISLE.
- The Bytecode Alliance Zulip at https://bytecodealliance.zulipchat.com/ for live discussion.
- llvm-overview.md for the contrast Cranelift was designed against.
- rustc-overview.md for the project that uses Cranelift as an alternative debug backend.
Zig (zigc), in shape
Zig is a systems programming language with a self-hosted compiler. The source lives at https://github.com/ziglang/zig. What makes it interesting in this book is twofold. First, Zig's bootstrap journey is the closest production parallel to ours: it went from a C++ implementation (stage1) to a self-hosted Zig implementation (stage2) the same way we are going from intercalc.sh to compiler.i to stage3.i. Second, Zig's comptime mechanism collapses generics, macros, conditional compilation, and reflection into one language feature, and that decision shapes the entire compiler architecture in a way nothing else in this Part does.
The lesson the Zig compiler teaches that nothing else does: a compile-time evaluation primitive can be the centre of gravity of a compiler. In Rust, const fn is a side feature. In Zig, comptime is the analyser. The Sema phase of zigc is the largest module in the compiler and the place where types, generics, conditional compilation, and constant folding all happen at the same time.
For a reader of this book, Zig is the production-scale mirror of what stage3.i would look like if our compiler were larger and the language were richer.
The pipeline
A Zig source file goes through this sequence:
source program.zig
→ tokens lib/std/zig/tokenizer.zig
→ AST lib/std/zig/Ast.zig
→ ZIR src/AstGen.zig
→ AIR src/Sema.zig
→ machine code src/codegen/{llvm,x86_64,aarch64,...}.zig
→ object via embedded linker or libllvm
→ executable via embedded linker (lld-equivalent) or system ld
Six stages, two intermediate representations (ZIR and AIR), and a choice of backends including LLVM, several self-hosted backends per architecture, and a C backend that transpiles Zig to C.
The lexer and parser sit in lib/std/zig/. They are part of the standard library, deliberately, because they are reused by tools like zig fmt and zls (the Zig language server). The AST is conventional: tokens with offsets, a node array, structural nodes for declarations, expressions, and statements.
AstGen (src/AstGen.zig) is the first compiler-specific phase. It walks the AST and emits ZIR, an instruction-list intermediate representation. ZIR is untyped: an instruction add %1 %2 does not say whether the operands are integers or floats. ZIR mixes runtime instructions and comptime-only instructions. The split between which is which only resolves later, in Sema.
Sema (src/Sema.zig) is the elephant: a tree-walking interpreter over ZIR that produces AIR (Analyzed IR). AIR is typed and contains only runtime instructions; everything comptime has been resolved into values. Sema does type checking, comptime evaluation, generic instantiation, monomorphisation, and conditional compilation simultaneously, in one pass. There is no separate type-check phase, no separate const-eval phase. They are inseparable in zigc by design.
After Sema, codegen lowers AIR to machine code. Multiple backends coexist in src/codegen/:
llvm.zig: production backend via libllvm. Emits LLVM IR, links against LLVM.c.zig: C backend. Transpiles Zig to C. Useful for porting Zig to platforms before a native backend exists.spirv.zig: SPIR-V backend for GPU compute targets.
Plus per-architecture self-hosted backends in src/arch/:
x86_64/CodeGen.zig: x86-64 native backend, no LLVM.aarch64/CodeGen.zig: AArch64 native backend.riscv64/CodeGen.zig: RISC-V 64 native backend.wasm/CodeGen.zig: WebAssembly native backend.sparc64/CodeGen.zig: SPARC64 native backend.
The list is not closed; new architectures are added as the project evolves.
The self-hosted backends exist for fast debug builds. They produce less-optimised code than LLVM but compile orders of magnitude faster, which matters for iteration. Production release builds typically use LLVM; debug builds increasingly use the self-hosted backends as they mature.
Why ZIR and AIR are different
This is one of the design decisions worth pausing on. Most compilers have a single intermediate representation that gets gradually transformed. Zig has two distinct representations because they serve very different purposes.
ZIR is the output of pure parsing-plus-naming. It is constructed without knowing types. Its instructions can mix runtime and comptime computations because Sema has not yet decided which is which. ZIR for a function exists per-source-file and is cached: changing one file does not invalidate the ZIR of another.
AIR is the output of Sema for a particular function instantiation. It is typed. Generic functions produce AIR per-instantiation; an ArrayList(u32) and an ArrayList(f64) produce different AIR. Comptime values are baked in as constants. Conditional-compilation branches that were not taken are absent.
The two representations are different on purpose. ZIR captures the source's structure independent of types and uses; AIR captures one specific concrete instantiation ready for codegen. The transformation between them is the job of Sema, and the transformation is non-trivial precisely because it involves type inference, comptime execution, and generic instantiation in one pass.
For a reader coming from rustc, the analogy is HIR-vs-MIR, but with the twist that Sema is doing what rustc's type checker, miri, and monomorphiser do all at once.
Sema, in detail
Sema is the central object of study. As of recent Zig (around 0.14), src/Sema.zig is a single Zig file of roughly 35,000 lines, growing over time.
What Sema does:
- Type checks all expressions and statements.
- Evaluates comptime expressions by interpreting ZIR directly.
- Resolves generic functions: every distinct instantiation produces new AIR.
- Performs conditional compilation: comptime-known
ifbranches not taken are not lowered to AIR. - Implements built-in functions (
@TypeOf,@typeInfo,@field, etc.) as Sema-internal calls. - Inlines functions marked
inlineor@inlineCall. - Maintains the comptime allocation arena.
The implementation is a tree-walking interpreter. There is no SSA form at this stage; ZIR is a linear instruction list, and Sema processes it in order, with a stack-of-scopes and a stack-of-frames structure for handling control flow.
Performance characteristics: Sema is the bottleneck of zigc. A generic function that is instantiated many times (a typical container, used at many element types) runs Sema once per instantiation. Type-rich code can produce surprisingly long compile times. The Zig core team has invested heavily in incremental compilation precisely because Sema is the hot path.
The implementation language constraint matters too. Sema is itself written in Zig, including comptime Zig. The compiler uses comptime to implement the comptime feature: for instance, the @typeInfo function returns a tagged union that is itself defined in lib/std/builtin.zig, and Sema reads that file's structure at compile time of zigc.
A self-hosting compiler implementing its own most distinctive feature is a recurring shape in this Part. Rust's core::intrinsics are written in a Rust subset. OCaml's compiler implements modules using its own module system. Zig's compiler implements comptime by using comptime. The shape rewards careful design: the feature has to be expressive enough that the compiler itself benefits from it.
Comptime: what it actually is
comptime is a marker that can be applied to:
- function parameters:
fn foo(comptime T: type, x: T) T { ... } - variable declarations:
comptime var i = 0; - block statements:
comptime { @compileLog("debug"); } - expressions:
const x = comptime fib(20);
Plus the related modifier inline for forced compile-time control-flow expansion (e.g., inline for, inline while, inline fn).
What comptime can do: anything Zig can do, except observable side effects (no I/O, no syscalls, no FFI). Loops, recursion, allocation against the comptime arena, error handling, generics: all permitted. There is no syntactic subset like Rust's const fn. Whether a function can run at comptime is determined by what it does, not by a marker on its declaration.
What comptime allows in practice:
-
Generics as comptime functions:
fn List(comptime T: type) type { return struct { items: []T, len: usize, }; } const IntList = List(i32);Listis a function. It runs at comptime. It returns a value of typetype. That value is then used as a type elsewhere. The compiler does not have a separate "generic instantiation" pass; instantiation is just callingListwith a particular argument. -
Reflection at compile time:
fn fieldNames(comptime T: type) []const []const u8 { const fields = @typeInfo(T).Struct.fields; var names: [fields.len][]const u8 = undefined; inline for (fields, 0..) |field, i| { names[i] = field.name; } return &names; }@typeInfo(T)returns a struct describing T's type structure. The function builds an array of field names at compile time. The result is a constant. -
Conditional compilation as a normal
if:if (builtin.os.tag == .linux) { syscall_linux(...); } else { syscall_macos(...); }When
builtin.os.tagis a known comptime value (which it always is in Zig), the not-taken branch is discarded. There is no#if, nocfg!, no separate language for conditional compilation. -
Generic specialisation as a side effect of caching: every distinct comptime argument produces a new instantiation. The compiler caches instantiations by argument value, so calling
List(i32)twice produces one definition.
The flip side of this expressive power is that the boundary between "this works" and "this does not" is not always obvious. A comptime function that tries to use a runtime-only operation (an external function call, for instance) fails late, after Sema has already gone deep into evaluation. Zig's error messages have improved over time, but the dependency between comptime feasibility and the runtime/comptime classification of every operation it touches makes them harder to debug than Rust's pre-checked const fn boundary.
Self-hosted backends and the LLVM exit ramp
Zig has had multiple backends since stage2 was promoted. The --release builds use LLVM by default; --debug builds increasingly use self-hosted backends.
Why have self-hosted backends at all? The straightforward answer is compile speed: LLVM is slow per function, and Zig values fast iteration. The deeper answer is that LLVM is a large, C++-flavoured dependency that complicates Zig's bootstrap and distribution. A self-hosted toolchain that does not need libllvm is a simpler thing to ship.
The current state varies per architecture. x86-64 self-hosted is the most mature; AArch64, RISC-V, and WebAssembly trail. The roadmap toward "no LLVM in any default path" is multi-year, but the direction is clear.
Code-quality tradeoff: self-hosted backends produce code that is functionally correct but not optimised the way LLVM optimises. There is no inlining heuristic, no vectorisation, no loop unrolling, no aggressive instruction scheduling. For debug builds, this is fine. For release builds, LLVM remains the production choice in 2026.
The 2025 milestone: the self-hosted x86_64 backend became the default in Debug mode on Linux and macOS. It passes around 1,987 behaviour tests (more complete in language coverage than the LLVM backend in some areas) and produces 5-50% faster wall-clock builds depending on the project. Windows still defaults to LLVM because the COFF linker work is incomplete. A new from-scratch aarch64 backend was merged in July 2025 (PR 24536) and will benefit from a recently added Legalize pass shared across backends. Release mode still uses LLVM on every architecture; production-ready self-hosted Release is the next milestone.
The architectural lesson: a project can pre-emptively build the alternative to its current dependency, and migrate gradually. This is rare. Most compilers commit to LLVM (Crystal, Rust, Swift, Julia) or commit to their own backend (Go, Haskell's NCG, OCaml's native, GCC) without gradual transition. Zig is one of the few that is mid-transition in production.
zig cc and cross-compilation
A Zig oddity that changed how some C/C++ projects build: zig cc is a drop-in replacement for gcc or clang, backed by the LLVM bundled in Zig, with bundled musl libc, macOS SDK headers, and Windows SDK pieces. Setting CC=zig cc in a Makefile gives you cross-compilation for free, without installing a cross-toolchain.
This works because Zig ships with everything: the LLVM frontends for C and C++, headers for every supported platform, sysroot equivalents per target. zig cc -target aarch64-linux-musl ... produces a Linux ARM64 musl binary on macOS without any extra setup.
For projects that adopted zig cc, the trick has been transformative. Bun (the JavaScript runtime) builds via Zig precisely for this reason. Some C projects use zig cc only for cross-compilation and stick to gcc/clang for native builds.
For a reader of this book, the relevant lesson is: a compiler can ship the entire toolchain, including platform headers and sysroots, as a self-contained package. Our INTERCAL compiler does the analogous thing at small scale: the runtime and syslib ship with the compiler, and cc is the only external dependency. Zig pushes this further by also bundling the platform SDKs.
The stage1 → stage2 → stage3 history
This is the part of Zig that mirrors our project most directly.
- Stage1 (2015 to ~2022): the original Zig compiler, written in C++. It implemented enough Zig to compile the second compiler. Like our
intercalc.sh. - Stage2 (2020 onwards, mainline since 2022): the self-hosted Zig compiler, written in Zig. Compiled by stage1 initially, then by itself. Equivalent to our
compiler.iand (eventually)stage3.i. - Stage3 in Zig parlance was originally the conceptual third generation; in practice the project treats stage2 as the compiler and validates that it can self-compile. Equivalent to our 3-generation fixpoint.
The bootstrap mechanics today:
- The repo contains
stage1/zig1.wasm, a WebAssembly file containing a stripped-down stage2 compiler. - A small C program (generated from the wasm) interprets the wasm.
- Running that interpreter against the current stage2 source produces a native stage2 binary.
- The fresh stage2 then self-compiles to verify the fixpoint.
The zig1.wasm artifact is, in spirit, the same kind of "primordial spark" that our intercalc.sh provides for INTERCAL. A small bootstrap that contains just enough to start the self-hosting chain.
The deprecation of stage1 (the C++ compiler) was a milestone celebrated by the community. After it, the repo had no C++ in the main compiler path; everything was Zig. This is a real-world example of completing a self-hosting transition, and it is documented in Andrew Kelley's blog posts on ziglang.org from 2021-2022.
Allocator-aware standard library
Zig's standard library does not have a global allocator. Every container, every dynamic data structure, takes an allocator as an explicit parameter. There are several allocator implementations in the standard library:
std.heap.page_allocator: minimal, pages from the OSstd.heap.GeneralPurposeAllocator: production-grade, with leak detectionstd.heap.ArenaAllocator: free-everything-at-oncestd.heap.FixedBufferAllocator: bump allocator on a fixed bufferstd.heap.c_allocator: malloc/free wrapperstd.testing.allocator: leak-detecting allocator for tests
Why this matters for the compiler: it is the most concrete embodiment of "explicit control" as a language design principle. Where Rust pushes ownership into the type system, where Go hides allocation behind GC, Zig keeps allocation explicit at every API boundary.
This affects the compiler's own implementation: Zig's compiler uses arena allocators heavily for transient data (parsing, Sema) and explicit allocators for persistent state. There is no implicit allocator anywhere. Reading any Zig data-structure module is reading explicit allocation pattern after explicit allocation pattern.
The pedagogical take: a language with no global allocator forces the API designer to think about lifetimes at every step. The result is code that is harder to write at first and easier to reason about later.
Error union types
Zig's error handling is a sister to Rust's Result<T, E> but built into the syntax: error{Foo, Bar}!T is a value that is either an error from {Foo, Bar} or a value of type T. Errors are values, not exceptions; there is no stack unwinding.
The compiler implementation uses a discriminant byte (or tag, depending on the size) plus the value, with a small special-case path for the common pattern of "error union of pointer types" using the null-pointer trick to encode both states in one machine word.
The relevance for this book is that the compiler implementation has to translate every try into a check-and-early-return at a runtime boundary. Tracking the set of possible errors a function can produce ("error inference", a Zig feature) is a Sema-level dataflow analysis: which errors does each call site contribute to the overall set of errors a function can raise?
For a reader, error unions are a clean example of a sum type at the semantic level translated to a tagged union at the runtime level, with the language semantics chosen to make that translation efficient. They are easier to compile to fast code than exceptions; the compiler does not need an unwinder, does not need landing pads, does not need exception tables. The runtime cost of try is a single conditional branch.
Repo layout
src/
Sema.zig The elephant: type checking + comptime + Sema
AstGen.zig AST → ZIR
Air.zig AIR data structure
Module.zig Module-level state and the orchestrator
codegen/
llvm.zig LLVM backend
c.zig C backend
spirv.zig SPIR-V backend
arch/
x86_64/ x86-64 self-hosted backend
aarch64/ AArch64 self-hosted backend
riscv64/ RISC-V 64 self-hosted backend
wasm/ WebAssembly self-hosted backend
link/ Linker (ELF/Mach-O/COFF/Wasm)
Compilation.zig Compilation driver
main.zig CLI entry point
lib/
std/ Zig standard library
std/zig/ Tokenizer, parser, AST, used by tools
std/builtin.zig Definitions Sema reads at comptime (e.g., @typeInfo result types)
build.zig Zig's build script (Zig itself)
stage1/zig1.wasm Bootstrap WASM blob
test/ Test suite
The lib/std/zig/ choice is worth noting: putting the parser in the standard library means tools like zig fmt, zls, and any third-party formatter can use the same parser. It is the "compiler-as-library" idea taken to a clean conclusion.
Comparison with our INTERCAL compiler
| Aspect | INTERCAL compiler | zigc |
|---|---|---|
| Bootstrap | intercalc.sh (zsh) → compiler.i → stage3.i | C++ stage1 → Zig stage2 → fixpoint |
| Primary language | INTERCAL | Zig |
| Distinguishing feature | Politeness rule, COME FROM | comptime |
| IRs | None (parse tree only) | ZIR (untyped) + AIR (typed) |
| Backends | Direct codegen per architecture | LLVM + 4 self-hosted + C + SPIR-V |
| Self-hosting status | MVP self-hosted; stage3 evolving | Fully self-hosted since 2022 |
| Codebase size | ~2,000 zsh + ~3,000 assembly + INTERCAL syslib | ~500,000 lines Zig |
The shapes are the same. The scale differs by two orders of magnitude. The choice points are similar: own backends or borrow LLVM, self-hosting strategy via a small bootstrap blob, compiler-as-library for tooling.
If you only read five files
For getting oriented in Zig's compiler:
src/Sema.zig: the heart. Type checking + comptime + monomorphisation.src/Zcu.zigandsrc/InternPool.zig: compilation unit and de-duped types/values.src/codegen/llvm.zigfor the LLVM backend;src/arch/x86_64/CodeGen.zigfor a self-hosted backend.src/link/Elf.zig: the ELF linker.lib/std/Target.zig: target descriptions, where every target attribute is enumerated.
Common contributor gotchas
- Comptime calls run on the compiler's own stack; deep recursion segfaults the compiler, not the user program. Raise
--stackwhen bootstrapping. - InternPool indices are not stable across compilations. Do not serialize them.
- Semantic analysis is per-decl and lazy. Side-effecting
comptimeblocks at file scope may never run if the decl is unused. - The self-hosted backends are work in progress. Falling back to LLVM with
-fllvmis sometimes necessary. - Zig's build system runs in a separate compiler invocation. Breakage of
build.ziglooks like compiler errors but is actually the cached build runner.
Area specialists
- Andrew Kelley (andrewrk): creator, lead.
- Jacob Young (jacobly0): x86 and aarch64 self-hosted backends.
- Matthew Lugg (mlugg): incremental compilation, Zcu.
- Jakub Konka: linker, Mach-O.
- Veikka Tuominen (Vexu): Sema.
- David Rubin: LLVM bindings.
Notable recent PRs
- PR #24536 (jacobly0, July 2025): aarch64 from-scratch backend. Read for an example of how a self-hosted backend is added end to end.
- PR #15569 (andrewrk): InternPool for all types and constant values. Read for the rationale of unifying type and value identity.
Diagnostic flags worth knowing
--verbose-air,--verbose-mir,--verbose-llvm-ir,--verbose-cimport,--verbose-link: per-stage verbosity.--debug-log <scope>: scoped tracing (e.g.,--debug-log sema); requires a debug-built compiler.-freference-trace=N: show N levels of caller context for errors.--time-report: per-pass compile-time breakdown.-fno-emit-bin -femit-llvm-ir: emit LLVM IR without producing a binary.
For ICE reduction: zig reduce (Zig's clone of creduce) trims a failing test to a minimal reproducer.
Reading order
A practical path for somebody who wants to get acquainted:
- Read the Zig language reference up to the
comptimesection. - Browse
lib/std/zig/Ast.zigto see the AST. - Open
src/AstGen.zigand read a few simple ZIR-emission functions. - Open
src/Sema.zigand search foranalyze_block. Watch how the recursion descends and how comptime evaluation interleaves with type checking. - Read one self-hosted backend,
src/arch/x86_64/CodeGen.zig. It is the most legible production backend in this Part. - Read Andrew Kelley's blog posts about deprecating stage1 if you want the bootstrap story.
How to contribute
GitHub PRs to https://github.com/ziglang/zig. The community is young and active. Live discussion on Discord (linked from ziglang.org). The bug tracker has labels including good first issue.
Beginner-friendly categories:
- Standard library improvements:
lib/std/is broad and many functions are straightforward. - Self-hosted backend bugs: small, well-scoped, immediately testable.
- Documentation: the language reference is comprehensive but the compiler internals are mostly source-code-only.
- Sema bugs: harder, but the most direct path to learning the compiler's heart.
Build:
git clone https://github.com/ziglang/zig
cd zig
cmake -B build -GNinja
ninja -C build install
Builds need a stage1 binary (downloadable from ziglang.org/download) or a bootstrap from the zig1.wasm blob. Recent versions can also use a system Zig if available.
Tests:
zig build test # the full suite
zig build test-stage2 # focus on stage2
zig build test-cases # behaviour tests
The full suite is large and can take an hour. PRs typically run a subset.
Where to go next
- The Zig language reference at https://ziglang.org/documentation/master/.
- Andrew Kelley's blog (Zig founder) at https://andrewkelley.me/ for design notes on the compiler.
- The Zig Software Foundation's developer notes on YouTube.
- self-hosting.md for our own bootstrap journey, structurally analogous.
- from-intercal-to-real-compilers.md for the bridge to the rest of Part VII.
Swift, in shape
The Swift compiler (swiftc) lives at https://github.com/swiftlang/swift (the project moved from apple/swift to the swiftlang organisation in mid-2024). Swift is Apple's modern systems-language project, used for application development on Apple platforms and increasingly for server-side code, machine-learning frameworks, and embedded targets. The compiler is interesting in this Part for one reason above others: SIL.
SIL stands for Swift Intermediate Language. It is a SSA-form IR that sits between Swift's typed AST and LLVM IR, and it carries language-level semantics that no other production IR carries to the same degree. Reference counting operations are first-class instructions. Generic functions exist as polymorphic SIL definitions before specialisation. Protocols and witness tables are explicit. Memory ownership is annotated. Errors and traps are visible.
This means SIL passes can do things ordinary LLVM IR passes cannot. ARC optimisation eliminates redundant retain/release pairs by reasoning about ownership at SIL level, before LLVM ever sees a load or store. Generic specialisation produces a concrete instantiation as a SIL function, avoiding LLVM's per-translation-unit duplication. Protocol dispatch is devirtualised at SIL level when types are known, before the call has been lowered to an indirect jump.
For a reader, Swift is the canonical example of "preserve language semantics in the IR". The contrast with rustc (which strips Rust-level information into MIR and then LLVM IR, with the borrow checker doing its work on MIR) and Go (which has SSA but no language-specific high-level IR) makes Swift's choice visible.
The pipeline
A Swift source file goes through this sequence:
source program.swift
→ tokens lib/Parse/Lexer.cpp
→ AST lib/Parse/Parser.cpp + lib/AST/
→ Sema-checked AST lib/Sema/
→ Raw SIL lib/SILGen/
→ Canonical SIL lib/SILOptimizer/Mandatory/
→ Optimised SIL lib/SILOptimizer/ (under -O)
→ LLVM IR lib/IRGen/
→ machine code LLVM
→ linked binary LLD or system linker
Eight stages, two distinct SIL forms, an LLVM-IR step, then LLVM's own backend pipeline. Each transition is explicit and named.
The frontend (Parse + AST + Sema) is conventional but rich. Swift's AST captures the source quite faithfully; module structure, inheritance, generic constraints, protocols, property wrappers all live as AST nodes. Sema typechecks the AST, resolving overloads, inferring types, applying coercions, checking conformances.
SILGen lowers the typed AST to raw SIL. "Raw" means the SIL has not yet been canonicalised; it may contain constructs that the rest of the pipeline rejects. Mandatory passes turn raw SIL into canonical SIL, fixing those issues and emitting diagnostics.
After canonical SIL, the optional Performance passes (-O) optimise the SIL. Then IRGen translates SIL to LLVM IR, which goes through LLVM's pipeline, ending in machine code.
Sema and the constraint solver
Swift's type checker, in lib/Sema/, is constraint-based. Each expression generates a constraint system: the type of e is unknown; the type of e.foo() requires e's type to have a foo method; the type of 1 + x requires the result type to satisfy Numeric constraints; and so on.
The constraint solver searches for a substitution that satisfies all constraints, with backtracking when ambiguities arise. Where multiple overloads of + exist, the solver tries each, propagating constraints, picking the one that succeeds (or reporting ambiguity if multiple succeed).
The sophistication of the solver is the source of two kinds of pleasures and two kinds of pain. The pleasures: Swift can infer types in DSL-like contexts (SwiftUI, result builders) where many languages would require annotations. The function View.background(_:) overloads on multiple types; the solver picks the right one based on what the surrounding context needs.
The pains: type-checking time can blow up. For complex expressions, the solver may explore many possibilities before settling. The infamous "expression too complex" errors come from this; when the solver hits a configurable timeout, it gives up and asks the user to break the expression apart. Swift evolution has spent years making the solver faster and more predictable; it remains one of the most CPU-intensive parts of the compiler.
SILGen: AST to raw SIL
lib/SILGen/ lowers the typed AST to raw SIL. The lowering preserves Swift semantics in SIL form:
- A class has a v-table (lookup of inherited methods).
- A protocol has a witness table per conforming type, holding pointers to the protocol's required methods for that type.
- A reference assignment becomes
strong_retain/strong_releaseinstructions explicitly. - A captured variable becomes either a closure box (if it is captured mutably and lives longer than the closure) or a direct capture (if it is shared by value).
- An optional value becomes a tagged union with
enum_elementinstructions.
The SIL after SILGen is "raw" because some constructs are tentative. The compiler may have emitted instructions that are valid in SIL grammar but disallowed in canonical SIL: for instance, a mark_uninitialized instruction marking a variable as not-yet-initialised, which the Definite Initialisation pass must resolve before any code runs.
Mandatory SIL passes
The mandatory passes (lib/SILOptimizer/Mandatory/) are required for correctness. They run regardless of optimisation level. Their job is to turn raw SIL into canonical SIL, emitting diagnostics where the source program is incorrect.
Notable mandatory passes:
- Definite Initialisation: every variable must be assigned before it is used. The pass tracks initialisation through control flow and emits errors where the rule is violated.
- Diagnostic Constant Propagation: constant folds, with the side effect of detecting overflow in arithmetic that would crash at runtime.
- Mandatory Inlining: inlines functions marked
@_transparent(a compiler-internal annotation, not user-facing). These are functions whose semantics are part of the language definition; they cannot be left as calls. - Diagnose Invalid Escaping Captures: closures that capture variables in ways the language disallows are caught here.
The split between mandatory and performance passes is a Swift-specific design choice worth noting. Mandatory passes are part of the language definition; running them produces canonical SIL, which is what the rest of the compiler defines its semantics on. Performance passes are pure optimisations; they do not change observable behaviour and can be skipped under -O0.
For a reader, this is the cleanest example of "correctness vs performance" passes being explicitly distinguished in the pass pipeline. Most compilers run the same passes at all optimisation levels and rely on heuristics to skip expensive ones at -O0; Swift draws a hard line.
Performance SIL passes (under -O)
The performance passes (lib/SILOptimizer/) include:
- GenericSpecialization: a generic function
func max<T: Comparable>(_ a: T, _ b: T) -> Tis one definition in SIL. When called withInt, the specialiser produces a separatemax_specialized_to_IntSIL function with type substitutions applied. The original generic version remains, for use in non-specialisable contexts. - Devirtualization: a method call on a class becomes a v-table lookup; if the receiver's exact type is known statically, the lookup is replaced by a direct call.
- ARC Optimisation: the headline pass. Every reference assignment in raw SIL has explicit
strong_retain/strong_releaseoperations. ARC optimisation analyses the lifetimes of references and eliminates retain/release pairs that are guaranteed to balance. The result is significant runtime speedup for reference-heavy code. - Inlining: budget-based, similar to GHC's or Go's.
- Closure Specialisation: when a closure is passed to a function and the function is called with that specific closure, the compiler can specialise the function for that closure, sometimes inlining the closure body.
- Cross-Module Optimisation (CMO): with
-cross-module-optimization, optimisations that cross module boundaries are enabled. Like LTO but specific to SIL. - SROA, mem2reg, simplify-cfg, dead-code-elim: conventional passes adapted for SIL.
The most distinctive of these is ARC optimisation. Reading the code in lib/SILOptimizer/Transforms/ARCOptimization/ is a way to see how reference-counting elimination really works. The algorithms (RR-Code-Motion, Lifetime Lengthening, Block Argument Removal) have a literature of their own, originally Apple's invention.
Generics: specialisation vs preservation
Generics in Swift are interesting because they survive into SIL.
When a Swift function is generic, SILGen produces one polymorphic SIL function. The body operates on values of "abstract type" T (or more precisely, takes an extra parameter that points to type metadata). Calls into the function pass the concrete type's metadata; operations on values of type T use the metadata to dispatch.
This contrasts with C++, which monomorphises generics at instantiation: each vector<int> and vector<string> is a separate set of template instantiations duplicated through the codebase. Swift's polymorphic SIL does not require that duplication. The runtime metadata makes the polymorphic version work.
But polymorphic SIL is slower than monomorphised SIL: every operation on a T value goes through metadata dispatch. So the performance pass GenericSpecialization looks for call sites where the concrete type is known and produces a specialised SIL function for them.
The result: Swift gets the binary-size benefits of polymorphic generics by default and the speed of monomorphisation where it matters. The tradeoff is per-call-site, computable, and tuneable.
For a reader, this is the most concrete demonstration of why preserving language semantics in the IR matters. A different compiler that lowered generics at SILGen time (say, with a C++-style monomorphiser) could not later choose to keep them polymorphic when binary size mattered. SIL keeps the option open.
Witness tables and protocol dispatch
A Swift protocol describes a set of methods (and types) a type must provide. A type conforms to a protocol by declaring an extension Foo: Bar { ... } block. The compiler produces a "witness table" for the (Foo, Bar) pair: a record with pointers to Foo's implementation of each Bar method.
In SIL, a protocol-typed value is an "existential": a tagged record containing the value plus a pointer to its witness table. When code calls a protocol method on the existential, SIL emits an apply through the witness table.
This is similar to Rust's trait objects (dyn Trait) but explicit at the SIL level. A trait object in Rust is an LLVM-level construct, fat pointer plus vtable. A Swift existential is a SIL-level construct visible to optimisations.
Optimisations can devirtualise: if the existential's underlying type is known, the witness lookup is replaced by a direct call. They can specialise: if the same existential is used multiple times, the witness can be hoisted. They can avoid existential allocation entirely: if the existential never escapes, it can be stack-allocated.
Reading SIL output (which the compiler can dump with -emit-sil) on a small Swift program with protocols makes this all visible. Each apply instruction is annotated with witness or direct-call information.
IRGen: SIL to LLVM IR
After SIL optimisation, IRGen (lib/IRGen/) lowers SIL to LLVM IR. This is where Swift's high-level constructs become standard LLVM:
- Class instances become heap-allocated structs with a v-table pointer.
- ARC operations become calls to runtime functions (
swift_retain,swift_release). - Metadata accesses become loads from the type metadata table.
- Witness lookups become calls through witness tables (loads + indirect call).
- Generic instantiations either become specialised functions (if specialised earlier) or remain polymorphic with metadata-driven dispatch.
LLVM then optimises the resulting IR through its conventional pipeline. The optimisations LLVM runs are mostly orthogonal to what SIL did, focused on machine-level concerns: register pressure, instruction scheduling, loop transformations, vectorisation.
This two-stage optimisation (SIL passes for language-level, LLVM passes for machine-level) is one of Swift's defining architectural choices. The benefit: each level optimises what it understands. The cost: more total compiler work, longer compile times, two optimisers to maintain.
Recent additions: ownership, noncopyable types, OSSA
Swift 6 promoted ownership annotations from compiler-internal SIL concepts to first-class language features. The relevant proposals:
- SE-0377: parameter ownership modifiers introduced
borrowingandconsumingas parameter modifiers, mutually exclusive with each other and withinout.borrowingis a temporary read-only reference.consumingtransfers ownership; the original binding is invalidated, and the callee may even mutate the value. - SE-0390: noncopyable types (
~Copyable) lets a type opt out of the implicitCopyableconformance every type otherwise has. Noncopyable types model resources whose ownership must not be silently duplicated (file handles, mutexes, hardware buffers). - SE-0432: noncopyable pattern matching added borrowing/consuming patterns in
switch.
For copyable types, borrowing and consuming are mostly compiler hints. For noncopyable types they are part of the API contract and the compiler enforces single-consumption on every path.
OSSA (Ownership SSA) is the SIL form coming out of SILGen since Swift 6. Each non-trivial SIL value is statically tagged @owned, @guaranteed, @unowned, or @none, and the verifier proves that owned values are consumed exactly once on every path. OSSA is being pushed further down the optimiser pipeline (more passes operate on OSSA before OSSA is lowered to plain SSA), which catches use-after-free and leak bugs in the optimisation passes themselves rather than in user code. Noncopyable types are checked entirely in OSSA.
The contrast with Rust:
- Rust enforces ownership at the type level, in the borrow checker on MIR, before any IR transformation.
- Swift enforces ownership at the IR level, in the OSSA verifier, after SILGen.
- Both produce the same correctness guarantee for the user. The implementation strategies differ: Rust burns the cost in the type system; Swift burns it in the IR verifier.
Embedded Swift
Embedded Swift is a language subset (not a separate dialect): code that compiles in Embedded Swift must also compile in regular Swift with identical behaviour. The compiler disables runtime reflection, library evolution, generics that need runtime metadata, and most of the dynamic-dispatch machinery to shrink the runtime footprint to fit microcontrollers.
A common misreporting: "Embedded Swift removes ARC". Not quite. Refcount metadata is still 4 or 8 bytes per class instance; weak/unowned still uses side tables. The "no ARC" framing applies to specific embedded modes targeting microcontrollers where the user opts to use only value types and avoid classes. ARC itself is not removed from the language.
Embedded Swift is positioned as a long-term subset, with active 2024-2026 work on better diagnostics and on Swift for embedded Linux (GSoC 2025 project).
Governance and the swiftlang migration
Apple announced the move to the dedicated github.com/swiftlang organization on 10 June 2024. The migration was phased: swift-evolution first, then the rest of the repos. Governance now spans multiple steering groups: the Core Team augmented by Language, Platform (new in 2024), and the recently-formed Ecosystem steering group focused on developer experience. The split signals what Apple has stated explicitly: Swift is no longer an Apple-only language project.
For somebody reading the chapter and wanting to contribute, the practical implication is that the repo URLs in older documentation are now stale; everything has moved to swiftlang/*. The swift-driver package is at swiftlang/swift-driver; SwiftPM is at swiftlang/swift-package-manager.
The runtime
Swift has a runtime, in C++, providing:
- ARC primitives (
swift_retain,swift_release, weak/unowned variants). - Dynamic dispatch helpers (witness lookup, generic dispatch).
- Type metadata (the structures the compiler emits for each type).
- Error handling (try/throw stack unwinding).
- Exclusivity enforcement (Swift's runtime law-of-exclusivity: a value being modified cannot be observed simultaneously through another path).
- The standard-library helpers that cannot be expressed in Swift itself.
The runtime is ~50,000 lines, in stdlib/public/runtime/ and stdlib/public/SwiftShims/. Most of it is C++ for performance, with carefully minimal interaction with the Swift type system.
The standard library proper is in stdlib/public/core/, written in Swift itself. Array, Dictionary, String, Optional: all defined in Swift, leaning on unsafe primitives where direct memory access or type conversion is required. The compiler treats certain library types specially (e.g., Array is known to the compiler so that array-literal expressions can be lowered efficiently), but the implementation is still Swift code.
Comparison with other compilers
| Aspect | Swift | rustc | Go |
|---|---|---|---|
| High-level IR | SIL (SSA, with semantic annotations) | MIR (SSA, after borrowck) | SSA (no Go-specific high-level IR, ir AST is conventional) |
| Memory management | ARC (compile-time inserted, optimised at SIL level) | Ownership at type level (no runtime) | Concurrent GC |
| Generics | Polymorphic SIL with optional specialisation | Monomorphisation at MIR level | Type parameters since 1.18, monomorphised |
| Backend | LLVM | LLVM (default), Cranelift, GCC | Self (no LLVM) |
| Distinguishing IR | SIL with explicit ARC and witness tables | MIR with explicit moves and borrows | none Go-specific |
| Codebase | ~3M lines C++ | ~3M Rust | ~50K Go (compile only) |
Swift's distinguishing trait is the SIL layer. A reader who learns Swift learns "what does an IR look like when it carries the language's semantic features". A reader who only learns LLVM IR misses this; LLVM IR is deliberately language-agnostic.
How Swift compares to our INTERCAL compiler
We have no SIL-equivalent. Our pipeline goes from parse tree directly to assembly, with no IR step that preserves INTERCAL-specific semantics.
What would an INTERCAL SIL look like? Plausibly: an IR with explicit STASH/RETRIEVE as instructions, explicit ABSTAIN flags as state, the politeness rule encoded as a node attribute. Optimisations could then operate on this IR: dead-flag elimination becomes "if this statement's ABSTAIN flag is provably never set, eliminate the check". Constant folding at INTERCAL semantic level becomes "if a syslib call's arguments are all constant, replace with the result".
We have these optimisations today, but they live as ad-hoc passes over the parse tree. A real INTERCAL SIL would make them more systematic. This is one of the candidates for "what we could bring back from this Part" we will weigh in the closing section of the bridge chapter.
Repo layout
lib/
Parse/ Lexer + parser
AST/ AST data structures
Sema/ Type checker (constraint solver)
SIL/ SIL data structures, instructions
SILGen/ AST → raw SIL
SILOptimizer/
Mandatory/ Correctness-required passes
Transforms/ Performance passes (-O)
Analysis/ SIL analyses (alias, escape, side effect, etc.)
IRGen/ SIL → LLVM IR
ClangImporter/ Bridge to use C/Objective-C from Swift
IDE/ SourceKit support, autocompletion, refactoring
stdlib/
public/
core/ Swift standard library, in Swift
runtime/ Runtime, in C++
SwiftShims/ Mixed C/C++ shims
tools/ Driver, debugger support, etc.
docs/ Compiler documentation
The ClangImporter/ deserves a footnote. Swift can import C and Objective-C headers directly: a Swift file can import Foundation and use Cocoa APIs. The ClangImporter does this by running an embedded Clang to parse the headers and translate the C/Objective-C declarations into AST nodes Swift's Sema can use. It is one of the engineering tour-de-forces of the compiler and the reason Swift can interoperate with the existing Apple platform code without a C-style FFI layer.
If you only read five files
For getting oriented in Swift's compiler:
lib/SILGen/SILGenExpr.cpp: AST to SIL.lib/SIL/IR/SILFunction.cppandinclude/swift/SIL/SILInstruction.h: SIL data structures.lib/SILOptimizer/Mandatory/DiagnoseLifetimeIssues.cpp: OSSA verification.lib/SILOptimizer/Transforms/ARCCodeMotion.cppandlib/SILOptimizer/ARC/ARCOpts.cpp: ARC optimisation.lib/IRGen/GenCall.cpp: SIL to LLVM IR.
Common contributor gotchas
- SIL has two forms: OSSA (ownership) and lowered. Optimisations must declare which they accept; miscategorising deletes ownership info silently.
- ARC optimisations rely on
RCIdentityanalysis. Breaking that gives you double-frees only at -O. sil-optis a separate binary that does not pick up driver flags. You must pass-enable-sil-ownershipetc. explicitly.- The Swift compiler uses LLVM but heavily forks include paths. Do not bump LLVM directly.
- Many SIL passes have
-enable-experimental-flags that gate behaviour. Look atswift_build_supportto see what is on by default.
Area specialists
- Andrew Trick: SIL design, OSSA, ARC.
- Erik Eckstein: SILOptimizer, ARC.
- Michael Gottesman: ownership SSA.
- Joe Groff: type system, runtime.
- Slava Pestov: generics, witness tables.
- Doug Gregor: Sema, macros.
Notable recent reads
- Erik Eckstein commits touching
lib/SILOptimizer/Transforms/: representative of how performance passes are written. - OSSA-by-default migration PRs (2024-2025).
- Embedded Swift SIL changes 2024-2025.
Diagnostic flags worth knowing
-Xllvm -sil-print-after=<pass>,-sil-print-before=<pass>,-sil-print-around=<pass>: per-pass dumps.-Xllvm -sil-print-all: every pass.-Xllvm -sil-opt-pass-count=N: bisect by limiting passes run.-Xllvm -sil-print-types: include type info in dumps.-Xllvm -sil-verify-all: abort on first SIL verifier failure (defaults are non-fatal in optimiser).-Xfrontend -debug-cycles,-dump-ast,-emit-silgen,-emit-sil: frontend dumps.
For miscompiles: bisect with -sil-opt-pass-count=N; reduce with bug_reducer (Swift's creduce for SIL, in utils/bug_reducer/).
Reading order
A practical path:
- Read the Swift Language Guide for context on the source language.
- Read the SIL specification at https://github.com/swiftlang/swift/blob/main/docs/SIL/SIL.md.
- Browse
lib/SIL/SILInstructions.def, the list of SIL instructions. Categorised by purpose. - Read one mandatory pass,
lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp. It is well-commented. - Read one performance pass,
lib/SILOptimizer/Transforms/ARCOpts/ReferenceCounting.cpp. ARC optimisation in concrete form. - Read
lib/IRGen/IRGenSIL.cppto see how SIL lowers to LLVM.
How to contribute
GitHub PRs to https://github.com/swiftlang/swift. The contribution flow is documented at https://swift.org/contributing/. Apple is the primary developer but the project is open source and external contributions are welcome.
Beginner-friendly categories:
- Standard library improvements.
- Diagnostic message improvements.
- SIL pass refinements.
- Documentation in
docs/. - Tests in
test/(lit-based, similar to LLVM).
Build:
The build is large. You need the swift repo plus llvm-project plus several swift-corelibs-* repos. Apple provides update-checkout and build-script to manage this:
git clone https://github.com/swiftlang/swift
cd swift
./utils/update-checkout --clone
./utils/build-script --release-debuginfo
The first build takes hours and ~50 GB of disk. After that, incremental builds are tractable but never fast.
For prospective contributors who do not want to commit to the full build, the Swift compiler driver is the lowest-friction starting point. It is a separate Swift package at https://github.com/swiftlang/swift-driver. Swift evolution proposals live at https://github.com/swiftlang/swift-evolution.
Where to go next
- The Swift compiler documentation at https://swift.org/swift-compiler/.
- Joe Groff and Chris Lattner's LLVM Developers' Meeting 2015 talk "Swift's High-Level IR: A Case Study of Complementing LLVM IR with Language-Specific Optimization".
- The Swift evolution proposals at https://github.com/swiftlang/swift-evolution document the language's growth and the implementation tradeoffs.
- Apple's WWDC sessions on the Swift compiler (search "swift compiler" on developer.apple.com).
- llvm-overview.md for the backend Swift uses.
- rustc-overview.md for the comparable system that takes different ownership choices.
V8, in shape
V8 is Google's JavaScript and WebAssembly engine, used in Chrome, Node.js, Deno, Electron, Cloudflare Workers, and a long tail of other runtimes. Source at https://github.com/v8/v8. It is the only JIT in this Part. Every other compiler we cover is ahead-of-time. The shift from AOT to JIT changes the design of every component, so V8 deserves its own chapter for that reason alone.
The lessons V8 teaches that nothing else does:
- Tiered execution: an interpreter, a baseline JIT, a mid-tier optimising JIT, and a top-tier optimising JIT all coexist for the same code, with hot functions being promoted up the tiers and cold functions running at the lowest tier.
- Speculation and deoptimisation: optimised code is generated under assumptions about runtime behaviour ("this property is always at offset 8", "this variable is always a small integer") that may not hold; when they fail, execution falls back to a lower tier, reconstructing the interpreter's state from the optimiser's.
- Sea-of-Nodes IR: the optimising tier (TurboFan) uses a graph IR where data flow and control flow are unified, an alternative to conventional SSA.
- Hidden classes: V8 makes JavaScript's dynamic objects behave statically, by maintaining a runtime "shape" for each object that consolidates its layout and lookup paths.
- Inline caches: per-call-site type feedback that bridges interpretation and optimisation.
For a reader of this book, V8 is the long-distance cousin to our INTERCAL compiler. Most of the architectural questions we have do not arise in V8 because V8 has no AOT pipeline and no static syscalls; everything is dynamic, on-demand, with the runtime as the dominant context.
Tiered execution
V8 has four tiers, top to bottom:
- TurboFan (top-tier optimiser, default since 2017): heavyweight, sea-of-nodes IR, deepest optimisation. Targets hot functions.
- Maglev (mid-tier optimiser, since 2023): lighter SSA-based IR, fewer optimisations. Bridges Sparkplug and TurboFan.
- Sparkplug (baseline JIT, since 2021): a near-single-pass machine code generator from bytecode (a brief loop-discovery pre-pass plus a code-emit pass). No IR.
- Ignition (interpreter, shipped 2016, default since 2017): bytecode interpreter, the floor.
A function's execution path:
- First call: the parser produces bytecode. Ignition interprets it. Inline caches collect type feedback.
- After it has been called enough times: Sparkplug compiles the bytecode to machine code in a single pass. The new code runs in place.
- After it has been called significantly more: Maglev produces a mid-tier optimisation, using the IC feedback. Promotion is automatic.
- For sufficiently hot functions: TurboFan does deep optimisation, producing the final tier.
Each tier is a complete code-generation pipeline. They share the bytecode (Ignition's input is also the input to Sparkplug, Maglev, and TurboFan) and the inline-cache state, but they emit independent machine code.
Why four tiers? Because the amortisation curve is steep. Generating optimised code is expensive, and most functions never run enough to recoup the cost. Generating no code (just interpreting) is cheap but slow per execution. Tiering lets V8 spend just enough compilation effort to match each function's actual demand.
Ignition: the bytecode interpreter
The bytecode for V8 is custom, ~200 opcodes, register-machine flavour. Each function is compiled to a sequence of bytecode instructions where operands name "registers" (slots in a per-frame register file).
The bytecode handlers themselves are written using V8's CodeStubAssembler (CSA), a TurboFan-backed macro assembler, and compiled at build time. A newer DSL, Torque (src/torque/), now layers on top of CSA and is the recommended way to write builtins, but Ignition predates Torque and uses CSA directly via the InterpreterAssembler subclass.
What Ignition does that an interpreter for a static language might not:
- Maintains the inline cache for every operation that involves type-dependent dispatch (property access, arithmetic, function calls). The IC starts uninitialised, transitions to monomorphic on the first call, polymorphic on subsequent different shapes, and megamorphic if the shape variety exceeds a threshold.
- Records type feedback in a per-function
FeedbackVectorthat the optimising tiers later consume. - Cooperates with the GC: every register slot is GC-walkable, the interpreter handles allocation triggers and write barriers.
For a reader, Ignition is the most legible production interpreter for a dynamic language. The Torque source for the interpreter's bytecode handlers is much shorter than equivalent hand-written C++.
Sparkplug: a baseline JIT in one pass
Sparkplug (src/baseline/) is the simplest of the JITs. It is a single-pass code generator: walk the bytecode, emit machine code, done.
What it does not have:
- An intermediate representation. Bytecode goes straight to machine code.
- A pass pipeline. There is one pass.
- An optimisation phase. Only minimal patterns.
- A register allocator beyond what the calling convention forces.
What it does have:
- The same stack frame layout as Ignition. Sparkplug-compiled functions can be called from Ignition and vice versa with identical activation records, which simplifies tier transitions.
- Direct emission of bytecode-level inline-cache logic. The IC state is shared with Ignition.
- Fast compilation: roughly two to three orders of magnitude faster than TurboFan, on the order of bytecode-generation cost per the V8 team's own measurements.
The point of Sparkplug is to eliminate Ignition's interpreter overhead (decoding each bytecode, dispatching to a handler) without paying the cost of an optimising compiler. For middle-tier-of-warmness functions, this is the right tradeoff.
The architectural lesson: a baseline JIT can be radically simple and still produce large speedups. Reading Sparkplug source is a fast education in "what is the minimum machine code generation that beats interpretation".
Maglev: a mid-tier optimising JIT
Maglev (src/maglev/) is the newest of V8's tiers, added in 2023. It uses a simpler SSA IR than TurboFan, and fewer optimisation passes.
The Maglev IR is conventional SSA: basic blocks, instructions, phi nodes (or block parameters, depending on the variant). Optimisation passes include type narrowing from feedback, simple constant folding, simple dead-code elimination. Lowering produces machine code through conventional instruction selection.
Why Maglev exists: Sparkplug code is slow, TurboFan compilation is slow. The gap was wide enough that adding a tier in between was worth the engineering effort. Maglev compiles roughly 10x faster than TurboFan and generates code "much faster than Sparkplug" but slower than TurboFan, per the V8 team's own announcement. The tradeoff fills the right slot in the warmth distribution.
For a reader, Maglev is the cleanest example of "optimising compiler, but lighter". Compared to TurboFan, Maglev does less; compared to Sparkplug, Maglev does more. The architectural decisions visible in its source are mostly about budgeting: how much optimisation is worth doing for a given amount of compile time.
TurboFan: sea of nodes
TurboFan (src/compiler/) is the top-tier optimiser. It is the largest and most distinctive piece of V8.
The TurboFan IR is Sea of Nodes, a graph IR introduced in Cliff Click's 1995 PhD thesis "Combining Analyses, Combining Optimizations" (Rice University) and used in HotSpot's C2 (Java's top-tier JIT). The sea-of-nodes idea:
- Each operation is a node in a graph.
- Edges represent dependencies between nodes, of three kinds: data flow ("the value of node A is used by node B"), control flow ("node A executes, then node B can execute"), and effect ("node A's side effect must precede node B's").
- The graph is not linear. Many nodes are "floating": they have no fixed position in any basic block. Their position is determined later by the scheduler, based on dependencies.
This is a big departure from traditional SSA. In LLVM's IR, every instruction has a basic block. In sea of nodes, many instructions float free until a final scheduling pass places them. The freedom to float means optimisations do not have to manage block placement; the scheduler does it.
The pipeline through TurboFan:
- Bytecode + feedback → graph (with inlining decisions guided by feedback).
- Typer (
src/compiler/typer.cc): each node gets a type from the type lattice, based on feedback and context. Types includeSmallInteger,HeapNumber,String,Object, more refined subdivisions for known shapes. - Typed lowering (
src/compiler/typed-optimization.cc): replace generic operations with type-specialised ones.JSAdd(x, y)where both are SmallInteger becomesInt32Add. - Simplification: classical dead-code, constant-fold, GVN, escape analysis, range analysis.
- Simplified lowering (
src/compiler/simplified-lowering.cc): more lowering toward machine-level. - Machine lowering: to a target-specific representation.
- Instruction selection (
src/compiler/backend/instruction-selector-<arch>.cc). - Register allocation.
- Code emission.
Each phase reads the graph, modifies it, hands it to the next. The graph data structure is mutated in place across phases, with verification passes between them.
For a reader, sea of nodes is conceptually the hardest IR in this Part. It is also the most rewarding once it clicks. The "C2: A Killer Compiler" papers (Cliff Click, various venues) are the canonical introduction.
Speculation and deoptimisation
V8's optimising tiers (Maglev and TurboFan) generate code under assumptions. Examples:
- "This variable is always SmallInteger": the optimiser emits Int32 arithmetic instead of generic JSAdd.
- "This object's shape is always Map A": the optimiser emits a direct field load at offset 8 instead of going through a property lookup.
- "This function call always targets
f": the optimiser inlinesfand emits direct code.
Each assumption is encoded as a deoptimisation check in the generated code: a runtime test that, if false, transfers control out of the optimised code and back to the interpreter (or a lower tier).
The deoptimisation flow:
- The check fails. Execution branches to a "deopt entry" stub.
- The stub knows how to reconstruct the interpreter's state from the optimised code's register state. This requires a side table generated at compile time, the deopt table.
- The interpreter resumes execution from the bytecode position corresponding to where the deopt happened.
- The function's optimisation status is downgraded; subsequent calls run lower-tier code, with new feedback, possibly different optimisation later.
There are two kinds of deopt: eager (deopt happens immediately when the check fails) and lazy (deopt is recorded but execution continues, with the deopt actually firing at a later safe point). Lazy deopt is used when re-execution from the bytecode position is correct; eager deopt is used when continuation in optimised code would produce wrong results.
The deopt machinery is the secret of V8's performance model. Optimised code can be aggressive because deopt is the safety net. The cost of speculation when it succeeds is one branch (the check); the cost when it fails is recompilation, eventually.
For a reader, speculation + deoptimisation is the JIT-specific lesson that has no parallel in AOT compilers. Static compilation must be conservative (every assumption must hold for every input); JIT compilation can be optimistic (every assumption only has to hold for the typical input, with deopt as fallback).
Inline caches and feedback vectors
The bridge between the interpreter and the optimisers is the inline cache.
An inline cache is a per-call-site mini state machine. Each property access, arithmetic operation, or call site has an IC. The IC records what the operation has seen so far, and dispatches based on that.
Initial state: uninitialised. The first time the operation runs, the IC observes the actual operands or shapes and transitions.
Monomorphic: only one shape has been seen. The IC has a fast path for that shape and a slow path for others. The fast path is a few instructions: type check, direct dispatch.
Polymorphic: a few shapes have been seen (default threshold is 4). The IC has fast paths for each, plus a slow fallback.
Megamorphic: many shapes have been seen. The IC gives up on per-shape optimisation; the operation does a generic lookup.
The IC state is recorded in the function's FeedbackVector, a per-function side table. The optimising tiers read this vector to decide what to specialise on.
For a reader, inline caches are the canonical mechanism for type-feedback-driven JIT. They were invented for Smalltalk in the 1980s, refined for Self, and brought to JavaScript by the V8 (and SpiderMonkey, JavaScriptCore) authors. Reading the IC machinery in src/ic/ shows what type feedback for a dynamic language looks like in production.
Hidden classes (Maps in V8 jargon)
JavaScript objects are dictionaries: keys are strings, values are anything. Naively implemented, every property access is a hash-table lookup. V8's optimisation: track each object's structural shape, and access properties as array indices when the shape is known.
A Map (V8's terminology, unrelated to JS's Map type) is a runtime structure describing an object's shape:
- Field offsets (which property is at which slot).
- Inline-property capacity vs out-of-line property storage.
- Constructor lineage.
- Element kind (small integers, doubles, mixed, packed, holey).
When you write obj.x = 1 in JavaScript, V8 transitions obj from its current Map to a new Map describing the layout with x. If many objects construct the same way (e.g., from the same constructor function), they end up with the same Map; their property accesses can be specialised to direct field loads at the right offset.
The Map system is V8's mechanism for treating dynamically-typed objects as if they were statically typed. It is not always able to: highly polymorphic code defeats the optimisation. But for typical JavaScript code, it works extraordinarily well.
For a reader, hidden classes are the JavaScript-specific lesson with no direct parallel in static-language compilers. It is the answer to "how do you make a dictionary-shaped object run fast".
Garbage collector: Orinoco
V8's GC, codenamed Orinoco, is generational and concurrent.
The young generation uses a copying collector with two semi-spaces. New allocations go into the active semi-space; when it fills, live objects are copied to the inactive one and the active becomes inactive.
The old generation uses a mark-sweep collector with optional compaction. Marking can be incremental and concurrent (running on a separate thread alongside JavaScript execution). Sweeping is parallel.
Write barriers: the JIT-generated code emits write barrier code at every pointer store, ensuring the GC knows about cross-generation pointers and concurrent-marking interactions.
The GC has had multiple major rewrites over V8's lifetime, each named (Mark-Sweep-Compact, Concurrent Marker, Orinoco). Each has improved pause times or throughput by a measurable margin. The 2017 Orinoco redesign is documented in V8 blog posts and is the basis for current V8.
For a reader, the GC is one of the cleanest examples of "concurrent algorithms in production". Every detail (write barriers, marker termination, snapshot-at-the-beginning, work-stealing) has been wrestled with in V8.
Recent additions: speculative inlining for WebAssembly
A 2025 development worth highlighting: bringing the speculation framework (deopt + IC-style feedback) into the WASM pipeline. Historically WASM optimisation in V8 was static; without runtime feedback there was nothing to speculate on. Chrome M137 changed that.
V8 now records call targets for indirect calls during Liftoff execution. Then TurboFan, when promoting a function, can speculatively inline up to four targets, with deopt fallback if the assumption breaks. Reported speedups: over 50% on Dart microbenchmarks and 1-8% on real WasmGC apps.
The implication: WebAssembly is no longer a purely-static target in V8. The same speculation/deopt machinery that makes JavaScript fast is now applied to WASM hot code. Browsers are increasingly running WasmGC programs (Dart, Kotlin/Wasm, soon others) where speculative inlining is the difference between competitive and non-competitive performance.
WebAssembly support: a parallel pipeline
V8 also runs WebAssembly. The pipeline is separate but shares much of the infrastructure.
WASM tiers:
- Liftoff: baseline WASM compiler. Like Sparkplug for JS. Single-pass, fast compilation, modest code quality. The default for first execution.
- TurboFan-WASM: TurboFan re-targeted for WASM. Heavy optimisation. Used for hot WASM functions or full-module optimisation.
Liftoff was added in 2018. The reason is the same as Sparkplug for JavaScript: WASM compile time matters, and Liftoff produces "good enough" code 10x faster than TurboFan.
For a reader, the WASM tier is interesting because WebAssembly is a typed bytecode (no inline caches, no hidden classes, no JavaScript-specific dynamism). The compiler has the structure of a static-language compiler running as a JIT. It is an instructive contrast with the JavaScript path.
Snapshot serialisation
V8 startup is famously slow; the engine has a lot of state to set up. The mitigation is snapshots: the engine pre-builds heap state at engine-build time, serialises it to disk, and deserialises at startup.
The snapshot includes built-in functions, type info for built-in objects, the initial JS context. Loading the snapshot is much faster than reconstructing it; startup goes from hundreds of milliseconds to tens.
Tools: mksnapshot (the snapshot builder, runs at V8 build time), embedded-builtins.cc (the embedding format).
For a reader, the snapshot mechanism is one of the cleanest examples of trading build complexity for runtime simplicity. Most languages do not bother because they do not have V8's startup cost; the techniques are valuable to know about even if your project never needs them.
Repo layout
src/
ast/ AST data structures (after parsing)
parsing/ Parser
interpreter/ Ignition (bytecode interpreter)
baseline/ Sparkplug (baseline JIT)
maglev/ Maglev (mid-tier JIT)
compiler/ TurboFan (top-tier JIT)
backend/ Per-arch instruction selection, regalloc
access-info.cc Property access reasoning
typer.cc Type lattice + propagation
simplified-lowering.cc
heap/ Orinoco GC
objects/ Object representations (Maps, fixed arrays, JSArray, ...)
ic/ Inline caches and feedback
runtime/ Runtime functions (called from generated code)
torque/ Torque DSL compiler
builtins/ Torque sources for built-ins
wasm/ WebAssembly support
snapshot/ Snapshot serialisation tools
regexp/ RegExp engine (compiles to bytecode)
test/ Tests (mjsunit, cctest, unittests, etc.)
tools/ Profilers, generators, diagnostic tools
The tools/ directory has a number of useful diagnostics: --trace-opt (log optimisation events), --trace-deopt (log deoptimisations), --print-code (dump machine code), --print-bytecode (dump bytecode). Running V8 standalone (d8, the standalone shell) with these flags is the easiest way to see what the compiler is actually doing on a given JS source.
Comparison with other compilers
| Aspect | V8 | LLVM (Clang) | rustc |
|---|---|---|---|
| Compilation model | JIT, four tiers | AOT, single tier | AOT, single tier |
| IR | Bytecode + Maglev SSA + TurboFan SoN | LLVM IR (single SSA) | HIR/THIR/MIR/LLVM IR |
| Speculation | Yes, with deopt | No | No |
| Type system | JavaScript dynamic + WASM static | Static | Static |
| GC | Yes (Orinoco) | No (host language) | No |
| Codebase | ~2.3M lines C++ | ~10M C++ | ~3M Rust |
V8 is on the JIT side of every comparison. The cost of being on that side: more runtime complexity, harder to debug, harder to reason about peak performance. The benefit: optimisations that depend on runtime behaviour, possible only with a JIT.
How V8 compares to our INTERCAL compiler
Almost every architectural choice differs. We are AOT, V8 is JIT. We have a static type system (four numeric types), V8 has runtime-typed values. We have no runtime feedback, V8's runtime feedback is the input to its top-tier optimisations. We have no GC, V8 has Orinoco.
The connection is at the conceptual level: both compilers translate source code into machine code. The lessons from V8 about speculation, tiered compilation, and deoptimisation do not transfer directly to our compiler, but they are the right vocabulary for understanding why some compilers are JITs and some are AOTs and what the tradeoffs are.
If we ever wanted to add a JIT mode to our INTERCAL compiler (for instance, an interactive debug session that compiles INTERCAL functions on demand), the relevant techniques would come from V8.
If you only read five files
For getting oriented in V8 source:
src/compiler/turboshaft/graph.handsrc/compiler/turboshaft/operations.h: the new IR (Turboshaft is replacing TurboFan; the JS pipeline migrated 2024-2026).src/maglev/maglev-graph-builder.cc: Maglev's IR construction.src/ic/ic.ccandsrc/ic/handler-configuration.h: the inline-cache machinery.src/codegen/code-stub-assembler.cc: CSA, the assembler-level macro language.src/compiler/pipeline.cc: the orchestrator, tier transitions.
Common contributor gotchas
- V8 has four tiers (Ignition, Sparkplug, Maglev, Turboshaft/TurboFan). A function can deopt back across them. Your "perf bug" may be a tier-up never happening; check
--print-opt-codeand%GetOptimizationStatus. - IC feedback informs Maglev. Breaking the IC slot layout silently regresses optimisation.
- Turboshaft is replacing TurboFan in 2024-2026; the JS pipeline already migrated. Do not write new TurboFan reducers.
- ICs are written in CSA. Edits live in
*.tq(Torque), not directly in.cc. d8(the standalone shell) runs without snapshot by default; mksnapshot crashes during build are usually due to a CSA assertion.
Area specialists
- Tobias Tebbi: Turboshaft, Torque.
- Nico Hartmann: Turboshaft, Maglev co-lead.
- Toon Verwaest and Leszek Swirski: Maglev.
- Jakob Kummerow: numeric, BigInt.
- Camillo Bruni: Sparkplug, perf tooling.
- Ross McIlroy: Ignition.
Notable recent reads
- V8 blog "Land ahoy: leaving the Sea of Nodes" (Turboshaft rationale).
- "Turbolev" series at blog.seokho.dev (2025).
- Maglev launch post at v8.dev/blog/maglev.
Diagnostic flags worth knowing
--trace-turbo: writes turbo.json for turbolizer.com (a graphical IR explorer).--trace-turbo-graph,--trace-maglev-graph-building,--trace-maglev-regalloc: per-IR tracing.--print-maglev-code: dump generated Maglev code.--trace-ic: trace inline-cache transitions.--trace-opt,--trace-deopt: trace optimisation tier transitions and deopts.--trace-turbo-reduction,--turboshaft-trace-reduction: trace IR reductions.--allow-natives-syntax: enables%DebugPrint,%OptimizeFunctionOnNextCall,%PrepareFunctionForOptimizationfor in-script introspection.
For graphical exploration: feed --trace-turbo JSON into https://v8.github.io/tools/head/turbolizer/ to step through reductions.
Reading order
A practical path:
- Read V8 design docs for orientation.
- Read the V8 blog posts on Sparkplug, Maglev, Orinoco at https://v8.dev/blog.
- Browse
src/baseline/to see the baseline JIT. It is the smallest tier and the most tractable starting point. - Read
src/compiler/typer.ccto see TurboFan's type lattice. - Read "Sea of Nodes" (Cliff Click 1995) before diving into TurboFan.
- Try the diagnostics: install d8, run with
--trace-opt, see what V8 actually does on a small program.
How to contribute
V8 uses Gerrit at https://chromium-review.googlesource.com. The process is documented at https://v8.dev/docs/contribute.
Beginner-friendly categories:
- Bug fixes in less-frequently-touched parts of TurboFan.
- Diagnostic-message improvements.
- Tests in
test/mjsunit/. - Improvements to standalone tools (
d8, profilers).
Build:
fetch v8
cd v8
gn gen out/x64.optdebug --args='is_debug=true is_component_build=true'
ninja -C out/x64.optdebug
Build setup uses depot_tools (Chromium's tool suite). The first build is slow (an hour or so on modern hardware) and downloads many gigabytes of dependencies.
Where to go next
- The V8 blog at https://v8.dev/blog.
- Mathias Bynens's articles at https://mathiasbynens.be/notes/ on V8 internals.
- Cliff Click's papers on sea of nodes and HotSpot.
- "Crankshaft, Octane, and the V8 Lineage" papers from the V8 team.
- llvm-overview.md for the AOT counterpart.
- from-intercal-to-real-compilers.md for the bridge back to this book.
Contributing to a production compiler
The standard advice for contributing to a real compiler is "find a good first issue and fix it". The hard parts are picking a project to start with, getting its source to build, and learning how its review process works. This chapter walks each of those steps for the ten compilers covered in Part VII: LLVM, GCC, rustc, Go, GHC, OCaml, Cranelift, Zig, Swift, V8.
The book in your hands has prepared the conceptual ground. What follows is the practical residue.
Pick a project that fits your interest
The ten compilers have different cultures and different on-ramps. None is universally easier than the others; they are different.
LLVM is modular by design. A new contributor often lands their first patch as a small optimisation pass, a target-specific instruction-selection improvement, or a documentation fix. The codebase is large but each pass is largely self-contained, and you can write an entire new pass in 200 lines without reading much of the rest.
rustc has the rustc-dev-guide explicitly aimed at new contributors. The compiler is in Rust, so if Rust is your stronger language, this is the most welcoming entry point. Most first patches concern diagnostic improvements, lint extensions, or small bugs in HIR/MIR-level checks.
GCC has a longer history and a different set of conventions (mailing-list patch review rather than GitHub PRs). The codebase is the most heterogeneous and has the steepest reading curve, but it also has the most breadth: more languages, more targets, more legacy systems supported. First patches often concern target-specific bugs in less-trodden architectures.
Go (gc) has a small, self-contained compiler in Go. The contribution flow goes through Gerrit (go-review.googlesource.com), which is unusual but well-documented. First patches often concern SSA optimisation rules in .rules files, runtime small bugs, or standard-library improvements.
GHC (Haskell) has a strong academic-paper-followed-by-implementation tradition. Contributions tend to be documented theoretically (a paper, an RFC, an issue) before being implemented. First patches concern error-message improvements, simplifier refinements, or library additions.
OCaml has a small, conservative review culture. The code is high quality and the maintainers value backwards compatibility. First patches tend to be small bug fixes or standard-library additions.
Cranelift has a small, welcoming community. The codebase is small enough that a single contributor can absorb most of it. First patches often add ISLE rules, refine regalloc2, or improve the documentation.
Zig has a young, active, personality-driven community. Andrew Kelley's vision shapes the project. First patches commonly improve the standard library, fix self-hosted backend bugs, or add platform support.
Swift is Apple-driven but open. The build is large (hours, ~50 GB) and the contribution flow is more formal than smaller projects. First patches typically improve diagnostics, refine SIL passes, or extend the standard library.
V8 is Google-driven via Gerrit (chromium-review). The build is heavy and depends on depot_tools. First patches usually fix bugs in less-trafficked TurboFan paths or improve diagnostic tooling.
If you have no preference, rough ranking by approachability: Cranelift and rustc are the friendliest first projects. Go is excellent if you already know Go. LLVM is the best for general compiler skills. GHC and OCaml for theoretical depth. GCC if you want to land patches on production systems software for decades. Swift and V8 are the heaviest lifts but offer access to two of the most-deployed compilers in the world. Zig is the most exciting if you want to contribute to a project still finding its shape.
Build the project locally
This is the step that turns a curious reader into an actual contributor. Each compiler has clear instructions; allow a couple of hours the first time.
Building LLVM
git clone https://github.com/llvm/llvm-project.git
cd llvm-project
cmake -S llvm -B build -G Ninja \
-DLLVM_ENABLE_PROJECTS="clang" \
-DCMAKE_BUILD_TYPE=Debug
ninja -C build
A debug build of just LLVM and Clang takes 15–30 minutes on a modern laptop. Release builds are faster to produce but give worse debugging. Most LLVM contributors keep both around.
Building rustc
git clone https://github.com/rust-lang/rust.git
cd rust
cp config.example.toml config.toml
# Edit config.toml: set profile = "compiler" for new contributors
./x.py build
The first build is the slowest, an hour or so, because it bootstraps through three stages of rustc compiling itself. After that, incremental builds of single crates take seconds. The x.py driver wraps everything: x.py test, x.py check, x.py doc. Read the rustc-dev-guide chapter on building.
Building GCC
git clone git://gcc.gnu.org/git/gcc.git
cd gcc
mkdir build && cd build
../configure --enable-languages=c,c++ --disable-multilib
make -j$(nproc)
GCC is autoconf+make, not CMake. The build takes about half an hour. You almost always want --disable-multilib (skips 32-bit support) and a narrow --enable-languages list to reduce the build time.
Building Go
git clone https://go.googlesource.com/go
cd go/src
./make.bash
Building Go requires a previous Go to bootstrap (Go 1.4 source or 1.17.13 binary, depending on the release). The Go install instructions document this. The build is fast (minutes).
To work on the compiler:
cd src/cmd/compile
go build .
This produces a fresh compile binary you can use via go build -toolexec=....
Building GHC
git clone https://gitlab.haskell.org/ghc/ghc
cd ghc
./boot
./configure
hadrian/build
GHC's build system is Hadrian (newer) or the legacy Make-based system. Bootstrapping requires an older GHC, which ghcup can install. The first build is significant (~30 minutes); subsequent incremental builds are much faster.
Building OCaml
git clone https://github.com/ocaml/ocaml
cd ocaml
./configure
make
make tests
OCaml's build is fast (~5 minutes on modern hardware) and self-contained. The repository ships a bytecode boot/ocamlc for bootstrapping, so no prior OCaml is needed.
Building Cranelift
git clone https://github.com/bytecodealliance/wasmtime
cd wasmtime
cargo build -p cranelift-codegen
Cranelift is Rust-only and builds with cargo like any Rust project. The build is fast (seconds for incremental, ~1 minute from scratch for just Cranelift, longer for the whole wasmtime).
Building Zig
git clone https://github.com/ziglang/zig
cd zig
cmake -B build -GNinja
ninja -C build install
Building Zig requires a stage1 binary (downloadable from ziglang.org/download) or bootstrapping through zig1.wasm (the WASM-encoded bootstrap). Recent versions can use a system Zig if available. The build is moderately heavy (~30 minutes).
Building Swift
git clone https://github.com/apple/swift
cd swift
./utils/update-checkout --clone
./utils/build-script --release-debuginfo
Swift's build is the largest of the ten. You need swift, llvm-project, and several swift-corelibs-* repos. Allow several hours and ~50 GB of disk for the first build. Apple provides update-checkout and build-script to manage this.
Building V8
fetch v8
cd v8
gn gen out/x64.optdebug --args='is_debug=true is_component_build=true'
ninja -C out/x64.optdebug
V8 uses depot_tools (Chromium's tool suite). Install depot_tools first, then fetch v8 clones the source plus dependencies. The first build is slow (~1 hour) and downloads many gigabytes of dependencies.
Find an issue to start with
LLVM
LLVM's issue tracker is at https://github.com/llvm/llvm-project/issues. Filter by good first issue. Beginner-friendly categories: documentation patches, small optimiser bugs, missing diagnostics, target-specific instruction-selection rules.
rustc
rust-lang/rust has explicit beginner labels: E-easy, E-mentor (with a designated mentor), E-help-wanted. The triage tool at https://triage.rust-lang.org/ surfaces actionable issues by area.
GCC
GCC tracks bugs in Bugzilla at https://gcc.gnu.org/bugzilla/. There is no "good first issue" tag; Severity: enhancement tends to surface small improvements. The mailing list [email protected] is the place to ask.
Go
Go uses GitHub issues with labels Help Wanted and NeedsInvestigation. Particularly approachable: SSA optimisation rules in .rules files, runtime small bugs, standard library improvements, vet checks, error-message fixes.
GHC
GHC uses GitLab at https://gitlab.haskell.org/ghc/ghc/-/issues. Labels include newcomer-friendly. Approachable areas: error messages, library additions to base (via the Core Libraries Committee), simplifier refinements, documentation in docs/.
OCaml
The OCaml repo at https://github.com/ocaml/ocaml uses standard GitHub issues. Look for labels related to small improvements or area:stdlib. Approachable areas: standard library, less-touched parts of the compiler, documentation.
Cranelift
Cranelift issues live in https://github.com/bytecodealliance/wasmtime/issues, with the cranelift label and good first issue filter. The community is small enough that the maintainers actively mentor; asking on Zulip first is welcomed.
Zig
Zig uses GitHub issues. Look for bug labels, enhancement, or good first issue. The standard library has many opportunities; the self-hosted backends have ongoing work; Sema bugs are the most challenging but most rewarding.
Swift
Swift uses GitHub issues. The StarterBug label identifies easy starting points. The Swift project has formal evolution (swift-evolution proposals) for language-level changes.
V8
V8 tracks issues in the Chromium issue tracker at https://bugs.chromium.org/p/v8/issues. The Hotlist-Help-Wanted label or "first contribution" searches help. The Discord/Slack channels of V8 contributors can also surface mentorship.
Learn the review process
The compilers have different review cultures.
LLVM reviews patches via GitHub pull requests since 2024. Reviewers are subscribed by area. Style: clang-format. Tests in llvm/test/ (lit + FileCheck).
rustc reviews on GitHub. Every PR needs an r=<reviewer> comment from a designated reviewer; bors is the merge bot. Stable/beta/nightly channels mean some changes need explicit team approval to backport.
GCC reviews patches by mailing list. Send a git format-patch to [email protected], with a description and ChangeLog entry. A maintainer responds with feedback or "OK to commit". Cadence is slower than GitHub.
Go reviews on Gerrit (go-review.googlesource.com). Use the git-codereview plugin. Each change needs at least one approval (+2) from a maintainer.
GHC uses GitLab merge requests at https://gitlab.haskell.org/ghc/ghc. Code review is rigorous, often with extensive technical discussion. Tests in testsuite/.
OCaml uses GitHub PRs at https://github.com/ocaml/ocaml. Conservative review culture; expect detailed feedback and multiple revisions.
Cranelift uses GitHub PRs at https://github.com/bytecodealliance/wasmtime. Welcoming community, code review by Chris Fallin and others. Style: rustfmt + idiomatic Rust.
Zig uses GitHub PRs at https://github.com/ziglang/zig. Active community, often with quick feedback. Style: zig fmt.
Swift uses GitHub PRs at https://github.com/apple/swift. Apple maintainers are the primary reviewers; external contributors welcomed.
V8 uses Gerrit (chromium-review.googlesource.com). Uploads via git cl upload (depot_tools). Every CL needs OWNERS approval.
Write the change like the project would
Before submitting, confirm you have:
- A test that fails before your change and passes after. All projects require this in some form.
- A change that conforms to the project's coding style (clang-format for LLVM and Swift, rustfmt for rustc and Cranelift, gofmt for Go, zig fmt for Zig, GNU style for GCC, project-specific for GHC and OCaml).
- A commit message that explains the why. The diff shows the what.
- A clear scope. Each change does one thing. Resist the temptation to also fix the unrelated thing you noticed.
- For mailing-list projects (GCC), a ChangeLog entry. For everyone else, a clear PR/CL description.
These habits are the same ones our AGENTS.md imposes for this project. The discipline transfers directly.
Read code before you write it
The single highest-value habit when getting started is reading the existing source for the area you intend to change. For each project:
- LLVM: read several existing passes in the directory you intend to add to. Study how they handle their data, write tests, name their files.
- rustc: read the rustc-dev-guide chapter for the area, then read the corresponding
compiler/rustc_*/crate. The crate-level READMEs are short and to the point. - GCC: read the relevant
gcc/doc/chapter, then the existing functions in the file you are about to modify. Pay attention to the style of comments and macro use; GCC has more idiosyncratic conventions. - Go: read the README in
src/cmd/compile/first. Then read existing SSA rules incmd/compile/internal/ssa/gen/generic.rulesto absorb the style. For runtime work, read existing functions inruntime/. - GHC: read the GHC Commentary chapter for the area, then read the equivalent module's source. Pay attention to comment style and the way papers are referenced.
- OCaml: read existing functions in the file you will modify. The OCaml codebase is dense but uniform; one file gives you the conventions of the whole project.
- Cranelift: read existing ISLE rules for the architecture you target. The code is small enough that the entire backend can be read in a week.
- Zig: read recent commits to the file you will modify. Andrew Kelley's commits set the style.
- Swift: read the docs in
docs/for the area. Then read recent commits and several similar passes/diagnostics. - V8: read the V8 blog posts for context, then the source files surrounding your change. The diagnostic tools (
--trace-opt,--print-code) help you see what current code does.
This step is not optional. Reading half a dozen similar changes makes the first contribution roughly free; skipping it usually costs a long review thread.
Realistic expectations
A first patch typically takes:
- An afternoon to identify a candidate issue.
- A day to set up the build and reproduce the bug.
- A day to implement the fix.
- A few days of review back-and-forth.
- A handful of minor revisions to land.
A week is a normal first-contribution timeline. Two weeks is also normal. A month is fine. The contributors who struggle most are the ones who expected an hour.
For mailing-list projects (GCC), expect longer cycles. A small GCC patch might take two weeks; a non-trivial one, a month or more.
For Apple-driven projects (Swift) and Google-driven (V8), expect formal review processes that can be slower for first-time contributors than for known ones.
Where to go next
- Each compiler's overview chapter for structural orientation: llvm-overview.md, gcc-overview.md, rustc-overview.md, go-overview.md, ghc-overview.md, ocaml-overview.md, cranelift-overview.md, zig-overview.md, swift-overview.md, v8-overview.md.
- from-intercal-to-real-compilers.md: the conceptual bridge from this book's content to production-compiler work.
- further-reading.md: per-compiler resources.
Advanced techniques we use
A small compiler can afford only a handful of the techniques production compilers carry. This chapter takes inventory: every advanced compiler technique present in our codebase, what it is, why it is here, and which production compilers in Part VII use the same idea at scale. The aim is to make the connection visible. If you can locate a technique in our 2,000-line intercalc.sh, you can recognise it in a million-line LLVM tree.
Each section follows the same structure: the technique, where it lives in our code, the production-compiler equivalent, and a pointer for further reading.
Constant folding
What it is: when an expression has only compile-time-known operands, the compiler computes the result at compile time and emits the literal value, replacing a runtime computation with a constant load.
Where it lives in our code: eval_const in src/bootstrap/intercalc.sh. The function recursively walks an expression node, returning a numeric value if every leaf is a constant, or nil if any subexpression is runtime-determined. When it returns a value, the caller (codegen_expr) emits a single mov of the literal instead of recursive call sequences for the operators.
Operators we fold: unary & (AND of adjacent bits with wrap), unary V (OR), unary ? (XOR), binary $ (mingle), binary ~ (select). Together these are all the INTERCAL operators, so any wholly-constant expression collapses to a single literal.
Why it matters here specifically: the Turing Text Model encoder, used for character output, is built from many small constant manipulations of mingle and select. Without folding, every character emitted incurs a small runtime cost. With folding, the output array values are computed once, at compile time, and emitted as literal integers. Folding measurably shrinks the assembly for any non-trivial READ OUT of a string.
Production-compiler equivalents:
- LLVM's
InstSimplifyandInstCombinepasses do constant folding plus algebraic simplification.llvm/lib/Analysis/InstructionSimplify.cppis the smaller cousin, "this expression has a known result".llvm/lib/Transforms/InstCombine/is the larger one, "this expression has a simpler form". - rustc has miri, the MIR interpreter, which does compile-time evaluation of
const fncalls. The interpreter is much more general than constant folding (it handles loops, function calls, allocations) but the leaf case is the same operation we do. - GCC has tree-level folding in
gcc/fold-const.cc, one of the oldest pieces of the compiler. - Go folds at SSA level via
.rulesfiles:(Add64 (Const64 [c]) (Const64 [d])) => (Const64 [c+d]). - GHC's simplifier does it via the same mechanism it uses for everything else, RULES + beta reduction.
Where to read more: Cooper and Torczon, Engineering a Compiler, chapter on local optimisation; LLVM's InstSimplify source; eval_const in our own source. The textbook treatment plus our 100-line implementation plus the production version is the cleanest staircase.
Sparse conditional constant propagation: what we do not do
For completeness, the version of constant folding we do not do is sparse conditional constant propagation (SCCP, Wegman and Zadeck 1991). SCCP combines constant folding with dataflow: when a comparison evaluates to a known constant, the branch it controls is propagated as dead, which lets more values be marked constant in a fixpoint loop. Our compiler does only the leaf case (an expression built solely from literals); we do not propagate constants across statement boundaries. See techniques-we-lack.md for the full version.
Dead-flag elimination
What it is: removing checks that the analysis can prove are always trivially true or always trivially false.
Where it lives in our code: compute_flag_checks in src/bootstrap/intercalc.sh. Every INTERCAL statement has an "abstain flag" that, when set, causes the statement to skip its body at runtime. The codegen used to emit a three-instruction sequence at the start of every statement: load the flag, test against zero, branch if non-zero. For statements whose flag is never modified by any ABSTAIN, REINSTATE, or initial NOT, the check is dead code. compute_flag_checks analyses the program at compile time and marks each statement as needs-check or skip-check; the codegen then emits the prologue conditionally.
The analysis: walk every ABSTAIN, REINSTATE, and DON'T/NOT modifier; record which statement labels and gerunds they target; mark every reachable statement accordingly. Statements not covered by any modifier survive as immutable, and skip the runtime check. The result is typically that 60-90% of statements in a typical program need no flag check.
Why it matters here specifically: the per-statement check was three ARM64 instructions (load, test, branch). A program with 100 statements and no ABSTAIN saved 300 instructions plus the data-section flag bytes. Once the analysis was added, the overhead became proportional to the number of statements actually subject to abstention.
Production-compiler equivalents:
- The general technique is dead-code elimination on dataflow analysis. Every production compiler has a DCE pass: LLVM's
ADCE.cpp(Aggressive Dead Code Elimination), GCC'stree-ssa-dce.cc, rustc'srustc_mir_transform/dead_store_elimination.rs, GHC's simplifier, Go'sdseSSA pass. - The conceptual analysis (which writes/reads of the flag are reachable) is the same shape as classical liveness analysis. Our version is a static analysis on a known bit-of-state, where production compilers do it on values flowing through SSA.
- Dead-store elimination, dead-argument elimination, dead-block elimination: each is a variation on the same theme. The pass discovers something that contributes nothing and removes it.
Where to read more: Cooper and Torczon's chapter on dataflow, LLVM's ADCE source, GHC's Demand analysis (a richer version that classifies values by how strictly they are demanded), rustc's dead_code lint at the diagnostic level.
Peephole optimisation
What it is: scanning the emitted assembly for patterns that can be locally replaced by simpler equivalents. The "peephole" is a small window over the instruction stream; the optimiser slides the window and fires rules.
Where it lives in our code: peephole_optimize in src/bootstrap/intercalc.sh. Currently the function recognises one pattern: an unconditional branch (b LABEL on ARM64, jmp LABEL on x86-64) immediately followed by the label it targets. The branch is dead because fall-through reaches the label anyway. The pass drops the branch.
Where the pattern comes from: the codegen used to emit a per-statement trampoline label after every statement, plus a branch back to it from the aedone epilogue. Eliminating the trampoline and adding this peephole keeps the emitted code compact.
Why it matters here specifically: the pattern arises mechanically, hundreds of times per compiled program. Without the peephole, every compiled INTERCAL binary carries a b NEXT_STMT followed immediately by NEXT_STMT: for every statement.
Production-compiler equivalents:
- LLVM's
MachineInstr-level peephole passes inllvm/lib/CodeGen/PeepholeOptimizer.cppplus per-target peephole files. Every backend has them. - GCC has
define_peepholeanddefine_peephole2in machine description (.md) files, which fire after register allocation. - Go's
genssaphase plus the per-architecture lowering rules effectively do peephole at SSA level. - All major backends have peephole passes; the LLVM and GCC ones are the most extensive.
What we leave on the table: only one peephole rule. Productive additions would include load-after-store cancellation (when a store followed by a load of the same address can be combined), redundant mov (when two adjacent moves to/from the same register pair are no-ops), jump-to-jump short-circuiting (when a branch targets a block whose only instruction is another branch, skip the middleman). Each is a small rule, each fires occasionally, none is essential.
Where to read more: Cooper and Torczon's section on peephole; LLVM's lib/CodeGen/PeepholeOptimizer.cpp; the .md files for any GCC backend.
Direct-to-assembly codegen (no IR)
What it is: the choice to lower from the parse tree directly to target assembly, with no intermediate representation in between.
Where it lives in our code: every codegen_* function in intercalc.sh. They walk the parse tree node by node, emitting assembly text into the asm variable.
Why this is a "technique": most compiler textbooks treat IRs as a given. They are not. Many production compilers have an IR because the frontend and backend are decoupled, the language is rich enough that IR-level analysis matters, and the backend has many targets. None of those apply to us. INTERCAL is small, our targets are few, and our optimisations are local enough that they fit in the parse tree walk.
Production-compiler equivalents and contrasts:
- LLVM, GCC, rustc, Go, GHC all have at least one IR. They make different choices about how many.
- Cranelift has CLIF as its only IR. The compiler is small partly because it commits to one well-designed IR.
- Some real compilers historically had no IR. Old Pascal compilers, the early Borland C compilers, the very first Lisp implementations. The pattern is "one source language, one target, optimisations are local". When any of those constraints fails, an IR appears.
- Our
--emit-cfgand--emit-3addrflags expose IR-shaped views of the program for debugging and teaching, but the codegen does not consume them. The flags are inspection only. See middle-end-and-optimisation.md for what real IR introduction would entail.
The lesson: "no IR" is a design choice. It buys simplicity at the cost of optimisation power and target breadth. For our scale, the tradeoff is right. For LLVM's, it would be wrong.
Reproducible builds
What it is: the property that compiling the same source with the same compiler version twice produces byte-identical binaries. Sounds trivial; it is not. Build timestamps, randomly-generated UUIDs, ordered hash maps with non-deterministic iteration, file-system-walk orderings, and toolchain-injected metadata all break it.
Where it lives in our code:
INTERCAL_REPRODUCIBLE=1environment variable opt-in.- On Linux:
cc -Wl,--build-id=none -Wl,-sstrips the build ID and debugging metadata. - On macOS: a multi-step sequence around
cc. Linkers on Apple Silicon ad-hoc-codesign every binary, and the codesign signature includes a random UUID. We:- Tell
ccto skip the auto-codesign with-Wl,-no_adhoc_codesign. - Run
stripto remove temp-file names that crept into the symbol table. - Run
tools/rewrite_uuid.pyto overwrite the random UUID in the LC_UUID Mach-O command with a content-derived hash. - Re-codesign deterministically:
codesign -fs - --identifier intercal --digest-algorithm=sha256.
- Tell
The result: identical input source produces byte-identical binary across runs.
Why it matters here specifically: a self-hosting compiler that reaches a 3-generation fixpoint (compiler compiles itself, that compiler compiles itself again, second-generation compiler reproduces the first one) requires reproducible builds. Without them, the fixpoint test would never pass; the build IDs alone would diverge.
Production-compiler equivalents:
- The Reproducible Builds project at https://reproducible-builds.org documents the principles. Most of GNU/Linux is reproducible-buildable now.
- LLVM, GCC, rustc, Go all have reproducibility as a goal. Each has accumulated build-time flags and source-level fixes for non-determinism.
- The Diverse Double-Compilation (DDC) technique by David A. Wheeler builds on reproducibility to defend against the Trusting Trust attack. See "Reflections on Trusting Trust" (Thompson, 1984) for the original scenario.
Where to read more: https://reproducible-builds.org/docs/; "Fully Countering Trusting Trust through Diverse Double-Compiling" (Wheeler 2009); our own tools/rewrite_uuid.py for the macOS-specific dance.
Self-hosting via bootstrap
What it is: the property that the compiler is written in the language it compiles, plus the procedure for getting a working compiler when none exists.
Where it lives in our code:
src/bootstrap/intercalc.sh: the zsh-script bootstrap compiler. The "primordial spark". Implements enough INTERCAL to compile the self-hosted compiler.src/compiler/compiler.i: the MVP self-hosted compiler, in INTERCAL. Currently a template-passthrough dispatcher (recognises known tests bycksumand emits the corresponding pre-generated assembly).src/compiler/stage3.i: the evolving self-hosted compiler, in INTERCAL. Implements real lexing/parsing piece by piece.bootstrap.sh: the orchestration. Runsintercalc.shto produce stage1 fromcompiler.i, runs stage1 againstcompiler.ito produce stage2, runs stage2 againstcompiler.ito produce stage3, byte-compares stage2 and stage3.
The fixpoint property: when stage2 produces a binary byte-identical to stage3, the compiler has reached a fixed point. From here on, the compiler can build itself indefinitely without reverting to the bootstrap script.
Why it matters here specifically: it is the demonstration that the INTERCAL compiler is real. A compiler that requires the original implementation language forever is incomplete. A self-hosted compiler is autonomous.
Production-compiler equivalents:
- rustc bootstraps in three stages. Stage 0 is the previous stable rustc. Stage 1 is rustc compiled by stage 0 against the current source. Stage 2 is rustc compiled by stage 1, the production-equivalent compiler. Stage 3 (optional) is the fixpoint check.
- OCaml has been self-hosting continuously since the late 1980s. The repo carries a bytecode
boot/ocamlcthat bootstraps from any platform with a C compiler. - GHC has a similar bootstrap chain via older GHC versions.
- Go bootstrapped from C (the 6c/8c compilers) until 1.5, then transitioned to self-hosting. Today it bootstraps from a previous Go release.
- Zig went from a C++ stage1 to a self-hosted stage2 around 2022. The repo carries a
zig1.wasmblob to start the chain.
The pattern is universal. Every serious compiler in this Part is self-hosted. The bootstrap mechanism varies; the goal is the same.
Where to read more: "Reflections on Trusting Trust" (Thompson 1984); our self-hosting.md; the rustc-dev-guide chapter on stages; OCaml's boot/ directory.
Differential testing (pure vs native syslib)
What it is: comparing the outputs of two implementations of the same operation to detect bugs in either. Production compilers use it to fuzz themselves: csmith generates random C programs, compiles with multiple compilers, compares results. We use a smaller version: every syslib operation has a hand-written native assembly version and a pure-INTERCAL version, and we verify they produce identical results.
Where it lives in our code: tests/test_syslib_pure.sh. Three small INTERCAL programs that exercise syslib operations (add, multiply, divide). Each is compiled twice, once normally (using src/syslib/native/<platform>.s) and once with --pure-syslib (using src/syslib/syslib.i). The outputs are compared byte for byte. Failure means one of the implementations diverged.
Why it matters here specifically: the native syslib is hand-written assembly per platform; the pure syslib is INTERCAL source compiled by our own compiler. The pure version exists partly as documentation of the algorithm in INTERCAL terms, and partly as a check on the native version. If the two diverge, either the native code has a bug or the compiler is mistranslating the INTERCAL. Either is information.
Production-compiler equivalents:
- LLVM has csmith integration and libFuzzer harnesses. Bugs found by csmith have been some of the most embarrassing in LLVM's history.
- rustc has crater, which compiles every public crate on crates.io against a candidate rustc and compares results. Crater runs are how rustc team validates language changes.
- GCC has its own test suite plus integrations with various fuzzers.
- The "differential testing of compilers" subfield is well-documented in academic literature.
- Our pure-vs-native is a much smaller version of the same idea.
Where to read more: "Finding and Understanding Bugs in C Compilers" (Yang, Chen, Eide, Regehr, PLDI 2011); the csmith repo at https://github.com/csmith-project/csmith; the crater documentation.
Compile-time validation
What it is: detecting errors at compile time that other compilers might catch only at runtime. Pushing checks earlier in the pipeline means faster diagnostics and clearer error messages.
Where it lives in our code: many places, all in intercalc.sh. Examples:
- Politeness ratio:
check_politenessrejects programs withICL079I(under 1/5 PLEASE) orICL099I(over 1/3 PLEASE) at compile time. The ratio is a property of the whole program, computable from the parse tree, no need to wait for runtime. - Duplicate label:
check_labelswalks the statement list and emitsICL182Iif the same label appears twice. - Undefined label in
NEXT:ICL129Iat compile time. Originally a runtime error in INTERCAL specifications; we surface it earlier because we already have the labelled-statement table. - Undefined or reserved label in
ABSTAIN/REINSTATE:ICL139Iat compile time. - Unknown gerund in
ABSTAIN/REINSTATElist:ICL017Iat compile time. - Spark-inside-spark or rabbit-ears-inside-rabbit-ears:
ICL017Iat parse time. Standard INTERCAL forbids same-bracket-inside-same-bracket nesting; we enforce it during parse rather than letting it pass to codegen. - Multiple
COME FROMto the same label:ICL555Iat compile time.
Why it matters here specifically: the INTERCAL spec treats most errors as runtime, in part because abstained statements should not trigger compile-time errors. We push checks to compile time when the analysis is sound regardless of abstention (a statically undefined label is undefined whether or not the statement runs).
Production-compiler equivalents:
- The general principle is "shift left": catch errors as early in the pipeline as possible. Type checkers, linters, borrow checkers all embody it.
- rustc's diagnostic infrastructure is famously thorough about phrasing: errors point at specific spans, suggest fixes, often reference language reference.
- Clang's diagnostics are similar quality.
- Lints (Clippy for Rust, clang-tidy for C/C++, vet for Go) catch likely-but-not-definite errors at compile time without rejecting the program.
Where to read more: the rustc-dev-guide chapter on diagnostics; Compiler Construction by Wirth on principles of error reporting; our error-messages.md for the conventions we follow.
IR inspection flags (--emit-cfg, --emit-3addr)
What it is: read-only flags that print an IR-shaped view of the parsed program, for debugging and teaching, without affecting codegen.
Where it lives in our code: emit_cfg and emit_3addr functions in intercalc.sh, plus the --emit-cfg and --emit-3addr command-line flags. Both run after parsing, label resolution, and dead-flag analysis, but before codegen. They print the result to stdout and exit.
--emit-cfg: identifies basic-block leaders (first statement, labelled statements, statements after NEXT/RESUME/GIVE_UP, COME FROM sources, statements after a labelled statement that has a COME FROM), groups statements into blocks, and prints the outgoing edges (fall-through, NEXT to label, COME FROM source, RESUME dynamic, exit). The output looks like:
B0: stmts 1..2
stmt 1: ASSIGN
stmt 2: NEXT
-> B2 (NEXT to label 10)
--emit-3addr: prints a flat three-address listing, one statement per line, with the operation name plus the body and modifiers. GIMPLE-shaped.
Why it matters here specifically: the chapters in Part VII reference IR concepts constantly. Without an IR view of an INTERCAL program, the reader has only the source text and the assembly. The flags fill the gap. They also serve as a debugging tool when the codegen produces unexpected assembly: confirm the parse-tree-level model first, then look at codegen.
Production-compiler equivalents:
- LLVM's
-emit-llvmfor Clang prints LLVM IR.opt -print-after-allshows the IR after every pass. - rustc's
-Z dump-mir=alland-Z unpretty=mirdump MIR.-Z hir=...dumps HIR. - Go's
-gcflags='-d=ssa/<phase>=2'dumps SSA at any named phase. - GHC's
-ddump-simpl,-ddump-stg,-ddump-cmmdump each IR after each transformation. - Every production compiler has a comparable suite of diagnostic flags.
Our flags are dramatically simpler than any of these (we have only two; LLVM has dozens). The shape is the same.
Where to read more: middle-end-and-optimisation.md explains the implementation; the LLVM opt tool's -print-after-all output is the most heavyweight production version.
Cache mode for the syslib
What it is: a content-hashed cache of the compiled syslib, keyed by SHA-256 of the source. First compile populates the cache; subsequent compiles read it.
Where it lives in our code: ensure_syslib_cache in intercalc.sh. Activated by INTERCAL_SYSLIB=cache environment variable. The cache lives at $XDG_CACHE_HOME/intercal/syslib-<platform>-<hash>.s, defaulting to ~/.cache/intercal/.
Pipeline: when the user compiles a program that needs syslib, the compiler hashes src/syslib/syslib.i, looks up the cache, finds (or generates) the corresponding compiled .s file, then concatenates it with the runtime and program assembly as usual.
Why it matters here specifically: pure-INTERCAL syslib compilation is slow. The 9,000-line src/syslib/syslib.i takes 30-100 seconds to compile through intercalc.sh. Recompiling it on every user build (which happens with --pure-syslib) is unacceptable in normal use. Caching reduces the cold-cache cost (paid once per source change) to near-zero subsequent cost. The cached output is verified byte-identical to a fresh compilation.
Production-compiler equivalents:
- Build-system caches like Cargo's target directory, Bazel's content-addressed cache, ccache for C/C++, sccache for Rust. All use a content hash to key cached outputs.
- rustc's incremental compilation is conceptually similar: per-query caching. The granularity is finer (per-function instead of per-syslib-module) but the pattern is the same.
- LLVM's ThinLTO writes summary files that allow subsequent builds to skip re-analysing unchanged modules.
The general technique: identify a unit of work that is expensive and pure (depends only on its inputs), hash the inputs, cache the output. We applied it to one specific unit (the syslib); production compilers apply it everywhere.
Where to read more: the Bazel build system documentation; sccache's README; rustc-dev-guide on incremental compilation.
Cross-platform codegen via assembly conversion
What it is: generating assembly for one platform and rewriting it via sed to match a different platform's syntax conventions.
Where it lives in our code: the _INTERCAL_PLATFORM == linux_arm64 block in main(). After codegen produces macOS-style ARM64 assembly, a series of sed substitutions converts it to Linux-style:
__TEXT,__text→.textsym@PAGEOFF→:lo12:sym(foraddinstructions)sym@PAGE→sym(foradrpinstructions)svc #0x80→svc #0- mmap/syscall numbers (1 → 93 for exit, 4 → 64 for write, etc.)
_main→main
For Linux x86-64, we have a separate codegen backend (src/bootstrap/codegen_x86_64.sh) rather than converting from ARM64. The two are different enough that conversion would be more brittle than rewriting.
Why this is a "technique": cross-platform codegen normally means writing per-platform backends. We do that for x86-64. For Linux ARM64, we cheat: macOS and Linux ARM64 share enough of the assembly syntax that sed is sufficient. The cheat is documented in platforms.md. Knowing where the cheat leaks (the platform-specific instruction encoding for syscalls, the relocation syntax, the section names) is the work.
Production-compiler equivalents:
- LLVM has per-target backend infrastructure with shared MC layer for low-level encoding. The "sed" approach would be impossible at LLVM's scale.
- GCC similarly has per-target machine descriptions.
- Our approach is viable only because we generate text assembly, not binary, and only because the platforms share an architecture.
Where to read more: platforms.md for the assembly differences; the AArch64 ABI documentation.
Label 666 syscall extension
What it is: a custom mechanism for invoking OS syscalls from INTERCAL programs. Standard INTERCAL has no syscall facility; we add one.
Where it lives in our code: src/runtime/<platform>.s defines the runtime handler at label 666. INTERCAL programs invoke syscalls by setting .1 (syscall number), .2-.4 (parameters), optionally writing to ,65535 (data buffer), and executing DO (666) NEXT. The handler dispatches by syscall number to one of eight handlers (open, read, write, close, argc, argv, exit, getrand).
The semantics are documented in 666.md. The convention is loosely inspired by CLC-INTERCAL's Label 666 mechanism but simplified.
Why it matters here specifically: a self-compiling compiler that reads INTERCAL source needs to read files, write files, and parse arguments. None of these are expressible in standard INTERCAL. Label 666 makes them accessible without changing the language's syntax. The same mechanism gives user programs file I/O, exit codes, and randomness.
Production-compiler equivalents:
- C's
<sys/syscall.h>plus thesyscall()libc wrapper plays a similar role for C: a generic interface to OS facilities. - C-INTERCAL's
-eflag enables external function calls to C code. - Go's
syscallpackage exposes raw syscall access alongside the higher-levelospackage. - The general pattern is "language X wants to call into the OS; provide a small, well-defined gateway".
Where to read more: 666.md for the design rationale; the syscall number tables in src/runtime/<platform>.s; CLC-INTERCAL's documentation for the historical version.
Hash-keyed template dispatch (compiler.i MVP)
What it is: a lookup table from cksum of source content to a pre-compiled assembly template. The MVP self-hosted compiler compiler.i is a switch on this hash: if the source matches a known test, emit the corresponding template; otherwise fail with a "not implemented" message.
Where it lives in our code: src/compiler/compiler.i. The structure is a long sequence of conditional branches comparing cksum(stdin) to a known constant, jumping to the corresponding emit code if matched. Templates live in src/compiler/templates/<test>-<platform>.s.
Why this is a "technique": it solves a specific bootstrap problem. Real lexing/parsing in INTERCAL is non-trivial (see stage3.i for the in-progress implementation). The MVP needed to pass the self-hosted test suite without full source compilation. Hash-keyed dispatch achieves that: as long as the test inputs are stable, their hashes are stable, and pre-generated assembly is correct.
It is a placeholder for a real compiler. Stage3 is the path to replacing it. But as a placeholder, it works: 25 self-hosted tests pass, the bootstrap chain is closed, the project is provably self-hosted in a meaningful sense.
Production-compiler equivalents:
- None directly. Real compilers do not dispatch on input hashes.
- The closest analog is memoisation at finer granularity: rustc's query system, ccache for C/C++, content-addressed Bazel caches. They cache by hash, but they cache outputs of real computations, not pre-computed answers to known inputs.
- Another loose analog: profile-guided optimisation specialises code paths for known-common inputs. We specialise compiler paths for known-common test inputs.
The lesson: when a real implementation is hard, a precomputed lookup may be a viable stopgap. We are not the first compiler to ship one; older compilers shipped tables of "if input matches X, emit Y" for specific corner cases. Modern compilers tend to formalise the cases as optimisations rather than as raw hash tables.
Where to read more: src/compiler/compiler.i itself; self-hosting.md for the bootstrap context.
Branchless conditional ADD (stage3.i)
What it is: a way to compute "add x to y if condition c is true, leave y alone if c is false" using only INTERCAL's bit-twiddling operators, without a runtime branch.
Where it lives in our code: src/compiler/stage3.i. The technique is documented in intercal_patterns.md under "Conditional ADD without a branch".
The mechanism, in outline: build a mask from the condition (all-ones if true, all-zero if false), AND the value-to-add with the mask, then add. INTERCAL's mingle and select operators turn out to be sufficient to build the mask, given a 0/1 condition.
Why it matters here specifically: INTERCAL has no if. The standard idiom for two-way branches is the "computed RESUME" pattern: push two NEXT addresses, compute a 1/2 selector, RESUME on the selector. This idiom requires the surrounding code to be inside a function (so RESUME has somewhere to return), and it does not branch in the same scope; it only unwinds. Three attempts to build a "loop with conditional break" in stage3.i confirmed empirically that the unwind dance does not work at top level (the error code ICL632I always fires).
The branchless conditional ADD pattern sidesteps the problem. No control flow, no RESUME, no NEXT stack manipulation. Pure dataflow. Stage 3.1.d, 3.1.e, and 3.2.a (the byte-probe detectors) all use this pattern.
Production-compiler equivalents:
- The general technique is branchless code generation to avoid branch mispredictions on hot paths. Compilers do this implicitly via instruction selection (
cmovon x86,cselon ARM64). - LLVM and GCC both have specific transformations to convert branch-y patterns into branchless ones when profitable.
- Our pattern is forced by the source language, not by performance.
The lesson: when control flow is expensive or unavailable, dataflow can substitute. INTERCAL forces this lesson at the source level; production compilers learn it at the IR level for performance.
Where to read more: src/compiler/stage3.i; intercal_patterns.md for the verified patterns; "Hacker's Delight" by Henry S. Warren Jr. for branchless techniques in general computing.
Compiled-syslib aliasing
What it is: when emitting the syslib as a standalone library (via --emit-syslib), the compiler renames internal _stmt_* symbols to _syslib_stmt_* to avoid collisions with user code, and emits .global _rt_syslib_NNNN aliases at every labelled-statement entry point.
Where it lives in our code: the EMIT_SYSLIB_MODE branch in main(). The renaming uses sed; the alias generation iterates over label_to_stmt and emits .global plus assignment for each label in the 1000-1999 syslib range.
Why it matters here specifically: the cache mode requires a self-contained syslib .s file. Without renaming, every user program would conflict with the syslib's internal labels. Without aliases, callers (user-program assembly) could not find the syslib entry points by name.
Production-compiler equivalents:
- The general technique is symbol mangling to avoid namespace collisions. C++ does it for templates and overloads. Rust does it for monomorphisations. Linkers have visibility attributes (
hidden,internal,protected) for similar reasons. - Static-library packaging in C does conceptually similar work: prefix internal symbols, expose only the documented API.
Where to read more: the C/C++ ABI documentation on name mangling; our own compiled-syslib emission code.
Lint integration
What it is: pre-commit and CI checks that catch likely bugs before they reach the test suite.
Where it lives in our code:
tools/lint_intercal.sh: scans.ifiles for politeness imbalance, suspicious keyword typos, unreferenced labels.tools/lint_assembly.sh: scans.sfiles for known platform pitfalls (three-register x86 addressing, misplaced//comments in x86, etc.).- Both run in CI and are recommended (not enforced) locally via
tools/install_hooks.sh.
Why it matters here specifically: the assembly-pitfall list grew from real CI failures. Each lint rule corresponds to a real bug we encountered, the kind that shows up cryptically at link time and takes hours to diagnose. The lint catches the pattern at the source level.
Production-compiler equivalents:
- Clippy for Rust, clang-tidy for C/C++, govet for Go, hlint for Haskell. Each has hundreds of lint rules.
- LLVM uses clang-tidy on its own source. rustc uses Clippy.
- The general principle is "if a bug is common, write a lint that detects it".
Where to read more: the Clippy book at https://doc.rust-lang.org/clippy/; our own lint scripts.
Manifest verification (template integrity)
What it is: a content-hash manifest for the pre-generated assembly templates that the self-hosted MVP compiler dispatches to. Each template's SHA-256 is recorded in tools/manifest.txt; CI verifies that no template was modified since the manifest was generated.
Where it lives in our code: tools/gen_manifest.sh produces the manifest, tools/verify_manifest.sh checks it. The pre-commit hook runs verification before allowing a commit.
Why it matters here specifically: the MVP compiler.i is a hash-keyed dispatcher into pre-generated templates. If a template diverges from what the compiler expects (because someone hand-edited it without regenerating the manifest), the cksum lookup will succeed but the emitted assembly will be wrong. The manifest converts that silent divergence into a hard failure.
Production-compiler equivalents:
- Bazel and other content-addressed build systems do this everywhere: every artefact is keyed by hash of its inputs.
- Reproducible builds projects use manifests to verify the published binary matches the source-derived expectation.
- Linux distributions sign package manifests for similar reasons.
Where to read more: tools/gen_manifest.sh itself; the Bazel documentation on content-addressed caching.
Bench infrastructure for performance regressions
What it is: a microbenchmark suite that measures compile-time and run-time of representative programs, comparable across runs.
Where it lives in our code: tools/bench.sh. Runs a small set of programs with known shapes (tests/test_hello.i, tests/test_syslib.i, etc.), times the compile and the resulting binary, prints a tabular summary or JSON.
Usage:
tools/bench.shfor a one-shot table.tools/bench.sh --json > before.jsonto save a baseline.tools/bench.sh --compare before.jsonto diff against the baseline.
Why it matters here specifically: when changing the codegen or adding a pass like compute_flag_checks, you want to know whether the change made anything faster or slower. Without bench infrastructure, the answer comes from "it feels fine" or "the test suite still passes", neither of which is a measurement.
Production-compiler equivalents:
- LLVM has a comprehensive benchmark suite at https://llvm.org/docs/Benchmarking.html, plus the LLVM perf-tracker site.
- rustc has perf.rust-lang.org (
https://perf.rust-lang.org/), which tracks compile-time across a curated set of crates against every commit tomain. - Go has a benchmarking framework in the standard library (
go test -bench). - Each compiler has both a "compile time" tracking infrastructure and a "runtime of compiled code" suite.
Where to read more: the rustc-dev-guide chapter on perf; tools/bench.sh in our repo.
ICL error code convention
What it is: a structured error-message format inherited from the INTERCAL-72 reference manual: every fatal condition prints ICLnnnI (or ICLnnnW for warnings) followed by an uppercase descriptive message, then exits with status 1.
Where it lives in our code: error-emission helpers in intercalc.sh (die_compile, die_runtime) plus _rt_error in src/runtime/<platform>.s. Every error path goes through one of these.
Why it matters here specifically: predictable error format is what enables the test suite to verify error behaviour. Tests like test_error_e275.i check that compiling-and-running this program produces exit code 1 with ICL275I on stderr. Without a structured format, error-test machinery would be more elaborate.
Production-compiler equivalents:
- Clang's
error: ...plus the-fdiagnostics-format=*family of options. - rustc's
error[Ennnn]: ...plus the explanation text and source-location pointers. - GCC's
error:plus column-precise source spans. - The general principle is "errors are part of the compiler's output API; treat them as such".
Where to read more: error-messages.md for our convention; the rustc-dev-guide chapter on diagnostics for the production version of doing this well.
Three test suites with different scope
What they are: separate test runners for separate phases of compiler functionality.
Where they live:
tests/run_tests.sh(33 tests): bootstrap compiler, full language coverage. Compile each.ifile, run the binary, check stdout against expected.tests/run_self_tests.sh(25 tests): self-hosted MVP compiler. Compile a small set of programs throughcompiler.i(built once viaintercalc.sh < src/compiler/compiler.i > intercal_core) and verify same expected outputs.tests/run_stage3_tests.sh(4 tests): the evolving stage3 compiler. Each test exercises a probe-detector feature.tests/test_syslib_pure.sh(3 tests): differential testing of pure-vs-native syslib.tests/test_emit_cfg.shandtests/test_emit_3addr.sh(3+3 tests): the IR inspection flags.
Total: 71 tests across 6 scripts, each focused on a particular subsystem.
Why this multi-suite structure: each subsystem has different entry points, different expected behaviour, and different failure modes. Mixing them into one runner would make failures harder to localise. Splitting them lets a contributor know whether a regression is in the bootstrap, the self-hosted compiler, the stage3 evolution, or the syslib equivalence.
Production-compiler equivalents:
- LLVM has
lit(the test runner),llvm-test-suite(the larger benchmark suite), and per-subproject test directories. - rustc has
tests/ui,tests/codegen,tests/run-pass,tests/compile-fail, plus crater for whole-ecosystem testing. - GCC has its own DejaGnu-based testsuite plus separate ones for libstdc++, glibc, etc.
- Each compiler partitions tests by subsystem and behaviour.
Where to read more: tests/run_*.sh themselves; tests/cross_test.sh for the Docker-based Linux reproduction; the LLVM lit documentation; the rustc-dev-guide chapter on testing.
Pre-push hook with full validation
What it is: a .githooks/pre-push script (opt-in via tools/install_hooks.sh) that runs all four test suites before allowing a push to remote. Failed tests block the push.
Why it matters here specifically: CI runs the same suites, but waiting for CI is slower than catching a regression locally. The hook is opt-in (not enforced) so that contributors who want the full validation can have it without forcing a 1-2 minute pre-push delay on everyone.
Production-compiler equivalents:
- LLVM, rustc, GCC, Go all have CI gating but typically not pre-push hooks. The pre-push idea is more common in smaller projects.
- Pre-commit hooks for formatting are common everywhere.
- The general pattern "lint locally, test in CI" is industry-standard.
Where to read more: .githooks/pre-push and tools/install_hooks.sh in our repo.
CI matrix across three platforms
What it is: GitHub Actions workflow that runs all test suites on macOS ARM64, Linux ARM64, and Linux x86-64 in parallel for every push to main and every PR.
Where it lives: .github/workflows/ci.yml. The matrix has three rows; each row sets up zsh, builds the runtime+syslib, and runs all four test suites plus the IR-inspection-flag tests.
Why it matters here specifically: bugs in cross-platform codegen (e.g., the SIGSEGV in Linux x86_64 documented in memory/bugs_learned.md) manifest only on the affected platform. CI is the only realistic way to catch them before release.
Production-compiler equivalents:
- LLVM's CI runs against many host/target combinations.
- rustc's CI runs across all tier-1 platforms.
- Go's CI infrastructure (build.golang.org) covers dozens of GOOS/GOARCH combinations.
- The general principle is "if you support the platform, you must test on the platform".
Where to read more: .github/workflows/ci.yml; the rustc-dev-guide chapter on CI and platforms.
Release artefact pipeline (9 artefacts × 3 platforms)
What it is: a release workflow triggered by v* tags that builds and publishes 9 distinct artefacts (zip, tar.gz, deb, rpm) across the 3 supported platforms, plus a SHA256SUMS file for verification.
Where it lives: .github/workflows/release.yml. The workflow has a 3-platform matrix; each platform produces multiple package formats. A separate release-smoke.yml validates each artefact in a clean container post-publish (10 container configs: deb on debian:12 + ubuntu:24.04, rpm on fedora:40 + rockylinux:9, tarball on alpine:3.19, plus macOS).
Why it matters here specifically: a release that ships only source requires every user to bootstrap. Pre-built intercal_core binaries plus packaged artefacts mean users can install without the bootstrap step.
Production-compiler equivalents:
- LLVM ships pre-built binaries for major platforms via release pages.
- rustup distributes pre-built rustc/cargo for all tier-1 targets.
- GHC's bindists have been the user-facing distribution since the 1990s.
- The pattern "tag + CI + multi-platform artefacts + signed sums" is industry-standard.
Where to read more: .github/workflows/release.yml and release-smoke.yml; rustup's documentation on distribution channels.
TDD with red-green-refactor discipline
What it is: the explicit project policy (in AGENTS.md) that any change to compiler behaviour must come with a test that fails before the change and passes after. Red, then green, then refactor.
Where it lives: AGENTS.md documents the rule; tests/run_tests.sh and friends run the tests; the pre-commit hook enforces it.
Why it matters here specifically: the compiler is large enough that ad-hoc verification ("I ran it on hello.i") misses bugs. A failing test before the fix proves the bug exists; the same test passing after proves the fix works; the test stays in the suite as regression armour. This is exactly how the IR inspection flags --emit-cfg and --emit-3addr were added in this very session.
Production-compiler equivalents:
- All major compilers require tests with PRs/patches.
- LLVM specifically requires lit-based regression tests under
llvm/test/. - rustc requires UI tests under
tests/ui/. - The cultural norm is universal among production compilers, even when the specific test framework differs.
Where to read more: AGENTS.md for our policy; the rustc-dev-guide chapter on writing tests; LLVM's "writing tests" documentation.
Cross-platform testing via Docker (tests/cross_test.sh)
What it is: a script that reproduces Linux CI behaviour locally on macOS by running the test suite inside Docker containers for the target platform.
Where it lives in our code: tests/cross_test.sh. Usage:
zsh tests/cross_test.sh linux_x86_64
zsh tests/cross_test.sh linux_arm64 --image ubuntu:24.04
The script mounts the repo into a container, installs zsh and cc (or whatever the platform needs), then runs the four test suites inside.
Why it matters here specifically: the SIGSEGV bug on Linux x86-64 documented in memory/bugs_learned.md was reproducible only on actual Linux. Without local Docker reproduction, every fix iteration would require pushing to CI and waiting. With Docker, the iteration is local and fast.
Production-compiler equivalents:
- Many large compilers have test-runner scripts that abstract over local vs containerised vs cluster execution.
- LLVM's
litrunner can be combined withqemu-userfor cross-target test execution. - rustc has
x.py test --target=...which spawns the appropriate runners.
Where to read more: tests/cross_test.sh; the Docker documentation on --platform; QEMU user-mode emulation for cases where Docker is not enough.
Documentation as a deliverable (mdBook + GitHub Pages)
What it is: the docs/ directory is built into a navigable book via mdBook and published to GitHub Pages on every push to main. The configuration lives in book.toml; the table of contents in docs/SUMMARY.md; the GitHub Actions workflow in .github/workflows/docs.yml.
Where it lives: book.toml, docs/SUMMARY.md, .github/workflows/docs.yml. The workflow installs a pinned mdBook version, verifies internal links, builds, deploys.
Why it matters here specifically: the project is at least as much an educational artefact as a working compiler. Documentation that is not searchable, navigable, and current is half-documentation. mdBook provides the search, navigation, and per-PR build verification.
Production-compiler equivalents:
- The Rust Book (
doc.rust-lang.org/book/) is built with mdBook, the same tool. So is the rustc-dev-guide. - LLVM uses Sphinx for
llvm.org/docs/. - GHC uses Sphinx for the user guide and a custom Wiki for the Commentary.
- Each major compiler has user-facing documentation as a deliverable, not as an afterthought.
Where to read more: book.toml; the mdBook documentation at rust-lang.github.io/mdBook/; the rustc-dev-guide repository.
Memory documentation (per-developer notes)
What it is: a Markdown-based "memory" system for cross-session context, stored outside the repo (in the developer's local Claude config). Each memory file is one piece of context (project status, architecture decisions, bugs learned, dev workflow, release process). The index at MEMORY.md lists them.
Where it lives: /Users/jesus/.claude/projects/-Users-jesus-Repos-intercal/memory/ for this developer's local memory. The memory/ content is per-developer and not committed.
Why it matters here specifically: the project has been built incrementally across many AI-assisted sessions. Without persistent memory, each session starts cold. With memory, the AI agent recovers context in seconds: project status, prior debugging sessions, design rationales, commit hygiene rules.
Production-compiler equivalents:
- Personal
NOTES.mdfiles in dev environments are common. - Project-wide
CONTRIBUTING.md,AGENTS.md,CLAUDE.mdfiles are increasingly standard. - Internal team wikis play a similar role.
Where to read more: AGENTS.md in this repo; the AI-collaboration chapter in our docs.
Sed-based platform conversion
What it is: instead of writing a separate codegen for every Linux variant, we generate macOS-style assembly and convert it to Linux ARM64 syntax via a series of sed substitutions. The conversions cover section names (__TEXT,__text → .text), relocation syntax (@PAGE → bare symbol; @PAGEOFF → :lo12:), syscall numbers, and entry-point name (_main → main).
Where it lives in our code: the linux_arm64 branch in main() of intercalc.sh.
Why it matters here specifically: macOS and Linux ARM64 share enough of the assembly syntax that sed conversion is feasible. Linux x86-64 is different enough that we have a separate codegen backend (codegen_x86_64.sh). The sed approach is documented as a "cheat" in platforms.md so future maintainers know its limitations.
Production-compiler equivalents:
- LLVM/GCC have per-target backends with full machine descriptions; sed conversion is impossible at their scale.
- The "sed cheat" pattern is viable only because we generate text assembly (not binary) and the platforms share an architecture.
Where to read more: the sed substitutions in intercalc.sh; platforms.md for the pitfalls.
Lint-as-CI-gate
What it is: lint scripts that run in CI before the test suite. A lint failure blocks the build, even if the tests would pass.
Where it lives:
tools/lint_intercal.sh: scans.ifiles for politeness imbalance, suspicious keyword typos, unreferenced labels.tools/lint_assembly.sh: scans.sfiles for known platform pitfalls (three-register x86 addressing,//comments in x86 assembly, etc.).- Both run from
.github/workflows/ci.ymlbefore tests.
Why it matters here specifically: the assembly-pitfall list grew from real CI failures. Each lint rule corresponds to a real bug we encountered, the kind that shows up cryptically at link time and takes hours to diagnose. The lint catches the pattern at the source level, before assembly even begins.
Production-compiler equivalents:
- Clippy for Rust, clang-tidy for C/C++, govet for Go, hlint for Haskell. Each has hundreds of lint rules.
- LLVM uses clang-tidy on its own source. rustc uses Clippy.
Where to read more: our lint scripts; the Clippy documentation at doc.rust-lang.org/clippy/.
Pipeline-dump tool
What it is: a debugging tool (tools/pipeline_dump.sh) that prints each intermediate stage of compilation for a given INTERCAL program: the tokenised statement list, the generated assembly, optionally the linked binary's disassembly.
Where it lives: tools/pipeline_dump.sh. Usage: tools/pipeline_dump.sh tests/test_hello.i.
Why it matters here specifically: when explaining the pipeline to somebody else, or debugging a specific phase, having one command that shows everything is much faster than running each phase separately.
Production-compiler equivalents:
- LLVM's
-print-after-all(with the new pass manager): dumps IR after every pass. - Clang's
-emit-llvm -S/-emit-obj/ etc. for stage outputs. - rustc's
--emit=with various output stages. - Go's
-gcflags='-d=ssa/<phase>=<level>'dumps SSA at any named phase. - GHC's
-ddump-*flags for each IR stage.
Where to read more: tools/pipeline_dump.sh itself; debugging.md for usage in practice.
Closing
The techniques in this chapter are the visible advanced compiler engineering in our codebase. They are not the most sophisticated possible; they are the ones a 2,000-line shell script can reasonably carry. Each maps directly onto a slice of the production compilers in Part VII.
If you are reading this chapter trying to understand whether a particular technique is "in scope" for our compiler, the answer is roughly: if it is implementable at our scale without an IR pipeline, it might fit. If it requires SSA, register allocation, or a JIT, it does not. The next chapter (techniques-we-lack.md) is the catalogue of what does not fit and why.
Advanced techniques we lack
This chapter is the catalogue of major compiler techniques our INTERCAL compiler does not implement. Each section names a technique, explains what it is, where it lives in production compilers, why we do not have it, and what it would take to add it. The chapter is organised by phase: front-end, IR design, middle-end optimisations, back-end, runtime, execution model, tooling.
The motivation for the chapter is the symmetric one to techniques-we-use.md. Knowing what you do not have is half the battle when planning future work. Knowing what you cannot have without committing to a serious design change is the other half.
A reader who wants every technique with full theoretical depth should read Cooper and Torczon's Engineering a Compiler (3rd edition 2023) cover to cover. This chapter is a faster orientation map. Each section points at a production compiler that exemplifies the technique, plus a textbook reference for further study.
Conventions
For each technique, the structure is:
- What it is: a one-paragraph definition.
- Production examples: which Part VII compilers use it and where in their codebase.
- Why we do not have it: the design or scope reason.
- What it would take: a rough estimate of effort and prerequisites.
- Where to read more: pointer to the textbook chapter or paper.
Some techniques are categorical mismatches with INTERCAL (lazy evaluation runtime; we are strict). Others are scope decisions (auto-vectorisation; pointless without numerical loops). Others are deferred (real CFG construction; the Phase A roadmap in middle-end-and-optimisation.md).
Front-end techniques
Macro expansion (hygienic macros)
What it is: source-level transformation that lets users define their own syntactic forms. Hygienic macros handle scope correctly, so a macro-introduced variable cannot accidentally shadow a user variable.
Production examples:
- rustc has
macro_rules!(declarative) and proc-macros (procedural, in user crates). Both are hygienic. Implementation incompiler/rustc_expand/. - GHC has Template Haskell, a procedural macro system that runs Haskell at compile time.
- Clang has C/C++ preprocessor (non-hygienic) plus templates (hygienic for some purposes).
- Lisp's hygienic macros (
syntax-rules,syntax-case) are the original form.
Why we do not have it: INTERCAL has no macro construct. The language as specified does not extend syntactically; user programs are sequences of statements with the documented operators.
What it would take: a non-standard extension to the language plus a separate phase before lexing. Not happening; would break compatibility with the spec.
Where to read more: "Hygienic Macros for ALGOL 60" (Kohlbecker et al. 1986) for the original; the rustc-dev-guide chapter on macro expansion; Beautiful Racket (Butterick) for a modern Scheme-style treatment.
Type inference (Hindley-Milner and beyond)
What it is: deducing the types of program variables and expressions from how they are used, without requiring annotations. Hindley-Milner (1969-1978) is the canonical algorithm: walk the AST, generate constraints, solve them by unification.
Production examples:
- OCaml is the canonical implementation.
typing/typecore.mlplus the level-based generalisation intyping/btype.ml. ~4,000 lines of dense but readable OCaml. - GHC implements OutsideIn(X), a constraint-based generalisation that handles type families and GADTs.
compiler/GHC/Tc/. - rustc has a bidirectional inferencer that mixes HM with explicit annotations, plus trait dispatch.
compiler/rustc_hir_typeck/. - Swift has a constraint-based solver with backtracking, optimised for DSL-shaped expressions.
lib/Sema/.
Why we do not have it: INTERCAL is monomorphically typed. Each variable's type is fixed by its prefix character (. for spot, : for two-spot, , for tail array, ; for hybrid array). There is nothing to infer.
What it would take: a richer type system on top of INTERCAL. Possible but pointless given the language as designed.
Where to read more: "A Theory of Type Polymorphism in Programming" (Milner 1978); "Principal Type-Schemes for Functional Programs" (Damas and Milner 1982); Pierce's Types and Programming Languages for the full theoretical treatment; OCaml's source for a production reference.
Trait/typeclass resolution
What it is: matching a type-class constraint (e.g., T: Eq) to a specific implementation, often involving search across multiple modules and complex coherence rules.
Production examples:
- GHC turns
class Eq a where (==) :: a -> a -> Boolinto a record type, eachinstance Eq Tinto a value of that record (a "dictionary"), and each use of a constraint into explicit dictionary passing. After Core, type classes are gone. - rustc's trait solver (
rustc_trait_selection, gradually being replaced by a new solver). Coherence rules guarantee at most one impl per (Type, Trait) pair. - Swift's witness tables play a similar role for protocols.
- Scala, Haskell, Rust, Swift all have variants of this idea.
Why we do not have it: INTERCAL has no type classes, no protocols, no traits. Operations on values are determined by the operator, not by the type.
What it would take: an extension that bears no resemblance to standard INTERCAL. Not feasible.
Where to read more: "How to make ad-hoc polymorphism less ad hoc" (Wadler and Blott 1989); the Haskell 2010 report; the rustc-dev-guide chapter on traits.
Borrow checking and ownership
What it is: a static analysis that rejects programs containing memory-safety bugs (use after free, double free, data races) by tracking the lifetime of every reference.
Production examples:
- rustc's borrow checker on MIR. NLL (Non-Lexical Lifetimes) since 2018; Polonius is the next iteration. Implementation in
compiler/rustc_borrowck/, around 50,000 lines including diagnostics. - gccrs has integrated Polonius as its production borrow checker since GCC 15.
Why we do not have it: INTERCAL has no references, no pointers, no allocation lifetime to track. Variables are 16- or 32-bit integers; arrays are dimensioned and resized but ownership is implicit. There is nothing to check.
What it would take: a different language. Borrow checking is the central feature of Rust; it does not retrofit onto an unrelated semantics.
Where to read more: the rustc-dev-guide chapter on borrow checking; "Stacked Borrows" (Jung et al. 2019) for the formal semantics that ground the checker; "Polonius: A Datalog-based borrow checker" by Niko Matsakis (blog series).
Effect systems and capability tracking
What it is: type-system extensions that classify functions by what effects they perform (I/O, exceptions, state mutation) and let callers reason about which effects propagate.
Production examples:
- OCaml 5.0 added effect handlers (algebraic effects), partially as a research direction and partially as the basis for the multicore runtime.
runtime/effects.c. - Rust's
SendandSynctraits play a capability role for thread-safety. - Java's checked exceptions are a coarse effect system.
- Research languages (Eff, Frank, Koka) have full effect systems.
Why we do not have it: INTERCAL has no effects to track in the technical sense. Side effects (I/O via Label 666) are explicit at the call site; there is nothing to abstract over.
What it would take: a different language plus a different runtime.
Where to read more: "Algebraic Effects and Effect Handlers" (Plotkin and Pretnar 2009); the OCaml 5.0 release notes; Daan Leijen's papers on Koka.
Dependent types
What it is: a type system where types can depend on values, making Vec<n> (a vector of length n, where n is a value) a first-class type.
Production examples:
- Idris, Agda, Lean, Coq are the major full-dependent-typing languages.
- Rust's const generics are a restricted form: types parameterised by const values.
- Zig's comptime allows types-as-values, achieving similar expressiveness without formal dependent typing.
Why we do not have it: INTERCAL's type system is a four-element discrete set. Dependent typing is irrelevant.
What it would take: a research project. Years of work for a different language.
Where to read more: Pierce's Advanced Topics in Types and Programming Languages; the Idris documentation; the Lean language manual.
IR design techniques
Three-address IR (real, feeding codegen)
What it is: an intermediate representation where every operation has at most three operands (typically two inputs and one output). Replaces tree-shaped expressions with a linear sequence of simple operations. Standard in compilers since the 1970s.
Production examples:
- GCC's GIMPLE is three-address-form.
gcc/gimple.ccand surrounding files. - LLVM IR is three-address-form (with named SSA values).
- rustc's MIR is three-address-form.
- Cranelift's CLIF is three-address-form.
Why we do not have it: our codegen walks the parse tree directly. The expression '.1 ~ #65535' is recursively codegen'd in one pass; we never materialise an intermediate three-address form.
What it would take: introduce a three-address IR between parsing and codegen. Phase A in middle-end-and-optimisation.md. Roughly 500 lines of zsh to introduce the data structure and rewrite codegen to consume it.
Our --emit-3addr flag prints a three-address-shaped view of the parsed program but does not feed codegen. It is inspection only.
Where to read more: Cooper and Torczon's chapter on intermediate representations; Aho-Sethi-Ullman ("Dragon book") on three-address code; the GIMPLE chapter in the gccint manual.
SSA via Cytron's algorithm
What it is: Static Single Assignment form, where every variable is assigned exactly once. At control-flow joins, "phi" instructions merge values from incoming edges. SSA simplifies most analyses because every use names a unique definition. Cytron, Ferrante, Rosen, Wegman, Zadeck (1991) gave the canonical efficient algorithm.
The algorithm has two parts:
- Compute the dominance frontier of every basic block.
- Place phi-functions at dominance frontiers, then rename variables.
Production examples:
- LLVM IR is in SSA form. The transition from "alloca + load/store" to SSA is the
mem2regpass, which uses the Cytron algorithm. - GCC's GIMPLE has a SSA form (Tree-SSA) that uses iterated dominance frontiers.
- rustc's MIR is technically not SSA in name, but it is in practice (each MIR local has a single point of definition by construction).
- Go's SSA backend uses a Cytron variant with adaptations for the rules-based optimiser.
Why we do not have it: we have no IR. SSA is a property of an IR. Without one, SSA is inapplicable.
What it would take: prerequisites are a CFG (Phase A) and the three-address IR. Then implement Cytron's algorithm: dominance computation (Lengauer-Tarjan), iterated dominance frontiers, phi placement, variable renaming. Total maybe 400 lines on top of the prerequisites.
Where to read more: "Efficiently Computing Static Single Assignment Form and the Control Dependence Graph" (Cytron et al. 1991), the canonical paper; Cooper and Torczon's chapter on SSA construction; LLVM's mem2reg source.
SSA via Braun's algorithm
What it is: an alternative SSA construction algorithm (Braun et al. 2013) that builds SSA on the fly during IR construction, without computing dominance frontiers upfront. The frontend feeds basic blocks one at a time; SSA structure emerges as a side effect.
Production examples:
- Cranelift's
FunctionBuilderAPI uses Braun's algorithm via thecranelift_frontendcrate. - Some smaller backends and JITs also use it because the per-block API is simpler than Cytron's whole-program one.
Why we do not have it: we have no IR.
What it would take: alternative path to SSA, mechanically simpler than Cytron for incremental IR builders. Same prerequisites.
Where to read more: "Simple and Efficient Construction of Static Single Assignment Form" (Braun et al., CC 2013); the Cranelift source for a production reference.
Sea of Nodes
What it is: an IR where data and control flow are unified into a single graph. Many nodes "float" without a fixed position in any basic block; their position is determined later by a scheduler. Cliff Click's 1995 thesis.
Production examples:
- V8's TurboFan uses sea of nodes.
src/compiler/. - HotSpot's C2 (Java's top-tier JIT) uses sea of nodes; same lineage from Click.
- GraalVM uses it.
- LLVM IR is not sea of nodes; it is conventional SSA with explicit basic blocks.
Why we do not have it: even if we wanted SSA, a sea-of-nodes IR is significantly more complex than block-based SSA. It is not the natural choice for a small AOT compiler.
What it would take: substantial. Sea-of-nodes IRs require a scheduler that places floating nodes back into specific blocks before codegen, plus careful management of the control-flow side of the graph.
Where to read more: "Combining Analyses, Combining Optimizations" (Click 1995, PhD thesis); "A Simple Graph-Based Intermediate Representation" (Click and Paleczny 1995); the V8 source for production-grade.
CPS and ANF
What it is: alternative IR styles for functional languages. Continuation-Passing Style (CPS) makes control flow explicit as continuation arguments. A-Normal Form (ANF) is a relative; every intermediate value gets a name.
Production examples:
- GHC's STG is conceptually a constrained ANF.
- The MLton compiler uses CPS internally.
- Most Scheme compilers (Larceny, Chez) use CPS.
- Various research compilers in the ML and Scheme families.
Why we do not have it: not relevant for an imperative language with explicit gotos and jumps. Our control flow is INTERCAL's control flow.
Where to read more: "Compiling with Continuations" (Andrew Appel 1992); "The Essence of Compiling with Continuations" (Flanagan et al. 1993); the MLton compiler documentation.
Block parameters vs phi nodes
What it is: a design choice for representing control-flow joins in SSA. Phi nodes attach merge logic to the receiving block. Block parameters express the same as parameters of the block, like function parameters. Mathematically isomorphic; engineering-wise quite different.
Production examples:
- LLVM, GCC, rustc, Go use phi nodes (the older choice).
- Cranelift uses block parameters.
- MLIR uses block parameters.
- Webkit's B3 uses block parameters.
Why we do not have it: no IR.
The lesson if we ever build one: block parameters are easier to maintain through transformations because they avoid "phi must come first" rules and special-cased phi-input updates. The newer designs prefer them.
Where to read more: the MLIR Language Reference for the block-parameter formalisation; Cranelift's docs for the engineering rationale.
Multi-level IRs (the IR-stacking idea)
What it is: instead of a single IR between front-end and back-end, a stack of IRs at progressively lower levels of abstraction. Each lowering step preserves enough information for the work that happens at that level.
Production examples:
- GCC: GENERIC → GIMPLE → RTL.
- rustc: HIR → THIR → MIR → LLVM IR (four layers).
- GHC: HsSyn → Core → STG → Cmm (four layers, each with formal semantics).
- Swift: AST → SIL (raw) → SIL (canonical) → SIL (optimised) → LLVM IR.
- MLIR generalises the idea: arbitrary "dialects" coexist in the same module, each lowered to the next.
Why we do not have it: we have one parse-tree-shaped representation. No IR stack.
What it would take: full re-architecture. Each new IR is hundreds of lines plus the lowering pass between it and its predecessor. Worthwhile only at scale.
Where to read more: Cooper and Torczon on intermediate representations; the rustc-dev-guide on HIR/THIR/MIR; the GHC Commentary on Core/STG/Cmm; the MLIR documentation on dialects.
Middle-end optimisations
Sparse Conditional Constant Propagation (SCCP)
What it is: a dataflow algorithm that combines constant propagation with reachability analysis. When a comparison evaluates to a known constant, the unreachable branch is propagated as dead, which lets more values be marked constant. Runs to fixpoint. Wegman and Zadeck (1991).
Production examples:
- LLVM has SCCP and IPSCCP (interprocedural).
llvm/lib/Transforms/Scalar/SCCP.cppandllvm/lib/Transforms/IPO/SCCP.cpp. - GCC has tree-level constant propagation in
gcc/tree-ssa-ccp.cc. - rustc has constant propagation passes on MIR.
- Most production optimisers have a variant.
Why we do not have it: SCCP requires SSA form, control-flow graph, and dataflow infrastructure. We have a leaf-level constant folder (eval_const) which is the simplest case but does not propagate across statement boundaries.
What it would take: prerequisites are CFG and SSA. Then SCCP is roughly 200 lines of dataflow on top.
Where to read more: "Constant Propagation with Conditional Branches" (Wegman and Zadeck 1991); LLVM's SCCP.cpp source; Cooper and Torczon on dataflow.
Common Subexpression Elimination (CSE)
What it is: detecting that the same expression is computed twice on a path through the program, replacing the second computation with the first one's result.
Production examples:
- LLVM's
EarlyCSE(llvm/lib/Transforms/Scalar/EarlyCSE.cpp) andGVN(a more powerful version, see below). - GCC has CSE on RTL (
gcc/cse.cc). - Go has CSE as an SSA pass (
cmd/compile/internal/ssa/cse.go). - Most production compilers have CSE.
Why we do not have it: we do not detect repeated expressions. INTERCAL programs are short enough that the wins would be small.
What it would take: SSA form, then a hash-based scan over expressions to find duplicates. Small.
Where to read more: Cooper and Torczon's chapter on local optimisation; Muchnick's Advanced Compiler Design and Implementation for the depth.
Global Value Numbering (GVN)
What it is: a more powerful CSE that recognises equivalent expressions even if textually different. Assigns each value a "number"; two computations producing equal values get the same number; redundant ones can be removed.
Production examples:
- LLVM's
GVNpass (llvm/lib/Transforms/Scalar/GVN.cpp). One of the larger and more sophisticated optimisers. - GCC has tree-level GVN (
gcc/tree-ssa-pre.ccfor partial redundancy elimination, which generalises GVN). - Cranelift's egraph-based optimiser is a modern relative.
Why we do not have it: not enough numerical computation in INTERCAL programs to justify the complexity.
Where to read more: "Detecting Equality of Variables in Programs" (Alpern, Wegman, Zadeck 1988) for value numbering; "Global Value Numbers and Redundant Computations" (Rosen, Wegman, Zadeck 1988); LLVM's GVN source.
Loop-Invariant Code Motion (LICM)
What it is: moving computations whose result does not change across loop iterations out of the loop body. The classical example: lifting a 2 * x computation out of a loop where x does not change.
Production examples:
- LLVM's
LICMpass (llvm/lib/Transforms/Scalar/LICM.cpp). - GCC's tree-level LICM (
gcc/tree-ssa-loop-im.cc). - All production optimisers have it.
Why we do not have it: INTERCAL has no formal loop construct. Loops are emergent from NEXT/COME FROM patterns. Detecting them is non-trivial.
What it would take: loop detection (a separate analysis on the CFG) plus the LICM transformation. Loop detection alone is significant; the transformation is small once you have it.
Where to read more: Cooper and Torczon's chapter on loop optimisation; Muchnick's chapters on natural-loop detection and LICM.
Induction Variable optimisation
What it is: recognising loop-induction variables (variables that change by a fixed amount per iteration) and simplifying expressions involving them. Includes strength reduction (replacing multiplications with additions) and induction variable elimination.
Production examples:
- LLVM's
IndVarspass (llvm/lib/Transforms/Scalar/IndVarSimplify.cpp) on top ofScalarEvolution. - GCC's tree-level
tree-ssa-loop-ivopts.cc. - A classic optimisation; every numerically-oriented compiler does it.
Why we do not have it: same reason as LICM. INTERCAL loops are emergent and rare.
Where to read more: Allen and Cocke's classical papers on loop optimisation; Cooper and Torczon's chapter; LLVM's IndVars and ScalarEvolution.
Loop unrolling
What it is: replacing a loop body with several copies in sequence, reducing branch overhead and enabling further optimisation across the unrolled iterations. The unroll factor is typically chosen by heuristic.
Production examples:
- LLVM's
LoopUnrollpass. - GCC's
tree-ssa-loop-unswitch.ccplus the unroll-related machinery. - Go does unrolling at SSA level.
- Compiler intrinsics (
#pragma unroll) let the user override the heuristic.
Why we do not have it: same as LICM.
Where to read more: Cooper and Torczon; "Optimal Loop Unrolling" by Davidson and Jinturkar (1995); LLVM's LoopUnroll source.
Loop fusion, fission, interchange
What they are: structural loop transformations. Fusion combines adjacent loops into one. Fission splits a loop into multiple. Interchange swaps nested loop order to improve memory access patterns. Each enables specific further optimisations and is sensitive to memory hierarchy.
Production examples:
- LLVM's
LoopFusion,LoopFission(less mature),LoopInterchange. - GCC's tree-level loop transformations.
- Polly (LLVM's polyhedral optimiser) does these comprehensively.
- HPC compilers (
icc,xlc) do them aggressively.
Why we do not have it: INTERCAL has neither matrix algorithms nor numerical loops where these matter.
Where to read more: Optimizing Compilers for Modern Architectures (Allen and Kennedy 2001), the canonical reference for loop transformations; Polly's documentation.
Auto-vectorisation (loop and SLP)
What it is: automatically converting scalar operations to vector (SIMD) operations. Two flavours: loop vectorisation (run multiple loop iterations in parallel using SIMD lanes) and SLP (Superword-Level Parallelism, finding parallelism across straight-line code).
Production examples:
- LLVM's
LoopVectorizeandSLPVectorizerpasses. - GCC's auto-vectoriser.
- Polly for polyhedral-driven vectorisation.
Why we do not have it: INTERCAL has no SIMD-friendly operations. mingle and select operate on bit patterns that have nothing to do with SIMD lanes.
Where to read more: "Vectorization in OpenMP" papers; "Loop Vectorization in LLVM" by Hal Finkel; SLP literature beginning with "Exploiting Superword Level Parallelism with Multimedia Instruction Sets" (Larsen and Amarasinghe 2000).
Inlining (with heuristics)
What it is: replacing a function call with the function body at the call site. The heuristic part is when to inline: small functions are obvious wins, but inlining everything would explode binary size and hurt instruction-cache performance.
Production examples:
- LLVM's
Inlinerpass with cost analysis inInlineCost.cpp. - GCC has inlining heuristics in
gcc/ipa-inline.cc. - rustc's
rustc_mir_transform/inline.rs. - Go's unified inliner with budget-based decisions and PGO bias.
- GHC inlines aggressively, including across module boundaries.
- Swift's optimiser inlines with
@inlinableannotations.
Why we do not have it: INTERCAL has no functions. NEXT to a label is a goto-with-stack, not a function call. Inlining a labelled section means inlining a whole code region that includes the corresponding RESUME, with care for abstention. Possible but tricky.
What it would take: detection of "call sites" (NEXT followed eventually by RESUME #1 patterns), then careful inlining preserving the abstain-and-COME-FROM semantics. Hundreds of lines minimum.
Where to read more: "Choosing the Best Heuristic for a NLPP" research; LLVM's Inliner source; the rustc-dev-guide on inlining decisions.
Function specialisation and devirtualisation
What they are: function specialisation generates a tailored version of a function for specific argument values or types. Devirtualisation replaces an indirect (virtual) call with a direct one when the target is known.
Production examples:
- Swift's generic specialisation at SIL level.
lib/SILOptimizer/Transforms/GenericSpecializer.cpp. - rustc's monomorphisation specialises every generic call site at MIR level.
- LLVM has specialisation infrastructure in
lib/Transforms/IPO/FunctionSpecialization.cpp. - Devirtualisation is a separate pass in most compilers.
Why we do not have it: no generics, no virtual calls.
Where to read more: Swift's SIL documentation on specialisation; the rustc-dev-guide chapter on monomorphisation.
Escape analysis
What it is: a static analysis to determine whether a value's lifetime can be bounded by its current scope (stack-allocatable) or it might "escape" to outlive the current frame (heap-allocatable). Used by GC'd languages to elide heap allocation when safe.
Production examples:
- Go's
cmd/compile/internal/escape/. The decision drives stack vs heap allocation. - HotSpot's escape analysis is one of its sophisticated optimisations.
- GCC has escape-analysis infrastructure for some C++ patterns.
- GraalVM's escape analysis is part of its partial-evaluation framework.
Why we do not have it: INTERCAL has no GC, no closures, no heap-allocated data structures (arrays go through mmap directly, not through a heap). There is nothing to escape.
Where to read more: "Escape Analysis: Correctness Proof, Implementation and Experimental Results" (Choi et al. 1999); Go's escape analysis source; HotSpot's escape analyser.
Alias analysis
What it is: determining whether two memory references could possibly refer to the same location. Critical for almost every optimisation that involves loads and stores: if two pointers might alias, you cannot reorder a load past a store between them.
Production examples:
- LLVM has multiple alias analyses:
BasicAA,TBAA(Type-Based AA),ScopedNoAliasAA,CFLAA. Composed into a sophisticated infrastructure. - GCC has tree-ssa-alias.cc.
- Cranelift has simpler heuristics.
Why we do not have it: INTERCAL has no general aliasing. Variables and array elements are addressed by index, not by pointer.
Where to read more: Hind's "Pointer Analysis: Haven't We Solved This Problem Yet?" (PASTE 2001); LLVM's alias-analysis documentation.
Polyhedral optimisation
What it is: a mathematical framework for representing and transforming nested loops over multidimensional arrays. Loop transformations become operations on integer polyhedra. Enables sophisticated fusion, interchange, tiling, and parallelisation.
Production examples:
- LLVM's Polly (
polly/). - GCC's Graphite (
gcc/graphite.cc). - HPC-targeted research compilers (Pluto, PoCC).
- Used in scientific computing toolchains.
Why we do not have it: INTERCAL has no nested loops over multi-dimensional arrays. Polyhedral optimisation is irrelevant.
Where to read more: "The Polyhedron Model" (chapter in Cooper and Torczon, or in Allen and Kennedy); the Polly documentation; "Pluto: A Practical and Fully Automatic Polyhedral Program Optimization System".
Profile-Guided Optimisation (PGO)
What it is: collecting runtime profile data (which branches taken, which functions hot) on a representative workload, then feeding that data into a subsequent compilation to bias optimisation decisions.
Production examples:
- LLVM has PGO via
-fprofile-instr-generateand-fprofile-instr-use. - GCC has it via
-fprofile-generateand-fprofile-use. - Go has PGO since 1.21.
- Swift has it.
- Most production toolchains support it.
Why we do not have it: INTERCAL programs are not performance-critical at scale. PGO is an answer to "this program runs for hours; help me make it faster". We do not have programs of that shape.
What it would take: instrumentation pass (count branches/calls), runtime support to dump counters at exit, second compilation pass that reads the dump and biases inlining/branch-layout decisions. Significant infrastructure.
Where to read more: "Profile-Guided Code Positioning" (Pettis and Hansen 1990) for the original; LLVM's PGO documentation; Go's PGO documentation.
Link-Time Optimisation (LTO)
What it is: optimisations that span translation units. Normally each .c file is compiled in isolation; LTO defers final code generation to link time, when the whole program is visible.
Production examples:
- LLVM's
ThinLTO(incremental, parallel) andFullLTO(slower, more thorough). - GCC's
lto1. - Swift's Cross-Module Optimisation (CMO).
- Standard in production builds of large C++ projects.
Why we do not have it: INTERCAL programs are usually one source file. The closest analog (separate compilation of syslib.i and the user program) is what INTERCAL_SYSLIB=cache does, but only for the syslib, and without cross-unit optimisation.
Where to read more: "ThinLTO: Scalable and Incremental LTO" (Johnson et al. 2017); the GCC LTO documentation; Swift's CMO documentation.
BOLT-style post-link optimisation
What it is: optimisations applied to already-compiled binaries, using profile data to reorder basic blocks for better branch prediction and instruction-cache locality.
Production examples:
- LLVM's BOLT (
bolt/). Reorders basic blocks in already-compiled binaries based on profile. - Propeller (an LLVM-related project) takes a similar approach with finer-grained profile data.
- AutoFDO is the profile collection side.
Why we do not have it: INTERCAL programs are not large enough that block ordering matters. BOLT is most relevant for binaries of millions of basic blocks.
Where to read more: the BOLT documentation; "BOLT: A Practical Binary Optimizer for Data Centers" (Panchenko et al. 2018); Facebook/Meta's blog posts on production BOLT use.
Back-end techniques
Real CFG construction (feeding optimisation)
What it is: building an explicit control-flow graph data structure as a first-class IR, with basic blocks as vertices and branches as edges, that subsequent passes consume.
Production examples: every production compiler in Part VII builds a CFG.
Why we do not have it: our --emit-cfg flag computes a CFG view but does not feed codegen with it. Codegen still walks the parse tree.
What it would take: Phase A in middle-end-and-optimisation.md. Replace the parse-tree walk with a CFG walk in codegen. Roughly 500 lines of zsh.
Where to read more: any compiler textbook chapter on CFG construction; LLVM's lib/IR/BasicBlock.cpp.
Liveness analysis (forward/backward dataflow)
What it is: at every program point, the set of variables that are live, meaning their current value will be used before being overwritten. Liveness is a backward dataflow analysis.
Production examples:
- LLVM's
LiveVariablesanalysis. - GCC's tree-ssa-live.cc.
- The foundation of register allocation everywhere.
Why we do not have it: we do not allocate registers (we always use stack slots). Without register allocation, liveness is unnecessary.
What it would take: SSA form, then standard backward dataflow. ~100 lines.
Where to read more: Cooper and Torczon's chapter on dataflow; the classical paper "Compilers and Computer Architecture" by Aho.
Instruction selection (BURS, DAG-based, ISLE, GlobalISel)
What it is: choosing which target instructions to emit for an IR-level operation. The choice is non-trivial because most architectures have many ways to compute the same operation, with different costs.
Production examples:
- LLVM's SelectionDAG (DAG-based, pattern-matched via TableGen).
- LLVM's GlobalISel (pass-based, in transition).
- GCC's
define_insnanddefine_expandpatterns in.mdfiles. - Cranelift's ISLE rules in
.islefiles. - Go's
.rulesfiles for arch-specific lowering.
Each compiler has a domain-specific language for describing instruction selection rules. The languages differ; the idea is the same.
Why we do not have it: we hand-write per-statement assembly templates. No instruction-selection logic.
What it would take: an IR (preferably SSA), then a pattern-matcher and a rules table. Significant. Easier in a clean rewrite than as a retrofit.
Where to read more: Cooper and Torczon's chapter on instruction selection; "BURS Instruction Selection" by Pelegri-Llopart and Graham (1988); LLVM's TableGen documentation; the Cranelift ISLE documentation.
Instruction scheduling
What it is: reordering instructions within a basic block to minimise pipeline stalls. The optimal order depends on per-instruction latency and the target's pipeline structure.
Production examples:
- LLVM's
MachineScheduler. Per-target scheduling models live in TableGen. - GCC's machine description specifies pipeline behaviour, used by
gcc/sched-*.cc. - Most production backends do scheduling.
Why we do not have it: we emit instructions in the natural order from the codegen walk. Modern out-of-order CPUs handle most of what an instruction scheduler would care about, but the technique is still important on ARM, RISC-V, and embedded targets.
Where to read more: Allen-Cocke; "List Scheduling" papers; LLVM's MachineScheduler source.
Register allocation (graph coloring, linear scan, SSA-based, backtracking, PBQP)
What it is: deciding which IR values live in which physical registers, and inserting spill/reload code when there are not enough registers. Multiple algorithms, each with tradeoffs.
Production examples:
-
Graph coloring (Chaitin 1981, Briggs 1989): build an interference graph, colour it with N colours where N is the number of available registers. NP-hard in general, but graph-coloring heuristics work well.
- GCC's old register allocator used graph coloring.
- GHC's NCG uses graph coloring.
-
Linear scan (Poletto-Sarkar 1999): walk live ranges in start-point order, assign registers greedily, spill when necessary.
- OCaml's
asmcomp/linscan.ml(~330 lines). - LLVM's
fastallocator is a variant.
- OCaml's
-
SSA-based linear scan: linear scan that operates on SSA form, with phi/block-parameter handling on edges.
- regalloc2's underlying machinery (though regalloc2 itself uses backtracking, not pure linear scan).
-
Backtracking (Ion-derived): regalloc2's actual algorithm. Live ranges grouped into bundles; bundles assigned with eviction and splitting on conflict.
- Cranelift's regalloc2.
-
PBQP (Partitioned Boolean Quadratic Programming): an OR-style formulation that solves the allocation as an optimisation problem.
- LLVM's
pbqpallocator (mostly research).
- LLVM's
-
LLVM greedy: prioritise live ranges by spill cost, assign registers in priority order, split on conflict.
- LLVM's default allocator in
lib/CodeGen/RegAllocGreedy.cpp.
- LLVM's default allocator in
-
GCC LRA (Local Register Allocator): replaced the older "reload" pass in 2013. Multi-pass: virtual-to-physical assignment, spill code insertion, post-allocation cleanup.
- GCC's
gcc/lra-constraints.ccand friends.
- GCC's
Why we do not have it: we use stack slots for everything. .1, .2, etc. are statically-located memory addresses. No register pressure to manage.
What it would take: SSA form, liveness analysis, then one of the algorithms. Linear scan is the easiest entry point (~400 lines for a reasonable implementation, using OCaml's linscan.ml as reference).
Where to read more: Chaitin's "Register Allocation and Spilling via Graph Coloring" (1982); Poletto-Sarkar's "Linear Scan Register Allocation" (1999); Briggs's "Coloring Heuristics for Register Allocation" (1989); Chris Fallin's "Cranelift, Part 4: A New Register Allocator" blog post (2022); LLVM's RegAllocGreedy.cpp.
Tail-call optimisation
What it is: when the last action of a function is a call, reuse the current stack frame for the called function instead of pushing a new one. Critical for recursion-based languages; important enough that some languages mandate it (Scheme).
Production examples:
- GHC mandates tail-call optimisation.
- OCaml mandates it.
- Scala has
@tailrec. - Rust has it as a long-discussed feature, no stable implementation.
- LLVM has
tailcccalling convention; languages using LLVM can opt in.
Why we do not have it: INTERCAL has no functions in the modern sense. NEXT+RESUME is the closest analog, and the stack is part of the language semantics; we cannot transform it away without changing semantics.
Where to read more: "Programming Language Implementation Techniques for Continuation-Passing Style" (Steele 1978); GHC's discussion of TCO.
Calling convention specialisation
What it is: choosing per-function how arguments and return values are passed in registers. Default conventions are stable ABIs; specialised ones can be faster but are private to a single program.
Production examples:
- LLVM has many calling conventions (
fastcc,coldcc,ghccc,tailcc, etc.). - GHC's
ghcccis its own calling convention optimised for the lazy-evaluation runtime. - Production compilers commonly use private conventions for inlined or specialised functions.
Why we do not have it: we follow standard System V AMD64 / AAPCS64 conventions for our runtime calls. INTERCAL's syslib calls go through standard registers.
Where to read more: the System V ABI documentation; LLVM's calling conventions list.
Runtime techniques
Garbage collection
What it is: automatic memory management. The runtime tracks which heap objects are reachable from program roots and reclaims unreachable ones.
Algorithms in production:
-
Reference counting: increment per assignment, decrement per scope-exit. Simple but cannot handle cycles.
- Swift's ARC (with weak references for cycle breaking).
- Python's CPython (with cycle collector).
-
Mark-sweep: walk the heap from roots marking reachable objects, then sweep unmarked ones into a free list. Single-pass.
- Some old Lisp systems.
- Often used as the major heap collector in modern systems.
-
Mark-compact: like mark-sweep but compacts surviving objects to eliminate fragmentation.
- Ruby's MRI uses mark-sweep with optional compaction.
-
Copying / generational: divide heap into generations; new objects in the young generation; promote survivors. Young-generation GC is fast (copying); old-generation GC is rare.
- Java's HotSpot uses several generational collectors (Parallel, G1, Shenandoah, ZGC).
- V8's Orinoco is generational.
- GHC, OCaml, Go all use generational copying for the young generation.
-
Concurrent / incremental: the GC runs concurrently with the program, with write barriers cooperating between them.
- Go's GC is concurrent tri-color mark-sweep.
- V8's Orinoco has concurrent marking.
- Java's ZGC and Shenandoah are concurrent compacting collectors.
- GHC has an optional concurrent GC.
-
Region-based / arena: explicit regions; objects allocated in a region; whole region freed at once.
- Common in C-style allocators.
- Cyclone language has region inference.
- Mesa, Cyclone, Cylinder languages had region types.
Production examples per algorithm above.
Why we do not have it: INTERCAL has no garbage collection. Arrays are allocated via mmap directly; there is no general-purpose heap. The language has no closures, no recursive data structures (no pointers), no allocation lifetime management to do.
What it would take: a different language. Adding GC to INTERCAL would mean adding language features (object types, references) that are not in the spec.
Where to read more: The Garbage Collection Handbook (Jones, Hosking, Moss 2nd ed. 2023), the canonical reference. Per-runtime documentation for Go, GHC, V8.
Automatic Reference Counting (ARC)
What it is: compile-time-inserted reference-count operations (retain/release) that the runtime executes. ARC is between full GC and manual memory management: the compiler does the bookkeeping; the runtime executes simple atomic counter updates.
Production examples:
- Swift's ARC, with the SIL-level ARC optimisation pass that eliminates redundant retain/release pairs.
- Objective-C 2.0+ ARC.
Why we do not have it: no reference types in INTERCAL.
Where to read more: Apple's ARC documentation; the LLVM-level ARC optimisation passes; Swift's SIL ARC optimisation source.
Exception handling (zero-cost via DWARF)
What it is: a mechanism for non-local error propagation. "Zero-cost" exceptions encode unwinding information in metadata tables (DWARF on Unix, similar formats elsewhere) so the happy-path code pays nothing; only the throw walks the tables.
Production examples:
- C++ exceptions on Itanium ABI.
- Rust panics (with
panic = "unwind"). - Swift error propagation.
- OCaml exceptions (lighter implementation, no DWARF tables).
Why we do not have it: INTERCAL has no exceptions. Errors are runtime-fatal (ICL...I codes); the program prints and exits. No unwinding.
Where to read more: the Itanium C++ ABI specification (sections on exception handling); the libunwind documentation; Bjarne Stroustrup's papers on C++ exception design.
Coroutines / fibers / green threads
What they are: lightweight execution contexts that the runtime multiplexes onto a smaller pool of OS threads. Concurrent programming without per-task OS thread overhead.
Production examples:
- Go's goroutines: M:N scheduling, runtime-managed stacks.
- Haskell's Control.Concurrent threads on top of GHC's RTS.
- Erlang/OTP processes (not the same as OS processes).
- Rust's async/await with a runtime like
tokio(no language-level fibers; the runtime provides the scheduling). - Crystal fibers.
- Lua coroutines.
Why we do not have it: INTERCAL has no concurrency.
Where to read more: Go's runtime source for the production-grade implementation; "Cooperative Threads in Lua" papers; Erlang/OTP design documents.
Stack growth
What it is: the runtime mechanism by which a function's stack can grow beyond its initial allocation. Critical for languages that nest deeply (functional languages) or that start with small stacks (goroutines).
Production examples:
- Go's split-stacks (until 1.2) and now contiguous-copy-and-grow stacks. Goroutines start with 2KB stacks.
- Erlang's per-process stacks grow dynamically.
- GHC's RTS manages thread stacks.
Why we do not have it: our compiled binaries use the OS stack, which is large enough for INTERCAL programs and grows on demand via OS facilities.
Where to read more: the Go runtime source on morestack; "Goroutines: A Brief Tour".
Execution model techniques
JIT compilation (single-tier)
What it is: compiling code at runtime, often from bytecode or directly from source. Distinct from AOT compilation, which produces an executable beforehand.
Production examples:
- LuaJIT (a single-tier tracing JIT).
- LLVM's MCJIT and ORC (general-purpose JIT infrastructure).
- HotSpot's C1 and C2 (multiple JIT tiers).
Why we do not have it: we compile ahead of time. INTERCAL has no use case demanding runtime compilation.
What it would take: significant infrastructure. JIT requires runtime memory management for code, instruction-cache flushing, deoptimisation paths.
Where to read more: "Implementing a Tracing JIT" (Mike Pall's LuaJIT writings); LLVM's ORC documentation; HotSpot's source.
Tiered JIT compilation
What it is: multiple JIT tiers operating on the same code, with promotion based on hotness. A function starts interpreted, gets baseline-JIT'd if warm, gets optimising-JIT'd if hot.
Production examples:
- V8 has Ignition, Sparkplug, Maglev, TurboFan (four tiers).
- HotSpot has Interpreter, C1, C2.
- JavaScriptCore has LLInt, Baseline, DFG, FTL.
- LuaJIT has interpreter and trace JIT.
Why we do not have it: AOT only.
Where to read more: V8's blog posts on each tier; "Crankshaft" papers from V8's history; Mike Pall's LuaJIT writings on trace selection.
Speculation and deoptimisation
What it is: optimised code generated under runtime assumptions ("this property is always at this offset"; "this variable is always SmallInt"). Deoptimisation is the safety net: when an assumption fails, control returns to a less-optimised tier, with state reconstructed from the optimised code.
Production examples:
- V8's TurboFan emits deoptimisation checkpoints. Lazy deopt vs eager deopt.
- HotSpot's C2 has the same machinery.
- LuaJIT's traces have side exits with reconstruction.
Why we do not have it: AOT only. Deoptimisation requires a runtime to fall back to.
Where to read more: "Self: An Object-Oriented Self-Reflective Programming Language" (Ungar and Smith 1987); Cliff Click's papers on HotSpot C2; V8 design docs on deoptimisation.
On-Stack Replacement (OSR)
What it is: replacing a currently-executing function with a more-optimised version mid-execution. Critical for hot loops where the function will not return for a long time.
Production examples:
- V8's TurboFan supports OSR.
- HotSpot supports OSR.
- LLVM has experimental support.
Why we do not have it: AOT only.
Where to read more: "Optimizing Java with Compile-Time Information" (Holzle 1994); HotSpot OSR documentation.
Inline caches
What it is: per-call-site type caches. A property access x.foo on first use is uncached; second use looks up the IC; if the receiver is the same shape, the cached field offset is used directly.
Production examples:
- V8's IC machinery.
- JavaScriptCore's polymorphic ICs.
- Self's monomorphic ICs (where the technique was invented).
- HotSpot uses inline caches for virtual calls.
Why we do not have it: INTERCAL is statically typed; there are no dynamic dispatch sites that would benefit.
Where to read more: "Customization: Optimizing Compiler Technology for Self, a Dynamically-Typed Object-Oriented Programming Language" (Chambers and Ungar 1989); V8's IC source.
Hidden classes / shape inference
What it is: the runtime tracks each object's structural shape, so that property accesses can be specialised to direct field loads when the shape is known.
Production examples:
- V8's Maps (the runtime structure, not the JS Map type).
- JavaScriptCore's structures.
- HotSpot's klassOop.
Why we do not have it: no dynamic objects.
Where to read more: "Customization" (Chambers and Ungar 1989); V8 design docs on Maps and transitions.
Tooling and infrastructure
Incremental compilation (queries, Salsa-style)
What it is: caching compilation work at fine granularity (per-function or per-query) so that small source changes do not require recompiling the world.
Production examples:
- rustc's query system: every cacheable computation is a
Query. The system tracks dependencies between queries automatically.compiler/rustc_query_system/. - The Salsa library (used by rust-analyzer and inspired by rustc).
- Bazel's content-addressed caching.
- Roslyn (C#'s compiler) for incremental compilation.
Why we do not have it: our compiler runs in milliseconds. Incremental compilation would help a project with hundreds of source files; we have none.
What it would take: substantial infrastructure. Each computation must be made into a memoised query, with input hashing and dependency tracking. ~1000 lines minimum.
Where to read more: the rustc-dev-guide chapter on the query system; Salsa's documentation; "Incremental Computation" by Niko Matsakis (blog series).
Parallel compilation
What it is: compiling different parts of a program in parallel, on multiple cores.
Production examples:
- Cargo runs
rustcinvocations in parallel (one per crate). - Bazel parallelises by build action.
- Go compiles packages in parallel.
- LLVM's ThinLTO parallelises module-level optimisation.
Why we do not have it: we compile one file. There is nothing to parallelise.
What it would take: a multi-file INTERCAL extension first, then per-file parallel compilation.
Where to read more: the Cargo documentation; Bazel internals; "ThinLTO: Scalable and Incremental LTO" (Johnson et al. 2017).
Distributed compilation
What it is: distributing compilation work across a cluster, with content-addressed caching shared between machines.
Production examples:
sccache: shared compilation cache for Rust and C/C++.distcc: distributed C/C++ compilation.goma: Google's distributed compilation service.- Bazel remote execution.
Why we do not have it: irrelevant at our scale.
Where to read more: sccache's README; the Bazel remote-execution documentation.
Language Server Protocol (LSP) integration
What it is: a protocol between IDEs and language servers. Editors implement the client; the language vendor implements the server.
Production examples:
- rust-analyzer for Rust.
- gopls for Go.
- haskell-language-server for Haskell.
- ZLS for Zig.
- clangd for C/C++.
- swift-tools/SourceKit-LSP for Swift.
Why we do not have it: nobody types INTERCAL inside an IDE. The cost-benefit is poor.
What it would take: an LSP server that wraps our parser and produces hover info, diagnostics, completions. Probably 1000+ lines.
Where to read more: the LSP specification at https://microsoft.github.io/language-server-protocol/; the rust-analyzer source; "Three Architectures for a Responsive IDE" by Aleksey Kladov (rust-analyzer's author).
Sanitizers
What they are: runtime-instrumented checking that detects classes of bugs at execution time. Each sanitizer targets a specific class.
Production examples:
- AddressSanitizer (ASan): use after free, buffer overflow, double free.
- ThreadSanitizer (TSan): data races.
- UndefinedBehaviorSanitizer (UBSan): undefined behaviour patterns.
- MemorySanitizer (MSan): uninitialised reads.
- All ship with both LLVM and GCC. Implementation in
compiler-rt/lib/.
Why we do not have it: INTERCAL has no concept of memory safety to violate. Variables are integers; arrays are bounds-checked at runtime; there is no pointer arithmetic to misbehave. The bugs sanitizers find do not exist in INTERCAL programs.
Where to read more: "AddressSanitizer: A Fast Address Sanity Checker" (Serebryany et al. 2012); "ThreadSanitizer" papers; the compiler-rt source in LLVM.
Fuzzing infrastructure
What it is: feeding random or mutation-generated inputs to a target to find crashes and undefined behaviour.
Production examples:
- libFuzzer (LLVM project).
- AFL and AFL++.
- syzkaller for kernel fuzzing.
- Google's OSS-Fuzz.
- Csmith for compiler fuzzing.
Why we do not have it: limited but possible. Csmith-style differential testing for INTERCAL would mean generating random INTERCAL programs and comparing our compiler's output against another INTERCAL implementation (C-INTERCAL, CLC-INTERCAL).
What it would take: a generator for valid INTERCAL programs, plus the comparator. Possible weekend project.
Where to read more: "AFL: American Fuzzy Lop" papers; "Finding and Understanding Bugs in C Compilers" (Yang et al. 2011); the libFuzzer documentation.
Differential testing at scale (csmith-like)
What it is: using a property-preserving program generator to find compiler bugs by compiling the same program with multiple compilers and comparing outputs.
Production examples:
- Csmith for C compilers. Found hundreds of bugs in GCC and LLVM.
- Crater for rustc (compiles every crates.io crate against a candidate rustc).
- Yarpgen (newer C generator).
Why we do not have it: our differential testing is much smaller (pure-vs-native syslib in tests/test_syslib_pure.sh). Csmith-scale would require a real INTERCAL program generator and another reference compiler to compare against.
Where to read more: the Csmith paper (Yang et al. 2011); Crater documentation; the OSS-Fuzz blog posts on compiler bugs.
Additional GC algorithms
The GC section above covered the algorithm families. The taxonomy hides a lot of important specific algorithms each with distinct trade-offs.
ZGC (Z Garbage Collector)
What it is: a scalable, low-latency collector for the JVM that performs nearly all work concurrently, achieving consistent pause times in the 0.1-0.5 ms range regardless of heap size, scaling to terabyte heaps. Uses 64-bit colored pointers (metadata stored in unused virtual address bits) plus load barriers to relocate objects while application threads run. JEP 439 added a generational variant.
Production: OpenJDK (default for many low-latency Java workloads).
Where to read more: JEP 333 and JEP 439 on openjdk.org; "Deep Dive into ZGC" (TOPLAS 2022).
Shenandoah
What it is: Red Hat's region-based concurrent compacting collector that performs evacuation while application threads run, using Brooks-style forwarding pointers and read/write barriers; pauses are independent of live-set size.
Production: OpenJDK since JDK 12, Red Hat Enterprise Linux Java workloads.
Where to read more: Flood et al., "Shenandoah" (PPPJ 2016); Red Hat developer guide on Shenandoah.
G1 (Garbage First)
What it is: region-partitioned, generational, mostly-concurrent collector that prioritises evacuating regions with the most garbage to meet a soft pause-time goal. Default in HotSpot since Java 9. The algorithmic ancestor of Shenandoah, ZGC, and Azul C4.
Production: OpenJDK default for general-purpose workloads.
Where to read more: Detlefs et al., "Garbage-First Garbage Collection" (ISMM 2004); Oracle's G1 tuning guide; "Deconstructing the Garbage-First Collector" (VEE 2020).
Immix (mark-region collector)
What it is: a mark-region collector that allocates into contiguous lines (128 B) within blocks (32 KB), reclaims at line and block granularity, and opportunistically evacuates fragmented blocks in a single pass. Combines the throughput of mark-sweep with the locality of copying collectors.
Production: Rubinius (Ruby), Crystal's experimental GC, MMTk (Memory Management Toolkit, used by V8 and OpenJDK research integrations).
Where to read more: Blackburn and McKinley, "Immix" (PLDI 2008).
Boehm-Demers-Weiser GC
What it is: a conservative mark-sweep collector for C/C++ that scans the stack and globals as untyped roots, treating any bit pattern that looks like a pointer as one. Trades precision for the ability to retrofit GC onto languages without type metadata.
Production: Mono (legacy), GNU Objective-C, Crystal, GCJ, GNU Guile, many embedded language runtimes.
Where to read more: hboehm.info/gc/ (the canonical site); Boehm and Weiser, "Garbage collection in an uncooperative environment" (SP&E 1988).
Deferred reference counting
What it is: Deutsch-Bobrow's optimisation that omits RC updates for stack and register references, then periodically reconciles by scanning roots against a zero-count table. Cuts roughly 99% of RC operations in Lisp/ML-like workloads, at the cost of delayed reclamation.
Production: original LISP implementations; conceptual basis for many modern RC systems.
Where to read more: Deutsch and Bobrow, "An Efficient, Incremental, Automatic Garbage Collector" (CACM 1976).
Biased reference counting
What it is: each object is "owned" by one thread; the owner uses non-atomic increments while other threads update a separate atomic counter, merged on ownership transfer. Halves RC cost in the common case where most updates come from one thread.
Production: Swift runtime since iOS/macOS 14 timeframe.
Where to read more: Choi, Shull, Torrellas, "Biased Reference Counting" (PACT 2018); Swift Forums design discussion.
Bacon cycle collection (trial deletion)
What it is: a concurrent algorithm that detects cycles by colouring potential roots "purple" on RC decrement, then performing trial decrement traversal to find self-sustaining subgraphs unreachable from outside. Avoids global heap walks.
Production: PHP since 5.3, IBM Recycler (Jalapeño JVM), conceptually CPython's gc module.
Where to read more: Bacon and Rajan, "Concurrent Cycle Collection in Reference Counted Systems" (ECOOP 2001).
Additional execution-model techniques
Trace JIT vs method JIT
What they are: two main JIT strategies. Method JITs (HotSpot C1/C2, V8 TurboFan) compile whole methods using profile data. Trace JITs (LuaJIT, early TraceMonkey, PyPy with tracing) compile linear hot paths starting at loop edges, inlining across function boundaries by following execution. Trace JITs excel at tight loops in dynamic languages but suffer at branch-heavy code.
Production: LuaJIT (Mike Pall) is the canonical trace JIT; PyPy uses a meta-tracing approach; HotSpot and V8 are method-based.
Where to read more: Mike Pall's LuaJIT design notes; Gal et al., "Trace-based Just-in-Time Type Specialization" (PLDI 2009).
Polymorphic inline caches (PICs)
What they are: extension of monomorphic ICs that record several (receiver-type, target) pairs per call site, enabling fast dispatch for sites with multiple but bounded receiver types and exposing concrete type information to the recompiler.
Production: Self, Strongtalk, HotSpot, V8, JavaScriptCore.
Where to read more: Hölzle, Chambers, Ungar, "Optimizing Dynamically-Typed OO Languages with Polymorphic Inline Caches" (ECOOP 1991); the foundational paper.
Stack maps for precise GC
What they are: per-call-site metadata recording exactly which stack slots and registers hold live GC pointers, enabling collectors to relocate objects without scanning untyped memory. The alternative (conservative scanning, Boehm-style) over-retains and forbids moving collectors.
Production: HotSpot OopMaps, .NET CLR GCInfo, LLVM gc.statepoint.
Where to read more: LLVM Statepoints documentation; LLVM GarbageCollection guide.
Safepoints
What they are: compiler-inserted polls (typically a load from a page that is unmapped to trigger SIGSEGV when GC is needed) that let mutator threads cooperatively pause at known points where stack maps are valid. Loop back-edges and method entries/exits are typical poll sites.
Production: HotSpot uses page-protected polling; V8 and .NET have similar mechanisms.
Where to read more: Aleksey Shipilev's "JVM Anatomy Quark #22: Safepoint Polls"; LLVM Statepoints.
Class hierarchy analysis (CHA)
What it is: static analysis of the loaded class graph that proves a virtual call has only one possible target (the method has no overrides), enabling devirtualisation. In dynamic systems it must be invalidated when classes are loaded.
Production: HotSpot, GraalVM, Soot, Go's golang.org/x/tools/go/callgraph/cha.
Where to read more: Dean, Grove, Chambers, "Optimization of Object-Oriented Programs Using Static Class Hierarchy Analysis" (ECOOP 1995).
Speculative devirtualisation
What it is: inline a likely target guarded by a type check (or rely on CHA plus a deopt trap if a new class is loaded), backed by deoptimisation when speculation fails. Bridges PICs and full inlining.
Production: HotSpot C2, GraalVM, V8 TurboFan.
Where to read more: Ishizaki et al., "A Study of Devirtualization Techniques for a Java JIT Compiler" (OOPSLA 2000); Shipilev, "Black Magic of Java Method Dispatch".
Inline cache repair and IC miss handling
What it is: on a cache miss, the runtime patches the call site (monomorphic to polymorphic to megamorphic) atomically, often by writing into JIT-generated stubs. Megamorphic sites may bail out to a method-table lookup.
Production: V8 (feedback vectors), JavaScriptCore (LLInt + Baseline tiers), HotSpot.
Where to read more: Brunthaler, "Inline caching meets quickening" (ECOOP 2010); Mathias Bynens's V8 ICs blog series.
Two-tier compilation (C1 + C2)
What it is: methods start in the interpreter, get promoted to the fast-compiling C1 (client) for profiling, and only the hottest are recompiled by the slower-but-better C2 (server). HotSpot defines five levels (interpreter through full C2). Balances startup latency against peak throughput.
Production: OpenJDK HotSpot (the original two-tier model), Azul Zing/Falcon, V8 with its four-tier extension (Ignition, Sparkplug, Maglev, TurboFan).
Where to read more: Microsoft's "How Tiered Compilation works in OpenJDK"; InfoQ's "What the JIT!?".
AutoFDO
What it is: sample-based PGO that consumes hardware counter (perf record) data from production, normalises it to a profile format, and feeds it into LLVM/GCC. No instrumented build needed.
Production: Google datacentre fleet (5-15% wins), Android kernel (up to 10% gains), the LLVM toolchain itself.
Where to read more: Chen et al., "AutoFDO: Automatic Feedback-Directed Optimization" (CGO 2016); Linux kernel AutoFDO docs.
Case studies in JIT compilation
A few production JIT stories worth singling out, because they illustrate different points in the design space:
PHP JIT (PHP 8.0): implemented "as an almost independent part of OPcache" using DynASM, the lightweight code generator from LuaJIT. Rather than introducing a separate IR, the system generates native code directly from PHP bytecode combined with SSA-framework analysis. Supports x86, x86_64, ARM. Performance varies by workload: ~4x on Mandelbrot, ~2x on general microbenchmarks, ~1.3x on PHP-Parser, near-zero on WordPress (typical web workloads are I/O-bound, not CPU-bound). The approval vote was 50-2 for PHP 8.0; an earlier 7.4 attempt had failed (18-36) due to engine-stability concerns. Lesson: JIT is high-payoff for CPU-intensive workloads, low-payoff for typical web workloads, and the maintenance cost is real (debugging requires reading machine code dumps). See https://wiki.php.net/rfc/jit.
Octave JIT (removed 2021): an LLVM-based JIT for the Octave numerical-computing language, originally implemented in Google Summer of Code 2012 by Max Brister. The implementation built an intermediate IR for type inference before converting to LLVM IR, because Octave's untyped AST cannot lower to LLVM IR directly. JIT only triggered at loop entry points, with fallback to the interpreter on compilation failure. Removed in 2021 because of LLVM API instability (each LLVM version broke the build) and the maintenance burden of a niche component. Lesson: JIT-via-LLVM trades simplicity (you reuse the LLVM optimiser) for sustainability (you commit to chasing the LLVM API forever). See https://wiki.octave.org/JIT.
LuaJIT: a from-scratch tracing JIT, no LLVM, no third-party backend. Hand-written x86/x64/ARM/ARM64/PPC/MIPS code generation with extreme attention to per-instruction quality. By many accounts the fastest JIT for any dynamic language, ahead of V8 on numerical workloads. Lesson: a full custom JIT can outperform LLVM-based ones if the language semantics are narrow enough that the optimiser can be tightly tuned to them.
The general lesson across these three: there is no one JIT design. The right choice depends on language semantics, target user base, maintenance willingness, and what existing infrastructure you can lean on. JIT writeups in The c2 Wiki (https://wiki.c2.com/?JustInTimeCompiler) and the Wikipedia article are useful jumping-off points before reading the production sources.
Security techniques in production compilers
Compilers are increasingly responsible for memory-safety enforcement at the binary level. Our INTERCAL compiler does none of these because INTERCAL has no memory-safety bugs to mitigate (no pointer arithmetic, no buffer overruns possible in the source language). But every modern toolchain ships them.
Stack canaries
What it is: a random word placed between local variables and the return address; verified on function exit. -fstack-protector covers functions with char buffers; -fstack-protector-strong extends to any function with arrays, address-taken locals, or local register variables, covering ~20% of functions at ~2% size cost.
Production: Linux kernel, glibc, every major distro, Chrome, Firefox.
Where to read more: Red Hat's "Use compiler flags for stack protection"; Kees Cook's "-fstack-protector-strong" blog post.
Control Flow Integrity (CFI)
What it is: at indirect calls, checks the target against a per-function-type bit vector built at LTO time; targets are rerouted through canonical jump-table entries. Defends against forward-edge hijacking.
Production: Android (kernel + userspace), Chrome OS, parts of iOS.
Where to read more: Clang's ControlFlowIntegrity.html; "CFI Design" doc in Clang source.
SafeStack
What it is: splits the stack into a "safe stack" (return addresses, spills, scalars accessed safely) at a randomised hidden address, and an "unsafe stack" (buffers, address-taken locals). Backward-edge protection without runtime checks.
Production: Clang's -fsanitize=safe-stack, Fuchsia OS.
Where to read more: Clang SafeStack documentation; Kuznetsov et al., "Code-Pointer Integrity" (OSDI 2014).
Shadow stacks
What it is: hardware- or compiler-maintained second stack holding only return addresses, checked on RET. Hardware variant (Intel CET SHSTK) has the CPU push to both stacks on CALL and trap on mismatch.
Production: Intel CET on 11th gen Core / Zen 3+; Windows 10/11 Hardware-enforced Stack Protection; Linux 6.4+.
Where to read more: Intel CET technical overview; Linux shstk docs.
ARM Pointer Authentication (PAC)
What it is: ARMv8.3-A instructions (PAC*/AUT*) sign pointers with a tweak (typically the SP) and a key, storing a MAC in unused upper address bits. Tampered pointers fail authentication and fault.
Production: Apple A12+/M1+ (arm64e ABI; XNU kernel uses a hardened variant), Linux kernel.
Where to read more: ARM "Pointer Authentication" learn module; Project Zero "Examining Pointer Authentication on iPhone XS"; Liljestrand et al., "PAC it up" (USENIX Security 2019).
Branch Target Identification (BTI)
What it is: ARMv8.5-A landing-pad scheme. Indirect branches (BR/BLR) trap unless the target is a BTI instruction of the matching kind (c/j/jc). Forward-edge counterpart to PAC.
Production: aarch64 Linux since 5.8 with PROT_BTI; Fedora aarch64; Apple silicon. NSA reported a 50x reduction in usable ROP gadgets.
Where to read more: LWN "ARMv8.5-A: Branch Target Identification support"; ARM developer guide on PAC, BTI, MTE.
ASLR and codegen interaction
What it is: Address Space Layout Randomization works best when the compiler emits position-independent code (PIC/PIE) and avoids absolute addresses; codegen must materialise globals via GOT/PLT or PC-relative lea. Static initialisers, JIT-emitted code, and TLS interact in subtle ways.
Production: every modern OS userspace, KASLR in Linux/Windows kernels.
Where to read more: PaX team's original design document; glibc Hardening manual.
RELRO and full RELRO
What it is: linker reorders ELF segments so relocations sit in a region that is mprotect'd read-only after dynamic loading. Partial RELRO protects .got but not .got.plt; full RELRO (-Wl,-z,relro,-z,now) resolves all PLT entries eagerly and freezes the entire GOT, blocking GOT overwrite attacks.
Production: every major distribution's hardened build flags.
Where to read more: Red Hat's "Hardening ELF binaries using RELRO"; Tk's original RELRO article.
Stack-clash mitigation
What it is: the compiler emits a probe (mov to [sp] or similar) every page when allocating large stack frames or alloca, ensuring the kernel guard page is touched and a stack-heap collision fails fast.
Production: GCC -fstack-clash-protection since 8; Clang since 12 on x86/SystemZ/PPC; default in RHEL 8+, Fedora 27+.
Where to read more: Red Hat's "Stack clash mitigation in GCC"; LLVM blog "Bringing Stack Clash Protection to Clang/X86".
-fcf-protection (Intel CET in GCC/Clang)
What it is: inserts ENDBR64 at all indirect-branch targets (IBT) and emits shadow-stack-aware prologues/epilogues. On non-CET CPUs ENDBR is a NOP, so binaries are forward-compatible.
Production: Linux kernel (IBT enforced since 6.2), Fedora, Ubuntu, Windows.
Where to read more: GCC Instrumentation Options manual page; Intel CET overview.
Additional middle-end optimisations
CSSPGO (Context-Sensitive Sample PGO)
What it is: extends AutoFDO with synchronised LBR + stack sampling to reconstruct calling contexts, plus pseudo-instrumentation pseudo-probes that make sample-to-IR mapping precise without runtime overhead. Roughly +2% over AutoFDO at -4% text size on SPEC2006.
Production: Meta uses CSSPGO on >75% of datacentre cycles; upstream LLVM.
Where to read more: He, Yu et al., "Revamping Sampling-Based PGO with Context-Sensitivity and Pseudo-instrumentation" (CGO 2024).
Propeller (post-link block reordering)
What it is: emits one ELF section per basic block (-fbasic-block-sections), then relinks using a fresh profile to lay out hot blocks contiguously, split cold blocks out, and reorder functions. Avoids binary rewriting (unlike BOLT).
Production: Google datacentre fleet, Clang itself (~7%), MySQL (~1%), kernels.
Where to read more: Shen et al., "Propeller" (ASPLOS 2023); google/llvm-propeller on GitHub.
Spectre mitigations: retpoline and LFENCE
What they are: Retpoline replaces indirect call/jmp with a return-trap that traps speculation in an infinite loop on the BTB-poisoning path. LFENCE-after-load serialises load address resolution before dependent branches.
Production: Linux kernel (CONFIG_MITIGATION_RETPOLINE), Windows kernel, hypervisors. Compiler flags: -mretpoline (Clang), -mindirect-branch=thunk (GCC).
Where to read more: Intel's "Retpoline" whitepaper; LWN "Retpoline" coverage; Linux Spectre kernel docs.
Branch divergence analysis (GPU)
What it is: dataflow analysis classifying values as uniform (same across a warp/wavefront) or divergent; branches on divergent conditions force SIMT serialisation. Used to skip divergence-handling code, drive control-flow linearisation, and inform register allocation.
Production: NVCC/PTX, AMD ROCm/HIPCC, LLVM LegacyDivergenceAnalysis and the newer UniformityAnalysis.
Where to read more: Han and Abdelrahman, "Reducing Branch Divergence in GPU Programs" (GPGPU 2011); LLVM UniformityAnalysis docs.
Memory dependence analysis
What it is: per-instruction queries answering "which prior store could this load see?" built on top of alias analysis. LLVM's MemoryDependenceAnalysis (and the newer MemorySSA) underpins GVN, DSE, LICM, and memcpy optimisation. SCEV-AA improves precision inside loops by reasoning about induction variables symbolically.
Production: LLVM, GCC's tree-SSA, Java HotSpot C2 (ideal graph).
Where to read more: LLVM Alias Analysis Infrastructure; LLVM MemorySSA documentation.
Concurrency primitives
Memory ordering models (SC, TSO, RC)
What they are: Sequential Consistency (textbook, expensive on hardware), Total Store Order (x86, SPARC: stores can be buffered past loads), Relaxed/Release-Consistency (ARM, POWER, RISC-V: loads and stores reorder freely without barriers). C++11/C/Rust atomics expose these via memory_order_*; the compiler picks the cheapest implementation per target.
Production: every multi-core compiler.
Where to read more: Sewell et al., "x86-TSO: A Rigorous and Usable Programmer's Model"; Boehm-Adve mappings to processors.
Atomics codegen: cmpxchg vs LL/SC
What it is: on x86 (TSO + locked instructions) the compiler emits LOCK CMPXCHG and XCHG; on ARM/POWER/RISC-V (LL/SC) it emits a load-exclusive / store-conditional retry loop, often expanded late (after register allocation) to satisfy hardware constraints on the loop body. Acquire/release become barriers (DMB ISH on ARMv7, LDAR/STLR on ARMv8).
Production: LLVM AtomicExpandPass, GCC __atomic_* builtins.
Where to read more: LLVM Atomics Concurrency Guide; Boehm-Adve C++0x mappings.
Lock elision / hardware transactional memory (TSX)
What it is: hardware speculatively executes a critical section without taking the lock; on conflict it aborts and retries non-speculatively. Compiler exposed via XACQUIRE/XRELEASE prefixes (HLE) or _xbegin/_xend intrinsics (RTM). HLE is now deprecated by Intel; RTM remains but has been disabled or sandboxed by microcode in many parts after MDS-class attacks.
Production: glibc had pthread_mutex HLE paths; mostly removed in 2019+.
Where to read more: Intel TSX Wikipedia summary with microcode-disable history.
Embedded and specialised techniques
-Oz code-size optimisation
What it is: Clang's most aggressive size pass. Like -Os (which is -O2 with size-tuned inliner and merge thresholds) but trades further runtime for smaller text. Disables loop unrolling, prefers tail-call over inlining, enables outliner. Roughly 15% smaller than -Os typically, with measurable perf loss.
Production: iOS apps default to -Os; embedded firmware uses -Oz.
Where to read more: Clang command guide; LLVM machine-outliner docs.
ROM placement
What it is: linker scripts and section attributes (__attribute__((section(".rodata.foo")))) place constants and code in flash/ROM regions, with RAM reserved for .data/.bss. Toolchain support includes copy-to-RAM stubs in startup code and XIP (execute-in-place) flash configurations.
Production: every embedded GCC/LLVM target; ARM Keil, IAR, Zephyr, FreeRTOS.
Where to read more: GCC linker script docs; Zephyr linker script architecture.
Link-time DCE for embedded (--gc-sections)
What it is: -ffunction-sections -fdata-sections -Wl,--gc-sections puts each function/variable in its own section so the linker can prove unreferenced ones unreachable and drop them. Combined with --print-gc-sections to audit.
Production: every embedded GCC build, Linux kernel (LTO mode), Android NDK.
Where to read more: MaskRay's "Linker garbage collection"; LWN "Shrinking the kernel with link-time garbage collection".
Fixed-point arithmetic
What it is: embedded DSP code uses Q-format integers (Q15, Q31) representing fractional values; compilers expose this via _Fract/_Accum types from ISO/IEC TR 18037 (Embedded C), or library intrinsics. Codegen emits scaled multiply-shift sequences and saturating ops.
Production: GCC fixed-point, TI C2000 codegen, ARM CMSIS-DSP.
Where to read more: ISO/IEC TR 18037 Embedded C; GCC fixed-point types docs.
Saturating arithmetic intrinsics
What they are: LLVM's @llvm.sadd.sat, @llvm.usub.sat, @llvm.ssub.sat, and target-specific intrinsics clamp on overflow rather than wrapping. Lower to SSAT/USAT/QADD/QSUB on ARM, PADDSB/PSUBSB on x86 SIMD, dedicated DSP ops on Hexagon.
Production: image/audio codecs, neural network kernels (XNNPACK, ARM Compute Library).
Where to read more: LLVM LangRef saturation intrinsics; ARM ACLE saturation.
WebAssembly-specific techniques
Wasm-specific optimisations
What they are: beyond MVP, the toolchain now exploits relaxed-SIMD (implementation-defined fast paths for FMA, swizzle), exception handling (lowering to native EH instead of branchy returncodes), and the GC proposal (typed (ref struct)/(ref array) instead of linear-memory shadow heaps).
Production: Binaryen (wasm-opt), Emscripten, Kotlin/Wasm, Dart Wasm backend; WasmGC enabled in V8/SpiderMonkey/JavaScriptCore and Wasmtime.
Where to read more: WebAssembly proposals tracker on GitHub; Binaryen optimisation docs.
Wasm Component Model
What it is: typed interfaces, resources, and a binary "component" format that wraps multiple core modules with strongly-typed shared-nothing linking driven by the Canonical ABI and WIT (Wasm Interface Types). Cross-language linking without C ABI compromises.
Production: Wasmtime (full support, late 2024), wit-bindgen for Rust/Go/Python/JS, jco.
Where to read more: component-model.bytecodealliance.org; WebAssembly/component-model repo.
WASI evolution
What it is: Preview 1 (snapshot of POSIX-flavoured syscalls) is now legacy; Preview 2 (WASI 0.2, January 2024) is built on the Component Model with capability-typed worlds (wasi:cli, wasi:http, wasi:io); Preview 3 (0.3, in flight 2025) adds native async via component-model streams and futures.
Production: Wasmtime, JCo, Spin, Wasmer; cloud platforms (Fastly, Fermyon).
Where to read more: WASI 0.2 announcement; WebAssembly/WASI repo.
Modern frontend infrastructure
Token-based diagnostic localisation
What it is: older compilers report errors by (file, line, column) derived from raw character offsets, which break on multibyte UTF-8 and re-tokenisation. Modern frontends attach diagnostics to token ranges (Roslyn SyntaxToken, Clang SourceRange, rust-analyzer TextRange), letting IDEs map them back through edits and macros.
Production: Roslyn, Clang/LLVM, rust-analyzer, swift-syntax.
Where to read more: Clang SourceManager design; Roslyn syntax overview.
Recovery parsing for IDE responsiveness
What it is: "resilient" parsers (Tree-sitter's GLR, Roslyn's hand-written, rust-analyzer's ungrammar-driven) produce a partial tree even with syntax errors using approaches like phrase-level recovery, synchronisation tokens, and inserted dummy nodes. Critical for syntax highlighting, completion, and inlay hints during typing.
Production: Tree-sitter (GitHub semantic, Neovim, Helix, Atom), Roslyn, rust-analyzer, swift-syntax.
Where to read more: Aleksey Kladov's "Resilient LL Parsing Tutorial"; Tree-sitter creator's design notes.
Semantic highlighting
What it is: LSP's textDocument/semanticTokens lets servers annotate tokens with type-derived categories (parameter, enumMember, unusedVariable) instead of relying on the editor's regex-based highlighter. Requires the type checker to emit per-token classification and supports incremental delta updates.
Production: clangd, rust-analyzer, gopls, OmniSharp, the TypeScript language server.
Where to read more: LSP semanticTokens spec; VS Code semantic highlight guide.
Macro hygiene algorithms
What they are: the Kohlbecker-Friedman-Felleisen-Duba (KFFD) timestamp algorithm renames identifiers introduced by a macro so they cannot capture user names; syntax-case (Dybvig) records syntax objects with marks; Set of Scopes (Flatt, Racket 6.3+) replaces linear timestamps with a set of scope tags per identifier. Rust uses a hygienic but simpler SyntaxContext-based scheme for macro_rules!.
Production: Racket, Chez Scheme, Rust, Clojure, Scala 3 macros.
Where to read more: Flatt, "Bindings as Sets of Scopes" (POPL 2016); KFFD original (ACM 1986).
Effect inference (research)
What it is: type-and-effect systems annotate function types with the side effects they perform (io, exn, div, alloc, user-defined). Koka uses row-polymorphic effects with Hindley-Milner-style inference, so most effect annotations are inferred. Algebraic effect handlers generalise exceptions, generators, and async.
Production: Koka (research/Microsoft), Eff, Frank, Effekt; OCaml 5 (handlers without inference).
Where to read more: Leijen, "Koka: Programming with Row-polymorphic Effect Types" (MSFP 2014); Leijen, "Type Directed Compilation of Row-Typed Algebraic Effects" (POPL 2017); Pretnar tutorial on algebraic effects.
Verifying compilers and formal methods
A subfield of compiler engineering that our INTERCAL compiler does not touch at all: the work of producing compilers (or compiler components) with mathematical proofs of correctness. The proofs are typically discharged in a proof assistant (Coq, HOL4, Lean) and cover the property "for every input source, the produced binary computes the same observable behaviour as the source did under the language's formal semantics".
CompCert
What it is: a Coq-verified optimising C compiler for a subset of C99. Written by Xavier Leroy and INRIA collaborators since 2005. About 100,000 lines of Coq plus generated OCaml. Targets PowerPC, ARM, x86-32, x86-64, RISC-V, Kalray K1.
Production: used in safety-critical avionics (Airbus, MTU Aero Engines), automotive (some Renault and PSA components), and security-sensitive kernel work. Commercially distributed by AbsInt.
What is verified: the entire pipeline from C AST to assembly. Every transformation, including standard optimisations (constant propagation, CSE, register allocation), is proved correct under CompCert's formal C semantics.
What is not verified: the parser (uses Menhir, separately verified by the Menhir-CompCertCASM project), the assembler/linker, the C library.
Lessons: building a verified compiler is a decade-plus project. CompCert produces code roughly 5-15% slower than gcc -O2 on representative benchmarks. The trade-off is "you get a proof, you lose some optimisation". For safety-critical software, that is acceptable; for general use, it is not.
Where to read more: compcert.org; Leroy's papers ("Formal verification of a realistic compiler", CACM 2009).
CakeML
What it is: a HOL4-verified ML compiler. Targets x86-64, ARM, MIPS, RISC-V. Self-bootstrapped: the bootstrap proof shows that CakeML (running CakeML's own source on its own runtime) produces a binary equivalent to the one verified to compile to.
Production: research/teaching primarily; growing presence in CHERI verification work and in academic projects requiring fully verified toolchains.
Where to read more: cakeml.org; "CakeML: A Verified Implementation of ML" (Kumar et al., POPL 2014).
RustBelt
What it is: a Coq-verified semantic model of Rust's type system, plus proofs that several core unsafe-Rust libraries (Arc, Mutex, RwLock, Cell) are sound. Built on the Iris separation-logic framework.
Production: not integrated into rustc directly. Influences the compiler through papers and through the rust-lang/unsafe-code-guidelines working group's decisions.
Where to read more: rustbelt project page; "RustBelt: Securing the Foundations of the Rust Programming Language" (Jung et al., POPL 2018).
Iris
What it is: a higher-order concurrent separation logic implemented in Coq. The framework underlying RustBelt and many other verified-software projects. The "right" tool for reasoning about heap-manipulating concurrent programs in 2026.
Where to read more: iris-project.org; tutorial at the Iris site; "Iris: Monoids and Invariants as an Orthogonal Basis for Concurrent Reasoning" (Jung et al., POPL 2015).
Verified parsers (Menhir, CompCertCASM)
What they are: parser generators (or hand-written parsers) that come with proofs of correctness against an LR grammar specification. Menhir's --coq mode generates Coq code that can be verified to be correct. The CompCertCASM project verified Menhir's output.
Where to read more: Menhir documentation, "Validating LR(1) parsers" (Jourdan, Pottier, Leroy, ESOP 2012).
Alive2
What it is: an automated tool for verifying LLVM IR-level optimisations are correct. Uses an SMT solver to check that a transformed function is observably equivalent to the original under LLVM's IR semantics.
Production: integrated into LLVM's CI in some configurations. Has found dozens of bugs in LLVM optimisations.
Where to read more: github.com/AliveToolkit/alive2; "Alive2: Bounded Translation Validation for LLVM" (Lopes et al., PLDI 2021).
Csmith and YarpGen
What they are: random C program generators that produce well-defined C programs with known expected outputs. Used to fuzz compilers via differential testing: compile with multiple compilers, compare outputs, file bugs on divergence.
Production: Csmith found hundreds of bugs in GCC and LLVM. YarpGen is the newer generator with better coverage of vector and floating-point code.
Where to read more: Csmith on github.com/csmith-project/csmith; "Finding and Understanding Bugs in C Compilers" (Yang et al., PLDI 2011).
KLEE, CBMC, SeaHorn
What they are: tools that turn programs into logical formulas and feed them to SMT solvers, looking for bugs.
- KLEE: symbolic execution on LLVM IR. Generates test inputs that trigger different execution paths.
- CBMC: bounded model checker for C. Unrolls loops to a fixed depth, then checks for assertion violations.
- SeaHorn: LLVM-based verification framework that combines abstract interpretation with model checking.
Production: KLEE is used in security research; CBMC in safety-critical software; SeaHorn in research.
Where to read more: klee.github.io; cbmc.org; seahorn.github.io.
Frama-C
What it is: a static analysis platform for C with multiple plug-ins (Eva for value analysis, WP for weakest-precondition reasoning, RTE for runtime-error checking). Uses ACSL (ANSI/ISO C Specification Language) for annotations.
Production: avionics (Airbus), defence software, automotive embedded.
Where to read more: frama-c.com; the Frama-C tutorial.
Advanced type systems beyond what we have
Refinement types
What they are: types augmented with logical predicates that constrain values. {x: Int | x >= 0} is a refined integer; the compiler emits SMT queries to verify that operations preserve the refinement.
Production:
- Liquid Haskell: refinement types for Haskell. Verifies properties like array-index safety, division by zero.
- F* (FStar): Microsoft's verification-oriented language combining refinement types with SMT.
- Refinement types in Idris 2.
Where to read more: "Refinement Types for Haskell" (Vazou et al., ICFP 2014); fstar-lang.org.
Dependent types in production
What they are: types that can depend on values. Vec n A is a vector of n elements of type A, where n is a value. The compiler must prove that operations preserve length constraints.
Production:
- Idris 2: a general-purpose programming language with dependent types. Compiles to native code via Chez Scheme or to JavaScript.
- Lean 4: a theorem prover with a usable native code generator. Compiles via C.
- Coq's Extraction: Coq programs can be extracted to OCaml or Haskell, then compiled normally.
Where to read more: idris-lang.org; lean-lang.org; "Programming in Lean 4" (Avigad).
Linear types vs affine types
What they are: type-system extensions that constrain how often a value can be used. Linear: exactly once. Affine: at most once. Useful for resources (file handles, mutex locks, memory) that must not be duplicated or forgotten.
Production:
- Linear Haskell (extension to GHC since 9.0).
- Granule (research linear/graded types).
- ATS (linear types for systems programming).
- Rust's affine types (a value can be moved, after which the original is invalidated).
Where to read more: "Linear Haskell" (Bernardy et al., POPL 2018); the Granule project.
Session types
What they are: types that describe communication protocols. A session type !Int.?Bool.End means "send an Int, receive a Bool, terminate". Communication that does not match the session type is a type error.
Production:
- Scribble (a protocol-description language with backends for Java, Erlang, Go).
- Session-typed APIs in Rust (the
sessioncrate). - Research languages like Pikelet.
Where to read more: scribble.org; "Multiparty Session Types" papers (Honda, Yoshida).
Capability and ownership systems beyond Rust
What they are: type-system features that track who can do what to a value.
- Pony's reference capabilities:
iso,val,ref,box,tag,trn. Each capability constrains aliasing and mutation. Pony's runtime is data-race-free by construction. - Project Verona (Microsoft Research): regions plus reference capabilities, aimed at gradual ownership.
- Alms: ML extension with linear types and capabilities.
- Mezzo: ML-family language with permission-based ownership.
Where to read more: ponylang.io; project-verona on GitHub.
F* (FStar)
What it is: a typed lambda calculus combining dependent types, refinement types, monadic effects, and SMT-aided proof. Compiles to OCaml, F#, or C (via KreMLin/Karamel).
Production: Microsoft Project Everest's verified TLS stack (HACL*, EverParse, EverCrypt). Linux kernel's WireGuard adopted HACL* code.
Where to read more: fstar-lang.org; the Everest project; "F*: A Tour de Force" papers.
GPU and HPC compilation
NVPTX backend
What it is: LLVM's NVIDIA GPU backend. Targets PTX (NVIDIA's intermediate assembly), which the NVIDIA driver JITs to actual GPU machine code. Used by CUDA Clang, CUTLASS, OpenAI's Triton, and the entire NVIDIA toolchain.
Where to read more: LLVM's lib/Target/NVPTX/; the PTX ISA reference manual; the OpenAI Triton compiler source.
AMDGPU backend
What it is: LLVM's AMD GPU backend. Targets GCN, RDNA, CDNA architectures. Used by ROCm/HIP, AMD OpenCL, and increasingly by ML frameworks.
Where to read more: LLVM's lib/Target/AMDGPU/; the AMD GPU ISA documentation.
SPIR-V codegen
What it is: SPIR-V is a portable IR for GPU shaders and compute kernels, used by Vulkan, OpenCL 2.1+, and OpenGL extensions. Compilers targeting SPIR-V (Clang OpenCL, glslang for GLSL, DXC for HLSL, IREE) emit SPIR-V; vendors translate it to their hardware.
Where to read more: KhronosGroup/SPIRV-Cross; the Vulkan specification.
Variable-length vectorisation: SVE, RVV, AVX-512
What they are: vector-instruction-set extensions where the vector length is a runtime parameter rather than fixed at compile time. The compiler emits length-agnostic loops that work for any vector width the CPU supports.
- SVE/SVE2 (ARM): Scalable Vector Extension. Aimed at HPC; widely deployed in 2024+ ARM chips.
- RVV (RISC-V): Vector Extension. The RISC-V analogue.
- AVX-512 (Intel): not technically variable-length but has length-masking that achieves similar flexibility.
LLVM has been adding length-agnostic vectorisation since around 2020. The work has produced the vscale concept and the <vscale x N x i32> vector type, where length is parameterised.
Where to read more: the ARM SVE programmer's guide; LLVM's vector predication proposal documents.
Halide
What it is: a domain-specific language and compiler for image-processing pipelines. The user writes the algorithm (what to compute) separately from the schedule (how to compute it: tiling, parallelism, vectorisation, fusion). Halide handles the schedule transformation, freeing the user from low-level optimisation.
Production: Adobe Photoshop, Google Pixel camera pipelines, embedded vision systems.
Where to read more: halide-lang.org; "Halide: Decoupling Algorithms from Schedules for High-Performance Image Processing" (Ragan-Kelley et al., PLDI 2013).
TVM
What it is: a tensor compiler that takes ML models (TensorFlow, PyTorch, ONNX) and lowers them through a TIR (Tensor IR) to optimised CPU/GPU/accelerator kernels. Uses learning-based schedule auto-tuning.
Production: AWS, ARM, Qualcomm, OctoML's commercial offerings.
Where to read more: tvm.apache.org; "TVM: An Automated End-to-End Optimizing Compiler for Deep Learning" (Chen et al., OSDI 2018).
MLIR linalg dialect
What it is: a high-level tensor-operation dialect in MLIR. Operations like matrix multiply, convolution, and element-wise apply are expressed structurally; lowering passes turn them into nested loops, GPU kernels, or vendor-specific calls.
Production: TensorFlow's MLIR backend, IREE, parts of OpenXLA.
Where to read more: MLIR linalg documentation; the IREE compiler source.
CIRCT (hardware synthesis with MLIR)
What it is: an LLVM/MLIR project for hardware design. Provides dialects for HDL (HardWare Description Language) representations and lowering paths from high-level descriptions (like Chisel's FIRRTL) to gate-level or Verilog output.
Production: emerging in academic and industrial hardware design flows.
Where to read more: circt.llvm.org; the CIRCT documentation.
Polly
What it is: LLVM's polyhedral loop optimiser. Represents loop nests as integer polyhedra, applies transformations (tiling, fusion, interchange) on the polyhedral representation, lowers back to LLVM IR. Optional pass; not on by default.
Production: enabled in some HPC builds; not default in Clang.
Where to read more: polly.llvm.org; the Polly tutorial.
Differentiable programming and DSL compilation
Enzyme
What it is: an LLVM-IR-level automatic differentiation framework. Transforms LLVM IR functions into their derivative functions, enabling autodiff for any LLVM-targeting language without source-language support.
Production: research, with growing adoption in scientific computing and ML.
Where to read more: enzyme.mit.edu; "Instead of Rewriting Foreign Code for Machine Learning, Automatically Synthesize Fast Gradients" (Moses and Churavy, NeurIPS 2020).
Swift autodiff
What it is: Swift had built-in automatic differentiation as a language feature (added in Swift 5.x, in the _Differentiation module). Different from Enzyme: Swift autodiff operates at SIL level, exploiting Swift's type system to ensure differentiability properties.
Status: actively maintained but not as visible as it once was; the Swift for TensorFlow project (which drove much of the original work) has wound down.
Where to read more: Swift-evolution proposal SE-0419; the Swift Differentiable Programming Manifesto.
JAX and XLA HLO
What they are: JAX is a Python library for differentiable numerical computing. Internally, JAX traces Python code to produce XLA HLO (High Level Operations), an IR for tensor computations. XLA compiles HLO to GPU/TPU/CPU code.
Production: Google internally; Anthropic for Claude training; Google DeepMind; many ML research labs.
Where to read more: jax.readthedocs.io; the XLA documentation.
Halide schedule auto-tuning
What it is: searching the space of possible schedules (orderings of loop transformations) for a Halide algorithm to find the fastest. Uses search heuristics, machine learning, or brute force depending on the variant.
Production: Halide's auto-scheduler; commercial offerings build on this idea.
Where to read more: "Learning to Optimize Halide with Tree Search and Random Programs" (Adams et al., SIGGRAPH 2019).
Build infrastructure
Bazel hermetic builds
What it is: Google's open-source build system. Hermetic by construction: every action declares its inputs (files, tools, env vars), and Bazel guarantees the action's output depends only on those inputs. Enables aggressive remote caching.
Production: Google internally, many large open-source projects (TensorFlow, gRPC, Kubernetes parts, Envoy).
Where to read more: bazel.build; the Bazel rules documentation.
Buck2
What it is: Meta's modern build system, written in Rust. Successor to Buck, with first-class support for incremental rebuilds, remote execution, and per-target caching.
Production: Meta internally; growing open-source adoption.
Where to read more: buck2.build; the Buck2 documentation.
Nix-based reproducible builds
What it is: Nix (the package manager) and NixOS (the OS) build everything from declarative descriptions, with builds isolated in sandboxes. Reproducible by construction. Build outputs hash-keyed.
Production: NixOS, the Nixpkgs project (>100,000 packages), some companies internally.
Where to read more: nixos.org; "Functional Package Management with Nix" (PhD thesis, Dolstra 2006).
sccache
What it is: a distributed cache for compiler invocations. Hashes the compile command plus inputs, caches the output (object file), serves cached outputs to other machines.
Production: Mozilla, many large Rust projects.
Where to read more: github.com/mozilla/sccache.
ABI tools (abidiff, abicompat)
What they are: tools that compare two versions of a shared library to detect ABI breaks. abidiff produces a diff; abicompat checks that an application built against one library version is compatible with another.
Production: Red Hat (libabigail), Linux distribution maintainers.
Where to read more: sourceware.org/libabigail; the Fedora ABI tracker.
Symbol versioning
What it is: a feature of ELF dynamic linkers that lets a library expose multiple versions of a symbol with different ABIs. Old binaries link to the old version; new binaries to the new. Critical for ABI-stable libraries like glibc.
Production: glibc, GTK+, many GNU libraries.
Where to read more: the LSB ABI documentation; "How to Write Shared Libraries" (Drepper 2003).
DWARF debug info generation
What it is: the standard format for embedding source-level debug information in compiled binaries. The compiler emits DWARF tables describing types, variable locations, line-number information, and call frames.
Production: every modern Unix-shaped toolchain. DWARF 5 is the current standard.
Where to read more: dwarfstd.org; "Introduction to the DWARF Debugging Format" by Eager.
CTF (Compact C Type Format)
What it is: a Sun/Oracle alternative to DWARF, much smaller, used in Solaris and FreeBSD kernels for type-aware debugging without the DWARF size cost. Linux's BPF subsystem also uses it.
Where to read more: the CTF specification at illumos.org; the BPF Type Format (BTF), Linux's adaptation.
Why we lack all of this
The reasons are not all equivalent.
For verifying compilers: INTERCAL has no formal semantics worth proving. The language is a parody; nobody is building safety-critical systems in it. Verified compilation would be silly here.
For advanced type systems: INTERCAL's type system is four numeric types. There is nothing to extend.
For GPU/HPC: INTERCAL programs do no useful numerical computation. SIMD is irrelevant.
For DSL/autodiff: same.
For build infrastructure: our build is one shell script. Bazel/Nix-scale infrastructure would be absurd.
The lesson: techniques exist for specific problems. A small esoteric-language compiler does not have those problems. Knowing the techniques exist, and what they solve, is the valuable thing.
What we deliberately exclude
Some techniques are not just absent but actively out of scope. Naming them prevents future confusion.
- Lazy evaluation runtime: GHC-specific. INTERCAL is strict.
- First-class continuations: Scheme-specific. INTERCAL has no closures or coroutines.
- First-class macros: not in the spec.
- Reflection: INTERCAL has no introspection.
- Modules with separate compilation: INTERCAL is one source file.
- Generics: INTERCAL is monomorphic.
- Type system extensions (subtyping, variance, GADTs, kind polymorphism): INTERCAL has no type system to extend.
- AOT to multiple targets simultaneously: INTERCAL programs target one platform per build.
These are all ways of being a different compiler. The commitment to INTERCAL means accepting them as out of scope.
What we might add (the realistic roadmap)
Of all the techniques in this chapter, a manageable subset would meaningfully improve our compiler without redefining its scope. In rough priority order:
- Real CFG construction (Phase A in middle-end-and-optimisation.md). Enables every later optimisation.
- SSA via Cytron's algorithm. Standard form for IR-based optimisations.
- SCCP. The natural extension of our existing constant folding.
- Liveness analysis + linear-scan register allocation. Eliminates stack-slot spills for short-lived values.
- Inlining of runtime primitives. Mentioned in middle-end-and-optimisation.md as a TODO.
- Real loop detection. Prerequisite for LICM and unrolling.
- Csmith-style differential testing. Improves bug-finding without major architecture changes.
Each of these would be a multi-week project. None requires moving away from "small AOT compiler for an esoteric language". The largest of them (1-4 combined) would roughly double the compiler's size; the project would still be a teaching artifact, not a production toolchain.
Closing
The list above is what production compilers contain that we do not. It is also approximately the curriculum of a compiler-engineering career. Each technique has a literature, a textbook chapter, a production reference, and a place in the broader puzzle.
A reader who is done with our compiler and wants more depth has an embarrassment of riches: pick a technique, read its papers, find it in a production compiler from Part VII, study how that compiler implements it, then sketch what it would look like in our compiler. The exercise is uniformly enlightening.
The other direction (read this chapter to know what you are missing) is the practical view. When you encounter "GVN" or "tail-call optimisation" or "ARC" in another compiler's documentation, you will have at least seen the term, the rough idea, and the reference to Part VII's example.
Improvement proposals: applying Part VII and Part VIII
This is the synthesis chapter: every concrete improvement we could bring back to the INTERCAL compiler from the production-compiler chapters of Part VII and the technique catalogues of Part VIII.
The chapter is organised in three tiers by effort. Tier 1 is "single-session" work, Tier 2 is "one to several weeks", Tier 3 is "multi-month, architecturally significant". The closing section recommends a sequence and names what is deliberately out of scope.
For each proposal: what it is, where the lesson comes from, where we would implement it, the algorithm or design sketch, the effort estimate, the test strategy under our existing TDD contract, the risks, and references for further reading.
These are proposals, not plans. The user picks which to act on.
Tier 1: quick wins
Low effort (one focused session each), low risk, immediately useful.
1. --emit-tokens flag
What it is. A read-only inspection flag that prints the tokenised statement table to stdout, completing the trilogy with the existing --emit-3addr and --emit-cfg flags. Output is one line per statement listing index, label, type, polite flag, negated flag, and a truncated body.
Lesson source. Every compiler in Part VII exposes per-phase intermediate output. rustc's -Zdump-mir family, Go's -d=ssa/<phase>, GHC's -ddump-parsed-ast/-ddump-rn-ast/-ddump-tc-ast, V8's --print-bytecode, OCaml's -dparsetree. The pattern is universal: a healthy compiler exposes its model of the program at every layer.
Where in our codebase. src/bootstrap/intercalc.sh: add a new emit_tokens() function next to emit_cfg and emit_3addr, plus the --emit-tokens argument parsing and dispatch in main(). Add a corresponding test in tests/test_emit_tokens.sh.
Algorithm. Walk stmt_count once. For each statement, format and print:
stmt N: [(label X)] TYPE [PLEASE] [NOT] body...
Use the existing stmt_label[], stmt_type[], stmt_polite[], stmt_negated[], stmt_body[] arrays.
Effort. ~30 lines zsh + ~50 lines for the test script. One session.
Dependencies. None; every needed datum is computed by tokenize() and the existing analysis passes.
Test strategy. TDD: write tests/test_emit_tokens.sh first asserting the format on three small programs (linear, COME FROM, syslib). Verify the script fails (no implementation yet), implement, verify pass. Add to .githooks/pre-push and .github/workflows/ci.yml.
Risks. Low. Read-only, does not affect codegen. Worst case is bad formatting that gets fixed.
Educational value. Teaches that tokenisation is its own inspectable layer, distinct from parsing. Surfaces the politeness/negation classification decisions for inspection.
References.
- rustc's
-Zdump-mir, Go's-d=ssa/<phase>=<level>, GHC-ddump-parsed-ast. - The pattern is described in techniques-we-use.md under "IR inspection flags".
2. --time-report flag
What it is. Per-phase timing breakdown at compile time. Reports milliseconds spent in each pass: read_source, tokenize, check_politeness, check_labels, resolve_come_from, detect_syslib, compute_flag_checks, codegen_program, peephole_optimize, plus the final cc invocation.
Lesson source. Zig's --time-report is the closest model. rustc has -Zself-profile plus summarize, GCC has -ftime-report, GHC has -v3 for phase-by-phase wall-clock. The motivation is the same everywhere: when compile time regresses, the only way to localise the cause is per-phase timing.
Where in our codebase. src/bootstrap/intercalc.sh: wrap each top-level phase call in main() with start/end time captures. Pull the data from $EPOCHREALTIME (zsh built-in providing sub-second precision).
Algorithm.
typeset -A phase_times
typeset -F start
time_phase() {
local name=$1; shift
start=$EPOCHREALTIME
"$@"
phase_times[$name]=$(( EPOCHREALTIME - start ))
}
# In main():
time_phase tokenize tokenize
time_phase politeness check_politeness
time_phase labels check_labels
# ... etc
if (( TIME_REPORT )); then
print -u2 "=== Compile-time breakdown ==="
for name in "${(@k)phase_times}"; do
printf " %-20s %.3f s\n" "$name" "${phase_times[$name]}" >&2
done
fi
Effort. ~60 lines zsh (phase wrappers + reporting), plus a test that runs --time-report on a small program and asserts the format and that the times sum approximately to the total.
Dependencies. None. zsh's $EPOCHREALTIME is available since 5.0.0 (we already require zsh).
Test strategy. TDD: tests/test_time_report.sh checks that the output contains every expected phase name, that the format phase_name N.NNN s is consistent, and that no individual phase takes more than the total wall-clock.
Risks. Low. Output goes to stderr to avoid interfering with --emit-* flags that go to stdout. Edge case: cc invocation timing must be inside the wrapper too if the user wants total accountability.
Educational value. Makes the pipeline tangible. A reader who runs --time-report on tests/test_syslib.i sees concrete numbers for which phases dominate (codegen, almost certainly).
References.
- Zig's
--time-reportdocumentation. - rustc-dev-guide chapter on profiling (
-Zself-profiledocumentation). - Linux's
timecommand, conceptually parallel.
3. --opt-bisect-limit=N flag
What it is. A flag that limits how many optimisation transformations the compiler is allowed to apply. Setting --opt-bisect-limit=5 runs only the first five optimisations that would have fired, then disables the rest. By binary-searching N, a developer finds the optimisation responsible for a miscompile.
Lesson source. LLVM's -mllvm -opt-bisect-limit=N is the canonical implementation. The mechanism is described in detail in llvm/lib/Transforms/Utils/BugDriver.cpp and the OptBisect class.
Where in our codebase. src/bootstrap/intercalc.sh: add a global counter OPT_BISECT_COUNT that every optional transformation increments and consults. The transformations are: each rule in peephole_optimize, each fold in eval_const, each statement-level dead-flag elimination in compute_flag_checks, each upcoming inline of a runtime primitive (proposal 5).
Algorithm.
# Globals
typeset -i OPT_BISECT_LIMIT=-1 # -1 = no limit
typeset -i OPT_BISECT_COUNT=0
opt_bisect_check() {
local name=$1
OPT_BISECT_COUNT=$((OPT_BISECT_COUNT + 1))
if (( OPT_BISECT_LIMIT >= 0 && OPT_BISECT_COUNT > OPT_BISECT_LIMIT )); then
(( OPT_BISECT_VERBOSE )) && print -u2 "BISECT: SKIP #$OPT_BISECT_COUNT $name"
return 1
fi
(( OPT_BISECT_VERBOSE )) && print -u2 "BISECT: APPLY #$OPT_BISECT_COUNT $name"
return 0
}
# In each transformation:
if opt_bisect_check "eval_const_unary_and"; then
# apply transformation
fi
Effort. ~100 lines: the helper plus per-call updates across eval_const, peephole_optimize, and compute_flag_checks.
Dependencies. None.
Test strategy. Deliberately add a buggy "fold rule" behind a feature flag, build a test program where it fires, assert that --opt-bisect-limit=0 produces correct output and the buggy rule's fold count identifies it. Then remove the deliberate bug.
Risks. Care needed that the bisect is deterministic: same input + same limit must always make the same decision. Use a stable enumeration order.
Educational value. Teaches the bisection-as-debugging technique that is fundamental to compiler engineering. Most contributors learn it the first time a miscompile appears.
References.
- LLVM's
-mllvm -opt-bisect-limit=Ndocumentation. - "Debugging LLVM" page at https://llvm.org/docs/DebuggingLLVM.html.
- Cooper and Torczon's chapter on testing optimisations.
4. Expanded peephole rules
What it is. Extend peephole_optimize from its current single rule (drop unconditional branches immediately followed by their target label) to cover several more patterns that arise mechanically in our generated assembly. The rules are local, syntactic, low-risk.
Lesson source. Every backend in Part VII has dozens to hundreds of peephole rules. LLVM's lib/CodeGen/PeepholeOptimizer.cpp, GCC's define_peephole2 patterns in machine descriptions, Cranelift's late-stage cleanups.
Where in our codebase. src/bootstrap/intercalc.sh: extend peephole_optimize. Each rule is a sed-substitution-or-loop on the asm variable. Per the --opt-bisect-limit proposal, each rule should call opt_bisect_check before firing.
Specific rules to add.
a) Load-after-store cancellation. A str x0, [SP, #N] followed immediately by ldr x1, [SP, #N] can become str x0, [SP, #N]; mov x1, x0. The load is replaced by a register copy. Net win: removes a memory access, possibly enables further moves to be optimised.
b) Redundant mov collapse. mov x0, x0 (identity move) is dead. Drop it.
c) Branch-to-branch (jmp-to-jmp). A b LABEL1 where LABEL1's only instruction is b LABEL2 can become b LABEL2. (We currently handle the simpler "branch immediately followed by its target" case; this generalises.)
d) Dead store elimination. str x0, [SP, #N] followed by another str x1, [SP, #N] with no intervening load: drop the first.
e) mov + load coalesce on x86_64. mov rax, rdi; mov rcx, rax where rax is not subsequently used: mov rcx, rdi.
Effort. ~150-300 lines for five rules plus per-rule tests.
Dependencies. Proposal 3 (opt-bisect-limit) is helpful for debugging but not strictly required.
Test strategy. Per rule: write a small INTERCAL program that produces assembly triggering the pattern (use INTERCAL_ASM_ONLY=1 to inspect). Verify the pre-rule assembly contains the pattern; verify the post-rule assembly does not. Verify the binary still produces correct output.
Risks. Medium. Peephole rules that look local can change semantics if context is wrong (e.g., load-after-store can be wrong if the load value is used to detect aliasing across calls). Each rule needs careful predicate.
Educational value. Concrete examples of how production compilers accumulate small optimisations into measurable wins. The growth pattern (one rule, then five, then dozens) mirrors LLVM and GCC.
References.
- LLVM's
lib/CodeGen/PeepholeOptimizer.cpp. - GCC's
define_peephole2documentation in the gccint manual. - Cooper and Torczon's chapter on local optimisation.
5. Inline runtime primitives
What it is. For short, frequently-called runtime helpers, replace the bl _rt_* call site with the body of the helper inline. Targets:
_rt_syslib_1020(in-place increment): currentlybl _rt_syslib_1020plus stack save/restore for.1,.3,.4. The actual increment is two instructions. Inlining removes the call overhead and the stack dance.- Unary
&(AND of adjacent bits): a tight loop in the runtime; for short statements this can become an unrolled inline sequence. - Unary
V(OR of adjacent bits): same. - Unary
?(XOR of adjacent bits): same.
Already mentioned as a TODO in middle-end-and-optimisation.md.
Lesson source. Inlining is fundamental to every production optimiser. LLVM's Inliner class with cost analysis. rustc's rustc_mir_transform/inline.rs. Go's unified inliner with budget-based decisions. GHC inlines aggressively, including across module boundaries.
Where in our codebase. src/bootstrap/intercalc.sh:
codegen_next: when the target is a known small syslib label (1020 first, others as they prove valuable), emit the inline body instead of ablplus stack management.codegen_exprfor unary operators: when the operand size and target architecture make the unrolled form competitive (e.g., 16-bit on ARM64), emit the unrolled body.
Algorithm sketch (for syslib 1020). Currently:
bl _rt_syslib_1020 // increments .1 in place
Inline form:
adrp x0, _var_dot_1@PAGE
add x0, x0, _var_dot_1@PAGEOFF
ldrh w1, [x0]
add w1, w1, #1
and w1, w1, #0xFFFF // wrap at 16 bits
strh w1, [x0]
Five instructions versus the call + save/restore + return.
Effort. ~100-200 lines for the first inlining (1020), with a framework that other inlines can plug into. Each subsequent inline is ~30 lines.
Dependencies. Proposal 3 (opt-bisect-limit) is useful so each inline can be individually disabled.
Test strategy. Programs that exercise the inlined operations should still produce correct output. Add tests with INTERCAL_ASM_ONLY=1 that check the absence of bl _rt_syslib_1020 in the generated assembly when the optimisation applies.
Risks. Medium. Register clobbering: the inline must respect the calling-convention assumptions of surrounding code. The body must use only registers that are scratch in the calling convention.
Educational value. Inlining is the single optimisation that buys the most performance in real compilers. A small version of it makes the cost-benefit calculation concrete (number of instructions saved, number of bytes added per call site).
References.
- middle-end-and-optimisation.md "What we leave on the table" section, "Inlining the runtime primitives".
- Cooper and Torczon's chapter on inter-procedural optimisation.
- "Choosing the Best Heuristic for a NLPP" research papers on inliner cost models.
6. Ignore-flag dead-code elimination
What it is. Mirror compute_flag_checks (which eliminates dead per-statement abstain checks) for variable-level ignore flags. Currently every scalar assignment begins with a check of the variable's _ign flag; if the variable is never IGNOREd in the program, the check is dead code.
Lesson source. Same dataflow-DCE pattern as compute_flag_checks. The general technique is described in every compiler textbook; LLVM's ADCE, GCC's tree-ssa-dce.cc.
Where in our codebase. src/bootstrap/intercalc.sh: add a compute_ignore_checks pass that mirrors compute_flag_checks but tracks per-variable ignore-flag mutations. Result is a var_needs_ignore_check associative array keyed by variable. codegen_assign consults it before emitting the prologue.
Algorithm.
compute_ignore_checks() {
typeset -A var_ignored
# Walk every statement; for IGNORE / REMEMBER, mark every named variable
for (( i=1; i<=stmt_count; i++ )); do
case "${stmt_type[$i]:-}" in
IGNORE|REMEMBER)
for v in $(extract_var_list "${stmt_body[$i]}"); do
var_ignored[$v]=1
done
;;
esac
done
# Result: var_needs_ignore_check[var] = ${var_ignored[var]:-0}
}
Then codegen_assign emits the ignore-flag check only when var_needs_ignore_check[$target_var] is set.
Effort. ~100 lines for the pass plus codegen change plus tests.
Dependencies. None.
Test strategy. Programs that never use IGNORE should produce assembly without _ign flag checks. Programs that IGNORE some variables should retain checks only on those.
Risks. Low if the analysis is correct. Soundness check: any variable mentioned in any IGNORE/REMEMBER statement, including dynamic ones reached through an UNKNOWN gerund, must be conservatively flagged.
Educational value. Second example of "static analysis to eliminate runtime checks" in our codebase. Together with compute_flag_checks, the two demonstrate the dataflow-DCE pattern at the statement level and the variable level.
References.
- Our own
compute_flag_checks. - LLVM's
lib/Transforms/Scalar/ADCE.cpp. - GCC's
gcc/tree-ssa-dce.cc.
7. DCE of unreferenced labels
What it is. A pass that detects labels that no statement targets via NEXT, RESUME, COME FROM, ABSTAIN FROM (label), or REINSTATE (label), then drops the label slot. Currently every labelled statement emits a _stmt_LABEL_N: symbol whether or not anyone references it.
Lesson source. Link-time DCE (-ffunction-sections -Wl,--gc-sections) is the production analogue. Every compiler at our scale has some pass that drops unreferenced symbols.
Where in our codebase. src/bootstrap/intercalc.sh: add a compute_label_references pass after resolve_come_from and detect_syslib. Output is a label_referenced associative array. codegen_* functions consult it before emitting _stmt_LABEL_N:.
Algorithm.
compute_label_references() {
typeset -A label_referenced
for (( i=1; i<=stmt_count; i++ )); do
local body="${stmt_body[$i]}"
case "${stmt_type[$i]:-}" in
NEXT)
label_referenced[${stmt_next_target[$i]:-}]=1
;;
COME_FROM)
label_referenced[${stmt_cf_target[$i]:-}]=1
;;
ABSTAIN|REINSTATE)
# Parse body for parenthesised numbers
for n in $(extract_label_targets "$body"); do
label_referenced[$n]=1
done
;;
esac
done
# Mark gerund-targeted statement types as referenced too
# (since ABSTAIN FROM CALCULATING affects every ASSIGN)
}
Effort. ~80 lines.
Dependencies. None.
Test strategy. Generate a program with several labelled statements where most are never referenced. Verify the assembly omits the unreferenced labels. Verify the binary still produces correct output.
Risks. Low if the gerund-based ABSTAIN/REINSTATE conservatively marks all matching statements. The analysis must be over-conservative, never under.
Educational value. Concrete use of the visitor pattern at compile time to compute reachability of named entities.
References.
- The
--gc-sectionslinker flag. - Cooper and Torczon's chapter on dead-code elimination.
8. The Note [...] documentation convention
What it is. Adopt GHC's longstanding convention of writing each cross-cutting design decision as a Note [Name]: explanation block in the source code, with grep as the index. Our existing docs/ chapters cover much of this material at a higher level; the Notes pattern moves the most subtle "why" comments back into the source where they can be evaluated next to the code.
Lesson source. GHC's source is famous for this pattern. Every major design decision in compiler/GHC/Core/Opt/Simplify/Iteration.hs and the rest of the optimiser is annotated with a Note. The pattern is mentioned in ghc-overview.md as one of the "common gotchas" for new contributors.
Where in our codebase. src/bootstrap/intercalc.sh and src/runtime/<platform>.s are the highest-yield targets. Specific places that would benefit:
- The politeness ratio computation in
check_politeness(why 1/5 to 1/3, where the rule comes from, what the boundary cases are). - The COME FROM resolution in
resolve_come_from(why COME FROM creates an implicit edge after the labelled statement, why multiple COME FROMs to one label are rejected). - The branchless conditional ADD pattern (already documented in
intercal_patterns.md, but a Note in the source where it is first used would make it discoverable). - The sed-based platform conversion for Linux ARM64 (why sed is sufficient, why the order matters:
@PAGEOFFbefore@PAGE). - The
_aedonetrampoline removal and corresponding peephole rule (why the trampoline existed, why removing it requires the peephole). - Why
compute_flag_checksis necessary at all (the cost it removes, the conservatism it requires).
Algorithm. None; this is documentation work. Rough form:
# Note [PoliteRatioBoundary]
# The 1/5..1/3 boundary uses inclusive integer arithmetic:
# "polite >= count/5" means "polite*5 >= count", computed as
# `(( polite * 5 >= count ))`. The asymmetry between lower and
# upper bound is intentional: the upper bound is "polite > count/3"
# (strict) per the INTERCAL-72 manual; the lower bound is inclusive
# ("at least 1/5", per the same source).
The convention: every Note has a [Name] tag, the name appears nowhere else in the source, and a contributor uses grep -n 'Note \[Name\]' to find references.
Effort. ~5 minutes per Note. Aim for ten Notes in the first pass; let more accumulate organically.
Dependencies. None. Update AGENTS.md to document the convention.
Test strategy. No test code, but a lint that grep-checks every Note [Name]: definition has at least one Note [Name] reference somewhere (or vice versa).
Risks. Low. Wrong-direction risk: Notes that lie or go stale. Mitigation: include the date the Note was written; re-read on touch.
Educational value. Establishes a culture of documenting why in source. Makes the code self-explanatory at the level production compilers achieve.
References.
- GHC source, especially
compiler/GHC/Core/. Trygit grep -n 'Note \[' compiler/GHC/Core/. - The "Notes in Hawaiian" GHC commentary chapter (informal documentation of the convention).
Tier 2: medium investments
One to several weeks each. Higher educational value; require some refactoring or new infrastructure.
9. Real three-address IR feeding codegen (Phase A)
What it is. Today our codegen_* functions walk the parse tree and emit assembly directly. The --emit-3addr flag prints a three-address listing that is parallel to but not consumed by codegen. This proposal makes the three-address form a real IR: codegen consumes it instead of the parse tree.
Lesson source. Every compiler in Part VII has at least one IR. GIMPLE for GCC, LLVM IR for LLVM-based compilers, MIR for rustc, CLIF for Cranelift, ZIR/AIR for Zig. The benefit is universal: passes are easier to write on a flat instruction list than on a tree, and the IR becomes the natural extension point for future optimisations.
Where in our codebase. A substantial reorganisation of src/bootstrap/intercalc.sh. The shape:
-
New module:
build_ir()runs after analysis, walks the parse tree, emits a flat IR represented as parallel arrays:ir_op[] # operation names (assign, load, mingle, select, unary_and, ...) ir_dst[] # destination operand ir_src1[] # first source ir_src2[] # second source (where applicable) ir_src3[] # third source (rare) ir_stmt[] # back-pointer to source statement for diagnostics ir_count # total instructions -
New module:
lower_ir()walksir_*and emits assembly. The existingcodegen_*functions are decomposed: the parse-tree walk that produces them becomesbuild_ir, the assembly emission becomeslower_ir.
The IR vocabulary is small. INTERCAL operations:
assign:dst = src1load:dst = LOAD(src1)(load named variable)store:STORE(dst, src1)(store to named variable)mingle:dst = MINGLE(src1, src2)select:dst = SELECT(src1, src2)(mask, value)unary_and,unary_or,unary_xor:dst = UNARY_*(src1, width)dim: dimension arraysubscript:dst = ARRAY[src1, src2, ...]next: control transfer to labelresume: control transfer pop Nforget: pop N from NEXT stackcome_from: implicit edge markerabstain,reinstate: flag manipulationignore,remember: variable flag manipulationstash,retrieve: variable stack opsread_out,write_in: I/Ogive_up: program termination
Roughly 20 ops; matches the GIMPLE-shaped vocabulary.
Algorithm. build_ir is a recursive-descent walk: each parse-tree node produces a sequence of IR instructions, with the last instruction's destination being the value of the subexpression. Temporaries are auto-numbered: t0, t1, etc.
lower_ir walks the IR linearly. Each op has a per-op codegen that takes the IR record and emits assembly. For most ops this is mechanical translation. The existing codegen_expr, codegen_assign, etc. are decomposed.
Effort. Significant. ~600-900 lines of zsh net change: new IR data structures (~50 lines), build_ir (~400 lines as a refactor of existing tree-walking logic), lower_ir (~300 lines as a refactor of existing emission logic), small adjustments to all 71 existing tests. One to two weeks of focused work.
Dependencies. None at the source-code level. Conceptually depends on having --emit-3addr already as the read-only version (which we have).
Test strategy. The big win: the existing 71 tests still pass byte-for-byte if the IR is correct. A regression test compares assembly output from a small set of programs before and after the refactor. Plus new tests that check IR shape directly via a --emit-ir-pre-codegen flag.
Risks. High. The refactor touches every codegen path. Risks of subtle assembly differences: IR's expression linearisation may differ from the parse-tree walker's evaluation order in ways that change the generated code. Mitigation: stage the migration. Implement IR + lowering for one statement type at a time (start with GIVE_UP, the simplest), keep the old codegen for the rest, gate each migration behind a flag, validate against the test suite, then delete the old path.
Educational value. Massive. After this proposal, our compiler genuinely has an IR. We can teach IR design, IR transformations, and the value of decoupling parsing from codegen in our own source.
References.
- GCC's GIMPLE:
gcc/gimple.h,gcc/gimplify.cc. - LLVM IR: the LangRef.
- rustc's MIR:
compiler/rustc_middle/src/mir/. - Cranelift's CLIF:
cranelift/codegen/src/ir/. - Cooper and Torczon's chapter on intermediate representations.
10. CFG construction feeding codegen
What it is. With Phase A's IR in place, group IR instructions into basic blocks and represent control flow explicitly as edges between blocks. The codegen then iterates over the block graph rather than the linear IR.
Lesson source. Every compiler in Part VII works on a CFG. Even our existing --emit-cfg flag computes a CFG view; this proposal makes it the representation codegen consumes.
Where in our codebase. Extends Phase A. Add:
bb_first[] # first IR instruction in each block
bb_last[] # last IR instruction in each block
bb_succ[] # successors (comma-separated block IDs)
bb_pred[] # predecessors
bb_label[] # label associated with the block (if any)
bb_count # number of blocks
ir_to_bb[] # IR instruction -> block ID
build_cfg runs after build_ir. lower_ir is restructured to iterate blocks and emit each block's instructions in linear order, with explicit block-end terminators (branches).
Algorithm. Standard leader detection plus block construction:
- Mark IR instruction 0 as a leader.
- For every branching instruction (next, resume, give_up, come_from), the immediately following instruction is a leader. The targets of branches are also leaders.
- Walk from each leader until the next leader; the inclusive range is a block.
- Compute successors per block from the terminator's targets.
- Compute predecessors as the inverse.
Effort. ~300 lines on top of Phase A. One week.
Dependencies. Proposal 9 (Phase A IR).
Test strategy. All 71 existing tests still pass. New tests directly check the CFG structure on canonical programs (linear, COME FROM, NEXT loops).
Risks. Medium. Edge case: COME FROM inserts an implicit edge after a labelled statement, with semantics that the labelled statement's normal fall-through is replaced. The CFG must model this correctly.
Educational value. High. Now we have a CFG that codegen actually uses. A reader can connect "what --emit-cfg shows" with "what gets emitted".
References.
- Cooper and Torczon's chapter on CFG construction.
- LLVM's
llvm/lib/IR/CFG.handllvm/lib/Analysis/CFG.cpp. - The original "Definition of Basic Block" papers (1959 onwards).
11. SSA construction via Braun's algorithm
What it is. Convert the CFG-based IR into Static Single Assignment form using Braun et al.'s on-the-fly algorithm (2013). Each variable definition is fresh; every use names a unique definition. Block parameters (Cranelift's choice; mathematically isomorphic to phi nodes) handle merges.
Lesson source. SSA is the foundation of every modern optimisation pipeline. Cytron et al. 1991 is the classical algorithm; Braun et al. 2013 is the simpler on-the-fly variant that Cranelift's FunctionBuilder uses. Block parameters in place of phi nodes are MLIR's and Cranelift's design choice, more mutation-friendly.
Where in our codebase. Extends Phases A and B. Add per-variable, per-block versioning:
var_defs[var:bb_id] # current SSA-version of var in this block
block_params[bb_id] # ordered list of block parameters (var, type)
build_ir is augmented to call read_variable(var, bb) and write_variable(var, bb, value) instead of direct variable access.
Algorithm. Braun et al. (2013), the canonical implementation. The interface is exactly four operations: writeVariable, readVariable, sealBlock, plus the internal addPhiOperands and tryRemoveTrivialPhi.
writeVariable(variable, block, value):
currentDef[variable][block] = value
readVariable(variable, block):
if currentDef[variable].has(block): # local value numbering
return currentDef[variable][block]
return readVariableRecursive(variable, block)
readVariableRecursive(variable, block):
if block not in sealedBlocks:
val = newPhi(block) # placeholder
incompletePhis[block][variable] = val
elif len(block.preds) == 1:
val = readVariable(variable, block.preds[0])
else:
val = newPhi(block)
writeVariable(variable, block, val) # break cycles BEFORE recursion
val = addPhiOperands(variable, val)
writeVariable(variable, block, val)
return val
addPhiOperands(variable, phi):
for pred in phi.block.preds:
phi.appendOperand(readVariable(variable, pred))
return tryRemoveTrivialPhi(phi)
sealBlock(block):
for variable in incompletePhis[block]:
addPhiOperands(variable, incompletePhis[block][variable])
sealedBlocks.add(block)
tryRemoveTrivialPhi collapses any phi whose operands are all equal (modulo the phi itself) into a single value, then re-checks all users (which may also become trivial). This is what gives "minimal" SSA without dominance frontiers.
Common implementation pitfalls (drawn from Cranelift's cranelift-frontend/src/ssa.rs and Saarland's reference):
- Forgetting
writeVariable(variable, block, val)beforeaddPhiOperandscauses infinite recursion in loops. tryRemoveTrivialPhimust rewrite users in place; if you skip the recursive re-check on users, you get cascades of redundant phis.- A block must be sealed only when all preds are known. For irreducible CFGs constructed in DFS order, sealing happens after the back-edge target's loop is finished.
Effort. ~500 lines on top of CFG. One to two weeks.
Dependencies. Proposal 9 (IR), Proposal 10 (CFG).
Test strategy. Verify SSA invariants programmatically: every ir_dst is unique across the IR. Existing 71 tests still pass with SSA-form IR feeding codegen.
Risks. Medium-high. Easy to get block-parameter handling wrong on irregular control flow (COME FROM creates joins that look unusual). Sealing blocks at the right moment is subtle.
Educational value. Very high. The first time a contributor watches our compiler produce SSA-form IR for a small program is a milestone. Every later optimisation lives on this foundation.
References.
- Braun et al., "Simple and Efficient Construction of Static Single Assignment Form" (CC 2013), https://pp.ipd.kit.edu/uploads/publikationen/braun13cc.pdf.
- Cranelift's
cranelift_frontend::FunctionBuildersource. - Cytron et al. 1991, the canonical paper for the dominance-frontier-based version.
12. Liveness analysis + linear-scan register allocation
What it is. Replace our current "every value goes on the stack" approach with register allocation. Compute live ranges per IR value via backward dataflow, then assign physical registers using Poletto-Sarkar linear scan (1999).
Lesson source. OCaml's asmcomp/linscan.ml is the cleanest production implementation, around 330 lines. Cranelift's regalloc2 is the modern backtracking variant. Every production backend has some register allocator; linear scan is the most pedagogically friendly entry point.
Where in our codebase. Add two passes after Phase B (SSA):
compute_liveness: backward dataflow on the SSA-form IR. For each program point, the set of live values.linear_scan: assign physical registers by Poletto-Sarkar.
Then lower_ir emits register references instead of stack slots wherever possible.
Algorithm. Poletto-Sarkar (1999), verbatim:
LinearScanRegisterAllocation:
active <- {}
for each live interval i, in order of increasing start point:
ExpireOldIntervals(i)
if length(active) == R:
SpillAtInterval(i)
else:
register[i] <- a register removed from pool of free registers
add i to active, sorted by increasing end point
ExpireOldIntervals(i):
for each interval j in active, in order of increasing end point:
if endpoint[j] >= startpoint[i]: return
remove j from active
add register[j] to pool of free registers
SpillAtInterval(i):
spill <- last interval in active # the one with farthest endpoint
if endpoint[spill] > endpoint[i]:
register[i] <- register[spill]
location[spill] <- new stack location
remove spill from active
add i to active, sorted by increasing end point
else:
location[i] <- new stack location # spill the new interval itself
The spill heuristic: spill the interval in active with the farthest endpoint, on the theory that it ties up a register the longest. If the new interval i outlives every active interval, spill i itself.
Pitfalls (from V8 Crankshaft's lithium-allocator.cc and IonMonkey's historical LinearScan.cpp):
- Computing live intervals naively bloats them across non-uses and forces unnecessary spills. Use lifetime holes / split intervals (Wimmer-Mössenböck extension) for production quality.
activemust stay sorted by endpoint; a hash set kills correctness.- When a spilled value is reloaded for a use, you need a scratch register reserved or you need to insert spill-and-reload pairs.
- Two-address machines (x86) need extra care: the destination of an
addclobbers a source, so register hints or move insertion are required.
Effort. ~400-600 lines. Two weeks.
Dependencies. Proposals 9, 10, 11.
Test strategy. Existing tests still pass. New tests verify that simple expressions avoid stack spills (use INTERCAL_ASM_ONLY=1 and grep for absence of unnecessary str/ldr pairs).
Risks. Medium. The hard part is correctness around calls (callee-saved vs caller-saved registers) and around the fact that our runtime expects specific registers for syslib calls.
Educational value. Very high. Register allocation is one of the classical compiler problems, and seeing it implemented over our SSA is real. The contrast with regalloc2 (backtracking) and with graph coloring (Chaitin-Briggs) becomes concrete.
References.
- Poletto and Sarkar, "Linear Scan Register Allocation" (TOPLAS 1999), https://dl.acm.org/doi/10.1145/330249.330250.
- OCaml's
asmcomp/linscan.mlfor the canonical small implementation. - Cranelift's regalloc2 docs for the modern backtracking variant.
- Briggs et al., "Coloring Heuristics for Register Allocation" for the graph-coloring alternative.
13. Sparse Conditional Constant Propagation (SCCP)
What it is. Wegman-Zadeck's SCCP (1991) extends our existing eval_const (which folds whole-constant subexpressions) with a dataflow that propagates constants across statement boundaries and prunes unreachable branches.
Lesson source. SCCP is the canonical example of a flow-sensitive constant-folding optimisation. Wegman-Zadeck's paper. LLVM's lib/Transforms/Scalar/SCCP.cpp. GCC's tree-ssa-ccp.cc.
Where in our codebase. A new pass after Phase B (SSA) and before lowering. Operates on SSA-form IR.
Algorithm. Wegman-Zadeck. Three-element lattice per SSA value:
TOP < CONST(c) < BOTTOM
TOP means "not yet visited", CONST(c) means "proven equal to c", BOTTOM means "non-constant or runtime-dependent".
Meet operator (used at phis):
TOP ⊓ x = xBOTTOM ⊓ x = BOTTOMCONST(c) ⊓ CONST(c) = CONST(c)CONST(c) ⊓ CONST(d) = BOTTOMwhenc ≠ d
Algorithm:
init:
for every SSA value v: lattice[v] = TOP
for every CFG edge e: executable[e] = false
CFGWorklist = { entry_edge }
SSAWorklist = {}
while CFGWorklist not empty or SSAWorklist not empty:
if CFGWorklist not empty:
edge (B_pred -> B) = pop()
if executable[edge]: continue
executable[edge] = true
for each phi in B: visitPhi(phi)
if this is the first executable in-edge of B:
for each non-phi instruction inst in B: visitInst(inst)
if B has only one out-edge: push that edge onto CFGWorklist
else:
v = pop(SSAWorklist)
for each use u of v:
if u is a phi: visitPhi(u)
else if the block containing u has any executable in-edge: visitInst(u)
visitPhi(phi):
new = TOP
for each (pred, val) in phi.operands:
if executable[pred -> phi.block]:
new = new ⊓ lattice[val]
if new != lattice[phi]:
lattice[phi] = new
push phi onto SSAWorklist
visitInst(inst):
if inst is a branch on condition c:
if lattice[c] == CONST(true): push true-edge
elif lattice[c] == CONST(false): push false-edge
elif lattice[c] == BOTTOM: push both edges
else (TOP): push nothing yet
else:
new = evaluate(inst, lattice) # arithmetic on lattice values
if new != lattice[inst.result]:
lattice[inst.result] = new
push inst.result onto SSAWorklist
Pitfalls (from LLVM's lib/Transforms/Scalar/SCCP.cpp and Go's cmd/compile/internal/ssa/sccp.go):
evaluatemust handleTOPoperands by returningTOP(notBOTTOM); otherwise you lose precision on first visit.- Forgetting to gate the phi meet by
executable[pred -> block]collapses to ordinary CP; you get fewer constants. - Once
executable[edge]flips totrueit must never flip back. The lattice descends monotonically. - After SCCP completes, the rewrite step is mandatory: replace
CONST(c)defs with literals; delete blocks reached only by non-executable edges. Skipping the rewrite makes SCCP a no-op.
Effort. ~300-500 lines on top of SSA.
Dependencies. Proposals 9, 10, 11.
Test strategy. Programs whose constants resolve across statements get folded. Compare assembly before and after.
Risks. Medium. Termination: the lattice has finite height (TOP → CONST → BOTTOM is at most 2 steps per value), so termination is guaranteed. Correctness: meet operator must be monotone (TOP ⊓ x = x; BOTTOM ⊓ x = BOTTOM; CONST(c) ⊓ CONST(c) = CONST(c); CONST(c) ⊓ CONST(d) = BOTTOM if c != d).
Educational value. SCCP is one of the most cited passes in compiler textbooks. Implementing it on our compiler closes the gap from "we have constant folding" to "we have proper constant propagation".
References.
- Wegman and Zadeck, "Constant Propagation with Conditional Branches" (TOPLAS 1991), https://dl.acm.org/doi/10.1145/103135.103136.
- LLVM's
lib/Transforms/Scalar/SCCP.cppandIPSCCP.cppfor production implementation. - Muchnick's Advanced Compiler Design and Implementation covers SCCP in detail.
14. Csmith-INTERCAL: random program generator + differential testing
What it is. A generator for valid INTERCAL programs that produces well-defined programs with predictable behaviour, then differential-tests our compiler against either C-INTERCAL (via the user's installed ick) or against our own pure-vs-native syslib. Bugs surface as output divergence.
Lesson source. Csmith (Yang et al., PLDI 2011) found hundreds of bugs in GCC and LLVM. YarpGen (OOPSLA 2020) is the modern successor. Crater is the rustc analogue. The pattern of "generate, compile, run, differential" finds bugs that exhaustive testing misses.
Where in our codebase. A new tool: tools/csmith_intercal.sh (generator) plus a runner tests/run_csmith_diff.sh.
Algorithm. Random generation strategies:
- Strict subset. Limit to a "safe" INTERCAL subset that excludes:
- Integer overflow paths (use only constants in safe ranges).
- Array indexing without bounds-check guarantees.
- I/O that depends on user input.
- The politeness rule risks (target ratios near 1/4 to stay safely in [1/5, 1/3]).
- Generate by template. Build programs from templates: a sequence of
DO .V <- #Nassignments, optional NEXT to a known-safe label, GIVE UP. No COME FROM (introduces complexity), no probability (introduces nondeterminism). - Compute expected output. Since the generator chose every value, the expected output is computable in pure shell at generation time.
- Validate. Compile with
intercalc.sh, run, compare actual stdout against expected. Optionally also compile with--pure-sysliband compare; optionally compile withick(C-INTERCAL) and compare.
Effort. ~600-1000 lines zsh: the generator, the expected-output computer, the differential runner. Two weeks for an MVP, plus ongoing work to expand the language subset coverage.
Dependencies. None.
Test strategy. Bootstrap by generating programs we know to be correct (pure constant assignments and outputs). Then expand carefully; a generator that produces a divergence is itself a unit of evidence.
Risks. Medium-high. Generating UB-free INTERCAL is non-trivial because INTERCAL's runtime errors are many (the ICL000 family) and easily triggered by random programs. The subset must be conservatively chosen.
Educational value. Very high. Differential testing is the most powerful debugging technique for compilers. Adding it to our project converts "we have 71 tests" to "we have 71 + an unbounded stream of generated tests".
References.
- Yang, Chen, Eide, Regehr, "Finding and Understanding Bugs in C Compilers" (PLDI 2011).
- Livinskii et al., "Random Testing for C and C++ Compilers with YARPGen" (OOPSLA 2020).
- Csmith on GitHub: https://github.com/csmith-project/csmith.
- The Crater documentation for rustc.
15. Declarative peephole rules (Go .rules / Cranelift ISLE style)
What it is. Replace the ad-hoc peephole_optimize function (currently growing as we add rules) with a small declarative DSL. Each rule is a pattern-match plus a rewrite. A rule compiler converts the DSL into zsh code that runs at compile time.
Lesson source. Go's cmd/compile/internal/ssa/gen/*.rules files (covered in detail in go-overview.md) and Cranelift's *.isle files (cranelift-overview.md) are the production examples. The same idea is in GCC's machine descriptions (define_peephole2).
Where in our codebase. A new directory tools/peephole/:
peephole/rules.peep: rule definitions (DSL source).tools/gen_peephole.sh: rule compiler. Producespeephole/rules_generated.sh.peephole/rules_generated.sh: included byintercalc.sh(or sourced as needed).
DSL example:
# Drop unconditional branch immediately followed by its target
rule "branch_to_next" {
pattern: 'b LABEL'
followed-by: 'LABEL:'
action: drop
}
# Redundant identity move
rule "redundant_mov" {
pattern: 'mov REG, REG'
action: drop
}
# Branch-to-branch
rule "jmp_to_jmp" {
pattern: 'b L1'
match-block-only-instr: 'L1: b L2'
action: 'b L2'
}
Algorithm. The rule compiler:
- Parses the
.peepfile into an AST. - For each rule, generates a zsh function that detects the pattern in the assembly text and applies the rewrite.
- The compiled rules are bundled into a single function called by
peephole_optimize.
Effort. ~400-600 lines for the rule compiler plus ~5 initial rules.
Dependencies. Proposal 4 (we should have a body of peephole rules to migrate).
Test strategy. Per-rule test that constructs assembly matching the pattern, runs the peephole, asserts the rewrite. Plus the existing 71 tests continue to pass.
Risks. Medium. The DSL is its own language to maintain; adding "edge case" patterns may require extending the DSL. Mitigation: keep the DSL deliberately restricted; complex rules stay as zsh code.
Educational value. Very high. The same idea (declarative pattern matching for compiler transformations) is in three of the production compilers we cover. Building our own teaches the tradeoffs (DSL flexibility vs. complexity, generated code vs. hand code).
References.
- Cranelift's ISLE:
cranelift/docs/isle-language-reference.md. - Go's
.rulesfiles:cmd/compile/internal/ssa/gen/. - GCC's
define_peephole2in the gccint manual. - Bravenboer and Visser, "Designing Syntax Embeddings and Assimilations for Language Libraries", as background on rule-based DSLs.
Tier 3: major undertakings
Multi-month projects that change the compiler's architecture or scope.
16. Stage3 self-hosted real compiler completion
What it is. Today src/compiler/compiler.i is a template-passthrough MVP: it dispatches by cksum of the source to a pre-generated assembly template. src/compiler/stage3.i is the evolving real compiler that reads source and emits assembly through an actual lexer/parser/codegen path. Stage3 is currently blocked on implementing a loop primitive in pure INTERCAL.
The proposal: complete stage3 to the point where it can compile our own tests and reach a 3-generation fixpoint.
Lesson source. OCaml's boot/ocamlc shows that a fully self-hosted compiler in a small language is achievable. Zig's stage1 → stage2 transition is the modern parallel.
Where in our codebase. src/compiler/stage3.i: extend from byte-probe detectors (current state) through:
- Real character-by-character tokenizer
- Statement classifier
- Expression parser
- Codegen emitting the same assembly templates we pre-generate today
- Eventually, full parity with
intercalc.sh's output
Algorithm. Several open problems to resolve first:
- Loop primitive. Two paths (per
memory/project_status.md):- Adopt a non-standard extension (e.g., computed COME FROM) that gives us a real conditional loop.
- Use a ~30-statement "abstain dance" scaffold per logical loop (pure INTERCAL, expensive but works).
- String construction. TTM (Turing Text Model) array building for emitting assembly text.
- Hash table or symbol table. Need to track variables, labels, statement types in a structure that pure INTERCAL can manage.
- File I/O. Already provided by Label 666 syscalls.
Effort. Many months of focused INTERCAL-in-INTERCAL work. 5,000-10,000 lines of INTERCAL.
Dependencies. Resolving the loop-primitive question. Either:
- Decide to extend the language (one-time decision, deviates from INTERCAL-72 but is well within "language extension" precedent).
- Commit to the abstain-dance approach (multiplies code size).
Test strategy. tests/run_stage3_tests.sh already exists with 4 tests on the byte-probe detectors. Extend incrementally: each new feature gets tests; reach feature parity with the bootstrap test suite (33 tests) as the long-term milestone.
Risks. High. Multi-month, INTERCAL-language constraints are punishing. The loop-primitive question is an architectural fork.
Educational value. Reaches the dream the project is named for: a real INTERCAL self-compiling compiler. Without this, the "self-hosted" label is partly aspirational.
References.
memory/project_status.mdfor the current blockers.docs/intercal_patterns.mdfor the verified patterns we have.- OCaml's
boot/ocamlcand the bootstrapping documentation. - Zig's
zig1.wasmblob and theGoodbye to the C++ Implementation of Zigpost.
17. Bytecode tier (OCaml-style)
What it is. Add a bytecode output mode complementing the native output. Bytecode is a portable instruction stream interpreted by a VM written once and shared across platforms. Compilation is faster (no assembly emission, no cc invocation); execution is slower (interpretation overhead). The VM is implemented as platform-specific assembly.
Lesson source. OCaml's dual ocamlc (bytecode) / ocamlopt (native) coexistence since 1996. Java's bytecode + JIT model. Many languages have considered or adopted this split.
Where in our codebase.
src/bytecode/bytecode.md: ISA spec.src/bytecode/runtime/<platform>.s: VM implementation per platform.src/bootstrap/intercalc.sh: new--bytecodeflag andcodegen_bytecode_*functions.
Algorithm. Define a small stack-based ISA:
LOAD vN: push variable's valueSTORE vN: pop and storeMINGLE,SELECT: pop 2, push resultUNARY_AND,UNARY_OR,UNARY_XOR: pop 1, push resultCONST imm: push immediateBRANCH offset: conditional/unconditional branchCALL syslib_label: invoke a syslib routineREAD_OUT,WRITE_IN,GIVE_UP: I/O and exit- (about 30 opcodes total)
The bytecode is a simple stream of (opcode byte, operand bytes) tuples. The VM is a switch-on-opcode dispatch loop.
Effort. ~1500-2500 lines: ISA spec, VM per platform (3 platforms), codegen, tests. Multi-month.
Dependencies. None functionally; conceptually depends on having a stable IR (Phase A, proposal 9) that bytecode codegen can also consume.
Test strategy. Programs run identically as bytecode and as native; existing 71 tests are duplicated to run in both modes; new tests/test_bytecode_*.sh checks the VM's specific behaviour.
Risks. Medium-high. Doubles the testing surface. The VM has its own bug class (interpreter loops, dispatch errors). Maintenance cost for two output paths.
Educational value. High. The contrast between bytecode and native compilation is a major theme in compiler design (OCaml's dual-target story is one of its distinguishing features).
References.
- Leroy, "The ZINC Experiment: An Economical Implementation of the ML Language" (1990).
- OCaml's
bytecomp/andruntime/directories. - Java Virtual Machine Specification.
18. Mini LSP server
What it is. A Language Server Protocol implementation for INTERCAL. Provides editor integration: diagnostics, hover, go-to-definition (for labels), find-references, symbol outline.
Lesson source. rust-analyzer, gopls, ZLS (Zig Language Server), clangd, Aleksey Kladov's "Three Architectures for a Responsive IDE". LSP is the standard interface for IDE/editor integration.
Where in our codebase. New top-level directory: src/lsp/. Implementation language is open. Options:
- Pure zsh: doable but unusual.
- Python: easier IPC handling.
- Rust: most natural for LSP given the tooling ecosystem (the
lsp-servercrate).
Algorithm. LSP is a JSON-RPC protocol. The server:
- Reads JSON-RPC messages from stdin.
- For each request:
textDocument/didOpen,didChange: re-parse the document, store diagnostics.textDocument/hover: return INTERCAL-specific info about the symbol under cursor.textDocument/definition: for labels, return the location of the labelled statement.textDocument/references: find every NEXT/RESUME/COME FROM/etc. that references a label.
- Writes responses to stdout.
Effort. ~1500-2500 lines depending on language choice.
Dependencies. The parser needs to be invocable from outside intercalc.sh. Either factor it out or run intercalc.sh --emit-tokens and parse the output.
Test strategy. Integration tests with tower-lsp-test-fixtures or equivalent. End-to-end test via VS Code's Extension Test Runner.
Risks. High maintenance burden. LSP servers are non-trivial; nobody types INTERCAL inside an IDE today, so the cost-benefit is poor unless we view it primarily as an educational artefact.
Educational value. High but specialised. Teaches LSP architecture, incremental parsing, IDE-friendly error recovery. Less directly applicable to compiler engineering specifically.
References.
- LSP specification: https://microsoft.github.io/language-server-protocol/.
- rust-analyzer source: https://github.com/rust-lang/rust-analyzer.
- Aleksey Kladov, "Three Architectures for a Responsive IDE".
19. DO INCLUDE multi-file extension
What it is. A non-standard language extension that lets one INTERCAL source file include another. Statement: DO INCLUDE "other.i". The included file is expanded inline at parse time.
Lesson source. C's #include, Modula-2's WITH, Ada's with. The simplest form of modular composition.
Where in our codebase. src/bootstrap/intercalc.sh: the parser detects DO INCLUDE "..." statements and recursively expands them before the rest of analysis.
Algorithm. Recursive textual expansion in read_source:
- Read the main file.
- Walk lines; when an
INCLUDEstatement is found, replace it with the contents of the named file. - Recurse: included files may include further files.
- Track a stack of current includes to detect cycles.
- Process each file at most once (to avoid duplicate label conflicts).
Effort. ~200-500 lines depending on label-namespace handling.
Dependencies. Depends on a decision about label scoping. Two options:
- Flat namespace. All labels share one space; conflicts are errors. Simple, but limits modularity.
- Per-file namespace. Labels are scoped to their file. Requires renaming during inclusion.
Test strategy. Programs split across files compile correctly; label resolution works across the boundary; cycle detection rejects circular includes.
Risks. Medium. Language change; not standard INTERCAL. Once shipped, supporting it forever.
Educational value. High. Teaches the simplest form of inter-file composition, the precondition for any real linking story. Without multi-file support, link-time optimisation has nothing to optimise.
References.
- C's
#includesemantics in the C standard. - Module systems in Modula-2, Ada, Standard ML.
- Discussion of include-vs-import in language-design literature.
20. Effect/error system: static analysis of ICL errors
What it is. A type-system-flavour static analysis that computes, for each statement, the set of ICL runtime errors (E000, E017, E123, E129, E139, E200, E240, E241, E275, E436, E533, E555, E562, E579, E621, E632, E633) that the statement could raise. Statements proven to raise no errors of a given class can have their runtime checks removed.
Lesson source. Haskell's strictness analysis. Koka's effect system. Rust's Result-typed return values. The general idea is "track properties of values through the program by dataflow".
Where in our codebase. A new pass after Phase B (SSA) that operates on the IR:
- For each statement, compute the set of error codes it could raise (based on the operations it performs).
- Propagate forward through the CFG: a statement's reachable error set is the union of its own errors and any caller's errors that pass through.
- Where the analysis proves a check is unreachable, remove it.
Algorithm. A forward dataflow analysis. The lattice is the powerset of error codes. The transfer function: for each statement, add the errors specific to its operation type; propagate to successors.
For example, a STASH statement on a never-RETRIEVEd variable cannot raise E436. A RESUME #N where N is a constant ≠ 0 cannot raise E621.
Effort. ~400-700 lines on top of SSA.
Dependencies. Proposals 9, 10, 11.
Test strategy. Programs that statically cannot raise certain errors should compile to assembly that lacks the corresponding runtime checks. Empirically verify code-size reductions on representative programs.
Risks. Medium-high. Soundness: the analysis must over-approximate the error set; missing an error is unsafe. Conservatism: some errors (E000, E017) can theoretically arise from any path; the analysis can prove their absence only in narrow cases.
Educational value. Very high. Effect-system-style analysis is the bridge from "imperative compilers" to "research-grade program analysis". The technique transfers to Koka, Eff, OCaml 5 effect handlers, and similar.
References.
- "Algebraic Effects and Effect Handlers" (Plotkin and Pretnar 2009).
- Daan Leijen's papers on Koka.
- GHC's strictness analysis:
compiler/GHC/Core/Opt/DmdAnal.hs. - Cousot and Cousot, "Abstract Interpretation: A Unified Lattice Model" (POPL 1977).
Out of scope (deliberately)
For completeness, the following are not proposed despite appearing in techniques-we-lack.md:
- Garbage collection: INTERCAL has no allocation. Arrays go through
mmapdirectly; no general-purpose heap. - JIT compilation: AOT serves us. Adding a JIT would mean a runtime mmap-and-emit infrastructure for no application benefit.
- ML/GPU compiler features: no numerical workload to justify.
- Borrow checker / ownership types: no references in the language.
- Type inference: four monomorphic types; nothing to infer.
- Verifying compiler in Coq: no formal semantics for INTERCAL exists worth proving against.
- Polyhedral optimiser: no nested numerical loops over multidimensional arrays.
- Tracing JIT: AOT only.
Each of these is documented with its specific rationale in techniques-we-lack.md.
Recommended sequence
If we adopt several proposals, the order matters because some build on others. A pragmatic sequence:
- Tier 1 (one to two sessions). Proposals 1, 2, 3 (the inspection/timing/bisect flags) in one TDD session. Then 4, 5, 6, 7 (peephole, inlining, ignore-DCE, label-DCE) over a few sessions.
- Documentation pass. Proposal 8 (Notes convention) in parallel; very low cost, accumulates value over time.
- Phase A landing (one to two weeks). Proposals 9 + 10 (real IR + CFG feeding codegen). Architectural lift; do this when the Tier 1 backlog is empty.
- SSA + classical optimisations (one month). Proposals 11 (SSA) + 12 (linear-scan regalloc) + 13 (SCCP) build on Phase A.
- Differential testing (one to two weeks, parallel). Proposal 14 (Csmith-INTERCAL) is orthogonal to Phase A and can land independently.
- Declarative rules (parallel). Proposal 15 (declarative peephole) is orthogonal; valuable once we have several rules in proposal 4.
- Tier 3 (multi-month, optional). Proposals 16-20 are major commitments. None is required for the project's identity. Stage3 (16) is the most defensible if the goal is "true self-hosting"; bytecode (17) if portability; LSP (18) if IDE story; INCLUDE (19) if modularity; effect system (20) if research interest.
Each proposal in this chapter is independently committable. The 71 existing tests are the regression armour for all of them.
Closing
The picture this chapter paints is not "we should do all twenty". It is "here are the twenty doors; we know what is behind each; we can open the ones that fit our path".
The Tier 1 set, taken together, would extend the compiler's introspection and optimiser surface measurably without changing its shape. The Tier 2 set, particularly Phase A through SSA-based passes, would move the compiler from "no IR" to "real IR with classical optimisations": educationally the largest jump available to us. The Tier 3 set is for when the project's ambitions grow.
Whatever we pick, the discipline is the same: TDD per AGENTS.md, one proposal per commit, regression tests that match production-compiler conventions, documentation chapters as deliverables.
The book is now richer than the compiler. Part VII names ten production compilers; Part VIII catalogues their techniques; this chapter says which of those techniques we could adopt and how much each would cost. The next move is whichever the maintainer wants.
Improvement-proposals status (live tracker)
This document tracks the implementation status of every proposal in improvement-proposals.md. It is updated as work progresses.
Tier 1 (8 proposals): all DONE
| # | Name | Status | Commit |
|---|---|---|---|
| 1 | --emit-tokens flag | DONE | c549fc6 |
| 2 | --time-report flag | DONE | 7f5ac36 |
| 3 | --opt-bisect-limit=N flag | DONE | 10aa092 |
| 4 | More peephole rules | DONE | 56501a9 |
| 5 | Inline runtime primitives (syslib 1020) | DONE | a478b3d |
| 6 | Ignore-flag DCE | DONE | d9f7c84 |
| 7 | DCE of unreferenced labels (reframed as warning) | DONE | 51d3ef2 |
| 8 | Note [Name] documentation convention | DONE | 68f7113 |
Tier 2 (7 proposals): all DONE (with codegen integrations)
| # | Name | Status | Commit |
|---|---|---|---|
| 9 | Real three-address IR | DATA STRUCTURE + BUILDER | bc85558 |
| 10 | CFG construction | INSPECTION via --emit-cfg | bf44fe3 |
| 11 | SSA via Braun | ANALYSIS-LAYER --emit-ssa | e46d105 |
| 12 | Linear-scan regalloc | ANALYSIS-LAYER --emit-regalloc | 99d5a35 |
| 13 | SCCP on SSA | ANALYSIS + CODEGEN INTEGRATION | 4df0351, 73c39ae |
| 14 | Csmith-INTERCAL fuzzer | DONE | (earlier session) |
| 15 | Declarative peephole rules DSL | DONE | (earlier session) |
Tier 2 additions to codegen
Proposal 13 now feeds the existing codegen with cross-statement
constants: when a variable is statically known to hold a literal at
the use site, codegen substitutes mov w0, #N instead of emitting
the load. Sound conservatism documented in Note [VarConstantProp];
gated by opt_bisect_check per substitution.
Proposal 9 now ships the IR data structure (ir_ops[]) plus a
build_ir builder. Codegen does not yet consume the IR; the rewrite
to consume it is the remaining future work. The IR is exposed via
--emit-ir-real for inspection.
Tier 3 (5 proposals): substantive landings
| # | Name | Status | Commit |
|---|---|---|---|
| 16 | Stage3 self-hosted real compiler | ROADMAP DOC | 8a64616 |
| 17 | Bytecode tier (OCaml-style) | EXTENDED SUBSET | f52f922 |
| 18 | Mini LSP server | SEMANTIC TOKENS + HOVER + MULTI-DIAG | c65247e |
| 19 | DO INCLUDE multi-file extension | DONE | c11311f |
| 20 | Effect/error static analysis | ANALYSIS + CODEGEN INTEGRATION | 4303acb, 6d834d5 |
Tier 3 additions to codegen
Proposal 20 now drives runtime-check elimination: per-statement analysis identifies ASSIGNs of literal #N where the value cannot overflow the target type, and codegen skips the cmp + b.hi _rt_error_E275 sequence. Note [E275Elim] documents the analysis.
Proposal 17 (bytecode tier) extended to a non-trivial subset: LOADI/LOADI2, COPY/COPY2, STASH/RETRIEVE with E436, IGNORE/REMEMBER, twospot variables. Test suite grew from 3 to 7 cases.
Proposal 18 (LSP) extended to advertise hoverProvider and semanticTokensProvider. Hover returns markdown documentation for INTERCAL keywords; semanticTokens returns the LSP delta-encoded token array classifying keyword/variable/number/label. publishDiagnostics now emits one diagnostic per ICL line on stderr, classifying ICLnnnW as Warning and ICLnnnI as Error.
Final tally
In the cumulative session series:
-
15/20 fully implemented or DONE-with-integration: Tier 1: 1, 2, 3, 4, 5, 6, 7, 8 (8/8). Tier 2: 13 (with codegen integration), 14, 15 (3/7). Tier 3: 17 (extended), 18 (extended), 19, 20 (with codegen integration) (4/5).
-
5/20 as analysis-layers / inspection / data-structure / roadmap: Tier 2: 9 (data structure + builder), 10 (--emit-cfg), 11 (--emit-ssa), 12 (--emit-regalloc) (4/7). Tier 3: 16 (roadmap doc) (1/5).
-
0/20 fully unimplemented.
Test growth: 71 (start) -> 130+ (end), across 20+ test scripts.
Updates in 2026-05-09 session
| # | Name | Status | Commit |
|---|---|---|---|
| 11 | IR-driven codegen | INCREMENTAL OPT-IN (INTERCAL_NEW_IR=1) | c1c8ac3 |
| 12 | Linear-scan integration | DECISIONS EXPOSED + HINTS (INTERCAL_REGALLOC_HINTS=1) | b2ea50d |
| 13 | Wegman-Zadeck SCCP | FULL ALGO behind --emit-sccp-wz | d3bde03 |
| 16 | Stage3 loop primitive | DECIDED (NEXT FROM, see docs/loop-extension.md) | bd008c9, b26b824 |
| 17 | Bytecode tier | + ARITHMETIC OPERATORS (mingle, select, unary) | ebc2d87 |
| 18 | LSP server v0.3.0 | + COMPLETION + GO-TO-DEFINITION | eacb5ef |
| 20 | Effect-driven elim | EXTENDED to E621 + E436 | 8724fba |
Substantive deltas:
-
NEXT FROM extension (#16): chose Option B (CLC-INTERCAL-style) over scaffolding or new ABSTAIN-loop syntax. Both unconditional and conditional forms emit a single
bortbnzwith no NEXT-stack push, so finite loops are now sound (no E123 risk on the 80th iteration). docs/loop-extension.md captures the rationale; tests/test_next_from.i and tests/test_stage3_loop.i exercise a counter loop and a 5-byte array scan. -
IR-driven codegen scaffold (#11): the legacy tree-walk path remains the source of truth. INTERCAL_NEW_IR=1 routes supported statement types through lower_ir_for_stmt() and falls back to legacy for unsupported types. Currently only GIVE_UP is wired through. The migration pattern is one statement type at a time, each gated independently, so future PRs can extend without disturbing the legacy path.
-
Regalloc hints (#12): compute_regalloc_decisions populates
var_reg[<varspec>]andvar_spilled[<varspec>]. With INTERCAL_REGALLOC_HINTS=1, codegen prefixes spot-variable stores with// regalloc: spot_N -> R<n>comments (visible in the intermediate assembly). Behavioural codegen change deferred. -
Wegman-Zadeck SCCP (#13): emit_sccp_wz implements the proper worklist algorithm: TOP/CONST/BOTTOM lattice, executable-edge gating (exec_into[i] = 1 when an incoming edge is proven reachable), monotone meet at confluence points, and per-stmt outgoing[] tracking. The simpler emit_sccp linear-walk dump remains as a teaching variant.
Genuinely remaining future work
For a session that wants to go deeper:
- Stage3 substage 1 wired into stage3.i (proposal 16 continuation): the loop mechanic is verified end-to-end in tests/test_stage3_loop.i; replacing the byte-probe scaffolding in src/compiler/stage3.i with a real tokeniser pass using NEXT FROM is the next stage. Substages 2-8 of the roadmap follow.
- IR-driven codegen for more statement types (proposal 11 continuation): extend lower_ir_for_stmt() to handle STASH/RETRIEVE/IGNORE/REMEMBER/READ_OUT, then ASSIGN. Each is independently guarded by INTERCAL_NEW_IR.
- Regalloc behavioural codegen (proposal 12 continuation):
when var_reg[X] is set and there's no intervening control-flow
stopper between the def and the use, emit
mov w_dst, w<r>instead ofldr w_dst, [_spot_X]. Requires a register-state cache that resets at every NEXT/COME FROM/RESUME boundary. - SCCP-WZ extension to syslib results (proposal 13 continuation): currently arithmetic syslib calls collapse to BOTTOM. Modelling them in the lattice (e.g., 1009 of two constants is a constant) would feed the codegen-side const-prop. Also: COME FROM source edges are not yet in preds[], so the meet at COME FROM target sites is not full.
- Bytecode parity with native (proposal 17): the bytecode VM has arithmetic operators but lacks COME FROM, NEXT, arrays. Each requires real control-flow plumbing in the VM dispatch.
- Effect-driven elim for more error classes (proposal 20): already extended to E621 and E436. E123 (stack overflow), E129 (undef label), E632 (resume past stack bottom) are candidates when static depth analysis is feasible.
Each is a focused multi-week project. None is required for the project's identity; each is depth.
Updates: 2026-05-09 (late session)
The deferred items above were partially or fully resolved in the late 2026-05-09 work. Status now:
| Item from the list above | Status |
|---|---|
| 2 — IR for more types | DONE (literal ASSIGN, var-copy, IGNORE/REMEMBER, STASH/RETRIEVE via DELEGATE; READ_OUT scalar) |
| 4 — SCCP-WZ syslib + COME FROM edges | DONE (1009/1010/1020/1030/1040/1050/1500/1509/1510/1520/1530/1540/1549/1550/1900/1910 + COME FROM source edges + INTERCAL_SCCP_WZ_FEED to feed codegen) |
| 5 — Bytecode parity | DONE (full subset: arithmetic, COME FROM, NEXT/RESUME/FORGET/NEXT FROM, ABSTAIN/REINSTATE label+gerund, multi-dim arrays, TTM in/out, WRITE IN, syslib eval, Label 666 file I/O, probability) |
| 6 — Effect-elim for more codes | DONE (E123 stack overflow, E240 zero-dim, E241 subscript bounds, E632 resume past stack bottom, plus E000 codegen bug fix in negated UNKNOWN) |
Still genuinely deferred:
- 3 (regalloc behavioural codegen): the register-keeping change
needs cross-statement state with careful invalidation. The
comments-only path under
INTERCAL_REGALLOC_HINTS=1provides the data structure. Multi-day audit risk over 35 tests. - Stage3 substages 2-7 + fixpoint: still multi-month INTERCAL. Substage-1-style demonstrators (byte loader, D counter, P counter) prove the loop primitive and equality test work reliably; the parser, semantics, codegen, and BSS emission layers remain to be written.
Deltas in this session:
- New flag
--emit-helpself-documenting CLI. BC_TRACE=1for bytecode VM debugging.tools/lint_zsh_quirks.shcatches the bug class of barelocal NAMEfollowed byfor NAMEand the LSP-style${var//\\X/$'\\X'}substitution that doesn't interpret.- New mdBook chapters:
bytecode-evolution.mdandeffect-elimination.md.
Stage 3 self-hosted real compiler: roadmap
This document describes the path from the current src/compiler/stage3.i (byte-probe detectors, ~110 lines) to a real INTERCAL self-hosted compiler that can parse arbitrary INTERCAL source and emit ARM64 assembly. It is the roadmap for proposal #16 in improvement-proposals.md.
Current state
src/compiler/compiler.i is the MVP self-hosted compiler. It dispatches by cksum of the source to a pre-generated assembly template per known test program. This is sound for our 25 self-hosted tests but trivially insufficient for novel inputs.
src/compiler/stage3.i is the evolving self-hosted compiler. As of this commit it implements byte-probe detectors that recognise specific source-byte patterns (D, O, P, A as the first byte; "DO" as the first two bytes). Each probe maps to a different fixed-output assembly template. Total stage3 surface as of writing: 4 tests passing in tests/run_stage3_tests.sh.
The blocker: loops in INTERCAL
A real compiler must:
- Read source character by character (loop over input length).
- Tokenise (loop over tokens within each statement).
- Build a per-statement table (one iteration per statement).
- Walk that table emitting assembly (one iteration per statement).
INTERCAL provides no for/while construct. Loops must be synthesised from NEXT/RESUME/COME FROM. Empirically (documented in docs/intercal_patterns.md and memory/bugs_learned.md):
- The standard "computed RESUME" idiom for a two-way branch only unwinds to a parent frame; it does not branch within the same frame. A loop with conditional break attempted this way always raises
ICL632I(RESUME ran past the bottom of the NEXT stack). - The branchless conditional ADD pattern works for compute-only loops with a fixed unrolled bound (used in stage3.i for byte-1, byte-2, byte-N probes). Each unrolled iteration costs a fixed overhead.
Three options for implementing a real loop primitive:
Option A: non-standard (label)* extension
Define a non-standard "while abstain (label)" that loops back to the labelled statement until the corresponding ABSTAIN flag is set. Runtime support: a counter that decrements each iteration with bound enforcement.
Pros: clean syntax, fits one statement. Cons: non-standard. INTERCAL purists object.
Option B: (label) NEXT FROM extension
Borrowed from CLC-INTERCAL. Like NEXT but pushes the current address as the target of an implicit COME FROM, creating a structured loop without explicit RESUME.
Pros: closer to existing INTERCAL machinery. Cons: non-standard.
Option C: scaffolding pattern
For each logical loop, expand to ~30 INTERCAL statements implementing a counter, abstain-flag-toggling break condition, and explicit NEXT/RESUME dance. Pure standard INTERCAL.
Pros: portable to any standard INTERCAL. Cons: stage3.i would balloon to thousands of lines for what is conceptually a small compiler.
Recommended path: Option A or B, with rationale
A real self-hosted compiler is a worthy goal. The 5,000-10,000-line stage3 implementation effort is justified only with a workable loop primitive. Standard INTERCAL is too constrained.
The recommendation: pick Option A or B as a documented language extension, parallel to our already-non-standard Label 666 syscall extension. Document the choice in AGENTS.md and docs/666.md (or a new docs/loop-extension.md).
Loop primitive: resolved
The loop-primitive question is resolved. We adopted Option B (NEXT FROM)
with the conditional refinement (LABEL) NEXT FROM <expr>. See
docs/loop-extension.md for the design and tests/test_next_from.i
plus tests/test_stage3_loop.i for end-to-end verification.
The latter is the substage-1 mechanic in miniature: a fixed array of five bytes, a counter that walks the array with NEXT FROM, an equality test against a target byte, and a branchless conditional ADD into the running count. Output: III, the count of matches. The same mechanic generalises to scanning the 60000-byte source array once the surrounding I/O scaffolding (already in stage3.i) is wired up to the new loop.
Sub-stages once the loop primitive lands
- Byte-by-byte tokeniser: read source, classify into D/P/N/space/letter/punctuation tokens. Output: a token stream as an array.
- Statement classifier: scan tokens, emit one record per statement (type, polite, negated, label, body). Output: parallel-array stmt table.
- Politeness check: count PLEASE statements, enforce 1/5..1/3 ratio. Reject otherwise.
- Label resolver: build label-to-stmt map.
- Expression parser: recursive descent over operator grammar, output expression tree as parallel arrays.
- Codegen orchestrator: walk stmt table, dispatch to per-type codegen routine.
- Per-type codegen routines: one per statement type (15 types).
- Runtime + syslib emission: concatenate the runtime/syslib .s with the program .s; pass the combined assembly to
ccvia the wrapper.
Each sub-stage is days to weeks of focused INTERCAL coding. The full stage3 is months of disciplined work.
Why not in this session
A multi-month project does not fit a single session, no matter how productive. The honest framing is:
- We have completed the inspection/optimisation/tooling improvements that fit a session (proposals 1-15, 17-20).
- Stage3's loop-primitive question is a language design question, not an implementation question. It must be discussed with the user before code happens.
- A half-implemented stage3 is worse than no progress: it fragments stage3.i, breaks the existing 4 tests, and leaves the project in an unstable state.
What you can do meanwhile
- Read
src/compiler/stage3.ito see the current byte-probe scaffold. - Read
docs/intercal_patterns.mdfor verified patterns and known dead idioms. - Read
memory/bugs_learned.mdfor the unwind-dance failure history. - Read this document.
- Decide whether to extend the language (Options A/B) or commit to the scaffolding (Option C).
When ready
The session that resolves the loop primitive is the prerequisite for stage3 work. The session after that is "implement substage 1: tokeniser". And so on.
Loop primitive: NEXT FROM extension
This compiler adopts a non-standard loop primitive borrowed from CLC-INTERCAL, under the same rationale as our Label 666 syscall extension: the standard does not provide what a real self-hosted compiler needs, and a single, surgical extension is preferable to the multi-month "abstain dance" scaffolding option.
The primitive lands in stage3 (src/compiler/stage3.i) and downstream code
generated by it. It does not affect the bootstrap compiler (intercalc.sh) or
the bytecode tier.
Decision
After evaluating the three options laid out in docs/stage3-roadmap.md:
- Option A (
(label)*while-abstain extension): requires a new postfix syntax, a new runtime counter mechanism, and bespoke codegen for an "iterate with abstain bound" semantics that has no precedent in any existing INTERCAL. - Option B (NEXT FROM, from CLC-INTERCAL): existing precedent in another well-known dialect, reuses existing label and branch machinery, requires one new statement form.
- Option C (scaffolding pattern, ~30 statements per logical loop): no compiler change, but stage3.i would balloon to thousands of lines and the resulting compiler would be slow and unreadable.
We adopt Option B with a small refinement: the conditional variant
(label) NEXT FROM <expression> makes loops directly expressible without
recursing into the abstain-dance problem (where conditionally toggling
ABSTAIN itself needs the same kind of conditional jump).
Syntax
Two new statement forms are accepted:
DO (LABEL) NEXT FROM
DO (LABEL) NEXT FROM <expr>
Both forms behave like an unconditional or conditional backward b to the
labelled statement at (LABEL). Neither form pushes onto the NEXT stack;
neither needs a matching RESUME.
<expr> is any standard 16-bit INTERCAL expression. The conditional form
jumps to (LABEL) if and only if bit 0 of <expr> is set. Bit 0 is the
canonical "boolean test" position, matching the existing zero-test idiom
'.X ~ .X' ~ #1.
The unconditional form is exactly equivalent to (LABEL) NEXT FROM #1.
Semantics
(LABEL) NEXT FROM <expr> is operationally:
- Evaluate
<expr>to a 16-bit valueV. - If
V & 1 == 1, transfer control to the statement labelled(LABEL)without modifying the NEXT stack. - Otherwise, fall through to the next statement.
This is a pure intra-procedural conditional branch. It does not interact with the NEXT/RESUME stack at all, so it does not consume a stack slot (no E123 risk) and does not produce an entry to RESUME from.
It can be the target of ABSTAIN FROM (label) like any other statement
(the label here being the optional prefix on the NEXT FROM line itself),
and it participates normally in the politeness count.
Why this design
- Backward branches without stack manipulation. Standard
NEXTpushes, so a tight loop overflows the 79-entry stack on the 80th iteration.NEXT FROMdoes not push. - Conditional in a single statement. The standard "computed RESUME" idiom
only unwinds to a parent frame and fails at top level
(verified empirically; see
memory/bugs_learned.mdanddocs/intercal_patterns.md). The conditional NEXT FROM gives us a working in-frame conditional branch. - CLC-INTERCAL precedent. Adopting from an existing dialect keeps the compiler in the family of known INTERCAL extensions rather than inventing a one-off design.
- Minimal codegen. Each NEXT FROM is one ARM64
cbnz/bplus a label; no new runtime function, no new BSS, no new error code.
Codegen sketch
For ARM64 (other platforms by translation):
; DO (LABEL) NEXT FROM
b _stmt_LABEL_N
; DO (LABEL) NEXT FROM <expr>
<emit-expression-into-w0>
tbnz w0, #0, _stmt_LABEL_N
tbnz (test bit and branch if non-zero) is the natural primitive for
"branch if bit 0 is set". The fall-through is the next statement.
What this lets stage3 do
Once NEXT FROM is wired up, the substages laid out in
docs/stage3-roadmap.md become straightforward:
- Byte-by-byte tokeniser. A counter
.poswalks from 0 to source length; each iteration probes the byte at,65535 SUB .posand records a token into a parallel array. Loop test:'(.pos - .len) ~ (.pos - .len)' ~ #1is non-zero while there is more source. - Statement classifier. One pass over the token array, advancing while inside a statement, emitting one record at each statement boundary.
- Politeness check. One pass counting PLEASE statements; reject if the ratio is out of range.
- Codegen. One pass over the statement table dispatching by type.
Each pass is one NEXT FROM at the end of a body block. The body block itself is open to use any standard INTERCAL constructs, including syslib calls, STASH/RETRIEVE, and (with care) inner NEXT FROM loops.
Compatibility
NEXT FROM is non-standard. INTERCAL programs intended to be portable to
ick/CLC-INTERCAL must not use it. We document the extension here so a
later port to another compiler is a known undertaking, not a surprise.
The bootstrap compiler (intercalc.sh) gains a small parse and codegen
case for NEXT FROM; existing programs that do not use it are unaffected.
tools/lint_intercal.sh is taught to recognise it so it does not flag
the new form as an unrecognised statement.
Test plan
A single new test file tests/test_next_from.i exercises:
- Unconditional NEXT FROM: a 5-iteration counter loop.
- Conditional NEXT FROM #1: same as unconditional.
- Conditional NEXT FROM with computed expression: scan a fixed-content array for a target byte; loop until found; READ OUT the index.
- ABSTAIN FROM the NEXT FROM line: confirm the loop is broken.
Test registered in tests/run_tests.sh and tests/run_self_tests.sh.
Roadmap relation
This document satisfies task #121 in the post-v0.1.0 work plan and unblocks #122 (substage 1 tokeniser). Implementation order:
- This doc (now).
- intercalc.sh codegen for NEXT FROM (next).
- One regression test demonstrating the loop in a small program.
- stage3 substage 1 tokeniser using NEXT FROM.
Learning by extending: a guided tour
The shortest path from "I read the chapters" to "I can change the compiler" is to follow a real change end to end. This chapter walks through three landings from the 2026-05-09 session, each one a different kind of compiler work, and each chosen so the analogue in a production compiler is direct.
The three changes:
- A new statement form (NEXT FROM) added to lexer, parser, analyses, and codegen. The mirror in production compilers: any frontend feature, from a new keyword to a new operator.
- An IR migration scaffold (
INTERCAL_NEW_IR=1) that routes one statement type at a time through a new lowering path. The mirror: GCC's GIMPLE introduction, rustc's MIR migration, V8's TurboFan replacing Crankshaft. - A real Wegman-Zadeck SCCP behind
--emit-sccp-wz. The mirror: every production compiler ships a constant-propagation pass; the 1991 paper is the canonical reference.
If you read these in order you will see the same shape of change at three different layers of the compiler. Each section ends with a "now do this" suggestion: a small extension you can pick up to practise the technique.
1. Adding a new statement: NEXT FROM
The motivating problem is documented in loop-extension.md. Standard
INTERCAL has no for, no while, and the standard COME FROM dance
needs ten or more statements per logical loop because conditional
ABSTAIN itself recurses the same control-flow problem.
We adopted Option B from CLC-INTERCAL: (LABEL) NEXT FROM <expr>,
a backward branch that does not push the NEXT stack and is
conditioned on bit 0 of an expression.
The change touched, in order:
- The classifier in
intercalc.sh:classify_statementlearned two new body shapes:(N) NEXT FROM <expr>for the conditional form,(N) NEXT FROMfor the unconditional form. Both setstmt_type[$idx]="NEXT_FROM"and store the optional expression in a new parallel arraystmt_next_from_expr[].
- Every analysis pass that enumerated control-flow stoppers
(
is_leader[]for basic-block detection, the predecessor computation incompute_var_constants, the STASH/RETRIEVE soundness analysis) gainedNEXT_FROMto its case alternation. - A new
codegen_next_from()emits a singleb _stmt_<ref>for the unconditional form, or evaluates the expression and emits atbnz w0, #0, _stmt_<ref>for the conditional form. No NEXT-stack push. - The
check_unreferenced_labels()pass added NEXT_FROM to the list of references so a label used only by NEXT FROM is not flagged. - A regression test,
tests/test_next_from.i, exercises a counter loop that prints "V" after exactly five iterations.
Production-compiler analogue. When LLVM gains a new IR opcode (e.g.,
freeze) the change is shaped identically: parser/builder
extension, every pass that switches on opcode learns the new case,
SelectionDAG/GlobalISel codegen gains the lowering, verifier gains
a check. The diff is bigger because LLVM has more passes; the shape
is the same.
Now do this. Add a third NEXT FROM form: (LABEL) NEXT FROM AT MOST <const> that branches at most const times and then falls
through unconditionally. You will need a new BSS counter per such
statement, an increment-then-compare in codegen, and a test that
shows the branch fires exactly const times.
2. Migrating codegen to consume an IR
The motivating problem comes from middle-end-and-optimisation.md. The legacy codegen walks the parse tree directly and emits assembly in one pass. There is no IR for an optimiser to chew on, so passes like SCCP, GVN, and DCE have nowhere to live.
We did not rewrite codegen. We installed a scaffold for an incremental migration. The shape of that scaffold is the same one GCC, rustc, and V8 used:
- A new IR data structure already exists (
ir_ops[], populated bybuild_ir(), dumped by--emit-ir-real). Read-only at first. - A feature flag (
INTERCAL_NEW_IR=1) gates the new path. Off by default; the legacy path is the source of truth. - The codegen dispatch in
codegen_statementnow has two branches:- With the flag set, try
lower_ir_for_stmt(i)first. Return on success. - Otherwise (or on fall-through from an unsupported op), use the
legacy
case "${stmt_type[$i]}" in ... esacdispatch.
- With the flag set, try
- The new lowering supports exactly one statement type today:
GIVE_UP. Each platform (macos_arm64,linux_arm64,linux_x86_64) has a per-platform exit-syscall sequence. - A regression test (
tests/test_new_ir.sh) confirms three things: the legacy path still works, the IR-driven path produces the same output, and a program mixing supported and unsupported statement types compiles correctly via the per-type fallback.
The flag is the load-bearing piece of the migration. It lets the
next slice (say, ASSIGN) be added by writing lower_ir_for_stmt
support for ASSIGN and a test for it, without touching the legacy
codegen at all.
Production-compiler analogue. GCC's GIMPLE was introduced this way in 2003: a new IR layered between the frontend and the existing RTL backend. RTL did not go away; for years GIMPLE-aware passes ran first, then the result was lowered to RTL for the rest of the pipeline. rustc's MIR migration in 2016-2018 followed the same shape: borrow checking moved from HIR to MIR one query at a time, gated by a query-cache flag, with the old path remaining as a fallback until parity was reached.
Now do this. Add lower_ir_for_stmt support for the next-easiest
statement type. Candidates in increasing complexity:
STASH(one-store-per-var, no expression evaluation).IGNORE/REMEMBER(one bit flip per var, no expression).READ_OUTfor scalars (call into the runtime's Roman-numeral routine).ASSIGNof a literal RHS (no expression tree to walk).
Pick one. Add an op to build_ir(). Add a case to
lower_ir_for_stmt(). Extend tests/test_new_ir.sh. The legacy
path stays in place; if you break the new path the flag stays off
and nothing else suffers.
3. Implementing a textbook algorithm: Wegman-Zadeck SCCP
The motivating problem is the standard one: const-prop should follow the CFG faithfully so it can prove unreachable branches dead and propagate constants across them. The 1991 Wegman-Zadeck paper is the canonical algorithm.
The change added emit_sccp_wz, separate from the simpler
emit_sccp linear-walk dump. The new function is a faithful
implementation of the paper at a small scale:
- Three-element lattice
TOP < CONST(c) < BOTTOM.meet_lattice()implements the pointwise meet:TOP ∧ x = x,BOTTOM ∧ x = BOTTOM,CONST(c) ∧ CONST(c) = CONST(c),CONST(c1) ∧ CONST(c2) = BOTTOMforc1 ≠ c2.
- Per-statement outgoing values stored in
outgoing[<stmt>_<varspec>]. - Executable-edge gating via
exec_into[i] = 1when an incoming edge has been proven reachable. Statements with no executable predecessors are not visited. - A worklist (
worklist=()array) of statement indices. Each pop re-evaluates the meet of executable predecessors and updates outgoing values; when something changes, successors are enqueued. - Predecessor edges include fall-through plus NEXT and NEXT_FROM source edges. (COME FROM source edges are still future work.)
The output is a teaching dump: per-statement lattice values,
listing every variable seen at each program point. It is not yet
consumed by codegen, but the data structure (outgoing[]) is the
exact thing a codegen pass would consult.
Production-compiler analogue. LLVM's SCCP transform in
Transforms/Scalar/SCCP.cpp is the same algorithm at production
scale; IPSCCP is the interprocedural variant. GCC's
tree-ssa-ccp.c is the GIMPLE counterpart. The shape is
identical: lattice + worklist + per-value tracking. The
production versions add: more lattice values (e.g., bit-level
known-value), broader value-evaluation rules (covering the full
operator set), and integration with the surrounding pass
manager.
Now do this. Extend emit_sccp_wz to model two more cases:
- The arithmetic syslib calls 1009 (add with carry flag) and
1010 (subtract). When the inputs are both
CONST(N), evaluate the operation and produceCONST(N+M)(mod 65536) for 1009. - COME FROM source edges in
preds[i]. Today, statements with an incoming COME FROM only see the fall-through predecessor; the lattice should meet with the source statement's outgoing value too.
Each is ten lines or so and exercises a different facet of the algorithm.
A common pattern across all three
The three changes have the same shape:
- A small change to one or two data structures.
- A new code path gated behind a flag, environment variable, or separate function name.
- A regression test that exercises the new path end to end.
- The legacy path left in place as the source of truth.
This pattern shows up in every production compiler. The pre-MIR
borrow checker stayed live in rustc for a year after MIR landed.
GCC's tree-ssa-uninit.c runs alongside the older
tree-ssa-strlen.c even though both touch the same warning
class. LLVM has both SimplifyCFG and JumpThreading for
overlapping cleanups. They coexist because the cost of removing
the old path early is higher than the cost of carrying it.
When you propose a change, default to this shape: feature flag, new path alongside the old path, regression test that proves the new path works on at least one input. The reviewers will thank you. The bisect log will be cleaner. The rollback is one boolean.
Inspection flags worth knowing about
While extending the compiler you will often want to see what an analysis pass actually produced. Each flag below answers a specific question, exits before codegen, and prints to stdout so you can pipe to grep or save for diff.
| Flag | Question it answers |
|---|---|
--diagnose | How many statements? Politeness ratio? Label and syslib summary? |
--emit-tokens | What did the lexer see? Token stream by category. |
--emit-3addr | What does each statement become at the GIMPLE-shaped flat IR level? |
--emit-cfg | Basic blocks and their edges, in the LLVM/MIR vocabulary. |
--emit-ir-real | The real three-address IR (CONST, LOADV, STORE, MINGLE, etc.) used by the IR-driven codegen path. |
--emit-ssa | Block-parameter SSA form (Cranelift-style). |
--emit-sccp | Linear-walk lattice values (simpler teaching dump). |
--emit-sccp-wz | Faithful Wegman-Zadeck SCCP with executable-edge gating and meet at confluence points. Models syslib 1009/1010/1020/1030 in the lattice. |
--emit-regalloc | Linear-scan register allocation trace (live intervals, spills). |
--emit-effects | Per-statement set of ICL error codes the statement could raise. |
--emit-opt-summary | Summary counts: how many E275/E621/E436 elisions fired, abstain-flag eliminations, constant-prop entries. |
--time-report | Per-phase timing breakdown. |
--opt-bisect-limit=N | Disable any optimisation past the N-th, for finding miscompile by bisection. |
Two environment variables also gate behaviour:
| Variable | Effect |
|---|---|
INTERCAL_NEW_IR=1 | Try the IR-driven lowering path before legacy. |
INTERCAL_REGALLOC_HINTS=1 | Emit // regalloc: comments at variable assignments. |
The pattern is the same for every flag: run the analysis, dump what it computed, exit. No flag changes generated code (with the sole exception of the two environment variables, which gate opt-in codegen paths).
What to read next
If you finish all three "now do this" exercises, you have a pattern you can apply to almost any compiler change. From here:
- Read
from-intercal-to-real-compilers.mdfor the bridge to the ten production compilers covered in Part VII. - Pick the production compiler closest to your interest (LLVM if
you want hands-on optimisation work; rustc if you want a
query-driven model; Cranelift if you want a small one to read
end to end). Read its chapter, then start by following its
CONTRIBUTING.md's "good first issue" path. - Come back to this compiler periodically. The point of a small compiler is that the round-trip is short: write the analysis, run it, debug it, in minutes. Production compilers reward patience; this one rewards iteration.
Cross-compiler cheatsheet
If you have worked on LLVM, GCC, rustc, or another production compiler and want to find the matching concept here, this table is the one-page index. Each row points to a file or symbol; the file is the place to start reading.
Front end
| Production-compiler concept | This compiler | File / function |
|---|---|---|
| Lexer / tokeniser | Inline tokeniser | intercalc.sh:tokenize |
| Parser | Inline statement classifier | intercalc.sh:classify_statement |
| AST | Parallel arrays per statement | stmt_type[], stmt_body[], stmt_label[], ... |
| Expression tree | Parallel arrays per expression node | expr_type[], expr_left[], expr_right[], ... |
| Diagnostics | die_compile / print_warning | intercalc.sh |
| Format-on-save | tools/format_intercal.sh | external |
Middle end
| Production-compiler concept | This compiler | File / function |
|---|---|---|
| GIMPLE / MIR / Cranelift CLIF | Three-address IR | build_ir, ir_ops[] |
| SSA construction | Block-parameter SSA | emit_ssa (read-only dump) |
| Pass manager | Sequential time_phase calls | intercalc.sh:main |
| Constant propagation | SCCP-WZ + chain-copy var-const | emit_sccp_wz, compute_var_constants |
| Dead-code elimination | Per-statement abstain-flag DCE | compute_flag_checks, stmt_needs_flag[] |
| Register allocation | Linear-scan (Poletto-Sarkar) | emit_regalloc, compute_regalloc_decisions |
| Effect analysis | Per-statement ICL-code reachability | emit_effects, stmt_e275_safe[], ... |
| Peephole | Sed-pass on emitted assembly | intercalc.sh:peephole_optimize |
| Optimisation bisect | --opt-bisect-limit=N | LLVM-style |
Back end
| Production-compiler concept | This compiler | File / function |
|---|---|---|
| Instruction selection | Per-statement-type emit functions | codegen_* |
| Calling convention | INTERCAL has no functions; the convention is the syslib labels | src/syslib/syslib.i |
| Linker driver | cc -x assembler - | inline in intercalc.sh |
| Per-platform target | src/runtime/{macos_arm64,linux_arm64,linux_x86_64}.s | hand-written runtime |
| Assembler post-processing | sed (ARM64 macOS → Linux), separate codegen for x86_64 | inline in intercalc.sh |
Tooling
| Production-compiler concept | This compiler | File / function |
|---|---|---|
| Compiler driver | intercal wrapper | shell script |
| Build system | None (single zsh script) | n/a |
| LSP | LSP v0.4.0 | src/lsp/intercal_lsp.sh |
| Linter | Static checks | tools/lint_intercal.sh |
| Formatter | Indent + uppercase | tools/format_intercal.sh |
| CI matrix | 3 platforms | .github/workflows/ci.yml |
| Differential testing | csmith-style program generator | tools/csmith_intercal.sh + tests/run_csmith_diff.sh |
| Bytecode tier | Stack VM | src/bytecode/intercalc_bc.sh + intercalc_vm.sh |
Migration patterns
If you have done one of these in another compiler, this is where to start in ours:
| You have done | Start reading |
|---|---|
| Added an LLVM IR opcode | lower_ir_for_stmt and the case in codegen_statement (NEXT_FROM was added the same way) |
| Added a GCC tree-ssa pass | compute_* analyses in intercalc.sh |
| Migrated a compiler from one IR to another (HIR → MIR; AST → GIMPLE) | INTERCAL_NEW_IR=1 opt-in flag and lower_ir_for_stmt's per-type fallback |
| Implemented Wegman-Zadeck SCCP | emit_sccp_wz — the algorithm in 200 lines |
| Built linear-scan regalloc | emit_regalloc (the algorithm) and compute_regalloc_decisions (the same algorithm without the trace, populating globals) |
| Wrote an LSP server | src/lsp/intercal_lsp.sh is one zsh file; jsonrpc framing is hand-rolled |
Reading order
Three suggestions depending on your goal:
-
Adding a feature. Read
learning-by-extending.mdfirst. Then pick the smallest possible analogue from this cheatsheet and trace through it end to end. -
Understanding the codegen path. Read
pipeline.md→code-generation.md→lower_ir_for_stmtand follow the feature-flag fork fromcodegen_statement. -
Bridging to a production compiler. Read the relevant Part VII chapter (LLVM, GCC, rustc, Go, GHC, ...) alongside the matching row in this cheatsheet. The shape of the change is the same; the diff size is two orders of magnitude larger but the steps map.
The bytecode tier
The native compiler in src/bootstrap/intercalc.sh produces an
ARM64 (or x86-64) executable. Alongside it lives a second tier in
src/bytecode/: a compiler-to-bytecode (intercalc_bc.sh) and a
stack-VM interpreter (intercalc_vm.sh). Both are implemented in
zsh and run anywhere zsh runs. Together they let any INTERCAL
program execute by two independent paths and cross-validate.
This chapter walks through the design, the op set, and what the bytecode tier covers today.
Why two tiers
Production compilers usually run code in two shapes for separate reasons:
- OCaml compiles to ZINC bytecode for fast development and to native code for shipping.
- V8 has Ignition (bytecode interpreter) and TurboFan (optimising JIT). New code starts on the interpreter; hot paths migrate to the JIT.
- GCC has GIMPLE and RTL. The IRs serve different optimisations.
- Cranelift compiles WebAssembly to its CLIF IR before lowering.
Each compiler trades off in its own dimension. Here the bytecode tier is not for performance: it is for differential testing, portability when no native runtime is built, and as a teaching device for this section's topic.
Architecture
The compiler reads INTERCAL source and emits a flat sequence of ops, one per line:
STMT_ENTER 1
IPUSH 5
POPV .1
ESTMT
STMT_ENTER 2
VPUSH .1
READOUT
ESTMT
STMT_ENTER 3
EXIT
ESTMT
The VM reads the entire op stream into an in-memory array, then
runs an interpreter loop that dispatches per opcode. A stack
stack[] holds intermediate expression values; named storage
holds variables (spot[], twospot[], arrays).
The op set
Pushed on the stack:
IPUSH Npush integer literalVPUSH .Npush spot variable valueVPUSH2 :Npush twospot variable value
Stack arithmetic:
MINGLE,SELECT— pop two, push resultUAND,UOR,UXOR— unary operators on adjacent bits
Statement boundaries:
STMT_ENTER N— abstain check, skip to ESTMT if abstainedESTMT— close the current statement; check for COME FROM redirect
Variable I/O:
POPV .N,POPV2 :N— store top of stackSTASH,RETRIEVE,IGNORE,REMEMBER— variable lifetime ops
Control flow:
LABEL N— mark a labelled stmt positionCOMEFROM N— register a redirect from label NCALL N— push current PC, jump to label NRESUME N— pop N entries, branch to last popped PCFORGET N— drop N entries from the call stackBRANCH N— unconditional jump to label N (NEXT FROM)BRANCH_NZ N— pop a value, jump if bit 0 setABSTAIN_LBL N/REINSTATE_LBL N— set / clear abstain bitABSTAIN_GER NAME/REINSTATE_GER NAME— by gerund
Arrays:
DIM_N <arr> <ndims>— allocate, store dim listAPUT_N <arr> <ndims>— pop subscripts and value, storeAGET_N <arr> <ndims>— pop subscripts, push element
I/O:
READOUT,READOUT2— print Roman numeralREADOUT_ARR <arr>— TTM output (bit-reversed tape head)WRITEIN .N— read English digit names, storeWRITEIN_ARR <arr>— same, per-element
Probability and exit:
PROB N— roll, skip the rest of the stmt ifRANDOM%100 >= NEXIT— terminate
What it can run
tests/test_bytecode_equiv.sh is the differential-testing harness.
It runs every tests/test_*.i regression program through both
the native compiler and the bytecode tier and asserts identical
output. As of the most recent landing, 16 of 35 regression
programs pass equivalence. The 19 skips are tests that exercise
features not yet ported (a few error-injection tests that
intentionally trigger ICL codes the bytecode reports differently)
or rely on the WRITE IN harness's stdin plumbing.
The 16 passes include:
- All literal-arithmetic programs.
- Programs using STASH/RETRIEVE/IGNORE/REMEMBER.
- COME FROM control flow.
- NEXT/RESUME with the call stack.
- ABSTAIN/REINSTATE (label + gerund).
- Multi-dimensional arrays.
- TTM string output (Hello, World!).
- Programs invoking syslib arithmetic (1009/1010/1530/etc.).
Cross-validation as a primary use
The bytecode tier and the native compiler are two independent
implementations of INTERCAL semantics. They share only the source
parser at the front (and even that is reimplemented in
intercalc_bc.sh). When they disagree on output, exactly one is
buggy. Running the equivalence sweep on every CI build is a cheap
way to catch regressions in either tier.
This is the same pattern Csmith uses against C compilers: compile the same program with two compilers, compare outputs, the diff points to a bug.
Tracing
BC_TRACE=1 tells the VM to emit one stderr line per executed op
with the current PC and the data stack:
[bc-trace pc=1 op=STMT_ENTER 1 stack=]
[bc-trace pc=2 op=IPUSH 5 stack=]
[bc-trace pc=3 op=POPV .1 stack=5]
Useful when bytecode and native disagree on a particular program.
What's deferred
The bytecode tier intentionally lacks features that have low educational return on investment:
- Two-tier JIT compilation. The bytecode is interpreted, never natively compiled. V8 / OCaml do this; we do not.
- The peephole optimisations the native compiler runs. The bytecode tier exists to validate semantics, not to be fast.
- Syscalls beyond the Label 666 set already supported.
If a new INTERCAL feature lands in the native compiler, the bytecode tier should grow a corresponding op so equivalence holds. The pattern is consistent: a new op, a per-op handler in the VM, a new bullet in the equivalence sweep's coverage.
Effect-driven elimination
INTERCAL has 16 documented runtime errors. Every assignment, RESUME, RETRIEVE, NEXT, ARRAY_DIM, and array access can in principle hit one of them. The native compiler emits the corresponding check at every site by default. When a static analysis can prove the check unreachable, the codegen omits it.
This is the same shape of optimisation production compilers run:
LLVM's InstCombine simplifies bound checks when the index is
known in range; GCC's tree-vrp (value-range propagation) does
similar work; rustc's MIR drops bounds checks behind unsafe
guarantees.
This chapter documents the seven elision passes this compiler
implements, the soundness conditions for each, and where in
intercalc.sh the analysis lives.
The seven elisions
| Pass | Check elided | Soundness condition |
|---|---|---|
| E275 | 32-bit value into spot (cmp+b.hi) | RHS literal #N with N ≤ 65535, or var-to-var copy of same width, or spot→twospot widening, or SCCP-bounded var copy |
| E621 | RESUME #0 (cbz) | Argument is literal #N with N ≠ 0 |
| E436 | RETRIEVE without prior STASH (load+test) | Earlier STASH of same vars on every reachable path; no intervening RETRIEVE / NEXT / COME FROM |
| E123 | NEXT stack overflow (cmp+b.ge) | Loop-free program (no COME FROM, no NEXT FROM, no REINSTATE), forward-only NEXTs (target is past the NEXT site), total NEXT count below the 79-entry limit |
| E240 | ARRAY_DIM dim of 0 (cbz) | All dim expressions are literal nonzero #N |
| E241 | Array subscript out of bounds (cmp+b.hs) | Subscript is literal #M and the array's dim is statically known with 1 ≤ M ≤ dim |
| E632 | RESUME pops past stack bottom (b.mi) | RESUME #1 placed in a labelled block reachable only via NEXT (no COME FROM, no NEXT FROM, no REINSTATE in the program) |
Each pass populates a hash stmt_eNNN_safe[i] keyed by the
statement index. Each codegen site reads its safety flag and, if
set, also calls opt_bisect_check "elim_eNNN_stmt_$i" so
--opt-bisect-limit=K can disable any subset of elisions for
debugging.
Where in the codebase
Every pass lives in compute_e275_safety() in
src/bootstrap/intercalc.sh. The function name is misleading;
it is the home of every elision analysis. The structure is one
case-arm per statement type with a final post-pass for cases that
need the full dim map. The function runs after
compute_var_constants so SCCP-style results inform E275.
The codegen sites that consult these flags:
codegen_assignfor E275 (and IGNORE check elision via a separate analysis).codegen_resumefor E621 and E632.codegen_retrieve_varfor E436.codegen_nextfor E123.codegen_array_dimfor E240.codegen_array_elem_assignand the array-load path incodegen_exprfor E241 (consultsstmt_e241_safe[current_stmt_idx]).
How to verify
--emit-opt-summary prints counts per pass:
ASSIGN stmts: 12
E275 elided (cmp+b.hi skipped): 8 / 12
RESUME stmts: 2
E621 elided (cbz skipped): 1 / 2
E632 elided (b.mi skipped): 1 / 2
RETRIEVE stmts: 3
E436 elided (empty-stash skip): 2 / 3
NEXT stmts: 5
E123 elided (stack-depth skip): 5 / 5
ARRAY_DIM stmts: 1
E240 elided (zero-dim skip): 1 / 1
Array-access stmts E241 elided: 2
tests/test_effect_elim_more.sh has 11 cases covering each pass
in two flavours: a positive case where the elision should fire
(emitted assembly contains zero references to _rt_error_eNNN)
and a negative case where the runtime check must stay (at least
one reference). The two flavours guard against unsound elision
slipping in.
SCCP-WZ feed
Setting INTERCAL_SCCP_WZ_FEED=1 runs a silent Wegman-Zadeck
SCCP pass and merges its CONST results into stmt_var_const,
which the simpler analysis didn't catch. The most common
beneficiary is E275 elision on programs that flow constants
through arithmetic syslib calls (1009/1010/1530/etc.) — the
simpler analysis bottoms on syslib calls; SCCP-WZ models them.
The feed is sound only when the program contains no STASH or RETRIEVE, since SCCP-WZ doesn't model the stash stacks. The feed checks this and skips entirely on STASH/RETRIEVE programs to avoid miscompiling.
Production-compiler analogues
| Pass | LLVM analogue | GCC analogue |
|---|---|---|
| E275 | InstCombine truncation patterns | tree-vrp value range |
| E621 | SimplifyCFG constant condition | tree-cfg |
| E436 | MemorySSA-driven dead-store elim | tree-dse |
| E123 | call-graph based stack-depth analysis | tree-call-cdce |
| E240 | LoopUnswitch constant condition | similar |
| E241 | IndVarSimplify + SCEV known range | graphite |
| E632 | function-summary SCC analysis | IPA |
The shape is the same in every production compiler: an analysis proves a property at a site; a codegen pass uses the property to omit a runtime check; a flag disables the elision for debugging. The scale and the depth of the analyses are different — LLVM's ScalarEvolution is thousands of lines, our E241 analysis is fifty. But a reader who has done one can read the other.
Adding a new elision
The pattern is fixed:
- Add
typeset -A stmt_eNNN_safenear the existing maps. - Add a clause to
compute_e275_safetythat populates the map per statement, using whatever upstream analysis is needed. - Add
opt_bisect_check "elim_eNNN_stmt_$i"at the codegen site that reads the map. - Add two tests to
tests/test_effect_elim_more.sh: a positive case the elision should catch, a negative case it must not. - Add a counter to
emit_opt_summaryand a row in this chapter.
Item 4 is the load-bearing one. An unsound elision compiled a program incorrectly is silent until someone notices a wrong output. Two flavours of test (must elide / must not elide) make the boundary visible.
Statement cheatsheet
A one-stop reference for every INTERCAL statement this compiler recognises, with syntax, a minimal example, the codegen function that handles it, and the runtime errors each can trigger. Aimed at somebody who knows INTERCAL and wants to look up a specific statement quickly.
For the pedagogical introduction see intercal-primer.md. For the formal grammar see appendix-grammar.md.
Conventions used below
<expr>: an arithmetic expression producing a 16- or 32-bit value.<var>: a variable reference (.N,:N,,N,;N).<label>: a number in parentheses,(N)where 1 ≤ N ≤ 65535.<n>,<k>: decimal number literals.<gerund>: one ofCALCULATING,NEXTING,FORGETTING,RESUMING,STASHING,RETRIEVING,IGNORING,REMEMBERING,ABSTAINING,REINSTATING,COMING FROM,READING OUT,WRITING IN.
Every statement can optionally be prefixed with a label and the verb can be DO / PLEASE / PLEASE DO; any of these can optionally be negated with NOT / N'T / DON'T; and any can take a %N probability. The table below shows the bare form.
Assignments
| Statement | Example | Codegen function | Errors |
|---|---|---|---|
<var> <- <expr> | DO .1 <- #5 | codegen_assign | ICL275I (32→16 overflow), ICL533I (arithmetic overflow) |
<array> <- <expr> | DO ,1 <- #10 | codegen_array_dim | ICL240I (zero dimension), ICL533I |
<array> <- <expr> BY <expr> | DO ,1 <- #3 BY #4 | codegen_array_dim | ICL240I, ICL533I |
<array> SUB <expr> ... <- <expr> | DO ,1 SUB #2 <- #42 | codegen_array_elem_assign | ICL241I (bad subscript), ICL275I, ICL533I |
Control flow
| Statement | Example | Codegen function | Errors |
|---|---|---|---|
<label> NEXT | DO (100) NEXT | codegen_next | ICL123I (stack overflow, runtime), ICL129I (unknown label, compile-time) |
RESUME <expr> | DO RESUME #1 | codegen_resume | ICL621I (RESUME 0, runtime), ICL632I (stack underflow, runtime) |
FORGET <expr> | DO FORGET #1 | codegen_forget | none |
COME FROM <label> | DO COME FROM (100) | implicit in target statement | ICL555I (duplicate target, compile-time), ICL129I (unknown target, compile-time) |
GIVE UP | DO GIVE UP | codegen_give_up | none |
Modifiers
| Statement | Example | Codegen function | Errors |
|---|---|---|---|
ABSTAIN FROM <label> | DO ABSTAIN FROM (100) | codegen_abstain | ICL139I (unknown label) |
ABSTAIN FROM <gerund>[+<gerund>]* | DO ABSTAIN FROM CALCULATING | codegen_gerund_modify | none |
REINSTATE <label> | DO REINSTATE (100) | codegen_reinstate | ICL139I |
REINSTATE <gerund>[+<gerund>]* | DO REINSTATE NEXTING + RESUMING | codegen_gerund_modify | none |
IGNORE <var>[ <var>]* | DO IGNORE .1 :2 | codegen_ignore | none |
REMEMBER <var>[ <var>]* | DO REMEMBER .1 :2 | codegen_remember | none |
Stash / retrieve
| Statement | Example | Codegen function | Errors |
|---|---|---|---|
STASH <var>[ <var>]* | DO STASH .1 .2 | codegen_stash | ICL999I (stash overflow, not yet enforced) |
RETRIEVE <var>[ <var>]* | DO RETRIEVE .1 .2 | codegen_retrieve | ICL436I (retrieve without stash) |
I/O
| Statement | Example | Codegen function | Errors |
|---|---|---|---|
READ OUT <var>[ <var>]* | DO READ OUT .1 | codegen_read_out | none (scalar) |
READ OUT <array> | DO READ OUT ,1 | codegen_read_out | none (array) |
WRITE IN <var>[ <var>]* | DO WRITE IN .1 | codegen_write_in | ICL562I (end of input), ICL579I (bad format) |
WRITE IN <array> | DO WRITE IN ,1 | codegen_write_in | ICL562I |
Whole-program
| Statement type | Example | Codegen function | Errors |
|---|---|---|---|
| Any unknown form | DO WOT A HULLABALOO | dispatcher fallthrough | ICL000I (executed unknown statement, runtime) |
| Bad spark/rabbit-ears nesting | DO .1 <- 'a $ 'b'' | parse_expr | ICL017I (compile-time) |
| Fallthrough past last statement | (missing GIVE UP) | implicit epilogue | ICL633I (fell off the end, runtime) |
| Politeness out of range | (whole program, ≥5 statements) | check_politeness at compile time | ICL079I (rude), ICL099I (polite) |
| Duplicate label | (whole program) | check_labels at compile time | ICL182I |
| Label outside 1–65535 | DO (0) NEXT | check_labels at compile time | ICL197I |
| Multiple COME FROMs to same label | (whole program) | resolve_come_from at compile time | ICL555I |
| Unknown gerund in ABSTAIN/REINSTATE | DO ABSTAIN FROM PROCRASTINATING | codegen_gerund_modify at compile time | (named diagnostic, not a numeric ICL) |
Expression operators
| Operator | Syntax | Meaning | Runtime routine |
|---|---|---|---|
| Binary mingle | '<a> $ <b>' | Interleave bits of two 16-bit values → 32-bit | _rt_mingle |
| Binary select | '<a> ~ <b>' | Select bits from <a> where <b> has 1s, pack right | _rt_select |
| Unary AND | &<var> | AND each bit with its right neighbour (wrapping) | _rt_unary_and_16 or _rt_unary_and_32 |
| Unary OR | V<var> | OR each bit with its right neighbour | _rt_unary_or_16 or _rt_unary_or_32 |
| Unary XOR | ?<var> | XOR each bit with its right neighbour | _rt_unary_xor_16 or _rt_unary_xor_32 |
Grouping: '...' (sparks) and "..." (rabbit-ears). Must alternate. No operator precedence; every subexpression that could be ambiguous must be grouped.
System library labels (call via NEXT)
16-bit:
| Label | Operation | Inputs | Outputs |
|---|---|---|---|
| 1000 | add | .1, .2 | .3 (silent wrap on overflow; *9 suffix variant has flag) |
| 1009 | add, with flag | .1, .2 | .3, .4 = 1 if ok / 2 if overflow |
| 1010 | subtract (wraps) | .1, .2 | .3 |
| 1020 | increment in place | .1 | .1 |
| 1030 | multiply | .1, .2 | .3 (silent wrap on overflow; use 1039 for flag) |
| 1039 | multiply, with flag | .1, .2 | .3, .4 |
| 1040 | divide | .1, .2 | .3 (0 if divisor 0) |
| 1050 | 32/16 divide | :1, .1 | .2 (silent wrap if quotient > 65535) |
32-bit:
| Label | Operation | Inputs | Outputs |
|---|---|---|---|
| 1500 | add | :1, :2 | :3 (silent wrap on overflow; use 1509 for flag) |
| 1509 | add, with flag | :1, :2 | :3, :4 |
| 1510 | subtract (wraps) | :1, :2 | :3 |
| 1520 | mingle explicit | .1, .2 | :1 |
| 1530 | 16×16 → 32 multiply | .1, .2 | :1 |
| 1540 | 32×32 multiply | :1, :2 | :3 (silent wrap on overflow; use 1549 for flag) |
| 1549 | 32×32, with flag | :1, :2 | :3, :4 |
| 1550 | 32-bit divide | :1, :2 | :3 (0 if divisor 0) |
Random:
| Label | Operation | Inputs | Outputs |
|---|---|---|---|
| 1900 | uniform random | (none) | .1 in [0, 65535] |
| 1910 | bounded random | .1 | .2 in [0, .1] |
Internal (do not call): 1525 (shift helper), 1999 (overflow exit).
Caller responsibility: STASH every variable in .1–.4 / :1–:4 that the routine will clobber, then RETRIEVE after the return. Failure to STASH leads to silent value loss; failure to RETRIEVE (or RETRIEVE without prior STASH) fires ICL436I.
Label 666 syscalls
Invoke with .1 set to the syscall number, then DO (666) NEXT. See label-666-intro.md for a walkthrough.
.1 | Syscall | Inputs | Outputs |
|---|---|---|---|
| 1 | open | .2 mode (0=read, 1=write), filename in ,65535 | .3 fd |
| 2 | read | .2 fd, .3 max bytes | .4 bytes read, data in ,65535 |
| 3 | write | .2 fd, .3 count, data in ,65535 | .4 bytes written |
| 4 | close | .2 fd | (none) |
| 5 | argc | (none) | .3 count |
| 6 | argv | .2 index (0-based) | .3 length, arg in ,65535 |
| 8 | exit | .2 status code | no return |
| 9 | getrand | .2 0 = uniform / >0 = range [0, .2] | .3 random |
Program must dimension ,65535 <- #65535 at entry and not use ,65535 for any other purpose.
Comment
There is no comment syntax in INTERCAL. The idiom for a no-op pseudo-comment is:
DON'T NOTE whatever you want to say here
This parses as a negated unknown statement, skipped at runtime, ignored by the codegen.
Statement order inside a body
Every statement body's tokens appear in the order specified above (verb, negation, probability, body), but operator expressions inside the body may be freely nested:
PLEASE DO %75 .1 <- '.2 $ "#5 ~ #3"' ~ #65535
This is a probabilistic assignment with a nested expression. The parser handles each piece in sequence.
Next reading
- intercal-primer.md: the narrative introduction for each group of statements.
- code-generation.md: how each
codegen_*function produces assembly. - runtime.md: the
_rt_*routines the codegen calls. - appendix-grammar.md: the formal grammar.
Appendix: INTERCAL grammar
This appendix gives a formal grammar for the INTERCAL subset that the compiler accepts. The notation is EBNF, with two deliberate non-strictnesses that track what our parser actually does:
- Alternation uses
|. - Optional items are in
[ ]. - Repetition (zero or more) uses
{ }. - Terminal keywords are in capital letters exactly as they appear in source.
- Literal punctuation is in quotes.
- Whitespace between tokens is implicit and consumed by the lexer.
The compiler enforces the alternation of sparks ' and rabbit-ears " at parse time: a same-in-same nesting (a spark immediately inside another spark) fails with ICL017I and a diagnostic that names the violation and the statement number. Where the grammar is otherwise looser than the language specification, a note calls it out below.
Top level
program ::= statement { statement }
statement ::= [ label ] verb [ negation ] [ probability ] body
label ::= "(" number ")"
verb ::= "DO" | "PLEASE" | "PLEASE" "DO" | "DON'T" | "PLEASE" "DON'T"
negation ::= "NOT" | "N'T"
probability ::= "%" number
Note that DON'T includes the negation; a DON'T verb never carries an additional NOT or N'T.
The label attaches to the statement and is unique across the whole program (duplicates fire ICL182I at compile time).
Statement bodies
body ::= assignment
| next_stmt
| resume_stmt
| forget_stmt
| abstain_stmt
| reinstate_stmt
| ignore_stmt
| remember_stmt
| stash_stmt
| retrieve_stmt
| read_out_stmt
| write_in_stmt
| come_from_stmt
| give_up_stmt
| unknown
assignment ::= lvalue "<-" expr
lvalue ::= variable | array_elem
array_elem ::= array_ref "SUB" primary { primary }
next_stmt ::= "(" number ")" "NEXT"
resume_stmt ::= "RESUME" expr
forget_stmt ::= "FORGET" expr
come_from_stmt ::= "COME" "FROM" "(" number ")"
give_up_stmt ::= "GIVE" "UP"
abstain_stmt ::= "ABSTAIN" "FROM" ( "(" number ")" | gerund_list )
reinstate_stmt ::= "REINSTATE" ( "(" number ")" | gerund_list )
ignore_stmt ::= "IGNORE" variable_list
remember_stmt ::= "REMEMBER" variable_list
stash_stmt ::= "STASH" variable_list
retrieve_stmt ::= "RETRIEVE" variable_list
read_out_stmt ::= "READ" "OUT" variable_list
write_in_stmt ::= "WRITE" "IN" variable_list
unknown ::= any_token_sequence
unknown is what the lexer assigns to any body that does not match one of the other productions. Executing an unknown statement at runtime fires ICL000I; an unknown statement that starts negated (DON'T) is the idiomatic comment syntax in INTERCAL.
Variables
variable ::= spot | twospot | tail_array | hybrid_array
spot ::= "." number
twospot ::= ":" number
tail_array ::= "," number
hybrid_array ::= ";" number
array_ref ::= tail_array | hybrid_array
variable_list ::= variable { variable }
Variable numbers are in the range 1–65535. The namespaces for spot, twospot, tail, and hybrid are independent: .1, :1, ,1, ;1 are four unrelated variables.
Expressions
expr ::= primary { binary_op primary }
binary_op ::= "$" | "~"
primary ::= const
| variable
| unary_var
| grouped
| array_elem_ref
const ::= "#" number
unary_var ::= unary_op ( variable | const )
unary_op ::= "&" | "V" | "?"
grouped ::= "'" expr "'" | "\"" expr "\""
array_elem_ref ::= array_ref "SUB" primary { primary }
There is no operator precedence. Two binary_ops in a row read left-to-right: a $ b ~ c means (a $ b) ~ c. To force right-associated evaluation, use grouping: a $ 'b ~ c'.
The language specification requires grouping to alternate between sparks (') and rabbit-ears ("): a spark may enclose either a grouped rabbit-ears expression or no grouping at all, but not another spark directly. The parser enforces this at parse time. A same-in-same nesting fails with ICL017I and a diagnostic naming the offending statement.
Gerunds
gerund_list ::= gerund { "+" gerund }
gerund ::= "CALCULATING"
| "NEXTING"
| "FORGETTING"
| "RESUMING"
| "STASHING"
| "RETRIEVING"
| "IGNORING"
| "REMEMBERING"
| "ABSTAINING"
| "REINSTATING"
| "COMING" "FROM"
| "READING" "OUT"
| "WRITING" "IN"
Gerunds are statement-type names used by ABSTAIN FROM and REINSTATE to operate on whole categories of statements. The mapping to statement types is one-to-one and is resolved at compile time: the codegen walks the statement list once per gerund in the list and emits one flag-store per matching statement.
Numbers
number ::= digit { digit }
digit ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
All numeric literals in source are decimal. There is no hexadecimal or octal syntax. Numbers larger than 65535 are technically valid in the grammar but cause a runtime error (ICL275I) if they flow into a 16-bit slot.
Whitespace and case
The lexer folds all whitespace (spaces, tabs, newlines) to single spaces, and uppercases every letter. This means the grammar above is case-insensitive in practice: do .1 <- #5 and DO .1 <- #5 are identical, as are please and PLEASE. Keywords in the grammar are written in uppercase because that is the lexer's canonical form.
Internal whitespace in a multi-word keyword is required. READ OUT is two tokens separated by at least one space; READOUT is not valid.
What the grammar leaves out
The language specification contains several features we do not implement and that this grammar accordingly omits:
- Unconditional
WRITE IN/READ OUTfor non-listed targets is spec-valid in corner cases we have not tested. - Computed labels and
NEXT FROM(a CLC-INTERCAL extension) are outside scope. - MAYBE and the other backtracking extensions are outside scope.
- TriINTERCAL (base 3–7) is outside scope. The file extensions
.3ithrough.7iare reserved but not consumed. - Wimpmode (decimal I/O) is outside scope.
The omissions are deliberate. The grammar describes what the compiler accepts today, not what INTERCAL-72 or any downstream dialect defines.
Differences from the parser
The following are cases where the parser is looser than the grammar above suggests:
- The
unknownproduction absorbs any sequence of tokens after the verb. The parser's statement-type classification is greedy: it matches the longest prefix that looks like a known type, and otherwise classifies asUNKNOWN. gerund_listis parsed by a dedicated routine that is tolerant of irregular whitespace around the+separator.- The
variable_listproduction is shared by ten statements. The parser implementation is one function (parse_var_list) called from each codegen routine.
These are implementation details; the grammar above describes the intended syntax.
Glossary
This glossary collects the vocabulary a reader needs to move between the INTERCAL specification, the compiler-theory literature, and the source of this repository. Entries are grouped by domain. Cross-references use the dot notation → term.
INTERCAL symbols
- Angle-worm,
<-. The assignment operator. Left-hand side is an lvalue, right-hand side is an expression. - Ampersand,
&. Unary AND of adjacent bits. - Big money,
$. Binary mingle. Interleaves the bits of two operands. - Book,
V(the letter, uppercase). Unary OR of adjacent bits. - Double-oh-seven,
%. Probability modifier on a statement.%50means execute half the time. - Hybrid,
;. Variable-prefix for 32-bit arrays. - Mesh,
#. Constant prefix.#5is the 16-bit constant 5. - Rabbit-ears,
". Expression grouping, alternates with → spark. - Spark,
'. Expression grouping, alternates with → rabbit-ears. - Spot,
.. Variable prefix for 16-bit scalars. - Sqiggle,
~. Binary select. Extracts bits from the left operand where the right operand (a mask) has 1s, packs them right-justified. - Tail,
,. Variable prefix for 16-bit arrays. - Two-spot,
:. Variable prefix for 32-bit scalars. - What,
?. Unary XOR of adjacent bits. - Wimpmode, a C-INTERCAL extension allowing decimal numeric I/O instead of Roman numerals and English digit names. Not implemented by this compiler.
- Wow,
!. Reserved symbol; not used by the grammar this compiler accepts.
INTERCAL statements
- ABSTAIN, deactivates a statement or a category of statements. Paired with → REINSTATE.
- COME FROM, the inverse of GOTO. After the labelled statement executes, control transfers to the COME FROM. Resolved at compile time.
- DO, the primary verb. Functionally identical to PLEASE DO; only politeness counting differentiates them.
- DON'T, tokenised contraction of DO + NOT. Marks a statement as abstained from the start.
- FORGET, pops N entries from the → NEXT stack without transferring control.
- GIVE UP, terminates the program. Every well-formed INTERCAL program ends with this.
- IGNORE, marks a variable as read-only. Paired with → REMEMBER.
- NEXT, pushes the current position onto the → NEXT stack and jumps to the labelled statement.
- PLEASE, the polite verb form. Contributes to the → politeness count.
- READ OUT, numeric output (Roman numerals) for scalars, → Turing Text Model output for arrays.
- REINSTATE, reverses an → ABSTAIN.
- REMEMBER, reverses an → IGNORE.
- RESUME, pops K entries from the → NEXT stack, returns to the last-popped address.
RESUME #1is a clean subroutine return. - RETRIEVE, pops the → stash stack, restoring the previous value of a variable.
- STASH, pushes the current value of a variable onto its per-variable stack.
- WRITE IN, numeric input (English digit names) for scalars, → Turing Text Model input for arrays.
INTERCAL runtime concepts
- Fixpoint, the point at which a self-hosting compiler's output stabilises. See self-hosting.md.
- Gerund, the
-INGform of a statement verb. Used by ABSTAIN/REINSTATE to target a whole class of statements. - Label, a parenthesised number attached to a statement, used by NEXT, COME FROM, ABSTAIN and REINSTATE to refer to that statement. Labels are unique and in the range 1–65535. Labels 1000–1999 are reserved for the → system library.
- Label 666, the syscall extension. See 666.md.
- NEXT stack, runtime stack of return addresses, 80 slots deep. Overflow fires ICL123I.
- Politeness, the ratio of PLEASE to total statements, required to be in [1/5, 1/3].
- Stash stack, per-variable stack of previous values, grown by STASH and shrunk by RETRIEVE.
- System library (syslib): arithmetic routines at labels 1000–1999. See syslib.md.
- Turing Text Model (TTM): the 256-position tape used for array-based text I/O. Character code is encoded as the tape-head displacement after a bit-reversal.
Host, target, and runtime
The three words describe different machines or environments involved in producing and running a compiled program. Confusing them is a common source of misunderstanding.
- Host: the machine the compiler itself runs on. When you invoke
zsh src/bootstrap/intercalc.sh < program.ion your laptop, the host is your laptop. - Target: the machine the compiled program will run on. For our compiler, the target is always the same as the host: we are a native compiler, not a cross-compiler. A Mac compiling INTERCAL produces a binary that runs on a Mac; it cannot today produce a binary that runs on a Raspberry Pi.
- Runtime: the collection of library code and services the target needs to execute the compiled program. Our runtime is the hand-written assembly under
src/runtime/<platform>.splus the syslib undersrc/syslib/. Every compiled INTERCAL binary links against it.
A cross-compiler is a compiler whose host and target are different machines. We are not one today. A self-hosting compiler is a compiler whose source language is the same as the language it compiles. Our bootstrap (intercalc.sh) is not self-hosting (it is zsh, not INTERCAL). Our goal is that src/compiler/stage3.i eventually will be self-hosting.
Compiler-theory vocabulary
- Abstract syntax tree (AST): a tree representation of a program's syntax, with operator nodes and leaves for literals and identifiers. Our expression parser produces an AST in parallel arrays; the statement-level representation is a flat list rather than a tree.
- Activation record, the per-call stack frame holding local variables, saved registers and return address. INTERCAL has no scope, so our "activation records" are degenerate: the NEXT stack holds only return addresses.
- Backend, the portion of the compiler responsible for emitting target-specific code. Our backend is each
codegen_<type>function (macOS/Linux ARM64) or its override incodegen_x86_64.sh. - Bootstrapping, the process of producing a self-hosting compiler without a pre-existing compiler for the same language. See self-hosting.md.
- BSS, the "Block Started by Symbol" section of an executable, holding zero-initialised data. Used here for statement-flag bytes, scalar variables, array pointers, the NEXT stack, etc.
- Bytecode, a fabricated machine code for a virtual machine, used as an intermediate representation in some compilers. We do not use bytecode; we emit target assembly directly.
- Calling convention, the contract between caller and callee about register usage, argument passing, and preservation. ARM64 macOS and Linux share the AAPCS64 convention; Linux x86-64 uses System V AMD64.
- Codegen, short for code generation, the phase that produces target code from the parsed program.
- Cross-compiler, a compiler running on platform A that produces binaries for platform B. Our compiler is not a cross-compiler today; it targets only the platform it runs on.
- Differential testing, a testing technique that runs the same input through two independent implementations and compares their outputs. We use it between pure and native syslib (see testing-and-workflow.md).
- Fixpoint, see above under INTERCAL runtime.
- Front end, the portion of the compiler responsible for reading the source language: lexer, parser, semantic analysis. Our front end is
tokenize,parse_expr, and the three check routines. - Intermediate representation (IR): a language-neutral representation between source and target. Our compiler has no IR.
- Lexer, also called scanner or tokeniser. Splits the source into tokens. Ours is
tokenize(). - Linker, the tool that combines object files into an executable. We invoke it via
cc -x assembler -, which uses the systemccas a driver forld. - Mach-O, the executable format used on Apple platforms. Our macOS target produces Mach-O binaries.
- Middle end, the portion of a compiler that operates on an → intermediate representation for optimisation purposes. We have no middle end.
- Parser, reads the token stream and produces an AST or equivalent. Ours is
parse_expr()for expressions; statement-level parsing is inlined intokenize. - RIP-relative addressing, an x86-64 instruction-addressing mode where displacements are relative to the instruction pointer. Used to produce position-independent code without a PLT.
- Runtime, the code that is present in every produced binary to implement language-level operations the compiler does not inline. See runtime.md.
- Scanner, synonym for lexer.
- Self-hosting, a compiler that can compile its own source. See self-hosting.md.
- Semantic analysis, checks that depend on meaning rather than syntax alone. Ours are politeness, label uniqueness, COME FROM resolution.
- Symbol table, the data structure that maps names in the source to their properties. Ours are
label_to_stmt,used_spot,used_twospot,used_tail,used_hybrid. - System V AMD64 ABI, the calling convention on Linux x86-64 and most other Unix-like x86-64 systems. Arguments in rdi, rsi, rdx, rcx, r8, r9.
- Tokenisation, the act of splitting source text into tokens.
- Translation unit, a source file that the compiler compiles in isolation. In INTERCAL, the whole program is a single translation unit; there is no preprocessor or
#include.
Project-specific vocabulary
- Chispa primigenea, the primordial spark, our term for the shell-bootstrap compiler
intercalc.sh. Spanish phrase chosen for poetic effect. - Generation, one compile of the self-hosted compiler by an older self-hosted compiler. See
bootstrap.shand self-hosting.md. - MVP, minimum viable product. The self-hosted template-dispatch compiler
compiler.iis the MVP;stage3.iis evolving past it. - Primordial spark. English rendering of → chispa primigenea.
- Template, a pre-generated assembly file under
src/compiler/templates/<platform>/<testname>.s. Used by the MVP's content-hash dispatch. - Templatised, of the MVP: the fact that its "compilation" is a lookup and not a real phase.
Further reading
An annotated bibliography of external resources that pair well with this repository. The resources are grouped by topic. For each, the annotation explains what the resource teaches, how it complements our docs, and which chapter here it pairs with most naturally.
All entries listed are free to read online or widely available in libraries. Priced texts are noted accordingly.
Comprehensive compiler-construction books, free online
-
Crafting Interpreters by Robert Nystrom. Available at https://craftinginterpreters.com. A hands-on introduction to scanning, parsing, and evaluation, written against a small scripting language called Lox. The Java half of the book walks through a tree-walk interpreter, the C half walks through a bytecode VM. Pairs with our pipeline.md and lexing-and-parsing.md. The book's deliberate choice to hand-write everything rather than use generators matches the style of this project.
-
Introduction to Compilers and Language Design by Douglas Thain, University of Notre Dame. Available at https://dthain.github.io/books/compiler/. A single-semester textbook that walks through a full compiler for a C-like language targeting real assembly. Broader than Crafting Interpreters in coverage, includes optimisation and register allocation, and closer in tone to a university syllabus. Pairs with code-generation.md and platforms.md.
-
Essentials of Compilation by Jeremy G. Siek. Available in both Python and Racket editions at https://github.com/IUCompilerCourse. An incremental approach: start with a tiny arithmetic language and grow it, chapter by chapter, into a realistic language. Emphasises the intermediate-representation design decisions that our no-IR approach skips. Pairs with self-hosting.md if the reader is considering adding an IR later.
-
Basics of Compiler Design by Torben Æ. Mogensen. Available at http://hjemmesider.diku.dk/~torbenm/Basics/. A compact, theory-forward textbook used at the University of Copenhagen. Stronger on formal grammar, parsing tables, and attribute grammars than the implementation-focused books above. Pairs with appendix-grammar.md and semantic-analysis.md.
-
Let's Build a Compiler by Jack Crenshaw. Available at https://compilers.iecc.com/crenshaw/. A 1988–1995 series of articles written in a conversational style, building a compiler in Turbo Pascal that emits Motorola 68000 assembly. Valuable for its "keep it simple" philosophy, which maps directly onto our own single-pass no-IR design. Pairs with code-generation.md.
Classic compiler textbooks (print)
-
Compilers: Principles, Techniques, and Tools, known as the Dragon Book, by Alfred V. Aho, Monica S. Lam, Ravi Sethi, and Jeffrey D. Ullman (Pearson, 2nd edition 2006). The canonical reference. Widely cited, dense, comprehensive. Covers topics our docs touch only lightly: LR parsing, SSA, register allocation, data-flow analysis. A legal reading copy is sometimes available at https://faculty.sist.shanghaitech.edu.cn/faculty/songfu/cav/Dragon-book.pdf (unofficial mirror). Pairs with the whole of our docs; serves as the authoritative academic reference.
-
Engineering a Compiler by Keith D. Cooper and Linda Torczon (Morgan Kaufmann, 3rd edition 2023). Emphasises the engineering side more than the Dragon Book: SSA is treated as a central IR, and the back-end chapters are unusually thorough. Good companion for readers who intend to add an IR and optimisation passes to our compiler.
-
Modern Compiler Implementation by Andrew W. Appel, with ML, Java, and C editions (Cambridge University Press). The tiger-compiler book. A tutorial-style walkthrough of a full compiler implementation, with a well-designed incremental structure. Pairs with self-hosting.md.
Bootstrapping and self-hosting specifically
-
"Bootstrapping and Metacompiling" by Tom Mewett. Available at https://tmewett.com/bootstrapping-metacompiling/. A short blog-length piece that lays out the two strategies for self-hosting (external language bridge, existing self-hosted compiler extension) with clear diagrams. Pairs with self-hosting.md.
-
"Reflections on Trusting Trust" by Ken Thompson. Turing Award lecture, 1984. Available at https://www.cs.cmu.edu/~rdriley/487/papers/Thompson_1984_ReflectionsonTrustingTrust.pdf. The canonical discussion of the trust implications of a self-hosted compiler: a malicious compiler can perpetuate itself through generations of self-compilation. Worth reading even though our compiler is too small to be a realistic vehicle for such an attack.
-
The Onramp project at https://github.com/ludocode/onramp. A portable self-bootstrapping C compiler designed to build itself on systems that lack any pre-existing C compiler. Different philosophy from ours, minimal subset first, grow outward, but the same family of problem. Pairs with self-hosting.md.
-
The shecc project at https://github.com/sysprog21/shecc. A self-hosting educational C compiler targeting ARM32 and RISC-V. Similar educational ambitions to this repository but for a real language. Good comparison point.
Per-compiler resources (Part VII deep dives)
LLVM
- LLVM Language Reference Manual (LangRef.rst), the IR specification, at https://llvm.org/docs/LangRef.html.
- "The Architecture of Open Source Applications: LLVM" by Chris Lattner at https://aosabook.org/en/v1/llvm.html.
- LLVM Developer Meetings (twice yearly, on YouTube) for talks on every part of the project.
- LLVM Weekly newsletter at https://llvmweekly.org/.
- The Clang Docs at https://clang.llvm.org/docs/ for the reference C/C++ frontend.
GCC
- GCC Internals manual at https://gcc.gnu.org/onlinedocs/gccint/. Covers GENERIC, GIMPLE, RTL.
- "An Introduction to GCC" by Brian J. Gough, free at https://nongnu.askapache.com/gcc-intro/.
- The GCC Summit proceedings (2003-2010) for retrospective architectural papers.
- GCC mailing list archives at https://gcc.gnu.org/lists.html.
rustc
- The rustc-dev-guide, the canonical reference for rustc internals.
- The Rustonomicon at https://doc.rust-lang.org/nomicon/ for unsafe Rust details the compiler enforces.
- Niko Matsakis's blog at https://smallcultfollowing.com/babysteps/ for design history of the borrow checker, NLL, and Polonius.
- Rust Internals forum at https://internals.rust-lang.org/.
- "Rust Compiler Performance" at https://perf.rust-lang.org/ for tracking compile-time regressions.
Go (gc)
- The Go internals series at https://internals-for-interns.com/posts/understanding-go-runtime/ walks the runtime piece by piece. Pairs with our runtime.md.
- Sazak's Go internals series at https://sazak.io/series/go-internals covers the SSA backend and walk pass in detail.
- The community-maintained https://github.com/emluque/golang-internals-resources indexes most Go internals material.
- Russ Cox's blog at https://research.swtch.com/ for original design notes.
- The Go assembly documentation at https://go.dev/doc/asm.
GHC (Haskell)
- "The Implementation of Functional Programming Languages" by Simon Peyton Jones (1987), free at https://www.microsoft.com/en-us/research/publication/the-implementation-of-functional-programming-languages/.
- "Implementing Lazy Functional Languages on Stock Hardware: The Spineless Tagless G-Machine" (Peyton Jones 1992), the canonical STG reference.
- "OutsideIn(X): Modular type inference with local assumptions" (Vytiniotis et al. 2011) for the type-checker algorithm.
- The GHC Commentary at https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary.
- "Trees that Grow" (Najd and Peyton Jones 2017) for the HsSyn AST design.
OCaml
- The OCaml manual at https://ocaml.org/manual.
- Real World OCaml by Yaron Minsky, Anil Madhavapeddy, Jason Hickey, free at https://dev.realworldocaml.org/.
- Xavier Leroy's papers at https://xavierleroy.org/publi/.
- "The ZINC Experiment: An Economical Implementation of the ML Language" (Leroy 1990) for the bytecode VM.
- "Linear Scan Register Allocation" (Poletto and Sarkar 1999), implemented in
asmcomp/linscan.ml.
Cranelift
- Cranelift documentation in the wasmtime repo at https://github.com/bytecodealliance/wasmtime/tree/main/cranelift/docs.
- Chris Fallin's blog at https://cfallin.org/ for design notes on regalloc2 and ISLE.
- "Simple and Efficient Construction of Static Single Assignment Form" (Braun et al., CC 2013) for the on-the-fly SSA construction algorithm.
- Bytecode Alliance Zulip at https://bytecodealliance.zulipchat.com/.
Zig
- The Zig language reference at https://ziglang.org/documentation/master/.
- Andrew Kelley's blog at https://andrewkelley.me/ for the bootstrap and self-hosted backend stories.
- Zig Software Foundation developer notes on YouTube.
- Zig source documentation in
src/Sema.zigand surrounding files.
Swift
- Swift compiler documentation at https://swift.org/swift-compiler/.
- The SIL specification in
docs/SIL.rstof the swift repo. - Apple WWDC sessions on the Swift compiler.
- Swift evolution proposals at https://github.com/apple/swift-evolution.
- Swift Intermediate Language: A High-Level IR to Complement LLVM by Chris Lattner.
V8
- V8 design docs at https://v8.dev/docs/.
- V8 blog at https://v8.dev/blog, particularly the posts on Sparkplug, Maglev, and Orinoco.
- Mathias Bynens's articles at https://mathiasbynens.be/notes/ on V8 internals.
- Cliff Click's papers on sea of nodes and HotSpot's C2.
Specific techniques
-
"Grammar: The language of languages" by Matt Might. Available at https://matt.might.net/articles/grammars-bnf-ebnf/. A clear, example-rich survey of BNF, EBNF, ABNF, and their uses. Pairs with appendix-grammar.md.
-
The Wikipedia article on recursive descent parsing at https://en.wikipedia.org/wiki/Recursive_descent_parser. Includes a complete implementation of a recursive-descent parser for Wirth's PL/0 language in C, which is a useful sanity check for somebody reading our
parse_expr. Pairs with lexing-and-parsing.md. -
The Wikipedia article on calling conventions at https://en.wikipedia.org/wiki/Calling_convention. Covers the ABI contract for every major architecture we target and several we do not. Pairs with platforms.md.
-
The OSDev wiki's "Making a Compiler" page at https://wiki.osdev.org/Making_a_Compiler. A brief survey of the compiler anatomy. Overlaps with map-of-the-compiler.md from a different angle: OS-development readers coming to compilers often arrive here first.
-
CS 6120: Advanced Compilers, Cornell, self-guided edition by Adrian Sampson. Available at https://www.cs.cornell.edu/courses/cs6120/2023fa/self-guided/. An introduction to modern compiler optimisation techniques. SSA, dataflow analysis, loop transformations. Useful for the reader who wants to see where a compiler goes after the basic pipeline this repository implements.
INTERCAL resources
-
The INTERCAL-72 reference manual. The original language specification by Donald Woods and James Lyon, 1973. Authoritative for the language semantics. Available as a scan at https://3e8.org/pub/intercal.pdf.
-
C-INTERCAL documentation at http://catb.org/~esr/intercal/. Maintained by Eric S. Raymond. Covers the C-INTERCAL extensions and some of the interpretation details that inform this compiler without being copied.
-
CLC-INTERCAL at https://uilebheist.srht.site/. Maintained by Claudio Calvelli. The source of the Label 666 idea, though we adopt a simpler parameter-passing convention than CLC-INTERCAL's "call by vague resemblance to the last assignment" (see 666.md).
-
The Esolang wiki entry for INTERCAL at https://esolangs.org/wiki/INTERCAL. A good encyclopedic overview, with pointers to related esoteric languages.
-
"INTERCAL: The Language Designed to Mock All Other Languages" by Viswhakarma K, available on DEV.to at https://dev.to/viz-x/intercal-the-language-designed-to-mock-all-other-languages-2dlf. A short, opinionated introduction for somebody entirely new to INTERCAL.
Executable formats and linking
-
The System V Application Binary Interface, multiple architecture supplements. The authoritative definitions of the calling conventions, executable layout, and symbol handling rules for every Unix-like target we support. Relevant volumes:
- x86-64: https://gitlab.com/x86-psABIs/x86-64-ABI.
- AArch64: https://github.com/ARM-software/abi-aa. Pairs with platforms.md.
-
The Apple Mach-O file format documentation, available in the MachO framework headers and at https://github.com/aidansteele/osx-abi-macho-file-format-reference. The closest thing to a spec for the Mach-O format our macOS binaries use.
-
"Linkers and Loaders" by John R. Levine (Morgan Kaufmann, 1999). The standard treatment of how the system linker glues object files into executables. We do not link manually (we invoke
ccas a driver), but understanding what it does under the hood illuminates the post-codegen phase.
Testing, TDD, and differential testing
-
"Finding and Understanding Bugs in C Compilers" by Xuejun Yang, Yang Chen, Eric Eide, and John Regehr. PLDI 2011. Available at https://www.flux.utah.edu/download?uid=114. Describes the Csmith fuzzer and the bug findings it produced across GCC and LLVM. The original high-profile demonstration that differential testing is a powerful compiler-verification technique. Pairs with testing-and-workflow.md.
-
"Differential Testing of a Verification Framework for Compiler Optimizations" by Brae J. Webb, Ian J. Hayes, and Mark Utting. 2022. https://arxiv.org/abs/2212.01748. An experience paper applying differential testing to GraalVM optimisation correctness. Directly relevant to our pure-vs-native syslib testing pattern.
Historical and philosophical
-
"The Evolution of Lisp" by Guy L. Steele Jr. and Richard P. Gabriel. HOPL-II, 1993. Available at https://www.dreamsongs.com/Files/Hopl2.pdf. Not about INTERCAL, but a beautifully written account of how a language evolves through implementation. The self-hosting arc Steele and Gabriel describe has clear parallels to our own three-phase bootstrap.
-
"Growing a Language" by Guy L. Steele Jr. OOPSLA 1998 keynote. Available in transcript form at https://www.cs.virginia.edu/~evans/cs655/readings/steele.pdf. A talk on how a small language grows into a large one through self-definition. Relevant mindset for the stage3 project.
What to read next, depending on your goal
- Build a toy compiler for a C-like language. Start with Thain, then Crenshaw, then Cooper & Torczon.
- Understand the INTERCAL dialect and why we chose specific tradeoffs. Read the INTERCAL-72 manual, then our overview.md and intercal-primer.md, then 666.md.
- Write a self-hosting compiler. Start with Mewett's essay, Mogensen, then self-hosting.md, then Appel.
- Contribute to this repository. Read AGENTS.md, then map-of-the-compiler.md, then the chapters relevant to the area you want to modify.
- Learn classical compiler theory rigorously. Dragon Book cover-to-cover, then Engineering a Compiler for modern practice.
Appendix: exercise hints
Hints, not full solutions, for the exercises that close most chapters. The hints are deliberately short. They unblock a stuck reader without short-circuiting the act of working through the problem.
If a chapter's exercises are not listed below, the exercises are direct enough that hints would be redundant.
intercal-primer.md
- 4/17 ≈ 23.5%, comfortably inside [20%, 33.3%]. The lower bound becomes binding when total = 20 (4/20 = 20%). Any further shrinkage breaks it.
- The smallest STASH/RETRIEVE program is two statements after dimensioning a politeness count. Swapping fires
ICL436I RETRIEVE WITHOUT STASH. #5is0b0000000000000101. Unary AND XORs each bit with its right neighbour. Bit 0 is1 & 0 = 0. Bit 1 is0 & 1 = 0. Bit 2 is1 & 0 = 0. The rest are0 & 0 = 0. Result: 0. Surprised? That is the lesson.- The idiom converts a 0/1 value into 1/2, pushes two NEXT targets, then
RESUMEs with the 1/2 variable.RESUME #1returns to the most recent target;RESUME #2skips one. - Alternatives:
DO .99 <- #0is nominally a no-op but actually wastes politeness count. Inserting a labelled statement and thenABSTAINing it is verbose.DON'T NOTEis shortest and idiomatically read as a comment.
pipeline.md
- The codegen prologue is everything before
_stmt_0_start.codegen_give_upproduces the exit syscall sequence (mov x0, #0; mov x16, #1; svc #0x80). Everything else is runtime. SOURCEis materialised once. The lexer splits it incrementally without making copies, thestmt_bodyentries are slices.- Swapping politeness and label checks would mean a duplicate-label program might silently fail the politeness check first. Functional difference: zero, because both are fatal.
DO (1000) NEXTflipsneeds_syslibto 1. Any label in [1000, 1999] does.- Putting the program first means its
_mainentry is followed by the runtime symbols. The linker accepts this, symbols are resolved by name, not order, but a sharper symbol search misses for the entry point. In practice the binary still works.
lexing-and-parsing.md
- Politeness is identical because both forms are negated; only the verb tokens differ. The runtime difference is that
DON'Tis one token andDO NOTis two, but both produce a negated statement. - The keyword list is in
tokenize(). None of them is a prefix of another in the current grammar (DOis not a prefix of any longer keyword;DON'Tis detected beforeDO). - The tree has 5 nodes: NODE_VAR for
.1, NODE_CONST for#5, NODE_CONST for#3, NODE_SELECT for the~, NODE_MINGLE for the$. The~is the parent of the two constants. - The two operators consume different token characters (
$vs~), so the parser can dispatch on the next token without lookahead. 'a + 'b''(or any spark inside spark) is accepted by the parser. At runtime the misnested expression fires ICL017I.
semantic-analysis.md
- For 7 statements: 2 ≤ PLEASE ≤ 2. For 12: 3 ≤ PLEASE ≤ 4. For 100: 20 ≤ PLEASE ≤ 33.
- The compiler's
label_to_stmtis bounded by the labels actually in source, so it would not need to change. The runtime's per-label tables (none, currently, labels are resolved at compile time) similarly would not change. The reduction would only affect the compile-time bounds check on label values. - Two
COME FROM (100)statements in the same program. The current behaviour is that the second silently overwrites the first; the spec saysICL555I MULTIPLE COME FROMS. - Reading an unwritten variable yields 0 (the BSS initial value). If we only recorded written variables, the codegen would not emit a BSS slot, and the read would dereference an undefined symbol, link error.
- For: catches a class of bugs at compile time. Against:
RESUMEtakes an expression that may not be statically computable. The compile-time check would flagRESUME #0but notRESUME .1where.1happens to be 0.
code-generation.md
- The abstain check is 4 instructions per statement (
adrp,add,ldrb,cbnz). On 1000 statements that is 4000 instructions. If the average statement body is 10 instructions, the overhead is ~30%. DO .1 <- '#5 $ #3'produces onebl _rt_mingle. A constant-folding pass would compute the result at compile time and emitmov w0, #Nwhere N is the precomputed mingle of 5 and 3.- Array element assignment skips the ignore check because arrays do not have an ignore flag in the current implementation. This is a feature gap, not a bug, the spec allows IGNORE on arrays but our compiler does not yet.
- The previous allocation is leaked. The runtime never calls
munmap. The OS reclaims at process exit. - Refactoring would require either a base-architecture-agnostic emit primitive or a templating layer that fills in per-architecture instruction names. Neither is large; the question is whether the duplication is bothersome enough to justify the abstraction.
runtime.md
_rt_write_romanforw0 = 0walks the Roman numeral table, finds nothing it can subtract, and writes nothing. The output is empty. Acceptable because Roman numerals do not represent zero.- With 128 entries, every character would map to two possible ASCII codes. The bit-reversal scheme requires a power-of-two tape size that is at least 256 to round-trip every byte.
- Yes.
,1is dimensioned to 3, then element 1 is 72 (ASCII H).READ OUT ,1walks the array; the first delta moves the head from 0 to 248 (= -72 mod 256), bit-reversed to ASCII H = 72. Print "H". - The runtime BSS reservation
_next_stackwould change from 80×8 to 1024×8. The codegen's overflow checkcmp w0, #79would change tocmp w0, #1023. The error message would still fire ICL123I. - The C program has to use the same ABI: AAPCS64 on ARM64, System V AMD64 on x86-64. Calling our
_rt_*functions from C is straightforward, the runtime functions follow the standard ABI. - A program that dimensions an array repeatedly inside a loop would leak memory faster than the OS reclaims it (until the program ends).
syslib.md
- The native binary is ~40 KB; the pure-syslib binary is ~1.3 MB. The factor is 33×.
- Three statements: STASH the variables, NEXT to label 1010 (subtract), then NEXT to label 1000 (add) and compare to
.1. - The 330× factor matches what you measure: a program that takes 0.09s with native takes ~30s with pure.
- Label 1900 invokes Label 666 syscall 9. Native: one syscall. Pure: ~10 INTERCAL statements that ultimately invoke the same syscall.
- The pure syslib needs the routine added in INTERCAL. The native syslib needs the matching assembly per platform. The compiler's
detect_syslibdoes not need changes, it already triggers on any 1000-1999 label.
self-hosting.md
bootstrap.shgrepscompiler.iforcodegen|_stmt_|.section. If none of those appear, it skips. The MVPcompiler.idoes not include them, sobootstrap.shexits cleanly without doing the bootstrap.- gen1 and gen2 can differ in (e.g.) register allocation; gen2 and gen3 cannot, because the compiler is now its own input and any compiler-determined difference would have shown up at gen2. Example where gen1 = gen2 = gen3: a compiler that generates byte-identical output regardless of which compiler compiled it. Possible only if the bootstrap and the self-hosted are byte-equivalent, which is exceptional.
- To distinguish DO from PLEASE DO, stage3 needs to read the verb word and branch. Smallest extension: ~30 lines of INTERCAL to scan past whitespace and compare the next 6 characters.
- Yes. Python is on every CI runner. The bootstrap would become Python instead of zsh; CI matrix and dependencies remain identical.
- No. The fixpoint test cares about the compiler reproducing itself, not about which syslib it links. Adding
--pure-syslibwould multiply compile time by 330× without gaining anything.
platforms.md
- macOS uses carry-flag conditionals because the underlying syscall ABI sets the carry on error. Linux returns negative values directly. Both predate AAPCS standardisation.
0x1002appears in themmapsyscall flags. Thesedis conservative; it would not match inside a comment because the pattern is anchored on the operand position.- Windows ARM64 should use a fresh codegen backend, the COFF format and Windows calling convention are too different for a
sedtranslation. - Yes. AT&T syntax requires every operand prefixed with
%and source-first ordering; the codegen output would have to be rewritten line by line. - About 60% slowdown is x86-64 emulation on ARM64; about 40% is Docker overhead. Measure independently by running the tests inside an x86-64 container on a real x86-64 machine.
testing-and-workflow.md
- The flags are
--filter,--verbose,--keep,--no-color,--platform.--filteris for iterating on a single failing test;--verboseshowsccstderr for assembly errors;--keeppreserves failed-test artifacts in/tmp/intercal_failuresfor post-mortem;--no-coloris for CI logs;--platformoverrides platform detection for cross-builds. - A test where the RHS is large and the variable is ignored: if the codegen reordered the checks, either the ignored write would still trigger an overflow error, or the overflow check would silently succeed because the ignore came first.
- A program exercising mingle and select with non-trivial bit patterns. Catches divergence in operator implementation that the existing add/sub/divide tests don't.
- For: workflow edits do not affect compiled program behaviour. Against: a broken workflow has surfaced subtle bugs (e.g. a CI yaml typo that masks failures).
- The slowdown ratio measures cumulative overhead. Subtract Docker startup (~3s) and you have the per-test x86-64 emulation cost.
walkthrough-hello.md
- Maximum: 5 PLEASEs is 29.4% (under 33.3%). 6 is 35.3% (over). So 5 is the maximum; one more flip is fine.
- ~12 instructions per statement (4 abstain check + 5 array element handling + 3 type/range), times 17 = ~200 instructions. Plus 20+ for the array dimensioning.
- The politeness ratio drops from 4/17 to 3/17 = 17.6%, below 20%. Compiler emits
ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE. - Hello world does not call any syslib labels (1000-1999).
--pure-sysliblinking is conditional on syslib usage. - Reducing dimension to 13:
READ OUT ,1would print 13 characters instead of 14, missing the last!. Increasing to 30: the unset elements default to zero, which the TTM tape interprets as "no head movement" and emits the same character repeatedly (or near-zero noise).
debugging.md
- ICL079I tests fail because the bound moved. Reproduce: change bounds, run tests, check
politeness_*failures. - 80 NEXTs without intervening RESUMEs trigger ICL123I (the 80th attempt fails).
- Multiplication tests fail first,
_rt_mingleis on every multiplication's hot path. Roughly half of the bootstrap suite exercises mingle directly or transitively through arithmetic syslib labels. - Use
git log --oneline | grep -i 'open\|write'to find candidate commits. Test each withgit bisect run. - Yes,
stage3.imay have a politeness or label issue caught by the linter.
anatomy-of-a-binary.md
- The diff appears in a single
.databyte, the constant value at the changed offset. - Hello world calls
_rt_write_romanzero times (it uses_rt_read_out_arrayfor character output).tests/test_read_out_num.icalls it once perREAD OUTof a scalar. - 1000-statement program: ~50 KB code, 1 KB BSS for stmt_flags, 500 bytes per scalar. Roughly 60 KB total.
stripremoves the symbol table, saving roughly half the size for small binaries. The remaining content is the actual code and data.- Hello world makes ~17 syscalls (one
writeper character emitted, plus theexit).
label-666-intro.md
- Set
.1=5,(666) NEXT, READ OUT.3. Done. - Open the file (syscall 1), loop 10 times reading 1 byte each (syscall 2), READ OUT each byte from
,65535 SUB #1, close (syscall 4). ,65535is overwritten by every Label 666 read. A program that uses it for its own purposes would have its data clobbered on the next syscall..2 = 0returns a uniform 16-bit random number. The runtime treats it as "no range limit specified".- The MVP uses syscalls 6 (argv), 1 (open), 2 (read), 4 (close), 3 (write).
lexer-theory.md
- Two states: a "start" state and a "consuming digits" state. The transition between them is the
#character; the transition out is whitespace or a non-digit. - Adding NOT and N'T as separate tokens after DO requires three more states: one for "after DO", one for "consuming N", one for emitting either NOT (after
OT) or N'T (after'T). - The lexer already uppercases everything, so a lowercase variant requires zero changes.
- SUB is a body-level keyword. Detecting it during expression parsing rather than lexing means the parser can resolve subscripts in their grammatical context. Moving it to the lexer would force the lexer to know which surrounding tokens make
SUBa keyword vs an identifier, which it cannot, since INTERCAL has no identifiers. - Collapsing the DO/DON'T branch into a single state machine is straightforward: read the verb-token, then check for
'Timmediately after.
parser-theory.md
- Each non-terminal's FIRST set:
exprstarts with primary's FIRST.primarystarts with#, prefix character, unary char, or grouping char. No overlap. - Add
@as a binary_op alternative. The parser changes by adding@to the binary-op test in the parse loop. - Five sparks/rabbit-ears deep:
'a $ "b $ 'c $ "d $ 'e' "' "' "' "'. An LR parser would consume tokens left-to-right and reduce on each grouping pair; recursion depth in our parser is exactly the nesting depth. - Unbalanced sparks: error message could be
expected ' but found ; line 5. Variable prefix without number:expected number after . at offset 12. - Sacrifices: pointer indirection is harder to follow; debugger inspection requires array-index lookup; the layout cannot grow more children per node without coordinated array growth.
calling-conventions.md
- Two register moves:
_spot_1address intox0, thenldr w0to fetch the value. One stack save: thestp x29, x30in_rt_write_roman's prologue. stp x19, x30, [sp, #-16]!thenldp x19, x30, [sp], #16; ret.r10is touched by syscalls (replacesrcx). The runtime saves and restores it where needed.- Every syscall wrapper saves
rcxandr11becausesyscallclobbers them. Look forpush rcx; push r11patterns. - Some ARM64 instructions (
stp,ldp) operate on aligned 16-byte pairs. 8-byte alignment would slow them down or rule them out.
executables-and-linking.md
file ./programprints the format and architecture. Match against the table in the chapter.- Mach-O hello world: ~25
_rt_*symbols, 17_stmt_N_*pairs (34 symbols). - On-disk size is smaller than the section table sums because BSS is not stored on disk.
- Without ICL633I, the program executes past the last instruction into uninitialised memory. SIGILL or similar.
- The implicit default section is
.textfor instructions and.datafor.ascii. A program with neither directive would land in whatever section the assembler defaults to at the start of the file, usually.text.
middle-end-and-optimisation.md
- Without
--pure-syslibthe cost is dominated by the codegen of user statements; with it, by tokenising and processing 9000 lines of syslib INTERCAL. - Three consecutive statements like
mov w0, #5; str w0, [_spot_1]; ldr w0, [_spot_1]can collapse tomov w0, #5; str w0, [_spot_1]. - 100 statements × 4 abstain instructions × possibly 2 cycles = 800 cycles saved. Negligible on modern out-of-order hardware.
- ~10 opcodes: assign, mingle, select, unary_op (×3), call, branch, label, return.
- Few. Most INTERCAL programs have <10 control-flow joins.
If you find yourself stuck on an exercise not listed here, drop a question into TODO.md or open an issue.
CLC-INTERCAL Syscall Investigation Report
Executive Summary
CLC-INTERCAL is a maintained implementation of INTERCAL that supports system calls through a special mechanism labeled "label 666". The syscall system uses an unusual parameter passing convention called "call by vague resemblance to the last assignment", which is unique to CLC-INTERCAL and has no parallel in any other programming language.
1. What is CLC-INTERCAL?
CLC-INTERCAL is a modern implementation of the INTERCAL programming language, maintained by Claudio Calvelli.
Key Characteristics:
- Extends standard INTERCAL with new features not in INTERCAL-72
- Introduces system-level programming capabilities
- Adds quantum operations and object-oriented extensions
- Provides advanced I/O mechanisms beyond standard INTERCAL (Baudot-based encoding)
Relevant Extensions:
- NEXT FROM statement: Like COME FROM but saves return address on the call stack
- Computed labels: Dynamic label resolution
- Syscall support: Via label 666 mechanism
- Compiler object system: Modular extensions loaded at compile time
Compiler Usage:
- Command:
sick(CLC-INTERCAL compiler) - To enable syscalls: Add letter 's' to compiler suffix
- Example:
sick -c sci program.i(c=CLC variant, s=syscalls, i=INTERCAL) - This loads the compiler object
syscall.io
- Example:
- Works with any INTERCAL compiler variant (even INTERCAL-72) if specified as preload
2. Label 666 Syscall Mechanism
Overview
Label 666 is a special reserved construct in CLC-INTERCAL that provides access to system-level operations. It is NOT part of standard INTERCAL and is CLC-INTERCAL's unique extension.
How It Works
CLC-INTERCAL implements a hidden "PLEASE NEXT FROM (666)" injected by the syscall.io compiler object. When enabled:
- The compiler reserves label 666 for syscall dispatch
- When your code executes
NEXTto label 666, it doesn't jump to user code - Instead, it traps into the syscall handler
- The handler reads the registers you set up, performs the syscall, and returns
Basic Syntax Example
(666) DO .5 <- #1
DO (666) NEXT
DO READ OUT .5
- Line 1: Set register
.5to syscall #1 - Line 2: Jump to label 666 (invokes syscall handler)
- Line 3: Read the result (now in
.5)
3. Parameter Passing Convention: "Call by Vague Resemblance"
This is CLC-INTERCAL's most distinctive and unusual feature. Quote from documentation:
"The system call will use up to five arguments, provided by registers .-$%OS, :-$%OS, ,-$%OS, ;-$%OS and @%$OS. This is called 'call by vague resemblance to the last assignment' and, to our knowledge, no other language has ever used this style of parameter passing."
The Mechanism in Detail
What is %OS?
%OSis a special register variable in CLC-INTERCAL- It tracks which register was last assigned to
- Its value is the number of the most-recently-assigned register
How it works:
Every time your program assigns a value to any register, %OS is updated:
DO .5 <- #1 * %OS now refers to register .5
DO :7 <- #100 * %OS now refers to register :7
DO ,1 <- #50 * %OS now refers to register ,1
When a syscall executes, it can access parameters via:
.-$%OS= the spot register with the number in %OS (e.g., if %OS=5, then .5):-$%OS= the two-spot register with the number in %OS (e.g., if %OS=5, then :5),-$%OS= the tail array register with the number in %OS;-$%OS= the hybrid array register with the number in %OS@%$OS= the whirlpool register with the number in %OS (rare)
Example Pattern:
DO .1 <- #42 * Set syscall #42
DO .2 <- #1000 * Set parameter 1
DO .3 <- #2000 * Set parameter 2
DO (666) NEXT * Execute syscall; %OS was bound to .3
* Syscall reads .-3, :-3, ,-3, ;-3, @3
DO READ OUT .1 * Result now in .1
After NEXT returns from label 666:
- The syscall handler has read .3, :3, ,3, ;3, @3 as parameters
- The handler wrote results back to those same registers
- Your program continues with the results available
Why This Design?
This is deliberately obscure and humorous - it reflects INTERCAL's design philosophy of being maximally difficult to understand. The name "vague resemblance to the last assignment" is intentional - it's vague because the language doesn't explicitly tell you which registers are parameters.
4. Known Syscalls
Syscall #1: Version Information
Purpose: Get CLC-INTERCAL version number
How to Call:
DO .5 <- #1
DO (666) NEXT
DO READ OUT .5
Parameters:
- Input: Syscall number #1 in register (e.g.,
.1 <- #1)
Output:
- Stores version number (as a large integer) in the register
Example Output:
- Version 1.-94.-2 would return a specific number encoding that version info
Other Syscalls
Critical Finding: The documentation found does NOT provide a comprehensive public list of syscalls beyond #1.
The investigation revealed references suggesting there may be additional syscalls for:
- File operations (open, read, write, close)
- Process control (fork, exit, etc.)
- Memory operations
- I/O stream control
However, the actual syscall numbers and specifications are not publicly documented. This is intentional - CLC-INTERCAL maintains deliberately obscure documentation as part of INTERCAL's design philosophy.
To discover the full syscall list, one would need to:
- Read the CLC-INTERCAL source code (Perl-based)
- Search the
syscall.iocompiler object implementation - Contact Claudio Calvelli directly
- Reverse-engineer from compiled CLC-INTERCAL programs
5. How Syscalls Are Invoked - Complete Process
Step-by-Step Invocation
Step 1: Set Up Parameters
DO .1 <- #1 * Syscall number
DO .2 <- #10 * Parameter 1
DO .3 <- #20 * Parameter 2
Step 2: %OS Binding Happens Automatically
- After
DO .3 <- #20,%OSis bound to register.3 - The syscall handler will look for parameters in .3, :3, ,3, ;3, @3
Step 3: Invoke Syscall
DO (666) NEXT
This causes:
- Code jumps to label 666
- Syscall handler intercepts (doesn't actually jump to label 666 user code)
- Handler reads registers based on %OS value
- Handler performs the syscall
- Handler returns via
RESUME #1to the next statement
Step 4: Retrieve Results
DO READ OUT .1 * Result is in .1 (or wherever output was placed)
The Hidden "NEXT FROM (666)"
The syscall.io compiler object inserts hidden code that effectively does:
PLEASE NEXT FROM (666)
* Syscall dispatch code (hidden from programmer)
* Reads .-$%OS, :-$%OS, etc.
* Performs syscall
* Puts result back in registers
This means:
- Label 666 is reserved - user programs cannot use it for other purposes
- The syscall mechanism intercepts NEXT to label 666 - user code never actually lands there
- The mechanism is completely transparent once enabled
6. I/O and File Operations in CLC-INTERCAL
Standard I/O (Non-Syscall Based)
Binary I/O:
- Works with hybrid (
;) registers only (32-bit values) - Must be dimensioned before READ OUT or WRITE IN
- Processed one element at a time
- Uses a "garbling algorithm" to encode/decode byte arrays
- Example:
DO ;1 <- #256 * Dimension array DO WRITE IN ;1 * Read bytes from stdin DO READ OUT ;1 * Write bytes to stdout
Text I/O:
- Uses Baudot-based encoding (5-bit character codes, not ASCII)
- Each character = two codes (shift state to change between letters/numbers + actual character code)
- Differs significantly from C-INTERCAL's Roman numeral / English digit approach
- Limited character set compared to full ASCII
Via Syscalls
Syscalls likely support:
- File operations (open, read, write, close)
- File system operations (stat, mkdir, etc.)
- Process control
- Other OS-level interactions
However, without the full syscall list, we cannot specify these precisely.
7. Compiler Configuration for Syscalls
To enable syscalls in CLC-INTERCAL:
sick -c sci program.i
Breaking down the suffix:
s= load syscall.io compiler object (enables label 666 syscalls)c= CLC-INTERCAL compiler variant (not INTERCAL-72)i= INTERCAL base language
Without the 's':
- Syscall.io is not loaded
- Attempting to use label 666 will try to jump to normal code (not a syscall)
- Will likely cause error or undefined behavior
Compiler objects can be combined:
- Different letters load different compiler objects
sspecifically enables syscall support- Other objects exist for I/O, optimization, debugging, etc.
8. Key Limitations & Observations
Known Constraints
- Limited Public Documentation: Only syscall #1 (version) is documented
- Unique Convention: "Call by vague resemblance" has no parallel in other languages
- Label 666 Monopoly: Only one syscall mechanism; programs cannot reuse label 666 for anything else
- Register Binding Singularity: %OS can only bind to one register at a time; last assignment always wins
- CLC-INTERCAL Extension Only: Syscalls do NOT exist in INTERCAL-72 or C-INTERCAL (different systems)
Architectural Implications
-
Not Standard INTERCAL: The syscall mechanism is a CLC-INTERCAL extension
-
Portability Issue: Programs written using label 666 syscalls will NOT work with other INTERCAL implementations
-
Self-hosting Options:
- Implement compatible syscall mechanism (requires understanding full spec)
- Or: generate code that doesn't rely on syscalls (stdin/stdout only) - simpler
- Or: implement our own simpler syscall mechanism
-
Deliberate Obscurity: CLC-INTERCAL intentionally keeps syscall documentation vague to match INTERCAL's design philosophy
9. Design Considerations for Our Compiler
Three Implementation Paths
Path A: Full CLC-INTERCAL Compatibility
Pros:
- Could compile existing CLC-INTERCAL programs
- "Idiomatic" compatibility
Cons:
- Requires reverse-engineering complete syscall specification
- Requires implementing "call by vague resemblance"
- Overkill for a new compiler
- Locks us into CLC-INTERCAL's design choices
- Very complex to implement correctly
Recommendation: NOT RECOMMENDED for initial implementation
Path B: Simplified Custom Syscalls
Pros:
- Sufficient for our use cases
- Simpler implementation than CLC-INTERCAL
- Can design our own cleaner parameter passing
- Can implement only what we need
- Documented clearly (no ambiguity)
Implementation:
- Keep label 666 convention (recognizable)
- Design simpler parameter convention (e.g., always use ., :, ,, ; registers with fixed numbers)
- Document fully in our compiler
- Make clear: "Not CLC-INTERCAL compatible, our extension"
Example syscalls to support:
- Open file, read file, write file, close file
- Get file size, delete file
- List directory
- Execute subprocess
Cons:
- Not compatible with CLC-INTERCAL programs
- But: CLC-INTERCAL programs probably rare anyway
- Must be documented to avoid confusion
Recommendation: RECOMMENDED for practical use
Path C: No Syscalls (Pure INTERCAL)
Pros:
- Simplest possible implementation
- Pure standard INTERCAL - no ambiguity
- No need to understand CLC-INTERCAL details
- Matches original CLAUDE.md plan (stdin/stdout filter)
- Self-hosting works perfectly
Implementation:
- Compiler reads
.ifrom stdin, writes binary to stdout - No file I/O needed during compilation
- Runtime library embeds as byte data in executable
- All I/O goes through standard streams
Cons:
- Limited for practical programs (can't read input files)
- More awkward for multi-file projects
Recommendation: RECOMMENDED for compiler self-hosting; can add Path B later for generated programs
Recommended Combined Approach
-
Phase 1 (Self-hosting): Use Path C - pure INTERCAL, stdin/stdout only
- Simpler to implement
- Sufficient for compiler to compile itself
- Matches original architecture
-
Phase 2 (Practical Programs): Add Path B - custom syscalls
- Document clearly as our extension
- Simple parameter passing (not "vague resemblance")
- Implement incrementally: start with file I/O
-
Phase 3 (Optional): Research full CLC-INTERCAL spec
- Only if CLC-INTERCAL compatibility becomes a requirement
- Not needed for initial compiler release
10. Sources & References
Primary Sources
-
Esolang Wiki - CLC-INTERCAL
- URL: https://esolangs.org/wiki/CLC-INTERCAL
- Content: Comprehensive overview of language features, examples of NEXT FROM, compiler objects documentation
- Reliability: Community-maintained, accurate
-
Debian Manual Pages - sick(1p)
- URL: https://manpages.debian.org/unstable/clc-intercal/sick.1p.en.html
- Content: SICK compiler documentation, compiler options, file type handling
- Reliability: Official Debian package
-
CLC-INTERCAL Implementation - Progopedia
- URL: http://progopedia.com/implementation/clc-intercal/
- Content: Implementation overview, version information
- Reliability: Maintained programming language reference
-
CLC-INTERCAL Reference Documentation
- URL: https://oshaboy.github.io/clc_intercal_docs/
- Content: Language reference (variable access issues noted in searches)
- Reliability: Community documentation effort
-
INTERCAL Reference Manual
- URL: https://3e8.org/pub/intercal.pdf
- Content: Original INTERCAL specification (for comparison)
- Reliability: Official specification
Key Quoted Passages
"The compiler object syscall.io hides a 'PLEASE NEXT FROM (666)' in a dark corner of your operating system."
"The system call will use up to five arguments, provided by registers .-$%OS, :-$%OS, ,-$%OS, ;-$%OS and @%$OS, in other words the spot, two spot, tail, hybrid and whirlpool register with the same number as whatever you last assigned to."
"This is called 'call by vague resemblance to the last assignment' and, to our knowledge, no other language has ever used this style of parameter passing."
"Every time your program assigns a value to a register, %OS is freed from any existing masters and enslaved to the register you've just assigned to."
11. Conclusions & Recommendations
Key Findings
- ✅ CLC-INTERCAL's syscall mechanism is real and functional, though deliberately obscure
- ✅ Label 666 is the confirmed syscall entry point using a unique "call by vague resemblance" convention
- ✅ Syscall #1 (version information) is the only publicly documented syscall
- ✅ Complete syscall specification is not publicly available - would require source code analysis
- ✅ For our compiler, full CLC-INTERCAL compatibility is NOT necessary
- ✅ Self-hosting via pure INTERCAL (stdin/stdout) is viable and matches the original plan
Recommendations for Our Project
For the Initial Release:
- Implement Path C (pure INTERCAL, no syscalls)
- Compiler: reads
.ifrom stdin, writes binary to stdout - Runtime: embeds as byte data in output executable
- No need to understand or implement CLC-INTERCAL's syscall mechanism
For Future Releases:
- Add Path B (custom simplified syscalls) for practical program support
- Design our own clean syscall interface
- Document clearly that it's our extension, not CLC-INTERCAL
- Can be done incrementally without breaking Path C compatibility
Never Required:
- Full CLC-INTERCAL compatibility (unless that becomes an explicit project goal)
- Reverse-engineering the complete CLC-INTERCAL syscall specification
- Implementing "call by vague resemblance" (too complex and not idiomatic)
Appendix: "Call by Vague Resemblance" Explained Visually
The Mechanism in Action
PROGRAM EXECUTION:
1. DO .5 <- #1
Effect: %OS now = 5 (bound to register .5)
2. DO .6 <- #1000
Effect: %OS now = 6 (bound to register .6)
3. DO .7 <- #2000
Effect: %OS now = 7 (bound to register .7)
4. DO (666) NEXT
Syscall invoked with %OS = 7
Syscall reads parameters from:
- .-7 (i.e., register .7)
- :-7 (i.e., register :7)
- ,-7 (i.e., register ,7)
- ;-7 (i.e., register ;7)
Syscall uses the values in these registers
as its parameters.
5. After NEXT returns:
Syscall results are in the same registers
Why It's Called "Vague"
The syscall doesn't explicitly tell you which registers are parameters:
- You set up values in .7, :7, ,7, ;7
- You jump to 666
- The syscall reads "whatever register .7, :7, ,7, ;7 happen to be"
- This is "vague" because the syscall doesn't declare "I need parameters in registers X, Y, Z"
- Instead, it says "I'll use the registers that match whatever you last assigned to"
This is intentionally confusing and perfectly captures INTERCAL's design philosophy.
INTERCAL patterns
Verified patterns for writing non-trivial programs in INTERCAL. Every snippet here was compiled with this repo's bootstrap (src/bootstrap/intercalc.sh) and the behavior observed empirically. Intended as reference for the Phase 4 self-hosted compiler work (src/compiler/stage3.i), where these patterns will need to be generated by codegen.
Zero test
Input: scalar .N. Output: .R = 0 iff .N == 0, else .R = 1.
DO .R <- '.N ~ .N' ~ #1
Why it works: .N ~ .N packs every set bit of .N into the low bits of the result (select-from-self). If .N == 0, no bits are selected, result is 0. Then ~ #1 extracts bit 0. So .R = 1 iff .N != 0.
Verified with .N ∈ {0, 1, 42} → output 0, 1, 1 respectively.
Equality test
Input: scalars .A, .B. Output: .R = 0 iff .A == .B, else nonzero.
DO STASH .1 .2 .3 .4
DO .1 <- .A
DO .2 <- .B
PLEASE DO (1010) NEXT DON'T NOTE .3 = .1 - .2 (wraps unsigned)
DO .R <- .3
DO RETRIEVE .1 .2 .3 .4
.R == 0 iff the values were equal. For a strict 0/1 predicate, chain with the zero test:
DO .EQ <- '.R ~ .R' ~ #1 DON'T NOTE 0 if equal, 1 if different
DO :20 <- '.EQ $ #1'
DO :21 <- '?:20'
DO .NEQ <- ':21 ~ #1' DON'T NOTE 1 if equal, 0 if different
Adding two scalars
Input: .A, .B. Output: .S = .A + .B, wraps mod 2^16 via 1009; 1000 raises ICL1999I on overflow.
DO STASH .1 .2 .3 .4
DO .1 <- .A
DO .2 <- .B
PLEASE DO (1000) NEXT
DO .S <- .3
DO RETRIEVE .1 .2 .3 .4
Use 1009 if overflow should not be fatal: .4 == 1 when no overflow, .4 == 2 when overflow.
In-place increment / decrement
DO (1020) NEXT with .1 = N sets .1 = N + 1 (wraps). No 1021 exists; to decrement use 1010 with .2 = #1.
Convert 0/1 boolean to 1/2 selector
Needed for computed RESUME (see "Early exit" below).
Given .B ∈ {0, 1}, want .S = 2 when .B == 0, .S = 1 when .B == 1:
DO :20 <- '.B $ #2'
DO :21 <- '?:20'
DO .S <- ':21 ~ #3'
The other direction (.S = 1 when .B == 0) uses $ #1 instead of $ #2:
DO :20 <- '.B $ #1'
DO :21 <- '?:20'
DO .S <- ':21 ~ #3'
Verified both; result matches the truth table exactly.
COME FROM infinite loop
(200) DO COME FROM (219)
DON'T NOTE body goes here
PLEASE DO READ OUT .COUNTER
DON'T NOTE decrement COUNTER via syslib 1010
(219) DO .99 <- #0
PLEASE DO GIVE UP DON'T NOTE unreachable; loop never exits on its own
Each time (219) executes, control jumps to the statement AFTER (200) (the body start). Verified by running and observing the counter underflow from 0 to 65535 and continue decrementing.
To make the loop terminate: abstain (200). Once (200) is abstained, the COME FROM no longer fires and (219) falls through to the statement after it.
Early exit / unwind ("two-way branch")
RESUME N pops N entries from the NEXT stack and returns to the N-th popped address (the oldest, furthest-back). This is the language's only mechanism for conditional control flow in the same frame.
(A) DO COME FROM ...
DO BODY
DO .SEL <- 1-or-2
DO (X) NEXT DON'T NOTE push addr-after-this
DO (Y) NEXT DON'T NOTE push addr-after-this
PLEASE DO RESUME .SEL DON'T NOTE when .SEL=1, return to the most recent NEXT;
DON'T NOTE when .SEL=2, return 2 levels up (the caller of A).
Important caveat observed empirically: (X) and (Y) both execute sequentially if they use RESUME #1 to return normally. The branching happens only when the targets do NOT return normally (typical: DO FORGET #1 to drop the NEXT push, then DO RESUME #1 to unwind the caller's stack instead). See src/syslib/syslib.i label 1000 for the canonical usage.
This pattern cannot select one of two code branches in the same scope, it unwinds to an ancestor. For same-scope conditional execution, use the ABSTAIN pattern below.
Conditional ABSTAIN (same-scope if-then)
To run statement S only when .COND == 1:
- Place
Swith a label(S_LABEL). - Place a companion
(GUARD) DON'T ABSTAIN FROM (S_LABEL)that starts abstained (DON'Tmakes a statement initially inactive). - When you want
Sto fire on the NEXT iteration,DO REINSTATE (GUARD). On the next visit,(GUARD)runs and abstainsS_LABEL, preventingSfrom firing THAT iteration, wait, that's backwards.
The cleaner shape (inverse logic):
(S_LABEL) DO STATEMENT: runs every iteration by default.- To prevent it running:
DO ABSTAIN FROM (S_LABEL). - To let it run again:
DO REINSTATE (S_LABEL).
But we need the ABSTAIN/REINSTATE calls themselves to be conditional, which recurses the problem. The fully general solution requires the COMPUTED RESUME pattern wrapping each conditional ABSTAIN call; in practice this is verbose (~10 statements per conditional).
Loop with break
Given the above, a bounded loop follows this shape:
(LOOP) DO COME FROM (LOOP_END)
DO <body>
DO <decrement-or-advance>
DO <check-termination> DON'T NOTE compute .SB = 1 if should break
DO <if .SB, abstain (LOOP)>
(LOOP_END) DO .99 <- #0
Because the "if .SB, abstain" step requires the unwind-based computed RESUME, the realistic minimum size of this construct is ~20 statements including the politeness-padding needed to stay within [1/5, 1/3].
Practical recommendation
For stage3.i, prefer:
- Unrolled operations where the iteration count is small and known.
- Calling syslib routines that already encapsulate loops internally (arithmetic, bit operations).
- Avoiding loops entirely until a dedicated "loop intrinsic" can be added as a compiler feature and implemented once in assembly.
When an actual loop is unavoidable (e.g., scanning 60000-byte source), the expected cost is ~30 statements of scaffolding around a small body, still feasible but worth factoring into the compiler structure.
Empirically: the unwind dance fails at top level
Several attempts at the standard (NEXT_A) (NEXT_B) (RESUME .sel) pattern revealed that it ONLY works when there are at least N pending NEXT-stack entries, where N is the maximum value of .sel. At top level of _main, the NEXT stack is empty, so any RESUME N (N >= 1) immediately fires ICL632I PROGRAM ENDED VIA RESUME INSTEAD OF GIVE UP.
Even inside a function, the pattern is fragile: (801) at the first NEXT always wins because it FORGETs its own push and unwinds. The second NEXT and the RESUME .sel line are unreachable in the normal flow. Empirically verified by testing syslib label 1000 with .1=#65535, .2=#1: it should error on overflow per the spec but actually returns silently, exit 0, no ICL code. The (1801) "no overflow" path always wins; the (1802) error path is dead code.
So the syslib's promised "error on overflow" for 1000 is documentation-only. Behavior matches 1009 (silent wrap).
Conditional ADD without a branch
A pattern that DOES work and avoids the conditional execution problem entirely:
DON'T NOTE compute .B = 1 if .A == .CMP else 0
DO STASH .1 .2 .3 .4
DO .1 <- .A
DO .2 <- .CMP
PLEASE DO (1010) NEXT DON'T NOTE .3 = .A - .CMP (wraps)
DO .D <- .3
DO RETRIEVE .1 .2 .3 .4
DO .Z1 <- '.D ~ .D' DON'T NOTE pack any set bit to LSB
DO .Z <- '.Z1 ~ #1' DON'T NOTE 0 if .D=0, 1 otherwise
DO :T1 <- '.Z $ #1' DON'T NOTE flip via mingle+xor: .B = NOT .Z
DO :T2 <- '?:T1'
DO .B <- ':T2 ~ #1' DON'T NOTE .B = 1 if .A==.CMP, 0 otherwise
DON'T NOTE then unconditionally accumulate
DO STASH .1 .2 .3 .4
DO .1 <- .COUNTER
DO .2 <- .B
PLEASE DO (1000) NEXT DON'T NOTE .COUNTER += 0 or 1
DO .COUNTER <- .3
DO RETRIEVE .1 .2 .3 .4
This is what stage3.i Stage 3.1.d uses to compute "is first byte equal to 'D'" without any branch instruction. ~15 statements per equality test, but no abstain dance, no unwind, no branch needed.
Status of the stage3.i loop work
Three attempts have been logged. Each ended at the same blocker: a clean conditional break in INTERCAL needs either a multi-statement abstain dance with computed REINSTATE, or the unwind pattern wrapped in a function with at least one ancestor frame. Both work in principle; both require careful design more than translation from a plan.
The pragmatic decision documented in TODO.md and the project status memory: the v0.1 release ships with the MVP template-passthrough self-hosted compiler (functionally complete for all 25 test programs). stage3.i continues to evolve via feature-by-feature unrolled additions (3.1.a byte count, 3.1.b first byte, 3.1.c last byte, 3.1.d is-first-D boolean...). Real loops with breaks deferred to v0.2+.
Politeness budget
Every statement that is DO, PLEASE, PLEASE DO, DON'T, or PLEASE DON'T counts. That includes DON'T NOTE comments.
Rule (enforced only when stmt_count >= 5):
polite * 5 >= stmt_count(at least 1/5 polite)polite * 3 <= stmt_count(at most 1/3 polite)
tools/lint_intercal.sh computes this statically. tools/pipeline_dump.sh prints the exact count and verdict for a given source.
Writing safe expressions
- Never nest
'...'inside another'...'. Never nest"..."inside another"...". Sparks and rabbit-ears MUST alternate. - When an expression would require same-type nesting, split into multiple statements using an intermediate twospot variable:
DO :TMP <- '?:INPUT'
DO .OUT <- ':TMP ~ #1'
This is strict; the bootstrap rejects bad nesting at parse time.
STASH/RETRIEVE discipline
Before calling a syslib routine, STASH every .1-.4 / :1-:4 that you need to preserve. After the call, RETRIEVE them immediately. Do not STASH inside a loop without a matching RETRIEVE, the stash stacks grow without bound.
DO STASH .1 .2 .3 .4
DO .1 <- .X
DO .2 <- .Y
PLEASE DO (1000) NEXT
DO .RESULT <- .3
DO RETRIEVE .1 .2 .3 .4
Expected gotchas (observed, documented in bugs_learned)
PLEASE NOTEexecutes as an UNKNOWN statement and triggers ICL000I at runtime. UseDON'T NOTEfor comments.- syslib.i must be APPENDED to source, not prepended. If prepended, syslib code runs before your program.
DON'Tis a single token with the apostrophe (byte 0x27). The tokenizer treats it as a keyword.- Assigning a 32-bit expression to a 16-bit scalar raises ICL275I at runtime.