Professional Documents
Culture Documents
Lecture On Compiler Design: Chapter 8: Intermediate Code Generation
Lecture On Compiler Design: Chapter 8: Intermediate Code Generation
By:
Md. Amjad Hossain
Lecturer, Dept. of CSE, KUET
Intermediate Code
What?
- Simple Machine independent code.
- Front end of compiler generates the I.C from which back end generate target
program.
Benefits:
- Retargeting is facilitated. Diff. back end with an existing front end
- Machine independent code optimizer can be applied (though its in back end).
Intermediate representations: -
Syntax trees , postfix notation and three address code but semantic rules for all are similar.
1. Graphical representation:
- syntax tree and DAG – natural hierarchical structure of a source program.
- Example: a := b * - c + b * - c
assign assign
+
a + a
*
* *
b uminus uminus
uminus b
c c b c
E - E1 {E.nptr = mkunode(‘uminus’,E1.nptr) }
E ( E1 ) {E.nptr = E1.nptr }
assign
left right
0 id b
id a
1 id c
2 uminus 1
+
3 * 0 2
4 id b
* *
5 id c
6 uminus 5
id b id b
7 * 4 6
uminus uminus 8 + 3 7
9 id a
id c id c 10 Assign 9 8
start
11 … … …
Three Address Code
Three address code:
t1:=z * w
t2:=y + t1
x:=t2
• Each statement usually contains three address, two for operands and
another for the result.
• In fact three-address code is a linearization of the tree.
Example of 3-address code
Three address code from syntax tree/ DAG:
- Three address code is a linearized representation of syntax tree or DAG in
which the explicit names correspond to the interior nodes of the graph.
Three address code for the Syntax tree for Three address code for the DAG for
a := b * - c + b * - c
a := b * - c + b * - c
t1:=- c t1:=- c
t2:=b * t1
t2:=b * t1
t3:=- c
t4:=b * t3 t5:=t2 + t2
t5:=t2 + t4 a:=t5
a:=t5
Types of Three-Address Statements.
Assignment Statement: x:=y op z
Assignment Statement: x:=op z
Copy Statement: x:=z
Unconditional Jump: goto L
Conditional Jump: if x relop y goto L
Stack Operations: Push/pop
More Advanced:
Procedure:
param x1
param x2
…
param xn
call p,n
Index Assignments:
x:=y[i]
x[i]:=y
Address and Pointer Assignments:
x:=&y
x:=*y
*x:=y
Syntax-Directed Translation into 3-address code
e.g. a := b * - (c+d)
What about things that are not assignments?
• E.g. while statements of the form “while E do S”
(intepreted as while the value of E is not 0 do S)