Code generator design and the target machine
Design of the code generator and the target machine: how a compiler maps intermediate code to machine code, choosing instructions, addressing modes, registers, stack layout and calling conventions for the target architecture.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Code generation is where a compiler turns intermediate code into runnable machine code. An engineer uses these ideas when writing a backend for a compiler, porting code to a new CPU, or tuning performance (register usage, instruction selection, calling convention). Good code generation directly affects runtime speed and binary size.
Key ideas
Instruction formats — the binary shape of instructions: e.g. R-type (register-register), I-type (register-immediate), J-type (jump). When writing answers, describe fields (e.g., in MIPS: opcode, rs, rt, rd, shamt, funct for an R-type). State assumed instruction length (e.g. 32-bit). Draw a box labeled with field widths and names. Also mention the target machine model (stack, accumulator, register-memory, or load-store/register-register) and, if asked, desirable properties of a target machine for code generation: an orthogonal instruction set, uniform general-purpose registers, simple and regular addressing modes (including scaled index), adequate immediate field sizes, efficient shift/add operations, and efficient procedure call/return support.
Addressing modes — ways an instruction computes the address of an operand. Define each:
- Immediate: operand encoded in the instruction.
- Register: operand in a register.
- Base+offset: address = base register + signed displacement.
- Indexed (base + index*scale + disp): common for arrays.
- PC-relative: address computed from program counter. Explain when each is used: immediates for constants, base+offset for local variables, indexed for arrays.
Register allocation and assignment — two phases:
- Allocation: decide which variables should go in registers vs spilled to memory. A common model: build an interference graph where nodes are live ranges and an edge means simultaneous liveness. The register allocation problem can be formulated as graph coloring: assign one of k colors (registers) so adjacent nodes have different colors. This is NP-complete in general; practical compilers use heuristics (Chaitin's algorithm, linear scan).
- Assignment: map colors to physical registers and emit load/store for spills. Give the formal definition: an interference graph G = (V,E) with V live ranges (temporaries) and (u,v) in E iff u and v live at same program point.
Live range — the maximal set of program points where a variable holds a value that may be used before being redefined. Draw: for a basic block list statements vertically, mark use/def points and draw horizontal intervals for live ranges.
Calling convention and activation record (stack frame) — rules for how functions pass arguments, return values, and preserve registers. Define caller-saved vs callee-saved registers. An activation record layout usually contains, from high to low addresses: saved callee-saved registers, return address, old frame pointer, local variables, temporaries; exact layout depends on convention. When asked for a diagram, draw the stack growing down: label frame pointer (FP), return address (RA), saved registers, local vars at negative offsets from FP, arguments passed on stack above FP or in caller area.
Prologue and epilogue — code at function entry/exit to set up and tear down the stack frame. Prologue typically: save old FP, set FP = SP, allocate locals (SP = SP - size), save callee-saved registers. Epilogue reverses these steps and returns.
Address calculation for arrays and structures — element address = base_address + index * element_size + field_offset. Account for ABI alignment/padding when determining field_offset. For multi-dimensional arrays with row-major order: address = base + ((i * num_cols) + j) * elem_size.
Code generation for control flow — translate conditional branches into compare + branch instructions or set-on-condition followed by branch. For boolean expressions, explain short-circuit translation to branch targets (true/false labels). Draw control-flow graph (CFG) with nodes as basic blocks and edges for jumps; annotate each jump with condition.
Peephole optimization — small local improvements after initial code emission (e.g. eliminate redundant load/store pairs to the same address when no intervening writes, or remove useless register-to-register moves). Define the window size (often 2–6 instructions) and give examples: replacing add r0, r0, #0 with no-op.
Assumptions to state in answers — word size (e.g. 32-bit = 4 bytes), register count, calling convention (which registers are callee-saved), and endianness if relevant. Always explicitly state when you choose a convention for exam answers.
Formulas
address = base + index * scale + displacement — base: register containing base address (bytes), index: integer index, scale: size of element in bytes (units: bytes), displacement: constant offset in bytes; applies to array/struct addressing.
three-address format: x = y op z — x,y,z are temporaries, variables or constants; op is a binary operator; used in intermediate code.
load r, mem — load value from memory address mem into register r. store r, mem — store r into mem.
prologue (example): push {callee-saved regs, FP, LR}; FP = SP; SP = SP - locals_size — symbols: FP = frame pointer, LR = link/return register, SP = stack pointer; applies to a convention with push/pop.
spill code sequence: store r_var -> [FP - offset]; later load [FP - offset] -> r — used when a variable is spilled to memory.
interference condition: (u,v) ∈ E iff live(u) ∩ live(v) ≠ ∅ — defines edges in the interference graph.
Worked examples
- Translating expression
a = b * c + d(32-bit word machine, registers r0..r7, caller/callee rules not relevant). Variables b,c,d,a in memory at offsets 0x100,0x104,0x108,0x10C from a global base GB.
Step 1: TAC: t1 = b * c t2 = t1 + d a = t2
Step 2: choose registers r0, r1, r2.
Step 3: Addressing: assume base+offset addressing with GB in register r7.
Emit (annotated): load r0, [r7 + 0x100] ; r0 = b load r1, [r7 + 0x104] ; r1 = c mul r0, r0, r1 ; r0 = r0 * r1 (t1) load r1, [r7 + 0x108] ; r1 = d add r0, r0, r1 ; r0 = t1 + d (t2) store r0, [r7 + 0x10C] ; a = r0
Final answer: bold the instruction sequence above as the emitted code. (State register usage and base addresses explicitly in exam.)
- Function call and activation record for: int sum(int x, int y) { int t[3]; t[0]=x; t[1]=y; return t[0]+t[1]; }
Assumptions: 32-bit words, arguments passed in registers r0,r1; caller must save caller-saved regs; callee must save callee-saved regs r4,r5 if used.
Activation record layout (draw stack growing down): [higher addr] caller args (if any) return address (LR) old FP local t[0] (FP - 4) local t[1] (FP - 8) local t[2] (FP - 12) [lower addr]
Prologue (step-by-step): push {FP, LR} ; save old FP and return address FP = SP SP = SP - 12 ; allocate 3 words for t[0..2]
Body: store r0 -> [FP - 4] ; t[0] = x store r1 -> [FP - 8] ; t[1] = y load r0, [FP - 4] ; r0 = t[0] load r1, [FP - 8] ; r1 = t[1] add r0, r0, r1 ; r0 = return value
Epilogue: SP = FP pop {FP, LR} ret
Explain that the return value is in r0, matching the assumed convention. Show offsets and explain how array indexing maps to FP - 4 - index*4.
- Address computation for array access: Given base address of int A[5][4] at r5, compute address of A[i][j] for row-major 2D array A[rows][cols] with rows=5, cols=4, element size 4 bytes; compute for i=2, j=3.
Formula: addr = base + ((i * cols) + j) * 4 Numbers: ((2 * 4) + 3) * 4 = (8 + 3) * 4 = 11 * 4 = 44 bytes Emit: mul r0, r_i, #4 ; r0 = i * cols (here cols=4) add r0, r0, r_j ; r0 = r0 + j shl r0, r0, #2 ; multiply by 4 (element size) by left shift 2 add r0, r5, r0 ; r0 = base + offset (44)
Conclude: address = r5 + 44.
Common mistakes
- Not preserving callee-saved registers or not restoring SP/FP in epilogue.
- Using immediate addressing for values that exceed instruction immediate field range.
- Treating arrays as column-major when the machine uses row-major (or vice versa) — always state memory layout.
- In register allocation: assuming graph coloring always finds optimal coloring; in exams mention NP-completeness and heuristics.
For your exam
Kinds of questions:
- Definitions and short notes: define target machine, instruction formats, addressing modes, activation record.
- Derivations: show how to compute array addresses, or derive register spill costs for a snippet using live ranges.
- Numericals/Traces: produce code for a given expression or function (you must state assumptions: architecture, register count, calling convention).
- Programs/algorithms: trace register allocation (graph coloring or linear-scan) on a small sequence and show spills.
- Diagrams: draw stack-frame layout, or label instruction format fields, or draw interference graph.
What a full-marks answer includes:
- Explicit target assumptions (word size, available registers, calling convention).
- Correct intermediate code and step-by-step mapping to machine instructions.
- Clear activation record diagram with byte offsets labelled.
- Correct handling of saving/restoring registers and return value placement.
- Brief justification for design choices (why chosen registers, why spill decisions).
Quick check
- Define an activation record in one sentence.
- Write the address formula for element A[i][j] in a row-major 2D array with element size S and columns C.
- What is an interference graph? Give its edge condition.
Answers: 1) An activation record (stack frame) is the region of the run-time stack that stores a function’s return address, saved registers, local variables and temporaries for one invocation. 2) address = base + ((i * C) + j) * S where base is the array base address, C is number of columns, S is element size (bytes). 3) An interference graph is an undirected graph with a node per variable; edge (u,v) exists iff live(u) ∩ live(v) ≠ ∅ (they are live at the same program point).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?