CodeBlanks Logo Icon CodeBlanks

Code generation

Learn the code generation phase.

Code generation (codegen)

Code generation (codegen) is the stage that turns the AST into a target language. The target can be real machine assembly, bytecode or another high-level language.

In this lesson we emit an assembly-like intermediate language. An emit function writes one instruction per AST node. A number node yields MOV; an operator node yields ADD. Codegen walks the tree in postorder: children's values are loaded into registers first, then the operator applies. This scheme runs on a simple virtual machine. Code quality depends on the target architecture.

emit patterns

Codegen usually runs through an emit function. It takes an instruction name and its arguments, then writes a formatted line. The instruction set depends on the target language.

For a simple virtual machine these suffice: MOV reg, value, ADD reg, reg, LOAD reg, addr, STORE addr, reg. Codegen walks in postorder: left child, right child, then root instruction. When register allocation is hard, the stack manages a small set of registers. Here we assume a single register; R0 holds every value.

Practice Emit assembly instructions

Define void emit(const char *instr, int arg) with body printf("%s %d\n", instr, arg);. In main call it for four instructions: ("MOV", 42), ("ADD", 7), ("STORE", 0), ("LOAD", 1).

Starter code

main.c
#include <stdio.h>

// Define emit function
// Call it for MOV, ADD, STORE, LOAD

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

void emit(const char *instr, int arg) {
    printf("%s %d\n", instr, arg);
}

int main(void) {
    emit("MOV", 42);
    emit("ADD", 7);
    emit("STORE", 0);
    emit("LOAD", 1);
    return 0;
}

Expected output

MOV 42
ADD 7
STORE 0
LOAD 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the codegen stage produce?

  • Tokens
  • AST
  • Symbols
  • Target code Correct answer

Explanation: Codegen writes code for the target language.

2 Match node types to instructions

Term Meaning
num MOV
binop ADD
var LOAD
assign STORE

3 Complete the emit call

Question
emit("MOV R0, #%d", ____);
Answer
emit("MOV R0, #%d", value);

Explanation: emit carries the numeric value into the MOV instruction.

All lessons in Expert