Intermediate Code Generation
Intermediate Code Generation
Intermediate Target
Front end code Back end machine
code
a * (b + c) E.nptr * E.nptr
a ( E.nptr )
E.nptr + E.nptr
b c
*
a +
b c
Abstract Syntax Trees versus DAGs
a := b * -c + b * -c
:= :=
a + a +
* * *
c c c
Tree DAG 6
Postfix Notation
a := b * -c + b * -c
t1 := - c t1 := - c
t2 := b * t1 t2 := b * t1
t3 := - c t5 := t2 + t2
t4 := b * t3 a := t5
t5 := t2 + t4
a := t5 Linearized representation
Linearized representation
of a syntax DAG
of a syntax tree
Three address code
• In a three address code there is at most one operator at the right side of
an instruction
• Example:
+
t1 = b – c
+ * t2 = a * t1
* d
t3 = a + t2
- t4 = t1 * d
a
t5 = t3 + t4
b c
Types of three address codes
• x := y op z
• x := op y
• x := y
• goto L
• if x goto L and if (false x) goto L1
• if x relop y goto L
Types of three address code
• Procedure calls using:
• param x
• call p, n
• y := call p, n
• return y
• x := y[i] and x[i] := y
• x := &y
• x := *y and *x :=y
Example
• do i = i+1; while (a[i] < v);
L: t1 = i + 1 100: t1 = i + 1
i = t1 101: i = t1
t2 = i * 8 102: t2 = i * 8
t3 = a[t2] 103: t3 = a[t2]
if t3 < v goto L 104: if t3 < v goto 100
• t1 : = -c Op Arg1 Arg2
• t2 := b * t1 (0) uminus c
• t3 : = - c (1) * b (0)
(2) uminus c
• t4 := b * t3
(3) * b (2)
• t5 := t2 + t4
(4) + (1) (3)
• a := t5
(5) := a (4)
Triples for arrays – ternary operation
x [i] : = y
op arg1 arg2
(0) []= x i
(1) assign (0) y
x : = y [i]
op arg1 arg2
(0) =[] y I
(1) assign x (0)
Representing three address codes
• Indirect triples
• In addition to triples we use a list of pointers to triples
• to list pointers to triples in the desired order
Example
D
A B C
foo foo foo foo
Main Main Main Main
Symbol Table semantic rules
Productions Semantic Rule
P MD;S {addwidth (top(tblptr), top(offset);
pop(tblptr); pop(offset)}
D D1 ; D2
T integer { T.type := ‘integer’; T.width := 4 }
T real { T.type := ‘real’; T.width := 8 }
T array [ num ] of { T.type := array(num.val, T1.type);
T1 T.width := num.val * T1.width }
T ^ T1 { T.type := pointer(T1.type); T.width := 4 }
Symbol table tracking
• Stack of tblptr is available to keep track of the available symbol table
• When a new procedure is called a symbol table is created and its
pointer pushed to this stack with offset
• When the call terminates this tblptr is popped
Declarations and Records in Pascal
x := a * b + c * d - e * f
Statement c
0
$0 := a * b 1
$1 := c * d 2
$0 := $0 + $1 1
$1 := e * f 2
$0 := $0 - $1 1
x := $0 0