Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

DAG representation of basic blocks

How to represent a basic block as a Directed Acyclic Graph (DAG) to expose common subexpressions and eliminate redundant computations in the compiler back end.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

DAG representation of a basic block is used by compiler engineers in the optimizer to detect and eliminate common subexpressions, remove dead code, and reduce the number of instructions before register allocation and code generation. It is a local (basic-block level), machine-independent optimization tightly linked to intermediate-code generation and basic-block analysis.

Key ideas

  • Purpose: DAG-based optimization implements local common subexpression elimination (CSE) and copy propagation inside the basic block. If two expressions compute the same value, they map to the same DAG node and need be computed once.

Exact algorithm (standard university statement). Input: a basic block given as a sequence of three-address instructions. Output: a DAG representing computations and a reduced set of instructions.

Assumptions: instructions are in three-address form: x = y op z, x = op y (unary), or x = y (copy). op may be commutative or non-commutative. Variables are SSA is not required but simpler if names change on each assignment; we give the algorithm for ordinary variables. We assume expressions have no side-effects (e.g., no calls with side effects, no volatile accesses), and that loads/stores to memory are modeled explicitly if present; otherwise CSE using a DAG may be unsafe.

Algorithm to build DAG (step-by-step):

  1. Maintain a set of DAG nodes. Each node has: op (operator or leaf type), pointers to child nodes (for operator nodes), and a set of labels (variable names currently holding the node's value). Also maintain a mapping var2node from variable names to DAG node objects.
  2. Process the basic block instructions in textual order. a. For a leaf operand (variable or constant), if a leaf node with same operand exists, reuse it; else create a new leaf node and add it to nodes. For variables, first consult var2node; create a leaf only on the first mention (when var2node has no entry), because later mentions of a reassigned variable map to whatever node var2node[v] currently names (which may be an operator node). b. For an instruction x = y op z: find nodes ny = var2node[y] (or create leaf if missing) and nz = var2node[z]. For commutative ops, canonicalize the pair (e.g., order by node id or canonical key). Search whether an operator node with op and children ny,nz already exists. If yes, reuse that node; else create new operator node with children pointers to ny and nz and add it to nodes. c. Remove x from the label sets of any node if x appears there (because x now gets a fresh value). Add x to the label set of the node that represents the right-hand side value. Update var2node[x] to that node. d. For copy x = y: set var2node[x] = var2node[y] and add label x to that node's label set; remove old label occurrences of x.
  3. At the end, the DAG nodes whose labels contain variables that are live at block exit are the required computations. Generate code by a post-order traversal: visit nodes in dependency order and emit code for a node only once, assigning its value to one of its labels (pick one live label or a new temporary). This produces fewer computations than original. Emit instructions only for operator nodes (leaves are just operands). If a node has multiple live-out labels, choose one representative label to receive the computed value and insert copies to the remaining live-out labels so that all required variable names hold the value at block exit. Liveness at block exit is required to decide which labels must be materialized; always emit the dependency closure of the live-out nodes.

Notes about commutativity and canonical keys: for a commutative op (like +, *), define a deterministic ordering of child keys, e.g., (min(node-id), max(node-id)), to detect duplicate expressions a + b and b + a. Also include the operator and operand types in the key (and, for constants, both literal value and type) to avoid incorrectly merging values of different types.

Diagrams to draw for an exam answer (exact instructions):

  • Draw boxes for nodes: leaf boxes labeled with variable or constant (e.g., a, 5). Operator nodes drawn as circles or boxes containing the operator +, *, etc.
  • Draw directed edges from an operator node to its children (operands). Label edges optionally as left/right if op non-commutative.
  • Annotate operator nodes with the set of variable labels that currently refer to that node (e.g., node N3 labels: {t1, x}).
  • For code generation, show an arrow from a node to the emitted three-address instruction that computes that node's value and show which label receives it.

Relationship to other compiler topics: DAGs operate on intermediate code for a basic block (see "Intermediate code" and "Basic blocks and flow graphs"). They implement local optimizations before global data-flow optimizations and before register allocation.

Formulas

x = y op z — three-address binary operation. x, y, z are variables, temporaries, or constants; op is an operator (with type). x = y — copy statement. x = op y — unary operation. var2node[v] — mapping from variable name v to its DAG node (no unit). Applies during DAG construction. labels(n) — set of variable names that refer to node n (no unit). Used for mapping nodes back to variables. Complexity: T_build = O(n) expected, where n = number of instructions, assuming node lookup by hash (average O(1)). Worst-case naive search T_build = O(n^2) if searching all nodes linearly.

Worked examples

Example 1 — medium-length three-address code (trace step-by-step) Basic block (original):

  1. t1 = a + b
  2. t2 = a + b
  3. t3 = t1 * c
  4. t4 = t2 * c
  5. d = t4

Step-by-step DAG construction:

  1. Instruction 1 t1 = a + b:
    • Create/lookup leaf a -> node L_a.
    • Create/lookup leaf b -> node L_b.
    • + with children (L_a, L_b): no existing op node, create node N1(op='+', children=L_a,L_b). labels(N1) = {t1} ; var2node[t1]=N1.
  2. Instruction 2 t2 = a + b:
    • var2node[a], var2node[b] are L_a, L_b.
    • Find op node with + and children (L_a,L_b): found N1. labels(N1) adds t2. var2node[t2]=N1.
  3. Instruction 3 t3 = t1 * c:
    • var2node[t1] = N1, leaf c -> L_c.
    • * with children (N1,L_c): create N2(op='*', children=N1,L_c). labels(N2) = {t3}. var2node[t3]=N2.
  4. Instruction 4 t4 = t2 * c:
    • var2node[t2] = N1, var2node[c] = L_c.
    • * with children (N1,L_c): found N2. labels(N2) adds t4. var2node[t4]=N2.
  5. Instruction 5 d = t4:
    • var2node[t4] = N2. labels(N2) adds d. var2node[d]=N2.

Final DAG nodes: L_a, L_b, N1(+){t1,t2}, L_c, N2(*){t3,t4,d}. Code generation by topological order (compute only nodes whose labels include live-out vars; assume d live):

  • Emit t = a + b (compute N1 into temp t).
  • Emit d = t * c (compute N2 into d). Optimized code (one possible correct output):
  1. temp1 = a + b
  2. d = temp1 * c

Final answer: two instructions instead of five.

Example 2 — handling copy and commutativity Basic block:

  1. x = y
  2. z = x
  3. a = b + c
  4. d = c + b
  5. e = a + 0

Trace (high level):

  • After 1 and 2, y maps to node L_y, labels include {y,x,z}.
  • a = b + c creates N3(+){a}.
  • d = c + b sees commutative plus: canonicalize children so (L_b,L_c) -> finds N3, so labels(N3) add d.
  • e = a + 0: if 0 leaf L_0 created, then a + 0 may be simplified by algebraic identity (this is a separate optimization — constant folding/strength reduction). DAG can represent a+0 as a node, but to eliminate identity you'd need a fold pass. If we do folding, e = a and set var2node[e] = var2node[a].

Optimized result (after canonical commutativity): single node for b+c, copies eliminated, and possibly a+0 folded to a.

Common mistakes

  • Not canonicalizing operands for commutative operators: misses duplicates like b + c vs c + b.
  • Attempting to use DAG across basic-block boundaries: DAG is defined per basic block only; global CSE requires global value numbering or SSA-based methods.
  • Emitting code in an order that violates dependencies (must use topological/post-order traversal of DAG).
  • Treating DAG nodes as machine instructions: DAG is a value graph; mapping nodes to actual instructions must consider side-effects, memory loads/stores, and instruction availability.

For your exam

Kinds of questions:

  • Definitions and short notes: define DAG, explain purpose, differences from expression trees.
  • Derivation/algorithm trace: given a basic block, construct the DAG, show var2node mappings after each instruction, and draw the DAG with labels.
  • Code-generation: from the DAG produce an optimized sequence of three-address instructions and explain why it is correct.
  • Complexity/analysis: argue time complexity with and without hashing.
  • Conceptual: explain limits of DAG (why not across basic blocks) and relation to SSA-based optimizations.

What a full-marks answer includes:

  • Clear definition of basic block and DAG and assumptions (three-address code, no side-effects).
  • Stepwise construction with var2node and labels updates; if asked, show canonicalization for commutative ops.
  • Correct final DAG drawn and labelled as described in Diagrams section.
  • Correct optimized code emitted in dependency order and short justification (each reused computation is emitted once).
  • If complexity asked: state expected O(n) with hashing and explain worst-case O(n^2) if naive matching.

Quick check

  1. What is the main purpose of building a DAG for a basic block?
  2. How do you handle a + b and b + a for a commutative operator when detecting common subexpressions?
  3. Why can't we directly use the same DAG across basic-block boundaries without extra analysis?

Answers: 1) To detect common subexpressions and eliminate redundant computations locally. 2) Canonicalize operand order (e.g., sort by node id or key) so both map to the same operator node. 3) Because different control-flow paths change variable values and basic blocks have differing live-in and live-out values; global correctness needs data-flow/SSA analysis.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?