Intermediate-Code Generation
local graph
Chapter 6 — Intermediate-Code Generation
Section titled “Chapter 6 — Intermediate-Code Generation”CHAPTER 6 Intermediate-Code Generation
Section titled “CHAPTER 6 Intermediate-Code Generation”In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target code. Ideally, details of the source language are confined to the front end, and details of the target machine to the back end. With a suitably defined intermediate representation, a compiler for language i and machine j can then be built by combining the front end for language i with the back end for machine j. This approach to creating suite of compilers can save a considerable amount of effort: m × n compilers can be built by writing just m front ends and n back ends.
This chapter deals with intermediate representations, static type checking, and intermediate code generation. For simplicity, we assume that a compiler front end is organized as in Fig. 6.1, where parsing, static checking, and intermediate-code generation are do sequentially; sometimes they can be combined and folded into parsing. We shall as syntax-directed formalisms of Chapters 2 and 5 to specify checking and translation. of the translation schemes can be implemented during either bottom-up or top parsing, using the techniques of Chapter 5. All schemes can be implemented by creat syntax tree and then walking the tree.
Figure 6.1 — Logical structure of a compiler front end. Parser, Static Checker, and Intermediate Code Generator comprise the front end; Code Generator comprises the back end. The two halves are linked by the intermediate code representation.
Static checking includes type checking, which ensures that operators are applied to compatible operands. It also includes any syntactic checks that remain after parsing.
For example, static checking assures that a break-statement in C is enclosed within while-, for-, or switch-statement; an error is reported if such an enclosing statement does not exist.
The approach in this chapter can be used for a wide range of intermediate representations, including syntax trees and three-address code, both of which were introduced in Section 2.8. The term “three-address code” comes from instructions of the general form x=y op z with three addresses: two for the operands y and z and one for the result a.
In the process of translating a program in a given source language into code for a given target machine, a compiler may construct a sequence of intermediate representations as in Fig. 6.2. High-level representations are close to the source language and low-level representations are close to the target machine. Syntax trees are high level; they depict the natural hierarchical structure of the source program and are well suited to tasks like static type checking.
Figure 6.2 A compiler might use a sequence of intermediate representations
A low-level representation is suitable for machine-dependent tasks like register allocation and instruction selection. Three-address code can range from high-to low-level, depending on the choice of operators. For expressions, the differences between syntax trees and three-address code are superficial, as we shall see in Section 6.2.3. For looping statements, for example, a syntax tree represents the components of a statement, whereas three-address code contains labels and jump instructions to represent the flow of control, as in machine language.
The choice or design of an intermediate representation varies from compiler to compiler. An intermediate representation may either be an actual language or it may consist of internal data structures that are shared by phases of the compiler. C is a programming language, yet it is often used as an intermediate form because it is flexible, it compiles into efficient machine code, and its compilers are widely available. The original C++ compiler consisted of a front end that generated C, treating a C compiler as a back end.
6.1 Variants of Syntax Trees
Section titled “6.1 Variants of Syntax Trees”Nodes in a syntax tree represent constructs in the source program; the children of a node represent the meaningful components of a construct. A directed acyclic graph (hereafter a DAG) for an expression identifies the common subexpressions (subexpressions cur more than once) of the expression. As we shall see in this section, DAG’s can aructed by using the same techniques that construct syntax trees.
6.1 Directed Acyclic Graphs for Expressions
Section titled “6.1 Directed Acyclic Graphs for Expressions”Like the syntax tree for an expression, a DAG has leaves corresponding to atomic operations and interior nodes corresponding to operators. The difference is that a node V in a DAG has more than one parent if V represents a common subexpression in a syntax tree. The tree for the common subexpression would be replicated as many times as the subexpression appears in the original expression. Thus, a DAG not only represents expressions more succinctly, it gives the compiler important clues regarding the generation of efficient code to evaluate the expressions.
Example 6.1
Section titled “Example 6.1”Figure 6.3 shows the DAG for the expression
a * a * (b = c) * (b = c) * d
The leaf for a has two parents, because a appears twice in the expression. More interestingly, the two occurrences of the common subexpression b-c are represented by one node, the node labeled -. That node has two parents, representing its two uses in the subexpressions a * (b-c) and (b-c) * d. Even though b and c appear twice in the complete expression, their nodes each have one parent, since both uses are in the common subexpression b-c.
Figure 6.3 Dag for the expression a + a * (b = c) + (b = c) * d
The SDD of Fig. 6.4 can construct either syntax trees or DAG’s. It was used to construct syntax trees in Example 5.11, where functions Leaf and Node created a fresh node each time they were called. It will construct a DAG if, before creating a new node, these functions first check whether an identical node already exists. If a previously created identical node exists, the existing node is returned. For instance, before constructing a new node, Node(op, left, right), we check whether there is already a node with label op, and children left and right, in that order. If so, Node returns the existing node; otherwise, it creates a new node.
| PRODUCTION | SEMANTIC RULES |
|---|---|
| 1) E→E1+T | E.node=new Node(’+‘,E1.node,T.node) |
| 2) E→E1-T | E.node=new Node(’-‘,E1.node,T.node) |
| 3) E→T | E.node=T.node |
| 4) T→(E) | T.node=E.node |
| 5) T→id | T.node=new Leaf(id, id.entry) |
| 6) T→num | T.node=new Leaf(num, num.val) |
Figure 6.4 Syntax-directed definition to produce syntax trees or DAG’s
Example 6.2
The sequence of steps shown in Fig. 6.5 constructs the DAG in Fig. 6.3, provided Node and Leaf return an existing node, if possible, as discussed above. We assume that entry-a points to the symbol-table entry for a, and similarly for the other identifiers.
-
p1= Leaf(id, entry-a)
-
p2= Leaf(id, entry-a)=p1
-
p3= Leaf(id, entry-b)
-
p4= Leaf(id, entry-c)
-
p5= Node(’-‘,p3,p4)
-
p6= Node(’*‘,p1,p5)
-
p7= Node(’+‘,p1,p6)
-
p8= Leaf(id, entry-b)=p3
-
p9= Leaf(id, entry-c)=p4
-
p10= Node(’-‘,p3,p4)=p5
-
p11= Leaf(id, entry-d)
-
p12= Node(’*‘,p5,p11)
-
p13= Node(’+‘,p7,p12)
Figure 6.5 Steps for constructing the DAG of Fig. 6.3
e the call to Leaf(id, entry-a) is repeated at step 2, the node created by the pre-ious call is returned, so Similarly, the nodes returned at steps 8 and 9 are the same as those returned at steps 3 and 4(i.e., and ). Hence the node returned at step 10 must be the same at that returned at step 5;i.e., .
6.1.2 The Value-Number Method for Constructing DAG’s
Section titled “6.1.2 The Value-Number Method for Constructing DAG’s”Often, the nodes of a syntax tree or DAG are stored in an array of records, as suggested by Fig. 6.6. Each row of the array represents one record, and therefore one node. In each record, the first field is an operation code, indicating the label of the node. In Fig. 6.6(b), leaves have one additional field, which holds the lexical value (either a symbol-table pointer or a constant, in this case), and interior nodes have two additional fields indicating the left and right children.
Figure 6.6 Nodes of a DAG for i = i + 10 allocated in an array
In this array, we refer to nodes by giving the integer index of the record for that node within the array. This integer historically has been called the value number for the node or for the expression represented by the node. For instance, in Fig. 6.6, the node labeled + has value number 3, and its left and right children have value numbers 1 and 2, respectively. In practice, we could use pointers to records or references to objects instead of integer indexes, but we shall still refer to the reference to a node as its “value number.” If stored in an appropriate data structure, value numbers help us construct expression DAG’s efficiently; the next algorithm shows how.
Suppose that nodes are stored in an array, as in Fig. 6.6, and each node is referred to by its value number. Let the signature of an interior node be the triple ⟨op, l, r⟩, where the label, l its left child’s value number, and r its right child’s value number. A unar ator may be assumed to have r = 0.
Algorithm 6.3 The value-number method for constructing the nodes of a DAG. INPUT: Label op, node l, and node r. OUTPUT: The value number of a node in the array with signature ⟨op, l, r⟩. METHOD: Search the array for a node M with label op, left child l, and right child r. If there is such a node, return the value number of M. If not, create in the array a new node N with label op, left child l, and right child r, and return its value number.
While Algorithm 6.3 yields the desired output, searching the entire array every time we are asked to locate one node is expensive, especially if the array holds expressions from an entire program. A more efficient approach is to use a hash table, in which the nodes are put into “buckets,” each of which typically will have only a few nodes. The hash table is one of several data structures that support dictionaries efficiently.¹ A dictionary is an abstract data type that allows us to insert and delete elements of a set, and to determine whether a given element is currently in the set. A good data structure for dictionaries, such as a hash table, performs each of these operations in time that is constant or close to constant, independent of the size of the set.
To construct a hash table for the nodes of a DAG, we need a hash function h that computes the index of the bucket for a signature ⟨op, l, r⟩, in a way that distributes the signatures across buckets, so that it is unlikely that any one bucket will get much more than a fair share of the nodes. The bucket index h(op, l, r) is computed deterministically from op, l, and r, so that we may repeat the calculation and always get to the same bucket index for node ⟨op, l, r⟩.
The buckets can be implemented as linked lists, as in Fig. 6.7. An array, indexed by hash value, holds the bucket headers, each of which points to the first cell of a list. Within the linked list for a bucket, each cell holds the value number of one of the nodes that hash to that bucket. That is, node ⟨op, l, r⟩ can be found on the list whose header is at index h(op, l, r) of the array.
Figure 6.7 Data structure for searching buckets
Thus, given the input node op, l, and r, we compute the bucket index h(op, l, r) and search the list of cells in this bucket for the given input node. Typically, there are enough buckets so that no list has more than a few cells. We may need to look at all the cells within a bucket, however, and for each value number v found in a cell, we must check whether the signature ⟨op, l, r⟩ of the input node matches the node with value number v in the list of cells (as in Fig. 6.7). If we find a match, we return v. If we find no match, we know no such node can exist in any other bucket, so we create a new cell, add it to the list of cells for bucket index h(op, l, r), and return the value number in that new cell.
A. V., J. E. Hopcroft, and J. D. Ullman, Data Structures and Algorithms, Addison-Wesley, a discussion of data structures supporting dictionaries.
Exercises for Section 6.1
Section titled “Exercises for Section 6.1”Exercise 6.1.1: Construct the DAG for the expression
Section titled “Exercise 6.1.1: Construct the DAG for the expression”((x + y) - ((x + y) * (x - y))) + ((x + y) * (x - y))
Exercise 6.1.2: Construct the DAG and identify the value numbers for the subexpressions of the following expressions, assuming + associates from the left.
Section titled “Exercise 6.1.2: Construct the DAG and identify the value numbers for the subexpressions of the following expressions, assuming + associates from the left.”(a) a + b + (a + b). (b) a + b + a + b. (c) a + a + (a + a + a + (a + a + a + a)).
6.2 Three-Address Code
Section titled “6.2 Three-Address Code”In three-address code, there is at most one operator on the right side of an instruction; that is, no built-up arithmetic expressions are permitted. Thus a source-language expression like x+y*z might be translated into the sequence of three-address instructions
t₁ = y * z t₂ = x + t₁
where t₁ and t₂ are compiler-generated temporary names. This unraveling of operator arithmetic expressions and of nested flow-of-control statements makes address code desirable for target-code generation and optimization, as discuss. Chapters 8 and 9. The use of names for the intermediate values computed by a program allows three-address code to be rearranged easily.
Example 6.4
Section titled “Example 6.4”Three-address code is a linearized representation of a syntax tree or a DAG in which explicit names correspond to the interior nodes of the graph. The DAG in Fig. 6.3 is repeated in Fig. 6.8, together with a corresponding three-address code sequence.
Figure 6.8 A DAG and its corresponding three-address code
6.2.1 Addresses and Instructions
Section titled “6.2.1 Addresses and Instructions”Three-address code is built from two concepts: addresses and instructions. In object-oriented terms, these concepts correspond to classes, and the various kinds of addresses and instructions correspond to appropriate subclasses. Alternatively, three-address code can be implemented using records with fields for the addresses; records called quadruples and triples are discussed briefly in Section 6.2.2.
An address can be one of the following:
A name. For convenience, we allow source-program names to appear as addresses in three-address code. In an implementation, a source name is replaced by a pointer to its symbol-table entry, where all information about the name is kept.
A constant. In practice, a compiler must deal with many different types of constants and variables. Type conversions within expressions are considered in Section 6.5.2.
A compiler-generated temporary. It is useful, especially in optimizing compilers, to create a distinct name each time a temporary is needed. These temporaries can be combined, if possible, when registers are allocated to variables.
We now consider the common three-address instructions used in the rest of this book. Symbolic labels will be used by instructions that alter the flow of control. A symbolic label represents the index of a three-address instruction in the sequence of instructions. Actual indexes can be substituted for the labels, either by making a separate pass or by “back-patching,” discussed in Section 6.7. Here is a list of the common three-address instruction forms:
-
Assignment instructions of the form x=y op z, where op is a binary arithmetic or logical operation, and x,y, and z are addresses.
-
Assignments of the form x=op y, where op is a unary operation. Essential unary operations include unary minus, logical negation, and conversion operators that, for example, convert an integer to a floating-point number.
-
Copy instructions of the form x=y, where x is assigned the value of y.
-
An unconditional jump goto L. The three-address instruction with label L is the next to be executed.
、onditional jumps of the form if x goto L and ifFalse x goto L. These in-suctions execute the instruction with label L next if x is true and false, respectively.unwise, the following three-address instruction in sequence is executed next, as ual.
onditional jumps such as if x relop y goto L, which apply a relational operator、==,>=,etc.) to x and y, and execute the instruction with label L next if x stands in relation relop to y. If not, the three-address instruction following if x relop y goto L is executed next, in sequence.
- Procedure calls and returns are implemented using the following instructions:param x for parameters; call p,n and y= call p,n for procedure and function calls, respectively; and return y, where y, representing a returned value. is optional. Their typical use is as the sequence of three-address instructions
generated as part of a call of the procedure The integer n, indicating the number of actual parameters in “call p,n,” is not redundant because calls can be nested. That is, some of the first param statements could be parameters of a call that comes after p returns its value; that value becomes another parameter of the later call. The implementation of procedure calls is outlined in Section 6.9.
-
Indexed copy instructions of the form x=y[i] and x[i]=y. The instruction x=y[i]sets x to the value in the location i memory units beyond location y. The instruction x[i]=y sets the contents of the location i units beyond x to the value of y.
-
Address and pointer assignments of the form x=& y,x=y, andx=y. The instruction x=&y sets the r-value of x to be the location(l-value) of y.2 Presumab a name, perhaps a temporary, that denotes an expression with an l-value A[i][j],and x is a pointer name or temporary. In the instruction x=*y,p bly y is a pointer or a temporary whose r-value is a location. The r-value of x equal to the contents of that location. Finally,*x=y sets the r-value of the o pointed to by x to the r-value of y.
Example 6.5
Consider the statement
Two possible translations of this statement are shown in Fig. 6.9. The translation in Fig. 6.9(a) uses a symbolic label L, attached to the first instruction.
The translation in(b) shows position numbers for the instructions, starting arbitrarily at position 100. In both translations, the last instruction is a conditional jump to the first instruction. The multiplication i* 8 is appropriate for an array of elements that each take 8 units of space.
2 From Section 2.8.3,l-and r-values are appropriate on the left and right sides of assignments, respectively.
L: t1=i+1 i=t1 t2=i8 t3=a[t2] if t3<v goto L 100:t1=i+1 101:i=t1 102:t2=i8 103:t3=a[t2] 104: if t3<v goto 100 (a) Symbolic labels. (b) Position numbers.
Figure 6.9 Two ways of assigning labels to three-address statements
The choice of allowable operators is an important issue in the design of an intermediate form. The operator set clearly must be rich enough to implement the operations in the source language. Operators that are close to machine instructions make it easier to implement the intermediate form on a target machine. However, if the front end must generate long sequences of instructions for some source-language operations, then the optimizer and code generator may have to work harder to rediscover the structure and generate good code for these operations.
6.2.2 Quadruples
Section titled “6.2.2 Quadruples”The description of three-address instructions specifies the components of each type of instruction, but it does not specify the representation of these instructions in a data structure. In a compiler, these instructions can be implemented as objects or as records with fields for the operator and the operands. Three such representations are called “quadruples,”“triples,” and “indirect triples.”
A quadruple(or just “quad”) has four fields, which we call op, arg1,arg2,and result. The op field contains an internal code for the operator. For instance, the three-address instruction x=y+z is represented by placing+in op,y in arg1,z in arg2,and x in result. The following are some exceptions to this rule:
-
Instructions with unary operators like x=minus y or x=y do not use arg2.Note that for a copy statement like x=y, op is=,while for most other operations, the assignment operator is implied.
-
Operators like param use neither arg2 nor result.
-
Conditional and unconditional jumps put the target label in result.
Example 6.6
Three-address code for the assignment a=b*-c+b*-c; appears in Fig. 6.10(a).The special operator minus is used to distinguish the unary minus operator, as inc, from the binary minus operator, as in b-c. Note that the unary-minus “three-address”statement has only two addresses, as does the copy statement a= t5.
The quadruples in Fig. 6.10(b) implement the three-address code in(a).
Figure 6.10 Three-address code and its quadruple representation
For readability, we use actual identifiers like a,b, and c in the fields , and result in Fig. 6.10(b),instead of pointers to their symbol-table entries. Temporary names can either by entered into the symbol table like programmer-defined names, or they can be implemented as objects of a class Temp with its own methods.
6.2.3 Triples
Section titled “6.2.3 Triples”A triple has only three fields, which we call op, arg1,and arg2. Note that the result field Fig. 6.10(b) is used primarily for temporary names. Using triples, we refer to the re an operation x op y by its position, rather than by an explicit temporary name. Thus, of the temporary t1 in Fig. 6.10(b), a triple representation would refer to posi Parenthesized numbers represent pointers into the triple structure itself. In Section positions or pointers to positions were called value numbers.
Triples are equivalent to signatures in Algorithm 6.3. Hence, the DAG and triple re resentations of expressions are equivalent. The equivalence ends with expressions, since syntax-tree variants and three-address code represent control flow quite differently.
Example 6.7
The syntax tree and triples in Fig. 6.11 correspond to the three-address code and quadruples in Fig. 6.10. In the triple representation in Fig. 6.11(b), the copy statement a= t5 is encoded in the triple representation by placing a in the arg1 field and (4) in the arg2 field.
A ternary operation like x[i]=y requires two entries in the triple structure; for example, we can put x and i in one triple and y in the next. Similarly, x=y[i] can implemented by treating it as if it were the two instructions and , where t is a compiler-generated temporary. Note that the temporary t does not actually appear in a triple, since temporary values are referred to by their position in the triple structure.
Why Do We Need Copy Instructions?
Section titled “Why Do We Need Copy Instructions?”A simple algorithm for translating expressions generates copy instructions for assignments, as in Fig. 6.10(a), where we copy t5 into a rather than assigning t2+ t4 to a directly. Each subexpression typically gets its own, new temporary to hold its result, and only when the assignment operator= is processed do we learn where to put the value of the complete expression.A code-optimization pass, perhaps using the DAG of Section 6.1.1 as an intermediate form, can discover that t5 can be replaced by a.
(a) Syntax tree
(b) Triples
Figure 6.11 Representations of a=b*-c+b*-c;
A benefit of quadruples over triples can be seen in an optimizing compiler, where instructions are often moved around. With quadruples, if we move an instruction that computes a temporary t, then the instructions that use t require no change. With triples, the result of an operation is referred to by its position, so moving an instruction may require us to change all references to that result. This problem does not occur with indirect triples, which we consider next.
Indirect triples consist of a listing of pointers to triples, rather than a listing of triples themselves. For example, let us use an array instruction to list pointers to triples in the desired order. Then, the triples in Fig. 6.11(b) might be represented as in Fig. 6.12.
Figure 6.12 Indirect triples representation of three-address code
direct triples, an optimizing compiler can move an instruction by reordering the n list, without affecting the triples themselves. When implemented in Java, an array of instruction objects is analogous to an indirect triple representation, since Java treats the array elements as references to objects.
6.2.4 Static Single-Assignment Form Static single-assignment form (SSA) is an intermediate representation that facilitates certain code optimizations. Two distinctive aspects distinguish SSA from three-address code. The first is that all assignments in SSA are to variables with distinct names; hence the term static single-assigment. Figure 6.13 shows the same intermediate program in three-address code and in static single-assignment form. Note that subscripts distinguish each definition of variables p and q in the SSA representation.
p = a + b q = p - c p = q * d p = e - p q = p + q
p1 = a + b q1 = p1 - c p2 = q1 * d p3 = e - p2 q2 = p3 + q1
(a) Three-address code. (b) Static single-assignment form.
Figure 6.13 Intermediate program in three-address code and SSA
The same variable may be defined in two different control-flow paths in a program. For example, the source program
if ( flag ) x = -1; else x = 1; y = x * a;
has two control-flow paths in which the variable x gets defined. If we use differen for x in the true part and the false part of the conditional statement, then whi should we use in the assignment y = x * a? Here is where the second distinctive of SSA comes into play. SSA uses a notational convention called the φ-function bine the two definitions of x:
if ( flag ) x1 = -1; else x2 = 1; x3 = φ(x1,x2);
Here, φ(x1,x2) has the value x1 if the control flow passes through the true part of the conditional and the value x2 if the control flow passes through the false part. That is to say, the φ-function returns the value of its argument that corresponds to the control-flow path that was taken to get to the assignment-statement containing the φ-function.
Exercises for Section 6.2
Section titled “Exercises for Section 6.2”Exercise 6.2.1: Translate the arithmetic expression a+(b+c) into:
(a) A syntax tree.
(b) Quadruples.
(c) Triples.
(d) Indirect triples.
Exercise 6.2.2: Repeat Exercise 6.2.1 for the following assignment statements:
i. a= b[i] + c[j].
ii. a[i]= bc- bd.
iii. x= f(y+1)+ 2.
iv. x=*p+&y.
!Exercise 6.2.3: Show how to transform a three-address code sequence into one in which each defined variable gets a unique variable name.
6.3 Types and Declarations
Section titled “6.3 Types and Declarations”The applications of types can be grouped under checking and translation:
Type checking uses logical rules to reason about the behavior of a program at run time. Specifically, it ensures that the types of the operands match the type expected by an operator. For example, the&& operator in Java expects its two operands to be booleans; the result is also of type boolean.
Translation Applications. From the type of a name, a compiler can determine the storage that will be needed for that name at run time. Type information is also needed to calculate the address denoted by an array reference, to insert explicit type conversions, and to choose the right version of an arithmetic operator, among other things.
In this section, we examine types and storage layout for names declared within a procedure or a class. The actual storage for a procedure call or an object is allocated at run time, when the procedure is called or the object is created. As we examine local declarations at compile time, we can, however, lay out relative addresses, where the relative address of a name or a component of a data structure is an offset from the start of a data area.
6.3.1 Type Expressions
Section titled “6.3.1 Type Expressions”Types have structure, which we shall represent using type expressions: a type expression is either a basic type or is formed by applying an operator called a type constructor to a type expression. The sets of basic types and constructors depend on the language to be checked.
Example 6.8
Section titled “Example 6.8”The array type int[2][3] can be read as “array of 2 arrays of 3 integers each” and written as a type expression array (2, array (3, integer)). This type is represented by the tree in Fig. 6.14. The operator array takes two parameters, a number and a type.
Figure 6.14 Type expression for int[2][3]
We shall use the following definition of type expressions:
-
A basic type is a type expression. Typical basic types for a language include
boolean,char,integer,float, andvoid; the latter denotes “the absence of a value.” -
A type name is a type expression.
-
A type expression can be formed by applying the
arraytype constructor to a number and a type expression. -
A record is a data structure with named fields. A type expression can be formed by applying the
recordtype constructor to the field names and their types. Record types will be implemented in Section 6.3.6 by applying the constructorrecordto a table containing entries for the fields. -
A type expression can be formed by using the type constructor → for function. We write
s → tfor “function from typesto typet.” Function types will be as when type checking is discussed in Section 6.5. -
If
sandtare type expressions, then their Cartesian products × tis a type expression. Products are introduced for completeness; they can be used to represent a list or tuple of types (e.g., for function parameters). We assume that × associates to the left and that it has higher precedence than →. -
Type expressions may contain variables whose values are type expressions. Compiler-generated type variables will be used in Section 6.5.4.
Type Names and Recursive Types
Section titled “Type Names and Recursive Types”Once a class is defined, its name can be used as a type name in C++ or Java; for example, consider Node in the program fragment
public class Node { … }
…
public Node n;
Names can be used to define recursive types, which are needed for data structures such as linked lists. The pseudocode for a list element
class Cell { int info; Cell next; … }
defines the recursive type Cell as a class that contains a field info and a field next of type Cell. Similar recursive types can be defined in C using records and pointers. The techniques in this chapter carry over to recursive types.
A convenient way to represent a type expression is to use a graph. The value-number method of Section 6.1.2, can be adapted to construct a dag for a type expression, with interior nodes for type constructors and leaves for basic types, type names, and type variables; for example, see the tree in Fig. 6.14.³
6.3.2 Type Equivalence
Section titled “6.3.2 Type Equivalence”When are two type expressions equivalent? Many type-checking rules have the form, “if two type expressions are equal then return a certain type else error.” Potential ambiguities arise when names are given to type expressions and the names are then used in subsequent type expressions. The key issue is whether a name in a type expression stands for itself or whether it is an abbreviation for another type expression.
When type expressions are represented by graphs, two types are structurally equivalent if and only if one of the following conditions is true:
- They are the same basic type.
- They are formed by applying the same constructor to structurally equivalent types.
- One is a type name that denotes the other.
If type names are treated as standing for themselves, then the first two conditions in the above definition lead to name equivalence of type expressions. Name-equivalent expressions are assigned the same value number. if we use Algorithm 6.3. Structural equivalence can be tested using the unification algorithm in Section 6.5.5.
6.3.3 Declarations
Section titled “6.3.3 Declarations”We shall study types and declarations using a simplified grammar that declares just one name at a time; declarations with lists of names can be handled as discussed in Example 5.10.The grammar is
The fragment of the above grammar that deals with basic and array types was used to illustrate inherited attributes in Section 5.3.2.The difference in this section is that we consider storage layout as well as types.
Nonterminal D generates a sequence of declarations. Nonterminal T generates basic, array, or record types. Nonterminal B generates one of the basic types int and float. Nonterminal C,for “component,”generates strings of zero or more integers, each integer surrounded by brackets. An array type consists of a basic type specified by B, followed by array components specified by nonterminal C. A record type(the second production for T) is a sequence of declarations for the fields of the record, all surrounded by curly braces.
6.3.4 Storage Layout for Local Names
Section titled “6.3.4 Storage Layout for Local Names”From the type of a name, we can determine the amount of storage that will be needed for the name at run time. At compile time, we can use these amounts to assign each name a relative address. The type and relative address are saved in the symbol-table entry for the name. Data of varying length, such as strings, or data whose size cannot determined until run time, such as dynamic arrays, is handled by reserving a known ax amount of storage for a pointer to the data. Run-time storage management is discus in Chapter 7.
Suppose that storage comes in blocks of contiguous bytes, where a byte is the sma unit of addressable memory. Typically, a byte is eight bits, and some number of bytes for a machine word. Multibyte objects are stored in consecutive bytes and given the address of the first byte.
The width of a type is the number of storage units needed for objects of that type.A basic type, such as a character, integer, or float, requires an integral number of bytes.
Compliers: Principles, Techniques and Tools
Address Alignment
Section titled “Address Alignment”The storage layout for data objects is strongly influenced by the addressing constraints of the target machine. For example, instructions to add integers may expect integers to be aligned, that is, placed at certain positions in memory such as an address divisible by 4. Although an array of ten characters needs only enough bytes to hold ten characters,a compiler may therefore allocate 12 bytes- the next multiple of 4-leaving 2 bytes unused. Space left unused due to alignment considerations is referred to as padding. When space is at a premium, a compiler may pack data so that no padding is left; additional instructions may then need to be executed at run time to position packed data so that it can be operated on as if it were properly aligned.
For easy access, storage for aggregates such as arrays and classes is allocated in one contiguous block of bytes.4
The translation scheme(SDT) in Fig. 6.15 computes types and their widths for basic and array types; record types will be discussed in Section 6.3.6. The SDT uses synthesized attributes type and width for each nonterminal and two variables t and w to pass type and width information from a B node in a parse tree to the node for the production C→\epsilon. In a syntax-directed definition,t and w would be inherited attributes for C.
T\,\rightarrow\,B\qquad\quad\{}\,t= B.\,type\,;\,w= B.\,width\,;\quad\} C\qquad\quad\{}\,T.\,type=C.\,type\,;\,T.\,width=C.\,width\,;\quad\} B\,\rightarrow\,int\qquad\quad\{}\,B.\,type=integer\,;\,B.\,width=4\,;\quad\} B\,\rightarrow\,float\qquad\quad\{}\,B.\,type= float\,;\,B.\,width=8\,;\quad\} C\,\rightarrow\,\epsilon\qquad\quad\{}\,C.\,type= t\,;\,C.\,width= w\,;\quad\}Figure 6.15 Computing types and their widths
The body of the T-production consists of nonterminal B, an action, and nonterminal C,which appears on the next line. The action between B and C sets t to B.type and w to B.width. If B→int then B.type is set to integer and B.width is set to 4, the width of an integer. Similarly, if B→float then B.type is float and B.width is 8, the width of a float.
The productions for C determine whether T generates a basic type or an array type. If C→\epsilon, then t becomes C.type and w becomes C. width.
4 Storage allocation for pointers in C and C++ is simpler if all pointers have the same width. The reason is that the storage for a pointer may need to be allocated before we learn the type of the objects it can point to. Otherwise, C specifies an array component. The action for C→[num] C₁ forms C.type by applying the type constructor array to the operands num.value and C₁.type. For instance, the result of applying array might be a tree structure such as Fig. 6.14.
The width of an array is obtained by multiplying the width of an element by the number of elements in the array. If addresses of consecutive integers differ by 4, then address calculations for an array of integers will include multiplications by 4. Such multiplications provide opportunities for optimization, so it is helpful for the front end to make them explicit. In this chapter, we ignore other machine dependencies such as the alignment of data objects on word boundaries.
Example 6.9 The parse tree for the type int[2][3] is shown by dotted lines in Fig. 6.16. The solid lines show how the type and width are passed from B, down the chain of C’s through variables t and w, and then back up the chain as synthesized attributes type and width. The variables t and w are assigned the values of B.type and B.width, respectively, before the subtree with the C nodes is examined. The values of t and w are used at the node for C→ε to start the evaluation of the synthesized attributes up the chain of C nodes.
Figure 6.16 Syntax-directed translation of array types
6.3.5 Sequences of Declarations
Section titled “6.3.5 Sequences of Declarations”Languages such as C and Java allow all the declarations in a single procedure to cessed as a group. The declarations may be distributed within a Java procedure, can still be processed when the procedure is analyzed. Therefore, we can use a vara offset, to keep track of the next available relative address.
The translation scheme of Fig. 6.17 deals with a sequence of declarations of the to m T id, where T generates a type as in Fig. 6.15. Before the first declaration is considered offset is set to 0. As each new name x is seen, x is entered into the symbol table with its This discussion of storage for record types carries over to classes, since no storage is reserved for methods. See Exercise 6.3.2.
Exercises for Section 6.3
Section titled “Exercises for Section 6.3”Exercise 6.3.1: Determine the types and relative addresses for the identifiers in the following sequence of declarations: float x; record { float x; float y; } p; record { int tag; float x; float y; } q;
! Exercise 6.3.2: Extend the handling of field names in Fig. 6.18 to classes and single-inheritance class hierarchies. (a) Give an implementation of class Env that allows linked symbol tables, so that a subclass can either redefine a field name or refer directly to a field name in a superclass. (b) Give a translation scheme that allocates a contiguous data area for the fields in a class, including inherited fields. Inherited fields must maintain the relative addresses they were assigned in the layout for the superclass.
6.4 Translation of Expressions
Section titled “6.4 Translation of Expressions”The rest of this chapter explores issues that arise during the translation of expressions and statements. We begin in this section with the translation of expressions into three-address code. An expression with more than one operator, like a + b * c, will translate into instructions with at most one operator per instruction. An array reference A[i][j] will expand into a sequence of three-address instructions that calculate an address for the reference. We shall consider type checking of expressions in Section 6.5 and the use of boolean expressions to direct the flow of control through a program in Section 6.6.
6.4.1 Operations Within Expressions
Section titled “6.4.1 Operations Within Expressions”The syntax-directed definition in Fig. 6.19 builds up the three-address code for an assignment statement S using attribute code for S and attributes addr and code for an expression E. Attributes S.code and E.code denote the three-address code for S and E, respectively. Attribute E.addr denotes the address that will hold the value of E. Recall from Section 6.2.1 that an address can be a name, a constant, or a compiler-generated temporary.
Consider the last production, E→id, in the syntax-directed definition in Fig. 6.19. When an expression is a single identifier, say x, then x itself holds the value of the expression. The semantic rules for this production define E.addr to point to the symbol-table entry for this instance of id. Let top denote the current symbol table. Function top.get retrieves the
| PRODUCTION | SEMANTIC RULES |
|---|---|
| S→id=E; | S.code=E.code |
| E→E1+E2 | E.addr=new Temp()E.code=E1.code |
| -E1 | |
| (E1) | |
| id |
Figure 6.19 Three-address code for expressions
entry when it is applied to the string representation id.lexeme of this instance of id.E.code is set to the empty string.
When , the translation of E is the same as that of the subexpression . Hence.E.addr equals E1.addr, and E.code equals E1.code.
The operators+ and unary- in Fig. 6.19 are representative of the operators in a typical language. The semantic rules for , generate code to compute the value of E from the values of E1 and E2. Values are computed into newly generated temporary names. If E1 is computed into E1.addr and E2 into E2.addr, then E1+E2 translates into , where t is a new temporary name. E.addr is set to t. A sequence of distinct temporary names is created by successively executing new Temp().
For convenience, we use the notation gen(x’=‘y’+‘z) to represent the three-address instruction x=y+z. Expressions appearing in place of variables like x,y, and z are evaluated when passed to gen, and quoted strings like’=’ are taken literally’. Other three-address instructions will be built up similarly by applying gen to a combination of expressions and strings.
When we translate the production , the semantic rules in Fig. 6.19 buu E.code by concatenating E1.code, E2.code, and an instruction that adds the values and E2. The instruction puts the result of the addition into a new temporary name f denoted by E.addr.
5 In syntax-directed denitions, gen builds an instruction and returns it. In translation schemes, gen buil an instruction and incrementally emits it by putting it into the stream of generated instructions. 382 Compilers: Principles, Techniques and Tools
The translation of E -> -E_1 is similar. The rules create a new temporary for E and generate an instruction to perform the unary minus operation. Finally, the production S -> id = E; generates instructions that assign the value of expression E to the identifier id. The semantic rule for this production uses function top.get to determine the address of the identifier represented by id, as in the rules for E -> id.
Example 6.11: the syntax-directed definition in Fig. 6.19 translates the assignment statement a = b + -c; into the three-address code sequence:
t1 = minus ct2 = b + t1a = t26.4.2 Incremental Translation
Section titled “6.4.2 Incremental Translation”Code attributes can be long strings, so they are usually generated incrementally. Instead of building up E.code as in Fig. 6.19, we can arrange to generate only the new three-address instructions, as in Fig. 6.20. In the incremental approach, gen constructs a three-address instruction and appends it to the sequence generated so far.
S -> id = E; { gen(top.get(id.lexeme) '=' E.addr); }E -> E1 + E2 { E.addr = new Temp(); gen(E.addr '=' E1.addr '+' E2.addr); } | -E1 { E.addr = new Temp(); gen(E.addr '=' 'minus' E1.addr); } | (E1) { E.addr = E1.addr; } | id { E.addr = top.get(id.lexeme); }Figure 6.20 Generating three-address code for expressions incrementally
The translation scheme in Fig. 6.20 generates the same code as the syntax-directed definition in Fig. 6.19. With the incremental approach, the code attribute is not used, since there is a single sequence of instructions created by successive calls to gen.
Intermediate-Code Generation the semantic rule for in Fig. 6.20 simply calls gen to generate an add instruction; the instructions to compute into and into have already been generated.
The approach of Fig. 6.20 can also be used to build a syntax tree. The new semantic action for creates a node by using a constructor, as in
Here, attribute addr represents the address of a node rather than a variable or constant.
6.4.3 Addressing Array Elements
Section titled “6.4.3 Addressing Array Elements”Array elements can be accessed quickly if they are stored in a block of consecutive locations. In C and Java, array elements are numbered 0,1…,n-1, for an array with n elements. If the width of each array element is w, then the i th element of array A begins in location
where base is the relative address of the storage allocated for the array. That is, base is the relative address of A[0].
The formula (6.2) generalizes to two or more dimensions. In two dimensions, let us write , as in C, for element in row Let be the width of a row and let be the width of an element in a row. The relative address of can then be calculated by the formula
In k dimensions, the formula is
where , for , is the generalization of and in (6.3).
Alternatively, the relative address of an array reference can be calculated in terms of the numbers of elements along dimension j of the array and the width of a single element of the array. In two dimensions(i.e.,k=2 and w=w2), the location for A[i1][i2]is given by
In k dimensions, the following formula calculates the same address as (6.4):
More generally, array elements need not be numbered starting at 0. In a one-dime array, the array elements are numbered low, low+1,…,high and base is the relative of A[low]. Formula(6.2) for the address of A[i] is replaced by:
The expressions (6.2) and (6.7) can be both be rewritten as , where the subexpres-sion c= base-lowxw can be precalculated at compile time. Note that c= base when low is 0. We assume that c is saved in the symbol table entry for A, so the relative address of A[i] is obtained by simply adding i xw to c.
Compile-time precalculation can also be applied to address calculations for elements of multidimensional arrays; see Exercise 6.4.5. However, there is one situation where we cannot use compile-time precalculation: when the array’s size is dynamic. If we do not know the values of low and high(or their generalizations in many dimensions) at compile time, then we cannot compute constants such as c. Then, formulas like (6.7) must be evaluated as they are written, when the program executes.
The above address calculations are based on row-major layout for arrays, which is used in C,for example.A two-dimensional array is normally stored in one of two forms, either row-major(row-by-row) or column-major(column-by-column). Figure 6.21 shows the layout of a 23 array A in(a) row-major form and(b) column-major form. Column-major form is used in the Fortran family of languages.
Figure 6.21 Layouts for a two-dimensional array.
We can generalize row-or column-major form to many dimensions. The generalization of row-major form is to store the elements in such a way that, as we scan down a block of storage, the rightmost subscripts appear to vary fastest, like the numbers on an odometer. Column-major form generalizes to the opposite arrangement, with the leftmost subscripts varying fastest.
6.4.4 Translation of Array References
Section titled “6.4.4 Translation of Array References”The chief problem in generating code for array references is to relate the address-calculation formulas in Section 6.4.3 to a grammar for array references. Let nonterminal L generate an array name followed by a sequence of index expressions:
As in C and Java, assume that the lowest-numbered array element is 0. Let us calculate addresses based on widths, using the formula (6.4), rather than on numbers of elements, as in (6.6).The translation scheme in Fig. 6.22 generates three-address code for expressions with array references. It consists of the productions and semantic actions from Fig. 6.20,together with productions involving nonterminal L.
\begin{array}{lcl} S&\rightarrow&{id=E}\,;&{\{gen(\text{ top.get}({id.lexeme})^{'=\,}{E.addr})\,;}\\\\{\|}&{L=E}\,;&{\{gen(L.array.base^{'}[\,^{L.addr}\,]^{'=\,{}^{E.addr})\,;}\}\\ E&\rightarrow&{E_{1}+E_{2}}&{\{E.addr={new\,Temp\,();}}\\{\|}&{id}&{\{E.addr={top.get({id.lexeme})\,;}\}}\\ &\|\quad{L}&{\{E.addr={new\,Temp\,();}}\\{\|}&{L}&{gen(E.addr^{'=\,}{L.array.base^{'}[\,^{L.addr}\,]^{'})};}\\ L&\rightarrow&{id\,[\,E\,]}&{\{L.array=top.get({id.lexeme})\,;}\\ &&L.type=L.array.type.elem;\\ &&L.addr={new\,Temp\,();}\\ &&gen(L.addr^{'=\,}{E.addr^{'*}\,L.type.width);}\\ &\|\quad{L_{1}\,[\,E\,]}&{\{L.array=L_{1}.array;}\\ &&L.type=L_{1}.type.elem;\\ &&t={new\,Temp\,();}\\ &&L.addr={new\,Temp\,();}\\ &&gen(t^{'=\,}{E.addr^{'*}\,L.type.width);}\\ &&gen(L.addr^{'=\,}{L_{1}.addr^{'+\,}}{t});\}\\ &&\end{array}Figure 6.22 Semantic actions for array references
Nonterminal L has three synthesized attributes:
-
L.addr denotes a temporary that is used while computing the offset for the array reference by summing the terms in (6.4).
-
L.array is a pointer to the symbol-table entry for the array name. The base address of the array, say,L.array.base is used to determine the actual l-value of an array reference after all the index expressions are analyzed.
-
L.type is the type of the subarray generated by L. For any type t, we assume that its width is given by t.width. We use types as attributes, rather than widths, since types are needed anyway for type checking. For any array type t, suppose that t.elem gives the element type.
The production ; represents an assignment to a nonarray variable, which is handled as usual. The semantic action for ; generates an indexed copy instruction assign the value denoted by expression E to the location denoted by the array re L. Recall that attribute L.array gives the symbol-table entry for the array. The ar address- the address of its 0th element- is given by L.array.base. Attribut denotes the temporary that holds the offset for the array reference generated o location for the array reference is therefore L.array.base[L.addr]. The generated instruction copies the r-value from address E.addr into the location for L.
Productions and are the same as before. The semantic action for the new production generates code to copy the value from the location denoted by L into a new temporary. This location is L.array.base[L.addr], as discussed above for the production ;. Again, attribute L.array gives the array name, and L.array.base gives its base address. Attribute L.addr denotes the temporary that holds the offset. The code for the array reference places the r-value at the location designated by the base and offset into a new temporary denoted by E.addr.
Example 6.12
Section titled “Example 6.12”Let a denote a 2x3 array of integers, and let c,i, and j all denote integers. Then, the type of a is array (2,array (3,integer)). Its width w is 24, assuming that the width of an integer is 4.The type of a[i] is array (3,integer), of width . The type of a[i][j] is integer.
An annotated parse tree for the expression c+a[i][j] is shown in Fig. 6.23.The expression is translated into the sequence of three-address instructions in Fig. 6.24.As usual, we have used the name of each identifier to refer to its symbol-table entry.
Symbolic Type Widths
Section titled “Symbolic Type Widths”The intermediate code should be relatively independent of the target machine, so the optimizer does not have to change much if the code generator is replaced by one for a different machine. However, as we have described the calculation of type widths, an assumption regarding basic types is built into the translation scheme. For instance. Example 6.12 assumes that each element of an integer array takes four bytes. Some intermediate codes,e.g.,P-code for Pascal, leave it to the code generator to fill in the size of array elements, so the intermediate code is independent of the size of a machine word. We could have done the same in our translation scheme if we replaced 4(as the width of an integer) by a symbolic constant.
Exercises for Section 6.4
Section titled “Exercises for Section 6.4”Exercise 6.4.1: Add to the translation of Fig. 6.19 rules for the following productions:
(a) .
(b) (unary plus).
Exercise 6.4.2: Repeat Exercise 6.4.1 for the incremental translation of Fig. 6.20.
Exercise 6.4.3: Use the translation of Fig. 6.22 to translate the following assignments:
(a) x=a[i]+ b[j].
(b) x= a[i][j]+ b[i][j].
!(c) x= a[b[i][j]][c[k]].
!Exercise 6.4.4:Revise the translation of Fig. 6.22 for array references of the Fortran style, that is, id[E1,E2,…,En] for an n-dimensional array.
Exercise 6.4.5:Generalize formula (6.7) to multidimensional arrays, and indicate what values can be stored in the symbol table and used to compute offsets. Consider the following cases:
(a) An array A of two dimensions, in row-major form. The first dimension has indexes running from l1 to h1, and the second dimension has indexes from l2 to h2. The width of a single array element is w.
(b) The same as(a), but with the array stored in column-major form.
!(c) An array A of k dimensions, stored in row-major form, with elements of size w. The jth dimension has indexes running from to
!(d) The same as(c) but with the array stored in column-major form.
Exercise 6.4.6: An integer array A[i,j], stored row-major, has index i ranging from 1 to 10 and index j ranging from 1 to 20. Integers take 4 bytes each. Suppose array A is stored starting at byte 0. Find the location of:
(a) A[4,5] (b) A[10,8] (c) A[3,17].
Exercise 6.4.6: Repeat Exercise 6.4.6 if A is stored in column-major order.
Exercise 6.4.8: A real array A[i,j,k] has index i ranging from 1 to 4, j ranging from 0 to 4, and k ranging from 5 to 10. Reals take 8 bytes each. If A is stored row-major, starting at byte 0, find the location of:
(a) A[3,4,5] (b) A[1,2,7] (c) A[4,3,9].
Exercise 6.4.9: Repeat Exercise 6.4.8 if A is stored in column-major order.
6.5 Type Checking
Section titled “6.5 Type Checking”To do type checking a compiler needs to assign a type expression to each component of the source program. The compiler must then determine that these type expressions conform to a collection of logical rules that is called the type system for the source language.
Type checking has the potential for catching errors in programs. In principle, any check can be done dynamically, if the target code carries the type of an element along with the value of the element. A sound type system eliminates the need for dynamic checking for type errors, because it allows us to determine statically that these errors cannot occur when the target program runs. An implementation of a language is strongly typed if a compiler guarantees that the programs it accepts will run without type errors.
Besides their use for compiling, ideas from type checking have been used to improve the security of systems that allow software modules to be imported and executed. Java programs compile into machine-independent bytecodes that include detailed type information about the operations in the bytecodes. Imported code is checked before it is allowed to execute, to guard against both inadvertent errors and malicious misbehavior.
6.5.1 Rules for Type Checking
Section titled “6.5.1 Rules for Type Checking”Type checking can take on two forms: synthesis and inference. Type synthesis builds up the type of an expression from the types of its subexpressions. It requires names to be declared before they are used. The type of is defined in terms of the types of and .A typical rule for type synthesis has the form
Here, f and x denote expressions, and s→t denotes a function from s to t. This rule for functions with one argument carries over to functions with several arguments. The rule (6.8) can be adapted for E1+E2 by viewing it as a function application add(E1,E2).⁶
Type inference determines the type of a language construct from the way it is used. Looking ahead to the examples in Section 6.5.4, let null be a function that tests whether a list is empty. Then, from the usage null(x), we can tell that x must be a list. The type of the elements of x is not known; all we know is that x must be a list of elements of some type that is presently unknown.
Variables representing type expressions allow us to talk about unknown types. We shall use Greek letters α,β,… for type variables in type expressions.
A typical rule for type inference has the form
if f(x) is an expression,
then for some a andβ,f has type a→β and x has type a(6.9)
Type inference is needed for languages like ML, which check types, but do not require names to be declared.
In this section, we consider type checking of expressions. The rules for checking statements are similar to those for expressions. For example, we treat the conditional statement “if(E) S;” as if it were the application of a function if to E and S. Let the special type void denote the absence of a value. Then function if expects to be applied to a boolean and a void; the result of the application is a void.
6.5.2 Type Conversions
Section titled “6.5.2 Type Conversions”Consider expressions like x+i, where x is of type float and i is of type integer. Since the representation of integers and floating-point numbers is different within a computer and different machine instructions are used for operations on integers and floats, the compiler may need to convert one of the operands of+ to ensure that both operands are of the same type when the addition occurs.
Suppose that integers are converted to floats when necessary, using a unary operator(float).For example, the integer 2 is converted to a float in the code for the expression 2*3.14:
We can extend such examples to consider integer and float versions of the operators; for example, int* for integer operands and float* for floats.
6 We shall use the term “synthesis” even if some context information is used to determine types. With overloaded functions, where the same name is given to more than one function, the cont i of may also need to be considered in some languages.
Type synthesis will be illustrated by extending the scheme in Section 6.4.2 for translating expressions. We introduce another attribute E.type, whose value is either integer or float. The rule associated with E→E1+E2 builds on the pseudocode
if(E1.type=integer and E2.type=integer) E.type=integer; else if( E1.type=float and E2.type=integer ) …
As the number of types subject to conversion increases, the number of cases increases rapidly. Therefore, with large numbers of types, careful organization of the semantic actions becomes important.
Type conversion rules vary from language to language. The rules for Java in Fig. 6.25 distinguish between widening conversions, which are intended to preserve information, and narrowing conversions, which can lose information. The widening rules are given by the hierarchy in Fig. 6.25(a): any type lower in the hierarchy can be widened to a higher type. Thus, a char can be widened to an int or to a float, but a char cannot be widened to a short. The narrowing rules are illustrated by the graph in Fig. 6.25(b): a type s can be narrowed to a type t if there is a path from s to t. Note that char, short, and byte are pairwise convertible to each other.
(a) Widening conversions (b) Narrowing conversions
Figure 6.25 Conversions between primitive types in Java
Conversion from one type to another is said to be implicit if it is done automatically by the compiler. Implicit type conversions, also called coercions, are limited in many languages to widening conversions. Conversion is said to be explicit if the programmer must write something to cause the conversion. Explicit conversions are also called casts.
The semantic action for checking E→E1+E2 uses two functions:
-
max(t1,t2) takes two types t1 and t2 and returns the maximum (or least upper bound) of the two types in the widening hierarchy. It declares an error if either t1 or t2 is not in the hierarchy; e.g., if either type is an array or a pointer type.
-
widen(a,t,w) generates type conversions if needed to widen the contents of an address a of type t into a value of type w. It returns a itself if t and w are the same type. Otherwise, it generates an instruction to do the conversion and place the result in a temporary, which is returned as the result. Pseudocode for widen, assuming that the only types are integer and float, appears in Fig. 6.26.
Addr widen(Addr a, Type t, Type w) if(t=w) return a; else if(t=integer and w=float){ temp= new Temp(); gen(temp’=”(float)‘a); return temp; } else error; }
Figure 6.26 Pseudocode for function widen
The semantic action for E→E1+E2 in Fig. 6.27 illustrates how type conversions can be added to the scheme in Fig. 6.20 for translating expressions. In the semantic action, temporary variable a1 is either E1.addr, if the type of E1 does not need to be converted to the type of E, or a new temporary variable returned by widen if this conversion is necessary. Similarly, a2 is either E2.addr or a new temporary holding the type-converted value of E2. Neither conversion is needed if both types are integer or both are float. In general, however, we could find that the only way to add values of two different types is to convert them both to a third type.
gen(E.addr\,=\prime\,a_{1}\,^{\prime+^{\prime}}a_{2});\,}Figure 6.27 Introducing type conversions into expression evaluation
6.5.3 Overloading of Functions and Operators
Section titled “6.5.3 Overloading of Functions and Operators”An overloaded symbol has different meanings depending on its context. Overloading is resolved when a unique meaning is determined for each occurrence of a name. In this section, we restrict attention to overloading that can be resolved by looking only at the arguments of a function, as in Java.
Example 6.13 The+ operator in Java denotes either string concatenation or addition, depending on the types of its operands. User-defined functions can be overloaded as well, as in void err() {…} void err(String s) {…} Note that we can choose between these two versions of a function err by looking at their arguments.
The following is a type-synthesis rule for overloaded functions: if f can have type , for , where for and x has type , for some (6.10) then expression f(x) has type .
The value-number method of Section 6.1.2 can be applied to type expressions to resolve overloading based on argument types, efficiently. In a DAG representing a type expression, we assign an integer index, called a value number, to each node. Using Algorithm 6.3, we construct a signature for a node, consisting of its label and the value numbers of its children, in order from left to right. The signature for a function consists of the function name and the types of its arguments. The assumption that we can resolve overloading based on the types of arguments is equivalent to saying that we can resolve overloading based on signatures.
It is not always possible to resolve overloading by looking only at the arguments of a function. In Ada, instead of a single type, a subexpression standing alone may have a set of possible types for which the context must provide sufficient information to narrow the choice down to a single type(see Exercise 6.5.2).
6.5.4 Type Inference and Polymorphic Functions
Section titled “6.5.4 Type Inference and Polymorphic Functions”Type inference is useful for a language like ML, which is strongly typed, but does not require names to be declared before they are used. Type inference ensures that names are used consistently.
The term “polymorphic” refers to any code fragment that can be executed with arguments of different types. In this section, we consider parametric polymorphism, where the polymorphism is characterized by parameters or type variables. The running example is the ML program in Fig. 6.28, which defines a function length. The type of length can be described as,“for any type a, length maps a list of elements of type a to an integer.” fun length(x)=
if null(x) then 0 else length(il(x))+1;
Figure 6.28 ML program for the length of a list
Example 6.14
Section titled “Example 6.14”In Fig. 6.28, the keyword fun introduces a function definition; functions can be recursive. The program fragment defines function length with one parameter x. The body of the function consists of a conditional expression. The predefined function null tests whether a list is empty, and the predefined function tl(short for “tail”) returns the remainder of a list after the first element is removed.
The function length determines the length or number of elements of a list x. All elements of a list must have the same type, but length can be applied to lists whose elements are of any one type. In the following expression, length is applied to two different types of lists(list elements are enclosed within “[” and “]”):
The list of strings has length 3 and the list of integers has length 4,so expression (6.11)evaluates to 7.
Using the symbol (read as “for any type”) and the type constructor list, the type of length can be written as
The symbol is the universal quantifier, and the type variable to which it is applied is said to be bound by it. Bound variables can be renamed at will, provided all occurrences of the variable are renamed. Thus, the type expression
is equivalent to (6.12). A type expression with a symbol in it will be referred to informally as a “polymorphic type.”
Each time a polymorphic function is applied, its bound type variables can denote a different type. During type checking, at each use of a polymorphic type we replace the bound variables by fresh variables and remove the universal quantifiers.
The next example informally infers a type for length, implicitly using type inference rules like (6.9), which is repeated here:
then for some and has type and x has type
Example 6.15 The abstract syntax tree in Fig. 6.29 represents the definition of length in Fig. 6.28. The root of the tree, labeled fun, represents the function definition. The remaining nonleaf nodes can be viewed as function applications. The node labeled+ represents the application of the operator+ to a pair of children. Similarly, the node labeled if represents the application of an operator if to a triple formed by its children(for type checking, it does not matter that either the then or the else part will be evaluated, but not both).
Figure 6.29 Abstract syntax tree for the function definition in Fig. 6.28 From the body of function length, we can infer its type. Consider the children of the node labeled if, from left to right. Since null expects to be applied to lists, x must be a list. Let us use variable a as a placeholder for the type of the list elements; that is, x has type “list of a.” If null(x) is true, then length(x) is 0. Thus, the type of length must be “function from list of a to integer.” This inferred type is consistent with the usage of length in the else part, length(tl(x))+1.
Since variables can appear in type expressions, we have to re-examine the notion of equivalence of types. Suppose of type is applied to of type t. Instead of simply determining the equality of s and t, we must “unify” them. Informally, we determine whether s and t can be made structurally equivalent by replacing the type variables in s and t by type expressions. A substitution is a mapping from type variables to type expressions. We write S(t) for the result of applying the substitution S to the variables in type expression t; see the box on “Substitutions, Instances, and Unification.” Two type expressions and unify if there exists some substitution S such that . In practice, we are interested in the most general unifier, which is a substitution that imposes the fewest constraints on the variables in the expressions. See Section 6.5.5 for a unification algorithm.
Substitutions, Instances, and Unification
Section titled “Substitutions, Instances, and Unification”If t is a type expression and S is a substitution (a mapping from type variables to type expressions), then we write S(t) for the result of consistently replacing all occurrences of each type variable α in t by S(α). S(t) is called an instance of t. For example, list(integer) is an instance of list(α), since it is the result of substituting integer for α in list(α).Note, however, that integer → float is not an instance of α → α, since a substitution must replace all occurrences of α by the same type expression.
Substitution S is a unifier of type expressions t₁ and t₂ if S(t₁) = S(t₂). S is the most general unifier of t₁ and t₂ if for any other unifier of t₁ and t₂, say S’, it is the case that for any t, S’(t) is an instance of S(t). In words, S’ imposes more constraints on t than S does.
Algorithm 6.16
Section titled “Algorithm 6.16”Type inference for polymorphic functions.
INPUT: A program consisting of a sequence of function definitions followed by an expression to be evaluated. An expression is made up of function applications and names, where names can have predefined polymorphic types.
OUTPUT: Inferred types for the names in the program.
METHOD: For simplicity, we shall deal with unary functions only. The type of a function f(x₁, x₂) with two parameters can be represented by a type expression s₁ × s₂ → t, where s₁ and s₂ are the types of x₁ and x₂, respectively, and t is the type of the result f(x₁, x₂). An expression f(a, b) can be checked by matching the type of a with s₁ and the type of b with s₂.
Check the function definitions and the expression in the input sequence. Use the inferred type of a function if it is subsequently used in an expression.
-
For a function definition fun id₁ (id₂) = E, create fresh type variables α and β. Associate the type α → β with the function id₁, and the type α with the parameter id₂. Then, infer a type for expression E. Suppose α denotes type s and β denotes type t after type inference for E. The inferred type of function id₁ is s → t. Bind any type variables that remain unconstrained in s → t by ∀ quantifiers.
-
For a function application E₁(E₂), infer types for E₁ and E₂. Since E₁ is used as a function, its type must have the form s → s’. (Technically, the type of E₁ must unify with β → γ, where β and γ are new type variables). Let t be the inferred type of E₂. Unify s and t. If unification fails, the expression has a type error. Otherwise, the inferred type of E₁(E₂) is s’.
For each occurrence of a polymorphic function, replace the bound variables in its type by distinct fresh variables and remove the V quantifiers. The resulting type expression is the inferred type of this occurrence.
For a name that is encountered for the first time, introduce a fresh variable for its type.
Example 6.17
Section titled “Example 6.17”In Fig. 6.30, we infer a type for function length. The root of the syntax tree in Fig. 6.29 is for a function definition, so we introduce variablesβ and y, associate the typeβ→γ with function length, and the typeβ with x; see lines 1-2 of Fig. 6.30.
| LINE | EXPRESSION:TYPE | UNIFY |
|---|---|---|
| 1) | length:β→γ | |
| 2) | x:β | |
| 3) | if:booleanxαi xαi→αi | |
| 4) | null:list(αn)→boolean | |
| 5) | null(x):boolean | list(αn)=β |
| 6) | 0:integer | αi=integer |
| 7) | +:integer integer→integer | |
| 8) | tl:list(αl)→list(αl) | |
| 9) | tl(x):list(αl) | list(αl)=list(αn) |
| 10) | length(tl(x)):y | y=integer |
| 11) | 1:integer | |
| 12) | length(tl(x))+1:integer | |
| 13) | if(…):integer |
Figure 6.30 Inferring a type for the function length of Fig. 6.28
At the right child of the root, we view if as a polymorphic function that is applied to a triple, consisting of a boolean and two expressions that represent the then and else parts. Its type is
Each application of a polymorphic function can be to a different type, so we make up a fresh variable ,(where i is from “if”) and remove the ; see line 3 of Fig. 6.30.The type of the left child of if must unify with boolean, and the types of its other two children must unify with
The predefined function null has type We use a fresh type variable (where n is for “null”) in place of the bound variable ; see line 4. From the application of null to x, we infer that the typeβ of x must match list(αn); see line 5.
At the first child of if, the type boolean for null(x) matches the type expected by if. At the second child, the type , unifies with integer; see line 6.
Now, consider the subexpression length(ll(x))+1. We make up a fresh variable (where t is for “tail”) for the bound variable a in the type of ll; see line 8. From the application ll(x), we infer list(a)=β=list(a); see line 9.
Since length(ll(x)) is an operand of+, its type y must unify with integer; see line 10.It follows that the type of length is list(a)→integer. After the function definition is checked, the type variable a remains in the type of length. Since no assumptions were made about a, any type can be substituted for it when the function is used. We therefore make it a bound variable and write
for the type of length.
6.5.5 An Algorithm for Unification
Section titled “6.5.5 An Algorithm for Unification”Informally, unification is the problem of determining whether two expressions s and t can be made identical by substituting expressions for the variables in s and t. Testing equality of expressions is a special case of unification; if s and t have constants but no variables, then s and t unify if and only if they are identical. The unification algorithm in this section extends to graphs with cycles, so it can be used to test structural equivalence of circular types.7
We shall implement a graph-theoretic formulation of unification, where types are rep-represented by graphs. Type variables are represented by leaves and type constructors are represented by interior nodes. Nodes are grouped into equivalence classes; if two nodes are in the same equivalence class, then the type expressions they represent must unify. Thus, all interior nodes in the same class must be for the same type constructor, and their corresponding children must be equivalent.
Example 6.18
Consider the two type expressions
In some applications, it is an error to unify a variable with an expression contain Algorithm 6.19 permits such substitutions.
The following substitution S is the most general unifier for these expressions
| x | S(x) |
|---|---|
| α₁ | α₁ |
| α₂ | α₂ |
| α₃ | α₁ |
| α₄ | α₂ |
| α₅ | list(α₂) |
This substitution maps the two type expressions to the following expression ((α₁→α₂)x list(α₁))→list(α₂)
The two expressions are represented by the two nodes labeled→:1 in Fig. 6.31. The integers at the nodes indicate the equivalence classes that the nodes belong to after the nodes numbered 1 are unified.
Figure 6.31 Equivalence classes after unification
Algorithm 6.19
Section titled “Algorithm 6.19”Unification of a pair of nodes in a type graph.
INPUT: A graph representing a type and a pair of nodes m and n to be unified.
OUTPUT: Boolean value true if the expressions represented by the nodes m and n unify; false, otherwise.
METHOD: A node is implemented by a record with fields for a binary operator and pointers to the left and right children. The sets of equivalent nodes are maintained using the set field. One node in each equivalence class is chosen to be the unique representative of the equivalence class by making its set field contain a null pointer. The set fields of the remaining nodes in the equivalence class will point(possibly indirectly through other nodes in the set) to the representative. Initially, each node n is in an equivalence class by itself, with n as its own representative node.
The unification algorithm, shown in Fig. 6.32, uses the following two operations on nodes:
boolean unify(Node m, Node n) { s = find(m); t = find(n); if (s = t) return true; else if (nodes s and t represent the same basic type) return true; else if (s is an op-node with children s1 and s2 and t is an op-node with children t1 and t2) { union(s, t); return unify(s1, t1) and unify(s2, t2); } else if (s or t represents a variable) { union(s, t); return true; } else return false; }
Figure 6.32 Unification algorithm.
find(n)returns the representative node of the equivalence class currently containing node n.union(m, n)merges the equivalence classes containing nodes m and n. If one of the representatives for the equivalence classes of m and n is a non-variable node,unionmakes that non-variable node be the representative for the merged equivalence class; otherwise,unionmakes one or the other of the original representatives be the new representative. This asymmetry in the specification ofunionis important because a variable cannot be used as the representative for an equivalence class for an expression containing a type constructor or basic type. Otherwise, two inequivalent expressions may be unified through that variable.
The union operation on sets is implemented by simply changing the set field of the representative of one equivalence class so that it points to the representative of the other. To find the equivalence class that a node belongs to, we follow the set pointers of nodes until the representative (the node with a null pointer in the set field) is reached.
Note that the algorithm in Fig. 6.32 uses s = find(m) and t = find(n) rather than m and n, respectively. The representative nodes s and t are equal if m and n are in
equivalence class. If s and t represent the same basic type, the call unify(m, n) returns true. If s and t are both interior nodes for a binary type constructor, we merge their equivalence classes on speculation and recursively check that their respective children are equivalent. By merging first, we decrease the number of equivalence classes before recursively checking the children, so the algorithm terminates.
The substitution of an expression for a variable is implemented by adding the leaf for the variable to the equivalence class containing the node for that expression. Suppose either m or n is a leaf for a variable. Suppose also that this leaf has been put into an equivalence class with a node representing an expression with a type constructor or a basic type. Then find will return a representative that reflects that type constructor or basic type, so that a variable cannot be unified with two different expressions.
Example 6.20 Suppose that the two expressions in Example 6.18 are represented by the initial graph in Fig. 6.33, where each node is in its own equivalence class. When Algorithm 6.19 is applied to compute unify (1, 9), it notes that nodes 1 and 9 both represent the same operator. It therefore merges 1 and 9 into the same equivalence class and calls unify (2, 10) and unify (8, 14). The result of computing unify (1, 9) is the graph previously shown in Fig. 6.31.
Figure 6.33 Initial graph with each node in its own equivalence class
If Algorithm 6.19 returns true, we can construct a substitution S that acts as the unifier, as follows. For each variable α, find(α) gives the node n that is the representative of the equivalence class of α. The expression represented by n is S(α). For example, in Fig. 6.31, we see that the representative for α₃ is node 4, which represents α₁. The representative for α₅ is node 8, which represents list(α₂). The resulting substitution S is as in Example 6.18.
Exercises for Section 6.5
Section titled “Exercises for Section 6.5”Exercise 6.5.1: Assuming that function widen in Fig. 6.26 can handle any of the types in the hierarchy of Fig. 6.25(a), translate the expressions below. Assume that c and d are characters, s and t are short integers, i and j are integers, and x is a float.
(a) x = s + c. (b) i = s + c. (c) x = (s + c) * (t + d).
Exercise 6.5.2: As in Ada, suppose that each expression must have a unique type, but that from a subexpression, by itself, all we can deduce is a set of possible types. That is, the application of function E₁ to argument E₂, represented by E→E₁(E₂), has the associated rule
E.type = {t| for some s in E₂.type, s→t is in E₁.type}
Describe an SDD that determines a unique type for each subexpression by using an attribute type to synthesize a set of possible types bottom-up, and, once the unique type of the overall expression is determined, proceeds top-down to determine attribute unique for the type of each subexpression.
6.6 Control Flow
Section titled “6.6 Control Flow”The translation of statements such as if-else-statements and while-statements is tied to the translation of boolean expressions. In programming languages, boolean expressions are often used to
-
Alter the flow of control. Boolean expressions are used as conditional expressions in statements that alter the flow of control. The value of such boolean expressions is implicit in a position reached in a program. For example, in if(E) S, the expression E must be true if statement S is reached.
-
Compute logical values. A boolean expression can represent true or false as values. Such boolean expressions can be evaluated in analogy to arithmetic expressions using three-address instructions with logical operators.
The intended use of boolean expressions is determined by its syntactic context. For example, an expression following the keyword if is used to alter the flow of control, while an expression on the right side of an assignment is used to denote a logical value. Such syntactic contexts can be specified in a number of ways: we may use two different nonterminals, use inherited attributes, or set a flag during parsing. Alternatively we may build a syntax tree and invoke different procedures for the two different uses of boolean expressions.
This section concentrates on the use of boolean expressions to alter the flow of control For clarity, we introduce a new nonterminal B for this purpose. In Section sider how a compiler can allow boolean expressions to represent logical
6.6.1 Boolean Expressions
Section titled “6.6.1 Boolean Expressions”Boolean expressions are composed of the boolean operators(which we denote&&,||,and!,using the C convention for the operators AND,OR,and NOT,respectively) applied to elements that are boolean variables or relational expressions. Relational expressions are of the form E1 rel E2, where E1 and E2 are arithmetic expressions. In this section, we consider boolean expressions generated by the following grammar:
We use the attribute rel.op to indicate which of the six comparison operators<,<=,=,!=,>,or>=is represented by rel. As is customary, we assume that|| and&& are left-associative, and that|| has lowest precedence, then&&,then!.
Given the expression , if we determine that is true, then we can conclude that the entire expression is true without having to evaluate Similarly, given , if is false, then the entire expression is false.
The semantic definition of the programming language determines whether all parts of a boolean expression must be evaluated. If the language definition permits(or requires)portions of a boolean expression to go unevaluated, then the compiler can optimize the evaluation of boolean expressions by computing only enough of an expression to determine its value. Thus, in an expression such as ,neither nor is necessarily evaluated fully. If either or is an expression with side effects(e.g., it contains a function that changes a global variable), then an unexpected answer may be obtained.
6.6.2 Short-Circuit Code
Section titled “6.6.2 Short-Circuit Code”In short-circuit(or jumping) code, the boolean operators&&,||, and! translate into jumps. The operators themselves do not appear in the code; instead, the value of a boolean expression is represented by a position in the code sequence.
Example 6.21
The statement
might be translated into the code of Fig. 6.34.In this translation, the boolean expression is true if control reaches label L2. If the expression is false, control goes immediately to , skipping and the assignment .
Figure 6.34 Jumping code
6.6.3 Flow-of-Control Statements
Section titled “6.6.3 Flow-of-Control Statements”We now consider the translation of boolean expressions into three-address code in the context of statements such as those generated by the following grammar:
S → if(B) S₁ S → if(B) S₁ else S₂ S → while(B) S₁
In these productions, nonterminal B represents a boolean expression and nonterminal S represents a statement.
This grammar generalizes the running example of while expressions that we introduced in Example 5.19. As in that example, both B and S have a synthesized attribute code, which gives the translation into three-address instructions. For simplicity, we build up the translations B.code and S.code as strings, using syntax-directed definitions. The semantic rules defining the code attributes could be implemented instead by building up syntax trees and then emitting code during a tree traversal, or by any of the approaches outlined in Section 5.5.
The translation of if(B) S₁ consists of B.code followed by S₁.code, as illustrated in Fig. 6.35(a). Within B.code are jumps based on the value of B. If B is true, control flows to the first instruction of S₁.code, and if B is false, control flows to the instruction immediately following S₁.code.
Figure 6.35 Code for if-, if-else-, and while-statements
The labels for the jumps in B.code and S.code are managed using inherited attributes. With a boolean expression B, we associate two labels: B.true, the label to which control flows if B is true, and B.false, the label to which control flows if B is false. With a statement S, we associate an inherited attribute S.next denoting a label for the instruction immediately after the code for S. In some cases, the instruction immediately following S.code is a jump to some label L. A jump to a jump to L from within S.code is avoided using S.next.
The syntax-directed definition in Fig. 6.36-6.37 produces three-address code for boolean expressions in the context of if-, if-else-, and while-statements.
| PRODUCTION | SEMANTIC RULES |
|---|---|
| P → S | S.next = newlabel() P.code = S.code |
| S → assign | S.code = assign.code |
| S → if(B) S1 | B.true = newlabel() B.false = S1.next = S.next S.code = B.code |
| S → if(B) S1 else S2 | B.true = newlabel() B.false = newlabel() S1.next = S2.next = S.next S.code = B.code |
| S → while(B) S1 | begin = newlabel() B.true = newlabel() B.false = S.next S1.next = begin S.code = label(begin) |
| S → S1 S2 | S1.next = newlabel() S2.next = S.next S.code = S1.code |
Figure 6.36 Syntax-directed definition for flow-of-control statements.
| PRODUCTION | SEMANTIC RULES |
|---|---|
| B→B1 | |
| B→B1&&B2 | B1.true=newlabel() B1.false=B.false B2.true=B.true B2.false=B.false B.code=B1.code |
| B→!B1 | B1.true=B.false B1.false=B.true B.code=B1.code |
| B→E1 rel E2 | B.code=E1.code |
| B→true | B.code=gen(‘goto’B.true) |
| B→false | B.code=gen(‘goto’B.false) |
Figure 6.37 Generating three-address code for booleans
We assume that newlabel() creates a new label each time it is called, and that label(L)attaches label L to the next three-address instruction to be generated.8
A program consists of a statement generated by P→S. The semantic rules associated with this production initialize S.next to a new label. P.code consists of S.code followed by the new label S.next. Token assign in the production S→assign is a placeholder for assignment statements. The translation of assignments is as discussed in Section 6.4; for this discussion of control flow, S.code is simply assign.code.
In translating S→if(B) S1, the semantic rules in Fig. 6.36 create a new label B.true and attach it to the first three-address instruction generated for the statement S1, as illustrated in Fig. 6.35(a). Thus, jumps to B.true within the code for B will go to the code for
8 If implemented literally, the semantic rules will generate lots of labels and may attach more than one label to a three-address instruction. The backpatching approach of Section 6.7 creates labels when they are needed. Alternatively, unnecessary labels can be eliminated during a subsequent mization phase.
S1. Further, by setting B.false to S.next, we ensure that control will skip the code for S1 if B evaluates to false.
In translating the if-else-statement S→if(B) S1 else S2, the code for the boolean expression B has jumps out of it to the first instruction of the code for S1 if B is true, and to the first instruction of the code for S2 if B is false, as illustrated in Fig. 6.35(b). Further, control flows from both S1 and S2 to the three-address instruction immediately following the code for S- its label is given by the inherited attribute S.next. An explicit goto S.next appears after the code for S1 to skip over the code for S2. No goto is needed after S2, since S2.next is the same as S.next.
The code for S→while(B) S1 is formed from B.code and S1.code as shown in Fig. 6.35(c).We use a local variable begin to hold a new label attached to the first instruction for this while-statement, which is also the first instruction for B. We use a variable rather than an attribute, because begin is local to the semantic rules for this production. The inherited label S.next marks the instruction that control must flow to if B is false; hence, B.false is set to be S.next. A new label B.true is attached to the first instruction for S1; the code for B generates a jump to this label if B is true. After the code for S1 we place the instruction goto begin, which causes a jump back to the beginning of the code for the boolean expression. Note that S1.next is set to this label begin, so jumps from within S1.code can go directly to begin.
The code for S→S1 S2 consists of the code for S1 followed by the code for S2. The semantic rules manage the labels; the first instruction after the code for S1 is the beginning of the code for S2; and the instruction after the code for S2 is also the instruction after the code for S.
We discuss the translation of flow-of-control statements further in Section 6.7.There we shall see an alternative method, called “backpatching,” which emits code for statements in one pass.
6.6.4 Control-Flow Translation of Boolean Expressions
Section titled “6.6.4 Control-Flow Translation of Boolean Expressions”The semantic rules for boolean expressions in Fig. 6.37 complement the semantic rules for statements in Fig. 6.36. As in the code layout of Fig. 6.35, a boolean expression B is translated into three-address instructions that evaluate B using conditional and unconditional jumps to one of two labels: B.true if B is true, and B.false if B is false.
The fourth production in Fig. 6.37,B→E1 rel E2,is translated directly into a comparison three-address instruction with jumps to the appropriate places. For instance, B of the form a<b translates into:
The remaining productions for B are translated as follows:
-
Suppose B is of the form B1||B2. If B1 is true, then we immediately know that B itself is true, so B1.true is the same as B.true. If B1 is false, then B2 must be evaluated, so we make B1.false be the label of the first instruction in the code for B2. The true and false exits of B2 are the same as the true and false exits of B, respectively.
-
The translation of B1 && B2 is similar.
-
No code is needed for an expression B of the form!B1: just interchange the true and false exits of B to get the true and false exits of B1.
-
The constants true and false translate into jumps to B.true and B.false, respectively.
Example 6.22 Consider again the following statement from Example 6.21: if (x < 100 || x > 200 && x != y) x = 0; (6.13) Using the syntax-directed definitions in Figs. 6.36 and 6.37 we would obtain the code in Fig. 6.38. Figure 6.38 Control-flow translation of a simple if-statement The statement (6.13) constitutes a program generated by P→S from Fig. 6.36. The semantic rules for the production generate a new label L1 for the instruction after the code for S. Statement S has the form if(B) S1, where S1 is x = 0;, so the rules in Fig. 6.36 generate a new label L2 and attach it to the first (and only, in this case) instruction in S1.code, which is x = 0. Since || has lower precedence than &&, the boolean expression in (6.13) has the form B1 || B2, where B1 is x < 100. Following the rules in Fig. 6.37, B1.true is L2, the label of the assignment x = 0;. B1.false is a new label L3, attached to the first instruction in the code for B2. Note that the code generated is not optimal, in that the translation has three more instructions (goto’s) than the code in Example 6.21. The instruction goto L3 is redundant, since L3 is the label of the very next instruction. The two goto L1 instructions can be eliminated by using ifFalse instead of if instructions, as in Example 6.21.
6.6.5 Avoiding Redundant Gotos
Section titled “6.6.5 Avoiding Redundant Gotos”In Example 6.22, the comparison x>200 translates into the code fragment:
L4:…
Instead, consider the instruction:
L4:…
This ifFalse instruction takes advantage of the natural flow from one instruction to the next in sequence, so control simply “falls through” to label L4 if x>200, thereby avoiding a jump.
In the code layouts for if-and while-statements in Fig. 6.35, the code for statement S1 immediately follows the code for the boolean expression B. By using a special label fall(i.e.,“don’t generate any jump”), we can adapt the semantic rules in Fig. 6.36 and 6.37 to allow control to fall through from the code for B to the code for S1. The new rules for S→if(B) S1 in Fig. 6.36 set B.true to fall:
Similarly, the rules for if-else-and while-statements also set B.true to fall.
We now adapt the semantic rules for boolean expressions to allow control to fall through whenever possible. The new rules for B→E1 rel E2 in Fig. 6.39 generate two instructions, as in Fig. 6.37, if both B.true and B.false are explicit labels; that is, neither equals fall. Otherwise, if B.true is an explicit label, then B.false must be fall, so they generate an if instruction that lets control fall through if the condition is false. Conversely, if B.false is an explicit label, then they generate an ifFalse instruction. In the remaining case, both B.true and B.false are fall, so no jump in generated.9
In the new rules for B→B1||B2 in Fig. 6.40, note that the meaning of label fall for B is different from its meaning for B1. Suppose B.true is fall; i.e, control falls through B, if B evaluates to true. Although B evaluates to true if B1 does,B1.true must ensure that control jumps over the code for B2 to get to the next instruction after B.
On the other hand, if B1 evaluates to false, the truth-value of B is determined by the value of B2, so the rules in Fig. 6.40 ensure that B1.false corresponds to control falling through from B1 to the code for B2.
9 In C and Java, expressions may contain assignments within them, so code must be generated for the subexpressions and , even if both B.true and B.false are fall. If desired, dead code can be eliminated during an optimization phase. test = E1.addr rel.op E2.addr
s = if B.true ≠ fall and B.false ≠ fall then gen(‘if’ test ‘goto’ B.true) || gen(‘goto’ B.false) else if B.true ≠ fall then gen(‘if’ test ‘goto’ B.true) else if B.false ≠ fall then gen(‘ifFalse’ test ‘goto’ B.false) else”
B.code = E1.code || E2.code || s
Figure 6.39 Semantic rules for B→E1 rel E2
B1.true = if B.true ≠ fall then B.true else newlabel() B1.false = fall B2.true = B.true B2.false = B.false B.code = if B.true ≠ fall then B1.code || B2.code else B1.code || B2.code || label(B1.true)
Figure 6.40 Semantic rules for B→B1|| B2
The semantic rules for B→B1 && B2 are similar to those in Fig. 6.40. We leave them as an exercise.
Example 6.23 With the new rules using the special label fall, the program (6.13) from Example 6.21 if ( x < 100 || x > 200 && x != y ) x = 0; translates into the code of Fig. 6.41. if x < 100 goto L2 ifFalse x > 200 goto L1 ifFalse x != y goto L1 L2: x = 0 L1:
Figure 6.41 If-statement translated using the fall-through technique
As in Example 6.22, the rules for P→S create label L1. The difference from Example 6.22 is that the inherited attribute B.true is fall when the semantic rules for B→B1|| B2 are applied (B.false is L1). The rules in Fig. 6.40 create a new label L2 to allow a jump over the code for B2 if B1 evaluates to true. Thus, B1.true is L2 and B1.false is fall, since B2 must be evaluated if B1 is false.
The production B→E₁ rel E₂ that generates x < 100 is therefore reached with B.true = L₂ and B.false = fall. With these inherited labels, the rules in Fig. 6.39 therefore generate a single instruction if x < 100 goto L₂.
6.6.6 Boolean Values and Jumping Code
Section titled “6.6.6 Boolean Values and Jumping Code”The focus in this section has been on the use of boolean expressions to alter the flow of control in statements. A boolean expression may also be evaluated for its value, as in assignment statements such as x = true; or x = a < b;.
A clean way of handling both roles of boolean expressions is to first build a syntax tree for expressions, using either of the following approaches:
-
Use two passes. Construct a complete syntax tree for the input, and then walk the tree in depth-first order, computing the translations specified by the semantic rules.
-
Use one pass for statements, but two passes for expressions. With this approach, we would translate E in while(E) S₁ before S₁ is examined. The translation of E, however, would be done by building its syntax tree and then walking the tree.
The following grammar has a single nonterminal E for expressions:
S→id=E;|if(E)S|while(E)S|S S
E→E||E|E&&E|ErelE|E+E|(E)|id|true|false
Nonterminal E governs the flow of control in S→while(E) S₁. The same nonterminal E denotes a value in S→id=E;and E→E+E.
We can handle these two roles of expressions by using separate code-generation functions. Suppose that attribute En denotes the syntax-tree node for an expression E and that nodes are objects. Let method jump generate jumping code at an expression node, and let method rvalue generate code to compute the value of the node into a temporary.
When E appears in S→while(E) S₁, method jump is called at node En. The implementation of jump is based on the rules for boolean expressions in Fig. 6.37. Specifically, jumping code is generated by calling En.jump(t,f), where t is a new label for the first instruction of S₁.code and f is the label S.next.
When E appears in S→id=E;, method rvalue is called at node En. If E has the form , the method call En.rvalue() generates code as discussed in Section 6.4. If E has the form E1&& E2,we first generate jumping code for E and then assign true or false to a new temporary t at the true and false exits, respectively, from the jumping code.
For example, the assignment x= a< b&& c< d can be implemented by the code in Fig. 6.42. ifFalse a < b goto L1 ifFalse c < d goto L1 t = true goto L2 L1: t = false L2: x = t
Figure 6.42 Translating a boolean assignment by computing the value of a temporary
Exercises for Section 6.6
Section titled “Exercises for Section 6.6”Exercise 6.6.1: Add rules to the syntax-directed definition of Fig. 6.36 for the following control-flow constructs: (a) A repeat-statement repeat S while B. !(b) A for-loop for (S1; B; S2) S3.
Exercise 6.6.2: Modern machines try to execute many instructions at the same time, including branching instructions. Thus, there is a severe cost if the machine speculatively follows one branch, when control actually goes another way (all the speculative work is thrown away). It is therefore desirable to minimize the number of branches. Notice that the implementation of a while-loop in Fig. 6.35(c) has two branches per interation: one to enter the body from the condition B and the other to jump back to the code for B. As a result, it is usually preferable to implement while (B) S as if it were if (B) { repeat S until !(B) }. Show what the code layout looks like for this translation, and revise the rule for while-loops in Fig. 6.36.
Exercise 6.6.3: Suppose that there were an “exclusive-or” operator (true if and only if exactly one of its two arguments is true) in C. Write the rule for this operator in the style of Fig. 6.37.
Exercise 6.6.4: Translate the following expressions using the goto-avoiding translation scheme of Section 6.6.5: (a) if (a==b && c==d || e==f) x == 1; (b) if (a==b || c==d || e==f) x == 1; (c) if (a==b && c==d && e==f) x == 1;
Exercise 6.6.5: Give a translation scheme based on the syntax-directed definition in Figs. 6.36 and 6.37.
Exercise 6.6.6: Adapt the semantic rules in Figs. 6.36 and 6.37 to allow control to fall through, using rules like the ones in Figs. 6.39 and 6.40.
!Exercise 6.6.7: The semantic rules for statements in Exercise 6.6.6 generate unnecessary labels. Modify the rules for statements in Fig. 6.36 to create labels as needed, using a special label deferred to mean that a label has not yet been created. Your rules must generate code similar to that in Example 6.21.
!!Exercise 6.6.8: Section 6.6.5 talks about using fall-through code to minimize the number of jumps in the generated intermediate code. However, it does not take advantage of the option to replace a condition by its complement,e.g.,replace if a<b goto L1; goto L2 by if a>= b goto L2; goto L1. Develop a SDD that does take advantage of this option when needed.
6.7 Backpatching
Section titled “6.7 Backpatching”A key problem when generating code for boolean expressions and flow-of-control statements is that of matching a jump instruction with the target of the jump. For example, the translation of the boolean expression B in if(B) S contains a jump, for when B is false, to the instruction following the code for S. In a one-pass translation, B must be translated before S is examined. What then is the target of the goto that jumps over the code for S?In Section 6.6 we addressed this problem by passing labels as inherited attributes to where the relevant jump instructions were generated. But a separate pass is then needed to bind labels to addresses.
This section takes a complementary approach, called backpatching, in which lists of jumps are passed as synthesized attributes. Specifically, when a jump is generated, the target of the jump is temporarily left unspecified. Each such jump is put on a list of jumps whose labels are to be filled in when the proper label can be determined. All of the jumps on a list have the same target label.
6.7.1 One-Pass Code Generation Using Backpatching
Section titled “6.7.1 One-Pass Code Generation Using Backpatching”Backpatching can be used to generate code for boolean expressions and flow-of-control statements in one pass. The translations we generate will be of the same form as those in Section 6.6, except for how we manage labels.
In this section, synthesized attributes truelist and falselist of nonterminal B are used to manage labels in jumping code for boolean expressions. In particular, B. truelist will be a list of jump or conditional jump instructions into which we must insert the label to which control goes if B is true. B.falselist likewise is the list of instructions that eventually get the label to which control goes when B is false. As code is generated for B, jumps to the true and false exits are left incomplete, with the label field unfilled. These incomplete jumps are placed on lists pointed to by B.truelist and B.falselist, as appropriate. Similarly, a statement S has a synthesized attribute S.nextlist, denoting a list of jumps to the instruction immediately following the code for S.
For specificity, we generate instructions into an instruction array, and labels will be indices into this array. To manipulate lists of jumps, we use three functions:
-
makelist(i) creates a new list containing only i, an index into the array of instructions; makelist returns a pointer to the newly created list.
-
merge(p1,p2) concatenates the lists pointed to by p1 and p2, and returns a pointer to the concatenated list.
-
backpatch(p,i) inserts i as the target label for each of the instructions on the list pointed to by p.
6.7.2 Backpatching for Boolean Expressions
Section titled “6.7.2 Backpatching for Boolean Expressions”We now construct a translation scheme suitable for generating code for boolean expressions during bottom-up parsing. A marker nonterminal M in the grammar causes a semantic action to pick up, at appropriate times, the index of the next instruction to be generated. The grammar is as follows:
B\rightarrow B_{1}||MB_{2}|B_{1}\,&&MB_{2}\,|\,!\,B_{1}\,|\,(B_{1})\,|\,E_{1}\,rel\,E_{2}\,|\,true\,|\,falseM→\epsilon
The translation scheme is in Fig. 6.43.
- B→B1||MB2{ backpatch(B1.falselist,M.instr);B.truelist=merge(B1.truelist,B2.truelist);B.falselist=B2.falselist;}2) B→B1&&MB2{ backpatch(B1.truelist,M.instr);B.truelist=B2.truelist;B.falselist=merge(B1.falselist,B2.falselist);}3)B→!B1{B1.truelist=B1.falselist;B.falselist=B1.truelist;}4)B→(B1){B.truelist=B1.truelist;B.falselist=B1.falselist;}5)B→E1 rel E2{B.truelist=makelist(nextinstr);B.falselist=makelist(nextinstr+1);gen(‘if’E1.addr rel.op E2.addr’goto-’);gen(‘goto-’);}6)B→true{B.truelist=makelist(nextinstr);gen(‘goto-’);}7)B→false{B.falselist=makelist(nextinstr);gen(‘goto-’);}8) M→\epsilon{M.instr=nextinstr;}
Consider semantic action (1) for the production . If is true, then is also true, so the jumps on . truelist become part of B.truelist. If is false, however, we must next test , so the target for the jumps . falselist must be the beginning of the code generated for . This target is obtained using the marker nonterminal . That nonterminal produces, as a synthesized attribute . instr, the index of the next instruction, just before code starts being generated.
To obtain that instruction index, we associate with the production the semantic action { M.instr = nextinstr; }
The variable nextinstr holds the index of the next instruction to follow. This value will be backpatched onto the . falselist (i.e., each instruction on the list . falselist will receive M.instr as its target label) when we have seen the remainder of the production .
Semantic action (2) for && is similar to (1). Action (3) for ! B swaps the true and false lists. Action (4) ignores parentheses.
For simplicity, semantic action (5) generates two instructions, a conditional goto and an unconditional one. Neither has its target filled in. These instructions are put on new lists, pointed to by B.truelist and B.falselist, respectively.
Figure 6.44 Annotated parse tree for x < 100 || x > 200 && x != y
Example 6.24 Consider again the expression x < 100 || x > 200 && x != y An annotated parse tree is shown in Fig. 6.44; for readability, attributes truelist, falselist, and instr are represented by their initial letters. The actions are performed during a depth-first traversal of the tree. Since all actions appear at the ends of right sides, they can be performed in conjunction with reductions during a bottom-up parse. In response to the reduction of x < 100 to B by production (5), the two instructions
100: if x < 100 goto _ 101: goto _
are generated. (We arbitrarily start instruction numbers at 100.) The marker nonterminal M in the production
B → B₁ || M B₂
records the value of nextinstr, which at this time is 102. The reduction of x > 200 to B by production (5) generates the instructions
102: if x < 100 goto _ 103: goto _
The subexpression x > 200 corresponds to B₁ in the production
B → B₁ && M B₂
The marker nonterminal M records the current value of nextinstr, which is now 104. Reducing x != y into B by production (5) generates
104: if x != y goto _ 105: goto _
We now reduce by B → B₁ && M B₂. The corresponding semantic action calls backpatch(B₁.truelist, M.instr) to bind the true exit of B₁ to the first instruction of B₂. Since B₁.truelist is {102} and M.instr is 104, this call to backpatch fills in 104 in instruction 102. The six instructions generated so far are thus as shown in Fig. 6.45(a).
The semantic action associated with the final reduction by B → B₁ || M B₂ calls backpatch({101},102) which leaves the instructions as in Fig. 6.45(b).
The entire expression is true if and only if the gotos of instructions 100 or 104 are reached, and is false if and only if the gotos of instructions 103 or 105 are reached. These instructions will have their targets filled in later in the compilation, when it is seen what must be done depending on the truth or falsehood of the expression.
6.7.3 Flow-of-Control Statements
Section titled “6.7.3 Flow-of-Control Statements”We now use backpatching to translate flow-of-control statements in one pass. Consider statements generated by the following grammar:
S → if (B) S | if (B) S else S | while (B) S | {L} A; L → L S | S 100: if x < 100 goto _ 101: goto _ 102: if x > 200 goto 104 103: goto _ 104: if x != y goto _ 105: goto _
(a) After backpatching 104 into instruction 102 100: if x < 100 goto _ 101: goto 102 102: if x > 200 goto 104 103: goto _ 104: if x != y goto _ 105: goto _
(b) After backpatching 102 into instruction 101
Figure 6.45 Steps in the backpatch process
Here S denotes a statement, I a statement list, A an assignment statement, and B a boolean expression. Note that there must be other productions such as those for assignment statements. The productions given, however, are sufficient to illustrate the techniques used to translate flow-of-control statements.
The code layout for if, if-else, and while statements is the same as in Section 6.6. We make the tacit assumption that the code sequence in the instruction array reflects the natural flow of control from one instruction to the next. If not, then explicit jumps must be inserted to implement the natural sequential flow of control.
The translation scheme in Fig. 6.46 maintains lists of jumps that are filled in when their targets are found. As in Fig. 6.43, boolean expressions generated by nonterminal B have two lists of jumps. B.muelist and B.falselist corresponding to the true and false exits from the code for B, respectively. Statements generated by nonterminals S and / have a list of unfilled jumps given by attribute nexlist that must eventually be completed by backpatching. S.nestlist is a list of all conditional and unconditional jumps to the instruction following the code for statement S in execution order. / is defined similarly.
Consider the semantic action (3) in Fig 6.46. The end layout for production S → while (B) S₁ is as in Fig 6.35(c). The two occurrences of the market nonterminal M in the production
S → while M₁ ( B ) M₁ S
record the instruction numbers of the beginning of the code for B and the beginning of the code for S₁. The corresponding labels in Fig. 6.35(c) are begin and B.mue respectively.
-
S → if(B) M S₁ { backpatch(B.truelist, M.instr); S.nextlist = merge(B.falselist, S₁.nextlist); }
-
S → if(B) M₁ S₁ N else M₂ S₂ { backpatch(B.truelist, M₁.instr); backpatch( B.falselist, M₂.instr); temp = merge(S₁.nextlist, N.nextlist); S.nextlist = merge(temp, S₂.nextlist); }
-
S → while M₁(B) M₂ S₁ { backpatch(S₁.nextlist, M₁.instr); backpatch(B.truelist, M₂.instr); S.nextlist = B.falselist; gen(‘goto’ M₁.instr); }
-
S → { L } { S.nextlist = L.nextlist; }
-
S → L { S.nextlist = null; }
-
M → ε { M.instr = nextmstr; }
-
N → ε { N.nextlist = makelist(nextmstr); gen(‘goto’ ‘0’); }
-
{ L → M S { backpatch(L.nextlist, M.instr); L.nextlist = S.nextlist; }
-
S → { L } { L.nextlist = S.nextlist; }
Figure 6.46 Translation of statements
We backpatch the jumps when B is true to the instruction M1.instr; the latter is the beginning of the code for S1. Similarly, we backpatch jumps when B is false to go to the beginning of the code for S2. The list S.nextlist includes all jumps out of S1 and S2, as well as the jump generated by N. (Variable temp is a temporary that is used only for merging lists.) Semantic actions (8) and (9) handle sequences of statements. In L → L1 M S the instruction following the code for L1 in order of execution is the beginning of S. Thus the L1.nextlist list is backpatched to the beginning of the code for S, which is given by M.instr. In L → S, L.nextlist is the same as S.nextlist. Note that no new instructions are generated anywhere in these semantic rules, except for rules (3) and (7). All other code is generated by the semantic actions associated with assignment-statements and expressions. The flow of control causes the proper backpatch-ing so that the assignments and boolean expression evaluations will connect properly. 6.7.4 Break-, Continue-, and Goto-Statements The most elementary programming language construct for changing the flow of control in a program is the goto-statement. In C, a statement like goto L sends control to the statement labeled L - there must be precisely one statement with label L in this scope. Goto-statements can be implemented by maintaining a list of unfilled jumps for each label and then backpatching the target when it is known. Java does away with goto-statements. However, Java does permit disciplined jumps called break-statements, which send control out of an enclosing construct, and continue-statements, which trigger the next iteration of an enclosing loop. The following excerpt from a lexical analyzer illustrates simple break-and continue-statements:
- for ( ; ; readch() ) {
- if( peek == ’ ’ || peek == ‘\t’ ) continue;
- else if( peek == ‘\n’ ) line = line + 1;
- else break;
- }
Control jumps from the break-statement on line 4 to the next statement after the enclosing for-loop. Control jumps from the continue-statement on line 2 to code to evaluate readch() and then to the if-statement on line 2. If S is the enclosing loop construct, then a break-statement is a jump to the first instruction after the code for S. We can generate code for the break by (1) keeping track of the enclosing loop statement S, (2) generating an unfilled jump for the break-statement, and (3) putting this unfilled jump on S.nextlist, where nextlist is as discussed in Section 6.73. In a two-pass front end that builds syntax trees, S.nextlist can be implemented as a field in the node for S. We can keep track of S by using the symbol table to map a special Identifier break to the node for the enclosing loop statement S. This approach will also handle labeled break-statements in Java, since the symbol table can be used to map the label to the syntax-tree node for the labeled construct.
Alternatively, instead of using the symbol table to access the node for S, we can put a pointer to S.nextlist in the symbol table. Now, when a break-statement is reached, we generate an unfilled jump, look up nextlist through the symbol table, and add the jump to the list, where it will be backpatched as discussed in Section 6.7.3.
Continue-statements can be handled in a manner analogous to the break-statement. The main difference between the two is that the target of the generated jump is different.
Exercises for Section 6.7
Section titled “Exercises for Section 6.7”Exercise 6.7.1: Using the translation of Fig. 6.43, translate each of the following expressions. Show the true and false lists for each subexpression. You may assume the address of the first instruction generated is 100.
(a) a==b && (c==d || e==f) (b) (a==b || c==d) || e==f (c) (a==b && c==d) && e==f
Exercise 6.7.2: In Fig. 6.47(a) is the outline of a program, and Fig. 6.47(b) sketches the structure of the generated three-address code, using the backpatching translation of Fig. 6.46. Here, through are the labels of the generated instructions that begin each of the “Code” sections. When we implement this translation, we maintain, for each boolean expression B, two lists of places in the code for B, which we denote by B.true and B.false. The places on list B.true are those places where we eventually put the label of the statement to which control must flow whenever B is true; B.false similarly lists the places where we put the label that control flows to when B is found to be false. Also, we maintain for
while {i1: Code for E1 if i2: Code for E2 while i3: Code for E3 S1; else {i4: Code for S1 if i5: Code for E4 S2; S3 i6: Code for S2 i7: Code for S3 i8: … } (a) (b)
Figure 6.47 Control-flow structure of program for Exercise 6.7.2 each statement S, a list of places where we must put the label to which control flows when S is finished. Give the value (one of through ) that eventually replaces each place on each of the following lists:
(a) B3.false (b) S2.next (c) B4.false (d) S1.next (e) B2.true
Exercise 6.7.3: When performing the translation of Fig. 6.47 using the scheme of Fig. 6.46. we create lists S.next for each statement, starting with the assignment-statements S1, S2, and S3, and proceeding to progressively larger if-statements, if-else-statements, while-statements, and statement blocks. There are five constructed statements of this type in Fig. 6.47:
S4: while (B3) S1. S5: if (B4) S2. S6: The block consisting of S5 and S3. S7: The statement if (B2) S4 else S6. S8: The entire program.
For each of these constructed statements, there is a rule that allows us to construct S1.next in terms of other S1.next lists, and the lists Bk.true and Bk.false for the expressions in the program. Give the rules for
(a) S4.next (b) S5.next (c) S6.next (d) S7.next (e) S8.next
6.8 Switch-Statements
Section titled “6.8 Switch-Statements”The “switch” or “case” statement is available in a variety of languages. Our switch-statement syntax is shown in Fig. 6.48. There is a selector expression E, which is to be evaluated, followed by n constant values that the expression might take, perhaps including a default “value,” which always matches the expression if no other value does.
switch (E) { case V1: S1 case V2: S2 … case : default: Sn }
6.8.1 Translation of Switch-Statements
Section titled “6.8.1 Translation of Switch-Statements”The intended translation of a switch is code to:
- Evaluate the expression E.
- Find the value in the list of cases that is the same as the value of the expression. Recall that the default value matches the expression if none of the values explicitly mentioned in cases does.
- Execute the statement associated with the value found.
Step (2) is an n-way branch, which can be implemented in one of several ways. If the number of cases is small, say 10 at most, then it is reasonable to use a sequence of conditional jumps, each of which tests for an individual value and transfers to the code for the corresponding statement.
A compact way to implement this sequence of conditional jumps is to create a table of pairs, each pair consisting of a value and a label for the corresponding statement’s code. The value of the expression itself, paired with the label for the default statement is placed at the end of the table at run time. A simple loop generated by the compiler compares the value of the expression with each value in the table, being assured that if no other match is found, the last (default) entry is sure to match.
If the number of values exceeds 10 or so, it is more efficient to construct a hash table for the values, with the labels of the various statements as entries. If no entry for the value possessed by the switch expression is found, a jump to the default statement is generated.
There is a common special case that can be implemented even more efficiently than by an n-way branch. If the values all lie in some small range, say min to max, and the number of different values is a reasonable fraction of max - min, then we can construct an array of max - min “buckets,” where bucket j - min contains the label of the statement with value j; any bucket that would otherwise remain unfilled contains the default label.
To perform the switch, evaluate the expression to obtain the value j; check that it is in the range min to max and transfer indirectly to the table entry at offset j - min. For example, if the expression is of type character, a table of, say, 128 entries (depending on the character set) may be created and transferred through with no range testing.
6.8.2 Syntax-Directed Translation of Switch-Statements
Section titled “6.8.2 Syntax-Directed Translation of Switch-Statements”The intermediate code in Fig. 6.49 is a convenient translation of the switch-statement in Fig. 6.48. The tests all appear at the end so that a simple code generator can recognize the multiway branch and generate efficient code for it, using the most appropriate implementation suggested at the beginning of this section.
code to evaluate E into t goto test L1: code for S1 goto next L2: code for S2 goto next … Ln-1: code for Sn-1 goto next Ln: code for Sn goto next test: if t = V1 goto L1 if t = V2 goto L2 … if t = Vn-1 goto Ln-1 goto Ln next:
Figure 6.49 Translation of a switch-statement
The more straightforward sequence shown in Fig. 6.50 would require the compiler to do extensive analysis to find the most efficient implementation. Note that it is inconvenient in a one-pass compiler to place the branching statements at the beginning, because the compiler could not then emit code for each of the statements Si as it saw them.
code to evaluate E into t if t = V1 goto L1 code for S1 goto next L1: if t != V2 goto L2 code for S2 goto next L2: … Ln-2: if t != Vn-1 goto Ln-1 code for Sn-1 goto next Ln-1: code for Sn next:
Figure 6.50 Another translation of a switch statement
To translate into the form of Fig. 6.49, when we see the keyword switch, we generate two new labels test and next, and a new temporary t. Then, as we parse the expression E, we generate code to evaluate E into t. After processing E, we generate the jump goto test.
Then, as we see each case keyword, we create a new label and enter it into the symbol table. We place in a queue, used only to store cases, a value-label pair consisting of the value of the case constant and ,(or a pointer to the symbol-table entry for ).We process each statement case by emitting the label attached to the code for ,followed by the jump goto next.
When the end of the switch is found, we are ready to generate the code for the n-way branch. Reading the queue of value-label pairs, we can generate a sequence of three-address statements of the form shown in Fig. 6.51. There, t is the temporary holding the value of the selector expression E,and is the label for the default statement.
case t V1 L1
case t V2 L2
case t Vn-1 Ln-1
case t t Ln
next:
Figure 6.51 Case three-address-code instructions used to translate a switch-statement
The case t L,instruction is a synonym for if t= goto ,in Fig. 6.49, but the case instruction is easier for the final code generator to detect as a candidate for special treatment. At the code-generation phase, these sequences of case statements can be translated into an n-way branch of the most efficient type, depending on how many there are and whether the values fall into a small range.
Exercises for Section 6.8
Section titled “Exercises for Section 6.8”!Exercise 6.8.1:In order to translate a switch-statement into a sequence of case-statements as in Fig. 6.51, the translator needs to create the list of value-label pairs, as it processes the source code for the switch. We can do so, using an additional translation that accumulates just the pairs. Sketch a syntax-directed definition that produces the list of pairs, while also emitting code for the statements that are the actions for each case.
6.9 Intermediate Code for Procedures
Section titled “6.9 Intermediate Code for Procedures”Procedures and their implementation will be discussed at length in Chapter 7, along with the run-time management of storage for names. We use the term function in this section for a procedure that returns a value. We briefly discuss function declarations and three-address code for function calls. In three-address code, a function call is unraveled into the evaluation of parameters in preparation for a call, followed by the call itself. For simplicity, we assume that parameters are passed by value; parameter-passing methods are discussed in Section 1.6.6.
Example 6.25
Suppose that a is an array of integers, and that f is a function from integers to integers. Then, the assignment
might translate into the following three-address code:
-
* 4
-
[ ]
3)param t2
-
t3= call f, 1
-
n= t3
The first two lines compute the value of the expression a[i] into temporary , as discussed in Section 6.4. Line 3 makes an actual parameter for the call of f on line 4.That line also assigns the return value to temporary t3. Line 5 assigns the result of f(a[i]) to n.
The productions in Fig. 6.52 allow function definitions and function calls.(The syntax generates unwanted commas after the last parameter, but is good enough for illustrating translation.) Nonterminals D and T generate declarations and types, respectively, as in Section 6.3. A function definition generated by D consists of keyword define, a return type, the function name, formal parameters in parentheses and a function body consisting of a bracketed statement. Nonterminal F generates zero or more formal parameters, where a formal parameter consists of a type followed by an identifier. Nonterminals S and E generate statements and expressions, respectively. The production for S adds a statement that returns the value of an expression. The production for E adds function calls, with actual parameters generated by A. An actual parameter is an expression.
Figure 6.52 Adding functions to the source language
Function definitions and function calls can be translated using concepts that have already been introduced in this chapter.
-
Function types. The type of a function must encode the return type and the types of the formal parameters. Let void be a special type that represents no parameter or no return type. The type of a function pop() that returns an integer is therefore “function from void to integer.” Function types can be represented by using a constructor fun applied to the return type and an ordered list of types for the parameters.
-
Symbol tables. Let s be the top symbol table when the function definition is reached. The function name is entered into s for use in the rest of the program. The formal parameters of a function can be handled in analogy with field names in a record (see Fig. 6.18). In the production for D, after seeing define and the function name, we push s and set up a new symbol table
Env.push(top); top = new Env(top);
Call the new symbol table, t. Note that top is passed as a parameter in new Env(top), so the new symbol table t can be linked to the previous one, s. The new table t is used to translate the function body. We revert to the previous symbol table s after the function body is translated.
-
Type checking. Within expressions, a function is treated like any other operator. The discussion of type checking in Section 6.5.2 therefore carries over, including the rules for coercions. For example, if f is a function with a parameter of type real, then the integer 2 is coerced to a real in the call f(2).
-
Function calls. When generating three-address instructions for a function call id(E, E,… , E), it is sufficient to generate the three-address instructions for evaluating or reducing the parameters E to addresses, followed by a param instruction for each parameter. If we do not want to mix the parameter-evaluating instructions with the param instructions, the attribute E.addr for each expression E can be saved in a data structure such as a queue. Once all the expressions are translated, the param instructions can be generated as the queue is emptied.
The procedure is such an important and frequently used programming construct that it is imperative for a compiler to generate good code for procedure calls and returns. The run-time routines that handle procedure parameter passing, calls, and returns are part of the run-time support package. Mechanisms for run-time support are discussed in Chapter 7.
6.10 Summary of Chapter 6
Section titled “6.10 Summary of Chapter 6”The techniques in this chapter can be combined to build a simple compiler front end, like the one in Appendix A. The front end can be built incrementally:
- Pick an intermediate representation: An intermediate representation is typically some combination of a graphical notation and three-address code. As in syntax
trees, a node in a graphical notation represents a construct; the children of a node represent its subconstructs. Three address code takes its name from instructions of the form x=y op z, with at most one operator per instruction. There are additional instructions for control flow.
Translate expressions: Expressions with built-up operations can be unwound into a sequence of individual operations by attaching actions to each production of the form E→E1 op E2. The action either creates a node for E with the nodes for E1 and E2 as children, or it generates a three-address instruction that applies op to the addresses for E1 and E2 and puts the result into a new temporary name, which becomes the address for E.
Check types: The type of an expression E1 op E2 is determined by the operator op and the types of E1 and E2. A coercion is an implicit type conversion, such as from integer to float. Intermediate code contains explicit type conversions to ensure an exact match between operand types and the types expected by an operator.
Use a symbol table to implement declarations: A declaration specifies the type of a name. The width of a type is the amount of storage needed for a name with that type. Using widths, the relative address of a name at run time can be computed as an offset from the start of a data area. The type and relative address of a name are put into the symbol table due to a declaration, so the translator can subsequently get them when the name appears in an expression.
Flatten arrays: For quick access, array elements are stored in consecutive locations. Arrays of arrays are flattened so they can be treated as a one-dimensional array of individual elements. The type of an array is used to calculate the address of an array element relative to the base of the array.
Generate jumping code for boolean expressions: In short-circuit or jumping code, the value of a boolean expression is implicit in the position reached in the code. Jumping code is useful because a boolean expression B is typically used for control flow, as in if(B) S. Boolean values can be computed by jumping to t= true or t=false, as appropriate, where t is a temporary name. Using labels for jumps, a boolean expression can be translated by inheriting labels corresponding to its true and false exits. The constants true and false translate into a jump to the true and false exits, respectively.
Implement statements using control flow: Statements can be translated by inheriting a label next, where next marks the first instruction after the code for this statement. The conditional S→if(B) S1 can be translated by attaching a new label marking the beginning of the code for S1 and passing the new label and S.next for the true and false exits, respectively, of B.
Alternatively, use backpatching: Backpatching is a technique for generating code for boolean expressions and statements in one pass. The idea is to maintain lists of incomplete jumps, where all the jump instructions on a list have the same target. When the target becomes known, all the instructions on its list are completed by filling in the target.
- Implement records: Field names in a record or class can be treated as a sequence of declarations. A record type encodes the types and relative addresses of the fields. A symbol table object can be used for this purpose.
6.11 References for Chapter 6
Section titled “6.11 References for Chapter 6”Most of the techniques in this chapter stem from the flurry of design and implementation activity around Algol 60. Syntax-directed translation into intermediate code was well established by the time Pascal [11] and C [6,9] were created.
UNCOL (for Universal Compiler Oriented Language) is a mythical universal intermediate language, sought since the mid 1950’s. Given an UNCOL, compilers could be constructed by hooking a front end for a given source language with a back end for a given target language [10]. The bootstrapping techniques given in the report [10] are routinely used to retarget compilers.
The UNCOL ideal of mixing and matching front ends with back ends has been approached in a number of ways. A retargetable compiler consists of one front end that can be put together with several back ends to implement a given language on several machines. Neliac was an early example of a language with a retargetable compiler [5]written in its own language. Another approach is to retrofit a front end for a new language onto an existing compiler. Feldman [2] describes the addition of a Fortran 77 front end to the C compilers [6] and [9]. GCC, the GNU Compiler Collection [3], supports front ends for C,C++, Objective-C,Fortran, Java, and Ada.
Value numbers and their implementation by hashing are from Ershov [1].
The use of type information to improve the security of Java bytecodes is described by Gosling [4].
Type inference by using unification to solve sets of equations has been re-discovered several times; its application to ML is described by Milner [7]. See Pierce [8] for a compre-hensive treatment of types.
-
Ershov,A.P.,“On programming of arithmetic operations,” Comm.ACM 1:8(1958),pp.3-6. See also Comm.ACM 1:9(1958),p.16.
-
Feldman, S. I,“Implementation of a portable Fortran 77 compiler using modern tools,” ACM SIGPLAN Notices 14:8(1979),pp.98-106.
-
GCC home page http://gcc.gnu.org/,Free Software Foundation.
-
Gosling, J.,“Java intermediate bytecodes,” Proc. ACM SIGPLAN Work-shop on Intermediate Representations(1995),pp.111-118.
-
Huskey, H. D., M. H. Halstead, and R. McArthur,“Neliac-a dialect of Comm.ACM 3:8(1960),pp.463-468. 428 Compilers: Principles, Techniques and Tools
-
Johnson, S.C., “A tour through the portable C compiler,” Bell Telephone Laboratories, Inc., Murray Hill, N.J., 1979.
-
Milner, R., “A theory of type polymorphism in programming,” J. Computer and System Sciences 17:3 (1978), pp. 348–375.
-
Pierce, B. C., Types and Programming Languages, MIT Press, Cambridge, Mass., 2002.
-
Ritchie, D. M., “A tour through the UNIX C compiler,” Bell Telephone Laboratories, Inc., Murray Hill, N.J., 1979.
-
Strong, J., J. Wegstein, A. Tritter, J. Olsztyn, O. Mock, and T. Steel, “The problem of programming communication with changing machines: a proposed solution,” Comm. ACM 1:8 (1958), pp. 12–18. Part 2: 1:9 (1958), pp. 9–15. Report of the SHARE Ad-Hoc Committee on Universal Languages.
-
Wirth, N. “The design of a Pascal compiler,” Software—Practice and Experience 1:4 (1971), pp. 309–333.
← node-book_compilers-principles-techniques-and-tools_chapter-05-syntax-directed-translation | node-book_compilers-principles-techniques-and-tools | node-book_compilers-principles-techniques-and-tools_chapter-07-run-time-environments →