Code Optimization


14th lecture, July 20, 2018

Language Theory and Compilers

Martin J. Dürst


© 2005-18 Martin J. Dürst 青山学院大学

Today's Schedule


Remaining Schedule


Summary of Previous Lecture


Homework from Two Weeks Ago

For the Turing machine given by the following state transition table:

Current state Current tape symbol New tape symbol Movement direction Next state
→1 0 1 L 1
→1 1 0 R 2
→1 _ _ L 3*
2 0 0 R 2
2 1 1 R 2
2 _ _ L 3*
  1. Draw the state transition diagram for this machine
  2. Show in detail how this machine processes the input ..._1101000_...
  3. Guess and explain what kind of calculation this machine does if the tape contains only a single contiguous sequence of '0'es and '1'es (surrounded by blanks) and where the leftmost non-blank symbol is a '1'

(this Turing machine always starts on the rightmost non-blank symbol)


Homework 1: Code Generation for Logical And

C fragment:

if (c<4 && f>=12)

Use hint: Conversion to nested if statement:

if (c<4)
    if (f>=12)
        a = d;


Homework 1: Example Solution



Homework 2: Code Generation for for Statement

(bonus problem)

C fragment:

for (i=0; i<20; i++)
    x *= y;

Preparation (use hint): Conversion to while statement:

i = 0;
while (i<20) {
    x *= y;


Homework 2: Example Solution



Goals of Optimization

Compilers provide options to choose different levels of optimization


Optimization Methods


Optimization Techniques: Faster and Smaller

Repeatedly try to use different techniques to continuously optimize the code further
(good example for Ruby implementation (video))


Optimization Techniques: Faster but Larger

Make execution faster even if the amout of code may increase


Optimization Techniques: Machine Dependent

Highly dependent on machine type


Example of Instruction Reordering

Expression: 743 * a

Before optimization:

        CONST   R1, 743
LOAD R2, a ; invisible waiting time
MUL R3, R1, R2

After optimization:

        LOAD    R2, a
CONST R1, 743 ; executed while LOAD still in progress
MUL R3, R1, R2


Dynamic Compilation

(also: Just-in-time compilation)


Examples of Actual Optimization


without optimization (gcc -O0 -S code.c)

with optimization (gcc -O1 -S code.c)

more optimized (gcc -O2 -S code.c)

much more optimized (gcc -O3 -S code.c, with parallel processing instructions)

(assembly language for Intel PCs (CISC))

Optimization options for gcc: English, Japanese



WEB アンケート

お願い: 自由記述に必ず良かった点、問題点を具体的に書きましょう

(悪い例: 発音が分かりにくい; 良い例: さ行が濁っているかどうか分かりにくい)



(no need to submit)

Prepare for term final exam. In particular, have a look at some optimization problems.



peephole optimization
control flow analysis
basic block
data flow analysis
constant folding
constant propagation
dead code elimination
function inlining
loop unrolling
dynamic compilation