Code generation is the final major phase of a compiler where intermediate code is converted into target machine code or assembly code.
Code generation is the process of converting intermediate representation (IR) of a program into target machine code.
👉 It produces executable code for the CPU.
| Input | Output |
|---|---|
| Intermediate Code (TAC, DAG, etc.) | Machine / Assembly Code |
Intermediate Code
↓
Code Generator
↓
Target Machine Code
The design of a code generator refers to how the compiler component converts IR into efficient machine code while considering correctness, speed, and memory usage.
✔ Correct output ✔ Fast execution ✔ Efficient memory usage ✔ Minimal instructions ✔ Proper register usage
Choosing correct machine instructions for IR.
t1 = a + b
Machine code:
MOV R1, a
ADD R1, b
Assign variables to CPU registers.
👉 Registers are faster than memory.
Arrange instructions for better performance.
Decide where variables will be stored:
Improve generated code without changing meaning.
The code generator takes Intermediate Representation (IR) like:
t1 = a + b
t2 = t1 * c
Output may be:
LOAD R1, a
ADD R1, b
STORE t1, R1
LOAD R2, t1
MUL R2, c
STORE t2, R2
Assigning variables to CPU registers to reduce memory access.
a → R1
b → R2
c → memory (if registers full)
x = a + b * c;
t1 = b * c
t2 = a + t1
x = t2
MOV R1, b
MUL R1, c
MOV R2, a
ADD R2, R1
MOV x, R2
A technique that improves small segments of code.
MOV R1, a
MOV R1, a
MOV R1, a
✔ Prefer registers over memory ✔ Minimize number of instructions ✔ Avoid redundant operations ✔ Reuse computed values ✔ Reduce memory access
Intermediate Code
↓
Instruction Selection
↓
Register Allocation
↓
Instruction Ordering
↓
Target Code Generation
✔ Code generation is final compiler phase ✔ Input = Intermediate Code ✔ Output = Machine/Assembly Code ✔ Main tasks:
Code generation is the compiler phase that converts intermediate representation of a program into target machine code. The design of a code generator focuses on instruction selection, register allocation, and efficient use of memory and CPU resources to produce optimized executable code.
| Concept | Description |
|---|---|
| Code generation | IR → machine code |
| Input | Intermediate code (TAC) |
| Output | Assembly / machine code |
| Instruction selection | Choose machine instructions |
| Register allocation | Assign variables to registers |
| Optimization | Improve performance |
| Peephole optimization | Local code improvement |
If you want next, I can explain:
Just tell 👍
Open this section to load past papers