-------- ----------- source | front | intermediate | code | target ---> | end | ---> ---> | generator | ---> code | | code | | code -------- ----------- user can compiler can improve compiler can -- profile program -- loops -- use registers -- change algorithm -- procedure calls -- select instructions -- transform loops -- address calculations -- do peephole transformationsFigure 10.1 from A. Aho, Ravi Sethi, and Jeffrey Ullman, Compilers, Principles, Techniques, and Tools, Addison-Wesley, ISBN 0-20-110088-6, 1986.
At the stage of intermediate code, the compiler can also eliminate common subexpressions, move iteration-invariant code outside of loops and looping constructs, and fold constants (e.g., convert a constant expression such 2*4*5 into a single constant 40). Common subexpression elimination and moving iteration-invariant code outside of loops are two ways that improve address calculations. Overhead of procedure calls can be improved by in-lining code, as discussed below.
At the level of target code, the compiler can allocate registers for local variables instead of memory, and pass values to routines through registers (e.g. for constant pointers in ANSI C). The compiler can be smart about choosing the best set of native instructions to implement operations. Peephole transformations include elimination of redundant instructions and unreachable code, optimization of flow-of-control (e.g., eliminate jump instructions to other jump instructions), and simplification based on algebraic identities (e.g., replacing x <- x * 0 with x <- 0). Another peephole transformation includes the use of machine idioms, such as using auto-incrementing and auto-decrementing addressing modes for computing statements such as i <- i + 1.
Here are additional transformations a compiler might perform;
Ideally, every transformation and optimization that the compiler performs should not change the input/output behavior of the program. As compiler writers are not perfect, optimization may need to be disabled on certain modules or classes. In the Ptolemy 0.6 software environment, for example, optimization in 13 of the 387 C++ files are disabled due to a bug in version 2.7.2 of the GNU C++ compiler (none of the 945 C programs have problems under the GNU C compiler). When using a debugger, it is often useful to disable optimization so that stepping through the execution of the program will correspond to the source code.