Master the fundamental concepts of code generation through this focused micro-challenge.
This task bridges tree-shaped ASTs to flat instruction lists. GCC's GIMPLE lowering and LLVM's IRBuilder::CreateAdd both flatten expressions into temporaries. Stack machines like JVM bytecode are three-address code with implicit operand stacks.
generate_expression returns the operand holding the result. For binary nodes, recurse on children, emit t = left op right, return t. Statements emit sequences: labels for control flow, param/call for functions.
cLoading…
new_temp() allocates fresh temporariesemit() appends to the instruction listProduction compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will implement a three-address code generator that walks the AST and emits instructions. This exercise requires generate_expression, generate_statement, and temporary allocation without stub placeholders that fake results.
Implement a three-address code generator from AST.
Define TAC instruction types:
TAC_BINARY: Binary operationsTAC_UNARY: Unary operationsTAC_COPY: AssignmentTAC_LABEL: Label definitionTAC_JUMP: Unconditional jumpTAC_CJUMP: Conditional jumpTAC_PARAM: Function parameterTAC_CALL: Function callTAC_RETURN: Return statementDefine TAC operand types:
OPERAND_TEMP: Temporary (t0, t1, ...)OPERAND_VAR: Variable nameOPERAND_CONST: Constant valueOPERAND_LABEL: Label nameImplement TAC generation:
generate_expression(): Generate TAC for expression, return result tempgenerate_statement(): Generate TAC for statementgenerate_function(): Generate TAC for functionHandle temporaries:
x = a + b * c to proper TACif (x > 0) y = 1; else y = 2; with labels/jumpsThree hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github