Lec08 Code Generation
Lec08 Code Generation
1
CODE GENERATION
➢ Requirements:
➢ Correctness
➢ Must preserve semantic meaning of source program
➢ Make effective use of available resources
➢ Must run efficiently
2
INPUT TO THE CODE GENERATOR
➢ Instruction Selection
➢ Register Allocation
➢ Evaluation Order
5 5
INSTRUCTION SELECTION
a := b + c
d := a + e
MOV b, R0
ADD c, R0
MOVR0,
MOV R0, aa If a is subsequently
used
MOVa,a, R0
MOV R0
ADD e, R0
MOV R0, d
8
INSTRUCTION SELECTION
MACHINE IDIOMS
9
REGISTER ALLOCATION
r4
11
REGISTER ALLOCATION
12
EVALUATION ORDER
➢ Simplest Approach
➢ Don’t mess with re-ordering.
➢ Target code will perform all operations in the same order as the
IR code
➢ Trickier Approach
➢ Consider re-ordering operations
➢ May produce better code
13
➢ ... Get operands into registers just before they are need
➢ ... May use registers more efficiently
MOVING RESULTS BACK TO MEMORY
➢ Immediately
➢ Move data back to memory just after it is computed.
➢ May make more registers available for use elsewhere.
➢ Wait as long as possible before moving it back
➢ Only move data back to memory “at the end”
➢ or “when absolutely necessary”
➢ May be able to avoid re-loading it later!
14
CODE GENERATION ALGORITHM #1
15
CODE GENERATION ALGORITHM #1
16
EXAMPLE TARGET MACHINE
17
EVALUATING A POTENTIAL CODE SEQUENCE
18
A BETTER COST MODEL
19
COST GENERATION EXAMPLE
20
BASIC BLOCKS
21
BASIC BLOCKS
22
BASIC BLOCKS
23
CONTROL FLOW GRAPH
24
SETHI-ULLMAN ALGORITHM
IDENTIFYING NO. OF REGISTERS REQUIRED
Intuition:
1. Label each node according to the number of
registers that are required to generate code for the node.
25
SETHI-ULLMAN ALGORITHM
(INTUITION)
Left Right
leaf leaves
Bottom-Up Labeling: visit a node after all its children are labeled.
26
LABELING ALGORITHM
end
27
LABELING ALGORITHM
28
If k = 1 (a node with two children), then the following relation
label (n1 ) : = max(label (ci ) + i − 1)
1i k
becomes :
maxlabel (c1 ), label (c2 ) if label (c1 ) label (c2 )
label (n) =
label (c1 ) + 1 if label (c1 ) = label (c2 )
28
EXAMPLE
Let’s
assume we have following set of instructions:
t1=a+b
t2=c+d
t3=e+t2
t4=t1+t3
Draw the tree corresponding to the given instructions
29
EXAMPLE
t4
t1 t3
a b e t2
c d
30
EXAMPLE
Labeling leaves:
t4 leftmost is 1, others are 0
t1 t3
a 1 b 0 e 1 t2
c 1 d 0
31
EXAMPLE
Labeling t2:
t4 label(c) ≠ label (d)
32
max(label(1),label(2))
Thus label(t2)=1
t1 t3
a 1 b 0 e 1 t2
c 1 d 0
32
EXAMPLE
Labeling t3:
label(e) = label (t2)
t4
max(label(1),label(2))
label(t3)=label(1)+1 =2
t1 t3
a 1 b 0 e 1 t2 1
c 1 d 0
33
EXAMPLE
Labeling t1:
t4 label(a) ≠ label (b)
34
max(label(1),label(2))
Thus label(t1)=1
t1 t3 2
a 1 b 0 e 1 t2 1
c 1 d 0
34
EXAMPLE
Labeling t4:
t4 label(a) ≠ label (b)
35
max(label(1),label(2))
Thus label(t4)=2
t1 1 t3 2
a 1 b 0 e 1 t2 1
c 1 d 0
35
EXAMPLE
t4 2
t1 1 t3 2
a 1 b 0 e 1 t2 1
c 1 d 0
36
THANKS
37