Intermediate Topic 30 of 50 Languages & Compilers
Code Generation
Emitting machine code from an IR.
How it works
Code generation is the compiler back-end phase that turns intermediate representation into target machine code or assembly. Main tasks are instruction selection, mapping IR operations to machine instructions, often via tree or DAG pattern matching, register allocation, instruction scheduling to avoid pipeline stalls, handling calling conventions, stack frame layout and emitting object files with relocation information. The result must preserve semantics and meet the target's ABI.
Step-by-step walkthrough
- The backend takes the IR.
- It maps each operation to target instructions.
- It assigns registers and spills extra values to the stack.
- It emits assembly or object code.
- Peephole optimizations then tidy up short sequences.
Where it is used
Every compiler, from GCC and Clang to JIT engines, includes a code generator for each supported architecture such as x86-64, ARM and RISC-V.
Common pitfall
Mistakes lead to miscompilation that is extremely hard to debug. Differences among targets in alignment, endianness and calling conventions cause portability issues. Poor selection or allocation yields slow code. Use mature backends such as LLVM when building a language, test with differential testing across optimization levels and inspect generated assembly for hot code.
Where it fits in the course
Code Generation is topic 30 of 50 in Languages & Compilers, rated Intermediate. It follows Control Flow Graphs. The next topic is Register Allocation.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Languages & Compilers quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Languages & Compilers quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Code Generation?
Where do people use Code Generation?
What is the most common mistake with Code Generation?
What should I learn before this topic?
How can I practice it?
Is Code Generation hard to learn?
How long does it take to learn Code Generation?
Which topics are related to Code Generation?
What should I study after Code Generation?
Related topics
- Control Flow Graphs (Languages & Compilers)
- Register Allocation (Languages & Compilers)
- Static Single Assignment (Languages & Compilers)
- Compiler Optimizations (Languages & Compilers)
- Code Style and Readability (Software Engineering)
- Code Reviews (Software Engineering)
- Code Smells (Software Engineering)