CSC 453 Intermediate Code Generation: Saumya Debray
CSC 453 Intermediate Code Generation: Saumya Debray
Intermediate Code
Generation
Saumya Debray
The University of Arizona
Tucson
Overview
Input: id + id * id
Syntax tree:
Statements:
a node’s label indicates what kind of
statement it is;
the children correspond to the components
of the statement.
mkTree(NodeType, Child1, Child2, …) allocates space for the tree node and fills in its node
type as well as its children.
CSc 453: Intermediate Code Generation 7
Three Address Code
Low-level IR
instructions are of the form ‘x = y op z,’ where x,
y, z are variables, constants, or “temporaries”.
codeGen_stmt(synTree_node S) codeGen_expr(synTree_node E)
{ {
switch (S.nodetype) { switch (E.nodetype) {
case FOR: … ; break; case ‘+’: … ; break;
case WHILE : … ; break; case ‘*’ : … ; break;
case IF: … ; break; case ‘–’: … ; break;
case ‘=‘ : … ; break; case ‘/’ : … ; break;
… …
} } recursively process the children,
then generate code for this node
and glue it all together.
When generating intermediate code, this just refers to a symbol table entry for a
variable or temporary that will hold that value;
codeGen_expr(E)
E intcon { /* E.nodetype == INTCON; */
E.place = newtemp(E.type);
E.code = ‘E.place = intcon.val’;
}
codeGen_expr(E)
E id { /* E.nodetype == ID; */
/* E.place is just the location of id (nothing more to do) */
E.code = NULL;
}
codeGen_expr(E)
E –
{
/* E.nodetype == UNARY_MINUS */
codeGen_expr(E1); /* recursively traverse E1, generate code for it */
E.place = newtemp( E.type ); /* allocate space to hold E’s value */
E.code = E1.code newinstr(UMINUS, E1.place, NULL, E.place);
E1
}
codeGen_expr(E)
E + {
/* E.nodetype == ‘+’ … other binary operators are similar */
codeGen_expr(E1);
codeGen_expr(E2); /* generate code for E1 and E2 */
E.place = newtemp( E.type ); /* allocate space to hold E’s value */
E1 E2 E.code = E1.code E2.code newinstr(PLUS, E1.place, E2.place, E.place );
}
evaluate RHS
copy value of RHS into LHS
E1 E2
B.trueDst = start of S1
B.falseDst = start of S2
The code generated for B jumps to the appropriate label.
CSc 453: Intermediate Code Generation 26
Logical Expressions 2: cont’d
Syntax tree:
codeGen_bool(B, trueDst, falseDst):
relop /* base case: B.nodetype == relop */
B.code = E1.code
E2.code
newinstr(relop, E1.place, E2.place, trueDst)
E1 E2
newinstr(GOTO, falseDst, NULL, NULL);