Unit content
Code generation and compiler optimization
After source meaning has been represented in a compiler's internal form, the compiler can transform it and generate instructions for a target machine.
Code generation
Operations in the intermediate representation are selected and arranged as machine instructions. The compiler must decide how values use registers, memory and calling conventions supported by the target architecture.
Optimization
An optimizing compiler can replace a program with another representation that has the same permitted observable behaviour but executes more efficiently.
Examples include constant folding, dead-code elimination, common-subexpression elimination and loop transformations.
As-if behaviour
Optimization is constrained by the language semantics. The compiler may change implementation details that the program cannot validly observe, but it cannot arbitrarily change the required result.
Optimization levels
Toolchains commonly expose several optimization levels that trade compilation time, debugging convenience, code size and runtime performance differently.
Source code does not map line by line
One source statement can become many machine instructions, several statements can collapse into one calculation, and unused computations can disappear entirely.
The optimized machine code is therefore an implementation of the source program's semantics, not a literal transcription of its lines.