22-12-2012, 06:05 PM
Three Address Code Examples
Address Code.pdf (Size: 80.64 KB / Downloads: 159)
Three Address Code
Three-address code (TAC) will be the intermediate representation used in our Decaf
compiler. It is essentially a generic assembly language that falls in the lower-end of the
mid-level IRs. Some variant of 2, 3 or 4 address code is fairly commonly used as an IR,
since it maps well to most assembly languages.
A TAC instruction can have at most three operands. The operands could be two operands
to a binary arithmetic operator and the third the result location, or an operand to
compare to zero and a second location to branch to, and so on. For example, below on
the left is an arithmetic expression and on the right.
Decaf TAC Instructions
The convention followed in the examples below is that t1, t2, and so on refer to
variables (either declared variables or temporaries) and L1, L2, etc. are used for labels.
Labels mark the target for a goto/branch and are used to identify function/method
definitions and vtables.
TAC Examples
What we have to do is figure out how to translate from Decaf to TAC. This includes not
only generating the TAC, but figuring out the use of temp variables, creating labels,
calling functions, etc. As we traverse our tree, we will create the TAC instructions one
at a time. We can immediately print them out or store them for further processing.
Most of the instructions can be emitted as we go and never re-visited, although in some
situations (most notably when performing optimization) we may go back and make
changes to earlier instructions based on information we gather later in the process.
We will simplify the Decaf language a little by excluding doubles for code generation
and internally treating bools as 4-byte integers. Classes, arrays, and strings will be
implemented with 4-byte pointers. This means we only ever need to deal with 4-byte
integer/pointer variables.
Using TAC For Other Languages
The TAC we use is fairly generic. Although we show our examples in the context of
Decaf, a TAC generator for any programming language would generate a similar
sequence of statements. For example, in the (in)famous dragon book, the following
syntax-directed translation is used to generate TAC for a while loop. (Check out pages
469 of Aho, Sethi, and Ullman)