Intermediate Code Generation
Intermediate Code Generation
generation
Intermediate Representations
Many ways to represent intermediate code
Three-Address Code (TAC)
• Each instruction can have at most three operands
• Large statements are broken into little operations that use temporary
variables
X=(2+3)+4
turns into to
T1=2+3;
X=T1+4;
• Exact instruction set might differ depending on
• Source language being compiled
• Target machine language
TAC instruction examples
• Assignment statements of the form x: = y op z, where op is a
binary arithmetic or logical operation
• . Assignment instructions of the form x:= op y, where op is a
unary operation
• Copy statements of the form x: = y
• The unconditional jump goto L
• Conditional jumps ifz value goto label
• Indexed assignments of the form x: = y[ i ] and x [ i ]: = y.
• Address and pointer assignments of the form x:= &y, x:= *y,
*x: = y
TAC instruction for Function calls
• A call of the function p(x1,, x2,..., xn) is implanted using the instructions
param x
call p, n //p is function name and n is # of parameters
return y
BeginFunc N // instruction reserving N bytes of space for locals and temporaries
EndFunc // When reached, cleans up stack frame and returns
• Afunction call is often translated into the sequence
param x1
param x2
…
param xn
call p, n
TAC examples
TAC examples
TAC examples
TAC examples
Compiling Functions
Consists of four pieces:
• A label identifying the start of the function
• A BeginFunc N; instruction reserving N bytes of
space for locals and temporaries
• The body of the function.
• An EndFunc; instruction marking the end of the
function. – When reached, cleans up stack frame
and returns.
TAC examples
TAC examples
TAC examples
TAC examples
TAC examples
TAC generation
TAC generation for Arithmetic Expressions
TAC generation for Basic Expressions Cont.
E constant E.place newtemp();
E.code gen(E.place,':=' , constant.value);
Example
TAC Generation for Boolean Expressions
S.false_branch := newlabel()
S.after := newlabel()
S.code :=E.code ||
gen(ifz E.place goto S.false_branch) ||
S1.code ||
gen('goto' S.after) ||
gen(S.false_branch ':') ||
S2.code ||
gen(S.after ':')
TAC for statement sequence
S S1; S2