Sub topic 8
Syntax trees and DAGs
This chapter assumes you can read parse trees, know what a syntax-directed definition is, and can follow three-address code at an introductory level. It covers how a compiler stores an expression as a tree, how a directed acyclic graph (DAG) removes repeated work from that tree, and how to count nodes in GATE-style questions.
From parse tree to syntax tree
A parse tree records every grammar step, including nonterminals such as E, T and F. A syntax tree (abstract syntax tree) keeps only the meaningful structure. Operators sit at interior nodes, and operands sit at the leaves or below them.
For a * (b + c), the parse tree has chains of E → T → F, plus parentheses. The syntax tree has three interior and leaf-level pieces: * with children a and +, and + with children b and c. The parentheses disappear because the tree shape already encodes grouping.
A syntax-directed definition builds this tree bottom-up. Each production calls a constructor such as mknode(op, left, right) or mkleaf(id, entry), and the attribute of each nonterminal is a pointer to the node built so far.
What a DAG adds
A DAG is a syntax tree in which identical subexpressions share one node. A node can then have more than one parent. The graph has no cycles, because an expression cannot contain itself.
Take a = b * -c + b * -c. The tree repeats b * -c twice. The DAG builds it once.
| Form | Nodes | Three-address instructions |
|---|---|---|
| Syntax tree | 11 | 6 |
| DAG | 7 | 4 |
The tree has 11 nodes: a, =, +, two *, two b, two minus, two c. The DAG has 7: a, b, c, minus, *, +, =. Reading the DAG in order gives:
t1 = minus c
t2 = b * t1
t3 = t2 + t2
a = t3The value-number method
Interior nodes are stored in an array. Each entry holds an operator and the value numbers (array positions) of its children. Before creating a node, the builder searches for an existing entry with the same operator and the same children. If one exists, it returns that number. Otherwise it appends a new entry.
A linear search costs O(n) per lookup. A hash table keyed on the tuple (operator, left, right) makes each lookup roughly constant time. The following program runs as shown.
class DagBuilder:
def __init__(self):
self.nodes = [] # entry i is stored at value number i + 1
self.index = {} # (op, *children) -> value number
def node(self, op, *kids):
key = (op, *kids)
if key not in self.index:
self.nodes.append(key)
self.index[key] = len(self.nodes)
return self.index[key]
def name(self, v):
key = self.nodes[v - 1]
return key[1] if key[0] == "id" else f"t{v}"
def emit(self):
for v, key in enumerate(self.nodes, 1):
op, kids = key[0], key[1:]
if op == "id":
continue
if op == "minus":
print(f"t{v} = minus {self.name(kids[0])}")
else:
print(f"t{v} = {self.name(kids[0])} {op} {self.name(kids[1])}")
def term(d):
b = d.node("id", "b")
c = d.node("id", "c")
return d.node("*", b, d.node("minus", c))
d = DagBuilder()
total = d.node("+", term(d), term(d))
d.emit()
print(f"a = {d.name(total)}")The output is t3 = minus c, t4 = b * t3, t5 = t4 + t4 and a = t5. Calling term twice adds no new entries the second time, because every lookup finds an existing node.
Why basic blocks need extra care
Within a basic block, a variable can change value. The builder therefore keeps a map from each variable name to the node that holds its current value. An assignment x = e moves the label x to the node for e. It does not create a node for x.
Consider this block:
x = a + b
a = c
y = a + bThe second a + b is not the same expression as the first. The first uses the original a. The second uses a after it was reassigned, which now refers to the node for c. The DAG has two separate + nodes. Treating them as one is a classic wrong answer.
Some operations also force the builder to stop reusing earlier nodes:
- A store through a pointer or into an array element may change any variable that could be an alias. Nodes depending on those variables cannot be reused afterward.
- A procedure call may change global variables and anything reachable through its arguments.
Uses and limits
The DAG gives three things inside one basic block:
- It detects common subexpressions, so each is computed once.
- It shows which variables are used in the block but not defined there (leaf nodes without a prior label).
- It shows which assigned values are used outside the block. An interior node with no live label can be dropped, which is a form of dead code elimination.
It does not work across blocks. Finding common subexpressions across branches and loops needs data flow analysis, covered in later chapters.
Counting patterns for GATE
- A tree has one node for each token occurrence that is an operand or an operator. Count them all.
- A DAG has one leaf per distinct variable or constant (at its current value) and one interior node per distinct (operator, children) pair.
- A repeated subexpression counts once, and so does everything beneath it. If
(b - c)appears twice, its two leaves and its operator count once.
For a + a * (b - c) + (b - c) * d, the tree has 13 nodes. The DAG has 9: leaves a, b, c, d, and interior nodes for b - c, a * (b - c), the first +, (b - c) * d, and the second +.
Exercise
How many nodes are in the syntax tree and in the DAG for a + a * (b - c) + (b - c) * d? How many three-address instructions does the DAG give?
Show answer
The tree has 13 nodes: 7 leaves (a, a, b, c, b, c, d) and 6 operators (+, +, , -, , -). The DAG has 9 nodes: leaves a, b, c, d and five interior nodes (b-c, a(b-c), the first +, (b-c)d, the second +). The DAG gives 5 instructions, one per interior node: t1 = b - c; t2 = a t1; t3 = a + t2; t4 = t1 d; t5 = t3 + t4.
Exercise
For the block x = a + b; a = c; y = a + b, how many + nodes does the DAG contain, and why?
Show answer
Two. The first + uses the original value of a. After a = c, the label a points to the node for c, so the second a + b has different children and gets its own + node.
Exercise
A hash table keyed on (operator, left, right) is used for the value-number method. What does it improve, and what does it not change about the resulting DAG?
Show answer
It reduces the cost of each lookup from O(n) in the number of existing nodes to about O(1). The resulting DAG is the same, because the hash table only speeds up finding an existing identical node.