Skip to content

Assembly, Lexer + Parser, Function Calls

This semester, I took a Compilers course where the problem sets involved incrementally implementing compiler features in OCaml. In this series, I’ll briefly summarize each piece. Taken together, I hope these posts provide a good foundation for understanding how compilers work.

The problem sets were fairly open-ended as long as the compiler produced correct results. My approaches won’t always match what a production compiler would do, but I’ve attempted to preserve the core ideas. Code is available in this repo.

Although the articles closely follow the problem sets, some also cover topics that weren’t directly tied to a specific problem set.


We start by implementing a RISC-V simulator. In this problem set, the CPU is represented as a state with registers, memory, and a program counter (PC).

type state = { r : regfile; pc : int32; m : memory }

The regfile and memory are maps that store the current state of the registers and memory. The starter code provided helper functions to look up and update these values.

To simulate RISC-V instructions, we update the state in a loop, modifying regfile and memory while advancing the PC. We execute one instruction at a time until the PC reads 0, indicating that all instructions have been executed.

Executing a single instruction follows the classic Fetch-Decode-Execute cycle.

  • Fetch: The simulator retrieves the next 32-bit word by reading from the memory location pointed to by the PC.

  • Decode: Next, we decode the word to determine the operation. The last 7 bits are the opcode, which we match to identify the specific instruction. We also parse the 32-bit word to extract the target registers or immediate values.

    For example, if the opcode is 0x33l, the operation is an Add. We can refer to the layout of an R-type instruction to parse the source (rs1 and rs2) and destination (rd) registers from their designated bit fields.

    Add: [funct7: 7b] [rs2: 5b] [rs1: 5b] [funct3: 3b] [rd: 5b] [opcode: 7b]
  • Execute: Finally, the simulator performs the operation and updates the state accordingly. In our Add example, the destination register rd is updated with the sum of the values stored in the source registers rs1 and rs2. Once the arithmetic is complete, the PC is incremented to point to the next instruction, and the cycle begins again.

With the simulator logic in place, we now understand how RISC-V instructions are executed. Understanding this low-level behavior is helpful as these instructions are the ultimate target of our compiler.


The next problem set was to implement a lexer and a parser for the “Fish” programming language. Fish is a “Fortran-ish” dummy language with a syntax similar to Java and C++.

In the previous assignment, we looked at the final output of compilers (RISC-V instructions). Now, we are taking a step back to learn the first stages of the pipeline: lexing and parsing.

For this problem set, we were given a choice between implementing the lexer/parser manually using a combinator-style approach, or using Lex (ocamllex) and Yacc (ocamlyacc). I chose the latter.

Lex and Yacc are classic tools used to build the compiler frontend for programming languages. ocamllex and ocamlyacc are the OCaml versions of these tools. They allow us to generate an Abstract Syntax Tree that can be executed by an evaluator written in OCaml.

The compiler frontend looks something like this: source program → lexer → tokens → parser → AST

The lexer’s job is to read raw text (code) and identify valid tokens. The input here is really just a stream of characters, so it is the lexer’s job to group characters into keywords (if, while, for), operators (+, -, *, /), variable names, and more. To give a sense of what the lexer does, here is a short snippet of the tokens defined in lex.mll.

rule lexer = parse
(* Keywords *)
| "if" { IF }
| "else" { ELSE }
...
(* Multi-character Operators *)
| "==" { EQ }
| "!=" { NEQ }
...
(* Single-character Operators & Syntax *)
| "+" { PLUS }
| "-" { MINUS }
...

Once the lexer has identified individual tokens, the parser establishes their relationship. When thinking about parsers, I find it helpful to imagine a stack. In Reverse Polish Notation, we store operands in a stack and pop them when we encounter an operator. Similarly, the parser stores unresolved tokens (shifts) and resolves them whenever a grammar rule is matched (reduce). This process is repeated until we are left with a single node, which serves as the root of the AST. To give a sense of how we define grammar in the parser, here is a short snippet from parse.mly.

program:
| EOF { (Ast.Return((Ast.Int(0), 0)), 0) }
| stmt_list EOF { $1 }
stmt_list:
| stmt { $1 }
| stmt stmt_list { (Ast.Seq($1, $2), rhs 1) }
stmt:
| exp SEMI { (Ast.Exp($1), rhs 2) }
| LBRACE stmt_list RBRACE { $2 }
...
exp:
| INT { (Ast.Int($1), rhs 1) }
| VAR { (Ast.Var($1), rhs 1) }
| exp PLUS exp { (Ast.Binop($1, Ast.Plus, $3), rhs 2) }
| exp MINUS exp { (Ast.Binop($1, Ast.Minus, $3), rhs 2) }
...

The ultimate goal of the parser is to reduce the entire stack into a single program node. As it reads through the input source, it continuously collapses smaller expressions (exp) into statements (stmt), and those statements into a sequence (stmt_list). Each time a rule is matched and “reduced,” the parser replaces those tokens on the stack with a single, larger AST node. This process continues until every token has been processed and only one entry-point node (program) remains.

The final AST for return 12 + 4 might look something like this. At the end, we are left with a single Return node that encapsulates rest of the operation.

((Return((Binop((Int 12)1)Plus((Int 4)1))1))1)

Before ending this section, I want to discuss an example that illustrates the subtleties of defining a grammar: the “dangling else” problem.

Consider if(x) if(y) s1; else s2;. After the parser reads if(y) s1;, it has two choices: it can reduce if(y) s1; as a complete statement (which would match the else with the first if(x)), or it can shift to include the else with the second if(y).

// Option 1
if(x)
if(y) s1;
else s2;
// Option 2 (Preferred)
if(x)
if(y) s1;
else s2;

Since both interpretations are valid, we have to explicitly assign precedence to avoid ambiguity. The typical approach is binding else to the closest preceding if.


ps3 bridged ps1 and ps2 by compiling a Fish AST into RISC-V instructions. For now, we don’t worry about performance as long as the generated RISC-V produces correct output. For example, if we compile return 12 + 4, the program should finish with 16 in register R10. We use R10 (x10) to store the program’s return value.

Our goal is to compile an AST like:
((Return((Binop((Int 12)1)Plus((Int 4)1))1))1)
to RISC-V like:
la x10, T1
sw x8, 0(x10)
li x10, 0xC
la x8, T3
sw x10, 0(x8)
...

Fish is simple: it doesn’t have functions or local variables. A Fish program is just a list of statements, which we treat as the body of main (though main is not explicitly defined). When a Fish program uses a variable, it lives in the global scope.

As we traverse the Fish AST, we can stack up the final result by appending instructions to a single list. For example, e1 + e2 can be broken down into: [instructions to evaluate e1 and save the result somewhere] + [instructions to evaluate e2 and save the result somewhere] + [instructions that load results from e1 and e2, add, and store the result in R10]. We end up with a single long list of instructions.

As I worked on this problem set, the two main challenges were: (1) using labels and (2) working with registers.

Compilers use labels to mark specific points in the stream of instruction. For example, the main label can mark the program’s entry point. Labels are essential for implementing control flow, as branches and loops work by jumping to labeled locations.

Let’s take a look at an example: if-else:

| Ast.If (cond, s_then, s_else) ->
let lelse = new_label () in (* generate a fresh label *)
let lend = new_label () in
compile_exp cond
@ [ Beq (R10, R0, lelse) ]
@ compile_stmt_body exit_lbl s_then
@ [
J lend;
Label lelse
]
@ compile_stmt_body exit_lbl s_else
@ [ Label lend ]

We see that if Beq (R10, R0, lelse) evaluates to true, we evaluate s_then and jump to lend. If Beq (R10, R0, lelse) was false, we jump to lelse and evaluate s_else .

When writing RISC-V, computations ultimately operate on registers, so values must be loaded from memory and stored back when necessary. Since the number of registers is limited, we need to manage them carefully to avoid overwriting values that are still needed later.

Fortunately, we can take advantage of the fact that labels correspond to concrete memory locations. When we’re worried that a register’s value might get overwritten, we can generate a fresh label and store the register value into that memory slot. Later, we can load from the label’s memory address to recover the saved value (the la “load address” instruction can be used to find a label’s memory address).

This means that as long as we’re willing to generate fresh labels and save values to .data, we don’t have to worry about running out of registers. We can always save an intermediate result to .data and load it back later. (Since Fish does not have functions, we’re not relying on stack or heap for now.)

The starter code does the heavy lifting: it expects the result of our compiler to have the form type result = { code : Riscv.inst list; data : Riscv.label list }, i.e, we simply have to return a list of labels in addition to the list of instructions. The labels will be placed in .data, so that we can read or write by loading their addresses with la.

In this problem set, we use R10 to hold the program’s final result, so it’s expected that our code will overwrite it. However, we can’t assume the same for other registers: if we use additional registers as scratch space, we need to make sure we restore their original values before return.

We need at least two registers to implement binary operations. For this problem set, I used one extra register (R8) alongside R10. With this convention, my RISC-V instructions always begins by saving the original value of R8 to memory (the prologue) and ends by restoring that saved value back into R8 (the epilogue).

let compile_stmt (p : Ast.stmt) : inst list =
let saved_r8 = new_temp () in (* label to preserve R8 before we overwrite it *)
let exit_lbl = new_label () in (* jump target for return (jump to end) *)
let prologue : inst list =
[ (* store R8 value so that it can be recovered later *)
La (R10, saved_r8);
Sw (R10, R8, z)
] in
let epilogue : inst list =
[ (* recover R8 *)
La (R8, saved_r8);
Lw (R8, R8, z);
jr R1
] in
prologue
@ compile_stmt_body exit_lbl p
@ [
Li (R10, w 0);
Label exit_lbl
]
@ epilogue

Now, let’s take a look at the RISC-V instructions corresponding to return 12 + 4. Hopefully, everything will make sense.

.text
.align 2
.globl main
main:
# save R8 to memory before add
la x10, T1
sw x8, 0(x10)
# store 12 to T3
li x10, 0xC
la x8, T3
sw x10, 0(x8)
# store 4 to T4
li x10, 0x4
la x8, T4
sw x10, 0(x8)
# load T3 to R8 and T4 to R10
la x8, T3
lw x8, 0(x8)
la x10, T4
lw x10, 0(x10)
# add R8 and R10
add x10, x8, x10
j L2 # jump to L2 for return
li x10, 0x0 # default return value
L2:
# restore R8 and return
la x8, T1
lw x8, 0(x8)
jalr x0, x1, 0x0
.data
.align 0
T1:
.word 0
T3:
.word 0
T4:
.word 0

Fish has served us well, but it’s time to tackle a slightly more complex programming language. Cish (“C-ish”) is the next step-up from Fish that adds functions, function calls, and local variables.

In Fish, a program was just a list of statements, which we treated as the body of main. In Cish, a program is a list of functions. The entry point is still main, but the compiler now compiles each function in the program. Each function gets a label in the .text segment, and a function call jumps to that label.

Compiling functions and function calls comes with two main challenges: (1) handling function arguments and (2) handling local variables. To make collecting local variables easier, the problem set gave us a parser that parses local variables in Let form.

Input programs look like:
main() {
let x = 12;
let y = 4;
return x + y;
}
parsed into:
Let ("x", Int 12,
Let ("y", Int 4,
Return (Binop (Var "x", Plus, Var "y"))))

The sp and fp registers are reserved to store the stack pointer and frame pointer. Each function call has its own stack frame: fp serves as the base of that frame, while sp tracks the current top of the stack. Our job is to update fp and sp on function calls and returns, and use them as reference points for accessing arguments and local variables.

Before we continue, let’s briefly review ps3. One of the problems we faced was that we wanted to write data to memory, but to retrieve it later, we also needed to keep track of its address. A simple solution was to take advantage of the fact that labels correspond to concrete memory locations; RISC-V’s la instruction makes it convenient to find and retrieve data with labels.

In ps4, we take a different approach. Instead of relying on labels, we treat special registers like sp and fp as anchors and use them as references to store data at precomputed offsets. sp and fp change over the course of a program, but we maintain that a local variable x can be found at fp - y where y is the known offset for x. I stored function arguments and local variables in the following layout:

+---------------------------+
| arg(k-1) | fp + 4*(k-1)
+---------------------------+
| ... |
+---------------------------+
| arg2 | fp + 8
+---------------------------+
| arg1 | fp + 4
+---------------------------+
| arg0 | fp + 0 <-- fp
+---------------------------+
| saved ra (x1) | fp - 4
+---------------------------+
| saved old fp (s0/x8) | fp - 8
+---------------------------+
| local0 | fp - 12
+---------------------------+
| local1 | fp - 16
+---------------------------+
| local2 | fp - 20
+---------------------------+
| ... (more locals/temps) |
+---------------------------+
<-- sp

Suppose main calls f. Before the call, main allocates space for f’s arguments on the stack (by advancing the sp) and writes them in order: the first argument at offset 0, the second at offset 4, and so on.

When we enter f, we treat the frame pointer as the base of this argument area, so the arguments are accessible at positive offsets from fp (Note that this approach doesn’t strictly follow RISC-V’s conventions, which typically pass the first few arguments in registers).

For local variables, the parser uses Let. When we compile a Let, we first evaluate the initializer expression and store the result in the stack at a negative offset from fp. Then, when we compile the Let body, the local variable’s value is already available in the frame. We also save and restore the return address and the old frame pointer in the stack frame, since a function call within a function can overwrite these registers.

When a function returns, the epilogue restores the saved return address and the old frame pointer, resets sp back to the frame base, restores fp, and then jumps back to the caller. After this, the stack-frame slots are invalid; they shouldn’t be accessed anymore.


I implemented this design using a two-pass approach. In the first pass, I scanned the AST to collect each function’s arguments and Let-bound local variables. From that, I built a map env from variable names to fixed offsets relative to fp. For example, if a function has two arguments x and y, I assign x -> +0 and y -> +4. I also precomputed offsets for local variables (-12, -16, and so on).

We can also compute the frame size in the first pass. Once the frame size is known, the function prologue can jump the stack pointer to reserve space for saved registers and local variables.

In the second pass, whenever we encounter a variable (whether it’s a function argument or a local variable), we can simply look it up in the current function’s env to get its fp offset and retrieve the value.

Let’s wrap up with an example.

f(a) {
return a * a;
}
main() {
f(2);
}

The RISC-V instructions for this code are shown below. Notice how fp (x8) is used repeatedly as the base register for sw and lw.

# sp = R2 # stack pointer
# ra = R1 # return address
# fp = R8 # frame pointer
# rv = R10 # return value
# t0 = R11 # scratch
# t1 = R12 # scratch
# t2 = R13 # scratch
.text
.align 2
.globl main
f:
# Prologue
add x11, x8, x0 # t0 = old fp
add x8, x2, x0 # fp = sp
addi x2, x2, 0xFFFFFFF8 # sp -= 8; reserve space for saved ra and saved fp
sw x1, -4(x8) # save ra at fp - 4
sw x11, -8(x8) # save old fp at fp - 8
# Evaluate a * a
lw x10, 0(x8) # rv = a; load first a from fp + 0
addi x2, x2, 0xFFFFFFFC # sp -= 4; make space to save left operand
sw x10, 0(x2) # push first a onto stack
lw x10, 0(x8) # rv = a; load second a from fp + 0
lw x11, 0(x2) # t0 = saved first a
addi x2, x2, 0x4 # sp += 4; pop temporary operand
mul x10, x11, x10 # rv = t0 * rv = a * a
# Return
j L1 # jump to epilogue/return
li x10, 0x0 # dead code: would set rv = 0
j L1 # dead code
L1:
# Epilogue
lw x11, -8(x8) # restore old fp into t0
lw x1, -4(x8) # restore ra
add x2, x8, x0 # sp = fp; discard this frame
add x8, x11, x0 # fp = old fp
jalr x0, x1, 0x0 # return to caller
main:
# Prologue
add x11, x8, x0 # t0 = old fp
add x8, x2, x0 # fp = sp
addi x2, x2, 0xFFFFFFF8 # sp -= 8; reserve space for saved ra and saved fp
sw x1, -4(x8) # save ra at fp - 4
sw x11, -8(x8) # save old fp at fp - 8
# Prepare call f(2)
addi x2, x2, 0xFFFFFFFC # sp -= 4; make space for argument
li x10, 0x2 # rv = 2
sw x10, 0(x2) # push argument 2 onto stack
# Call f
jal x1, f # call f; ra gets return address
# Clean up argument after return
addi x2, x2, 0x4 # sp += 4; pop argument
# main returns 0
li x10, 0x0 # rv = 0
j L2 # jump to epilogue
L2:
# Epilogue
lw x11, -8(x8) # restore old fp into t0
lw x1, -4(x8) # restore ra
add x2, x8, x0 # sp = fp; discard this frame
add x8, x11, x0 # fp = old fp
jalr x0, x1, 0x0 # return
.data
.align 0