Verifying compilers (Part 1)
I wanted to run an experiment on compiler formalization and autoresearch on optimization. Basically, I wanted to write a simple language and compiler by hand, then state some laws and properties that prove the compiler correct (preserving semantics) and then throw AI compute to make optimizations that preserve my proofs.
If the correctness theorem is locked, the AI can try whatever it wants: if the proof still goes through, the optimization is correct no matter how weird it is.
My focus was basically on the formalization part, not on the language. I wanted to reinforce on how to formalize compilation steps and strategies to do so. So I picked a very small and simple language: IMP.
This is a 2-part post. In this first part we build the whole thing: the language, what its programs mean, a small stack machine, the compiler, and the theorem that says the compiler is correct (and its proof).
I'll also cover the AI optimization management by locking the theorem and seeing how fast they can make the generated code without breaking it. Spoiler: code ends up running 81% fewer machine steps, and every single optimization is proved.
In part 2 I'll dig deeper into how to formalize actual semantics. Currently, we compile to an abstract machine and count instructions. However, in a real compiler we'd like to compile to an actual target such as arm or x86 (or something simpler, like RISC-V which will probably be my choice).
What does "verified compiler" even mean?
A compiler translates a program in one language into another language. To say it is correct, we need four things:
- A precise meaning for the source language (what does a program do?)
- A precise meaning for the target language (what does the machine do?)
- The compiler itself, as a function from source programs to target programs
- A theorem connecting them: running the compiled code does the same thing as running the source program
Real projects like CompCert (C to assembly, in Coq) and CakeML (ML to machine code, in HOL4) do exactly this at a huge scale. We're doing the toy version, but the shape is the same. In one picture:

The top arrow is the source semantics: program c starting in state σ ends in state σ'. The bottom arrow is the machine: the compiled code C(c), starting at instruction 0, runs until just past its last instruction. The theorem says that whenever the top arrow exists, the bottom one exists too, and it lands on the same final store σ'. Keep this picture in mind, most of this post is about building those four pieces.
Everything is written in Lean 4 (core library only, no Mathlib).
IMP
IMP is the classic toy imperative language from semantics textbooks. It has arithmetic, booleans, assignment, sequencing, if and while. No functions, no heap, nothing fancy. Its grammar is tiny:
a ::= n | x | a + a | a - a | a * a
b ::= true | false | a = a | a ≤ a | ¬b | b ∧ b
c ::= skip | x := a | c ; c | if b then c else c | while b do c
skip is the command that does nothing (useful as the empty else branch), and c ; c runs one command and then the other. In Lean, each line of the grammar becomes an inductive type:
inductive Arithmetic : Type where
| num : Nat → Arithmetic
| var : String → Arithmetic
| add : Arithmetic → Arithmetic → Arithmetic
| sub : Arithmetic → Arithmetic → Arithmetic
| mul : Arithmetic → Arithmetic → Arithmetic
inductive Boolean : Type where
| tru : Boolean
| fal : Boolean
| eq : Arithmetic → Arithmetic → Boolean
| leq : Arithmetic → Arithmetic → Boolean
| not : Boolean → Boolean
| and : Boolean → Boolean → Boolean
inductive Command : Type where
| skip : Command
| assign : String → Arithmetic → Command
| seq : Command → Command → Command
| ifte : Boolean → Command → Command → Command
| whil : Boolean → Command → Command
Note that we don't have <, ≠ or or. We don't need them: a < b is ¬(b ≤ a) and a ∨ b is ¬(¬a ∧ ¬b). Fewer constructors means fewer cases in every proof, which is a good deal.
Programs read and write variables, so we also need a state: a map from variable names to values. The simplest way to write that in Lean is a function:
abbrev State : Type := String → Nat
def State.set (s : State) (key : String) (val : Nat) : State :=
fun y => if y = key then val else s y
Every variable has a value (unset ones are just whatever the initial state says, usually 0), and State.set returns a new state where key now maps to val. Values are natural numbers, which means subtraction is truncated: 3 - 5 = 0. It looks weird, but it's a perfectly fine semantics, as long as the compiler agrees with it (and it will, because the machine uses the same Nat subtraction).
What does an IMP program mean?
Expressions are easy. They always terminate, so their meaning can be plain recursive functions:
def Arithmetic.eval (s : State) (a : Arithmetic) : Nat := match a with
| num n => n
| var x => s x
| add a b => (Arithmetic.eval s a) + (Arithmetic.eval s b)
| sub a b => (Arithmetic.eval s a) - (Arithmetic.eval s b)
| mul a b => (Arithmetic.eval s a) * (Arithmetic.eval s b)
Boolean.eval is the same idea, returning a Bool.
Commands are the interesting part, because of while. A while loop may never terminate, and Lean only accepts total functions. So we can't just write Command.eval : Command → State → State. There are two common ways out:
- Give the evaluator fuel, a counter that goes down on every loop iteration, and return
nonewhen it runs out. - Define the meaning as a relation instead of a function.
I went with the relation. It's the standard choice for this kind of proof, and it's also closer to how semantics are written on paper. We define Exec c s s', which reads "running c from state s ends in state s'". If c loops forever from s, there is simply no s' that makes this true.
On paper, this relation is a set of inference rules (the same notation I discussed in Type Theory 101): premises above the line, conclusion below.
─────────────
⟨skip, σ⟩ ⇒ σ
─────────────────────────────
⟨x := a, σ⟩ ⇒ σ[x ↦ eval a σ]
⟨c₁, σ⟩ ⇒ σ₁ ⟨c₂, σ₁⟩ ⇒ σ₂
─────────────────────────────
⟨c₁ ; c₂, σ⟩ ⇒ σ₂
eval b σ = true ⟨c₁, σ⟩ ⇒ σ'
───────────────────────────────
⟨if b then c₁ else c₂, σ⟩ ⇒ σ'
eval b σ = false ⟨c₂, σ⟩ ⇒ σ'
────────────────────────────────
⟨if b then c₁ else c₂, σ⟩ ⇒ σ'
eval b σ = false
─────────────────────
⟨while b do c, σ⟩ ⇒ σ
eval b σ = true ⟨c, σ⟩ ⇒ σ₁ ⟨while b do c, σ₁⟩ ⇒ σ₂
──────────────────────────────────────────────────────────
⟨while b do c, σ⟩ ⇒ σ₂
And in Lean, each rule is a constructor of an inductive Prop. Here are a few of them:
inductive Exec : Program → State → State → Prop where
| skip (s : State) : Exec .skip s s
| assign (s : State) (x : String) (a : Arithmetic) :
Exec (.assign x a) s (State.set s x (Arithmetic.eval s a))
| seq (s s1 s2 : State) (c1 c2 : Command) :
Exec c1 s s1 →
Exec c2 s1 s2 →
Exec (.seq c1 c2) s s2
-- ifTrue, ifFalse, whileFalse ...
| whileTrue (s s1 s2 : State) (b : Boolean) (c : Command) :
Boolean.eval s b = true →
Exec c s s1 →
Exec (.whil b c) s1 s2 →
Exec (.whil b c) s s2
Read whileTrue slowly: if the condition is true in s, the body takes s to s1, and the whole loop again takes s1 to s2, then the loop takes s to s2. The loop is defined in terms of itself, and that's fine, because a proof of Exec is a finite tree. A terminating loop has a finite derivation, and a non-terminating one has none.
A small confession: my first version of whileTrue had Exec (.whil b c) s s1 in the third premise instead of s1 s2. Lean accepted it happily, because it's a perfectly valid inductive type. It just means something else (and something wrong). This is the bad part of formal verification: the proofs are checked by the machine, but the definitions are not. If the semantics is wrong, you get a perfectly checked proof of the wrong theorem. The definitions are what you have to trust, so they're the part worth reading twice.
The target: a stack machine
Now, what do we compile to? My first thought was real assembly. But then the final step (printing the assembly and running it on a real CPU) is outside the proof, and you have to trust it. I wanted the whole chain to be formal (for now), so the target is an abstract stack machine, defined in Lean like everything else.
A machine configuration has three parts: the program counter, a stack of numbers, and the store (the same State as before).
structure Config where
pc : Int
stack : List Nat
store : State
inductive MachineInstruction where
| ldn : Nat → MachineInstruction -- push a number
| ldv : String → MachineInstruction -- push a variable's value
| str : String → MachineInstruction -- pop, write to a variable
| add | sub | mul -- pop two, push the result
| jmp : Int → MachineInstruction -- jump
| jeq : Int → MachineInstruction -- pop two, jump if equal
| jne : Int → MachineInstruction -- pop two, jump if not equal
| jle : Int → MachineInstruction -- pop two, jump if ≤
| jgt : Int → MachineInstruction -- pop two, jump if >
Two design choices here matter later:
- Jumps are relative:
jmp ksetspc := pc + k. Sojmp 1is a no-op, and a negativekjumps backwards (that's whypcis anInt). We'll see why relative jumps make the proof much nicer. - There are no registers and no temporaries. Everything goes through the stack.
The machine semantics is a function step that does one instruction. Since some configurations can't step (pc out of the program, or add with fewer than two values on the stack), it returns an Option:
def step (program : List MachineInstruction) (cfg : Config) : Option Config :=
match fetch cfg.pc program, cfg.stack with
| some (ldn n), st => some { cfg with pc := cfg.pc + 1, stack := n :: st }
| some (ldv x), st => some { cfg with pc := cfg.pc + 1, stack := cfg.store x :: st }
| some (str x), v :: st => some { cfg with
pc := cfg.pc + 1, stack := st, store := State.set cfg.store x v }
| some add, y :: x :: st => some { cfg with pc := cfg.pc + 1, stack := (x+y) :: st }
-- sub, mul ...
| some (jmp k), _ => some { cfg with pc := cfg.pc + k }
| some (jle k), y :: x :: st => some { cfg with
pc := if x ≤ y then cfg.pc + k else cfg.pc + 1,
stack := st }
-- jeq, jne, jgt ...
| _, _ => none
Note the order in binary operations: the stack is y :: x :: st, so x was pushed first and is the left operand. Getting this backwards is a classic bug, and here it would make 5 - 3 compute 3 - 5. Here's what running x := 2 + y * 3 looks like, with y = 4:

Finally, "many steps". Steps p c c' means the program p takes configuration c to c' in zero or more steps. It's the reflexive-transitive closure of step:
inductive Steps : List MachineInstruction → Config → Config → Prop where
| refl (p : List MachineInstruction) (c : Config) : Steps p c c
| step (p : List MachineInstruction) (c c1 c2 : Config) :
step p c = some c1 →
Steps p c1 c2 →
Steps p c c2
Now we have both sides of the square. Time for the arrow in the middle.
The compiler
Arithmetic
Compiling arithmetic to a stack machine is the textbook post-order traversal: compile the left operand, compile the right operand, then emit the operator.
def Arithmetic.compile : Arithmetic → List MachineInstruction
| num n => [ldn n]
| var x => [ldv x]
| add a b => a.compile ++ b.compile ++ [MachineInstruction.add]
| sub a b => a.compile ++ b.compile ++ [MachineInstruction.sub]
| mul a b => a.compile ++ b.compile ++ [MachineInstruction.mul]
The promise this code makes: running C(a) from stack st ends with eval a σ :: st. One extra value on top, everything below untouched.
Booleans
Booleans are more interesting. The machine has no boolean values, only conditional jumps. So instead of computing true or false, a boolean compiles to code that jumps or doesn't. This is a classic trick (Xavier Leroy's course on mechanized semantics compiles booleans the same way, with two offsets, one for true and one for false, where we use a flag): B(b, f, k) is the code for b that jumps forward k instructions past its own end if b evaluates to f, and falls through otherwise.

Why the extra f? Because it makes not free: B(¬b, f, k) = B(b, !f, k). No instructions at all, just flip what we're testing for.
def Boolean.compile : Boolean → Bool → Int → List MachineInstruction
| tru, f, k => if f then [jmp (k+1)] else []
| fal, f, k => if f then [] else [jmp (k+1)]
| eq a b, f, k =>
a.compile ++ b.compile ++ (if f then [jeq (k+1)] else [jne (k+1)])
| leq a b, f, k =>
a.compile ++ b.compile ++ (if f then [jle (k+1)] else [jgt (k+1)])
| not a, f, k => compile a (!f) k
| and a b, false, k =>
let B2 := compile b false k
let B1 := compile a false (B2.length + k)
B1 ++ B2
| and a b, true, k =>
let B2 := compile b true k
let B1 := compile a false (B2.length)
B1 ++ B2
A couple of things to notice:
kcounts from the end of the code, but jumps count from the jump instruction itself. The jump is the last instruction, sitting atE - 1, so to reachE + kit needs offsetk + 1. These off-by-ones are exactly the kind of thing the proof catches for you.andis short-circuit. To jump whena ∧ bis false: ifais false, jump straight to the target, overB2(that's why the offset is|B2| + k). Ifais true, fall intoB2, which handlesb. For "jump whena ∧ bis true",abeing false just skipsB2and falls out the end.
Commands
Commands put everything together.
def Command.compile : Command → List MachineInstruction
| skip => []
| assign x a => a.compile ++ [str x]
| seq c1 c2 => c1.compile ++ c2.compile
| ifte b c1 c2 =>
let C1 := c1.compile
let C2 := c2.compile
Boolean.compile b false (C1.length + 1)
++ C1
++ [jmp (C2.length + 1)]
++ C2
| whil b c =>
let Cb := c.compile
let Bb := Boolean.compile b false (Cb.length + 1)
Bb
++ Cb
++ [jmp (-(Bb.length + Cb.length))]
The if layout: test b, and if it's false jump over C1 and the jmp into C2. If it's true, fall into C1, then jump over C2 to the end.

And while: test b, and if false jump past the whole loop. If true, run the body and jump back to the test.

Let's see the real output for a program that sums 1..n:
s := 0; i := 1;
while i ≤ n do (s := s + i; i := i + 1)
0: ldn 0 s := 0
1: str s
2: ldn 1 i := 1
3: str i
4: ldv i test: i ≤ n ?
5: ldv n
6: jgt 10 if i > n, exit (6 + 10 = 16, the end)
7: ldv s s := s + i
8: ldv i
9: add
10: str s
11: ldv i i := i + 1
12: ldn 1
13: add
14: str i
15: jmp -11 back to the test (15 - 11 = 4)
Each iteration runs 12 instructions. For n = 10 that's 127 machine steps in total.
The theorem
Here's the statement, the bottom of the whole project:
theorem Spec.compiler_correct
(c : Command) (s s' : State) (st : List Nat) :
Exec c s s' →
Steps c.compile ⟨0, st, s⟩ ⟨c.compile.length, st, s'⟩
If c takes s to s', then the compiled code, starting at pc 0 with any stack st, ends at pc c.compile.length (just past the last instruction, which is where the machine halts), with the same stack st, and with store exactly s'. That's the square from the beginning of the post, written down.
Why "any stack st" instead of the empty stack? Because of induction. When we compile a + b, the code for b runs with the value of a already on the stack. If the theorem for b only talked about the empty stack, we couldn't use it there. This is a very common trick when proving things by induction: the statement you want is often too weak to prove directly, and you have to prove a more general one. The same goes for expressions:
theorem Arithmetic.compile_correct (a : Arithmetic) (st : List Nat) (s : State) :
Steps a.compile ⟨0, st, s⟩ ⟨a.compile.length, Arithmetic.eval s a :: st, s⟩
theorem Boolean.compile_correct (b : Boolean) (f : Bool) (k : Int)
(st : List Nat) (s : State) :
Steps (b.compile f k) ⟨0, st, s⟩
⟨(b.compile f k).length + (if Boolean.eval s b = f then k else 0), st, s⟩
The boolean one is the picture of B(b, f, k) above, as a theorem: you end at the end of the code, plus k if b evaluated to f.
How the proof goes
Two small lemmas about Steps do most of the work.
The first is transitivity: if p takes a to b and b to c, it takes a to c. This is how we glue runs together ("run C1, then run C2").
The second is the important one. The compiler always builds code by concatenation, P1 ++ code ++ P2. And the induction hypothesis talks about code alone, starting at pc 0. We need to know that the same run happens when code is placed somewhere in the middle of a bigger program:
theorem Steps.embed {code : List MachineInstruction} {c c' : Config}
(P₁ P₂ : List MachineInstruction) :
Steps code c c' →
Steps (P₁ ++ code ++ P₂)
{ c with pc := c.pc + P₁.length }
{ c' with pc := c'.pc + P₁.length }

This is where relative jumps pay off. Shifting the code by |P₁| doesn't change any jump offset, so every step of the small run is a step of the big run with pc shifted by |P₁|. With absolute jump addresses this lemma would be false, and we'd have to relocate code.
With these two, every case of the main proof has the same shape. Take x := a + b, compiled to C(a) ++ C(b) ++ [add] ++ [str x]:
C(a)runs from position 0: by the induction hypothesis (embedded withP₁ = []), the stack becomeseval a :: st.C(b)runs from position|C(a)|: induction hypothesis again, now witheval a :: stas "any stack" (this is where the generalization is used), embedded withP₁ = C(a).- One step of
add, one step ofstr x, computed directly withsimp [step, fetch]. - Glue the four runs with transitivity.
The main theorem is proved by induction on the Exec derivation, not on the command. This matters for while: in the whileTrue case, the induction hypothesis covers both the body run (s to s1) and the rest of the loop (s1 to s2), because both are sub-derivations. Induction on the command wouldn't give us the second one, since while b do c is not a sub-term of itself. The whileTrue case then reads exactly like the picture: run the test (falls through, since b is true), run the body, take the backwards jmp to pc 0, and continue with the hypothesis for the rest of the loop.
What's left is a lot of arithmetic on positions. pc is an Int, lengths are Nat, and every goal looks like ↑|C(b)| + ↑|C(a)| + 1 = .... Lean's omega tactic closes almost all of them. Without it, this proof would be ten times longer.
On writing the proofs
Let me be honest here. I wrote all the definitions above by hand: the syntax, Exec, the machine, step, Steps, the compiler, and the theorem statements. The proofs themselves (about 500 lines) were written by two Claude agents, one for Steps.lean and one for the correctness file, each working in an isolated copy of the repo.
Is that cheating? I don't think so, and the reason is the whole point of formal verification. You don't need to trust who wrote the proof, you need to trust the statement and the checker. So the setup was built so that the agents couldn't cheat even if they wanted to:
- Only the agent's assigned proof file is copied back. Any change to the definitions, the compiler or the build setup is thrown away without being looked at.
Imp/Spec.leanrestates the main theorem in its own words. If the proved statement is weakened in any way, that file stops compiling.- The proof files must not contain
sorry,admit,native_decide,axiomand other escape hatches (a plain text search). #print axioms Spec.compiler_correctmust list only Lean's three standard axioms:propext,Classical.choiceandQuot.sound. Nothing assumed, nothing smuggled in.
The checks run from a clean copy, against a pinned commit of the locked files. When all of them pass, it doesn't matter who wrote the 500 lines: Lean's kernel checked them against a statement I wrote and read.
Hold on to this setup, because it's the entire trick of automatic optimization. If an agent can't cheat on the proof, then we can also let it change the compiler, and keep only the changes it can prove.
Measuring
Last piece. To optimize something, you need a number. The machine has a runner that executes a program with a fuel limit and counts steps. On top of that there's a benchmark suite: 22 IMP programs (counting loops, primes by trial division, Collatz, gcd, nested loops, branchy code, dead code to remove...), each run on several inputs, 79 runs in total. Every run is checked against a separate reference interpreter, so a wrong result fails the bench even if it's fast.
The compiler above, the straightforward one, takes 68,080 machine steps on the whole suite. That's our baseline.
Letting AI optimize it
Same lock as for the proofs, with one change: now the agents can edit the compiler (Imp/Compiler/) and its proofs (Imp/Proofs/), and nothing else. The source semantics, the machine, the step counter, the benchmarks and Spec.lean stay locked. A candidate is accepted only if it passes the same gates as before, every benchmark run is still correct, and the total number of steps went down (code size only breaks ties). The brief also says optimizations must be general: no recognizing the benchmark programs.
Each round, two Claude agents work in parallel, each in its own git worktree: an explorer looking for new optimizations, and a merger porting good ideas from the last round that didn't make it into the winner. I run the gate on both and commit the better one.

Most optimizations end up as source-to-source passes on IMP (opt : Command → Command), proved by showing that Exec c s s' implies Exec (opt c) s s', and then compiled with the already proved code generator. Over 11 rounds the agents proved things like:
- constant folding and dead store removal (the whole final store is observable, so only writes that are overwritten before anyone reads them can go)
- bottom-tested loops: the test moves to the end, so each iteration runs one jump instead of two
- closing counting loops into their final value (after that one, I added benchmarks whose loops can't be closed)
- loop unrolling with merged bodies, and constant propagation that peels the first iterations
- jump threading on the machine code itself

The sum loop from before now compiles to 183 instructions instead of 16, and runs n = 10 in 35 steps instead of 127 (n = 100 in 71 instead of 1,207). For small n, the code is a tree of tests on n that jumps straight to precomputed values, because the first iterations only depend on constants. For large n, the loop runs 32 iterations at a time:
37: ldv i
38: ldn 32
39: mul
40: ldv s
41: ldn 496
42: add
43: add
44: str s s := i*32 + (s + 496) (i + (i+1) + ... + (i+31))
45: ldv i
46: ldn 32
47: add
48: str i i := i + 32
49: ldv i
50: ldn 31
51: add
52: ldv n
53: jle -16 loop while i + 31 ≤ n
It wasn't all good, though. The metric only counted steps, so the agents happily traded size for speed: 608 instructions became 10,884, and in round 11 one change pushed it to 47,727 for a 15% gain, which I reverted. I also checked for overfitting by running the final compiler on new inputs and on 10 programs it never saw. Everything was correct, and the new programs ran about 3.6× faster (5.2× on the benchmarks), but two of them got slower than with the original compiler: short loops, where the extra tests of the unrolled code cost more than they save. The proofs guarantee the code is correct. They don't guarantee the metric is the one you actually wanted.
What's next
In part 2 we drop the abstract machine and compile to a real target (probably RISC-V), which means formalizing its semantics too.
That's it for today. If you're still here, thanks for reading! If you find any mistake, feel free to reach out.
References
- Xavier Leroy, Mechanized semantics, Collège de France course (2019-2020), Coq development, compiles IMP to a stack machine (
Compil.v), with the same idea for booleans using two offsets - Benjamin Pierce et al., Software Foundations, Vol. 1, Imp chapter, IMP in Coq, with a stack compiler exercise for expressions
- Tobias Nipkow and Gerwin Klein, Concrete Semantics, chapter on compiling IMP to a stack machine
- CompCert
- CakeML
- Theorem Proving in Lean 4