Computer Science and IT‹›⌂ 0:00 studied

Module 8 · 15 min read · Free chapter

Syntax-directed translation and intermediate code

In short

A syntax-directed definition attaches attributes and rules to a grammar. Synthesised attributes flow up from children, inherited ones come from the parent or left siblings. S-attributed rules suit LR parsing, L-attributed rules suit LL parsing. Intermediate code is often three-address code, stored as quadruples or triples, and a DAG removes repeated subexpressions.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: a shop bill that adds up

Look at a bill from a kirana shop. Each line has a quantity and a rate, and its amount is the product of the two. The total at the bottom is the sum of the line amounts. Values here travel upward, from the small parts to the whole.

Now suppose a festival discount of 10 percent is printed at the top of the bill. Every line must use that rate, so this value travels downward from the top to each line. A bill thus has two kinds of information: what a line computes from its own parts, and what a line receives from above.

A compiler attaches values to a parse tree in exactly these two ways. A synthesised attribute flows up from children to parent, like the total. An inherited attribute flows down from a parent, or across from a sibling, like the discount.

Why it matters. Attaching such rules to a grammar is how a compiler checks types, builds syntax trees and produces intermediate code while it parses. GATE asks you to evaluate such rules on an input and to classify them as S-attributed or L-attributed.

Syntax-directed definitions and annotated parse trees

A syntax-directed definition (SDD) is a grammar in which each symbol can carry attributes, and each production carries semantic rules that compute them. The attribute of a symbol XX is written X.valX.\mathit{val}. The standard example is a desk calculator.

Meaning Production Semantic rule
Print the result L→E nL \to E\ \mathbf{n} print(E.val)\mathit{print}(E.\mathit{val})
Add E→E1+TE \to E_1 + T E.val=E1.val+T.valE.\mathit{val} = E_1.\mathit{val} + T.\mathit{val}
Pass up E→TE \to T E.val=T.valE.\mathit{val} = T.\mathit{val}
Multiply T→T1∗FT \to T_1 * F T.val=T1.val×F.valT.\mathit{val} = T_1.\mathit{val} \times F.\mathit{val}
Pass up T→FT \to F T.val=F.valT.\mathit{val} = F.\mathit{val}
Brackets F→(E)F \to (E) F.val=E.valF.\mathit{val} = E.\mathit{val}
Number from the lexer F→digitF \to \mathbf{digit} F.val=digit.lexvalF.\mathit{val} = \mathbf{digit}.\mathit{lexval}

The subscript in E1E_1 only separates the two copies of EE in one production. Every rule here computes a parent's attribute from its children, so every attribute is synthesised. The value of a digit comes from the lexer as lexval\mathit{lexval}, and terminals never have inherited attributes.

Worked example. For the input 3 * 5 + 4, the parse tree has F.val=3F.\mathit{val} = 3 and F.val=5F.\mathit{val} = 5 at the bottom left, so T.val=15T.\mathit{val} = 15. The right FF gives 4, and the top gives E.val=15+4=19E.\mathit{val} = 15 + 4 = 19. A parse tree with such values written at its nodes is an annotated parse tree.

In what order should the rules run? Draw a dependency graph, with an edge from attribute aa to attribute bb whenever the rule for bb uses aa. Any topological order of this graph is a valid evaluation order, and if the graph has a cycle, no order works.

Why it matters. The annotated parse tree is how you answer "what value is printed?" questions. Drawing the tree first and filling values bottom-up avoids almost every error.

S-attributed and L-attributed definitions

Inherited attributes are needed when information must flow sideways or down. The classic case is a declaration such as float x, y, z, where the type is read first and must reach every name after it.

D→T L{L.inh=T.type}D \to T\,L \quad \{L.\mathit{inh} = T.\mathit{type}\}
T→float{T.type=float}T \to \mathbf{float} \quad \{T.\mathit{type} = \mathit{float}\}
L→L1,id{L1.inh=L.inh; addtype(id.entry,L.inh)}L \to L_1 , \mathbf{id} \quad \{L_1.\mathit{inh} = L.\mathit{inh};\ \mathit{addtype}(\mathbf{id}.\mathit{entry}, L.\mathit{inh})\}
L→id{addtype(id.entry,L.inh)}L \to \mathbf{id} \quad \{\mathit{addtype}(\mathbf{id}.\mathit{entry}, L.\mathit{inh})\}

Here L.inhL.\mathit{inh} is inherited: it comes from the left sibling TT, and then down the chain of LL nodes. Each identifier's symbol-table entry receives the type through the call to addtype\mathit{addtype}.

Two classes of SDD can be evaluated while parsing, without building the whole tree first. An S-attributed SDD uses only synthesised attributes. It can be evaluated in post-order, which is exactly the order in which an LR parser performs reductions.

An L-attributed SDD allows inherited attributes too, under one condition. In A→X1X2…XnA \to X_1 X_2 \dots X_n, an inherited attribute of XjX_j may depend only on inherited attributes of AA, on attributes of the left siblings X1,…,Xj−1X_1, \dots, X_{j-1}, and on attributes of XjX_j itself without forming a cycle. Information therefore flows from left to right, and a single depth-first, left-to-right walk evaluates everything, which suits top-down parsing.

Worked example. Classify A→B CA \to B\,C with the rules B.i=A.iB.i = A.i, C.i=B.sC.i = B.s and A.s=C.sA.s = C.s. Every inherited attribute depends on the parent or a left sibling, so it is L-attributed but not S-attributed. If instead B.i=C.sB.i = C.s, then BB inherits from its right sibling, and the SDD is not L-attributed.

Why it matters. "Which of these SDDs is L-attributed?" is a common GATE question. Check each inherited rule and look only for a dependence on a right sibling or on the parent's synthesised attribute.

Translation schemes: actions inside productions

A syntax-directed translation scheme (SDT) writes program fragments, called semantic actions, inside the production bodies within braces. An action runs when the parser reaches its position, so the position matters. When all actions sit at the right ends of productions, the SDT is a postfix SDT, and an LR parser runs each action as it reduces.

Worked example (postfix output). The SDT below prints each operator after its operands.

E -> E + T   { print('+') }
E -> E - T   { print('-') }
E -> T
T -> digit   { print(digit.lexval) }

For the input 9 - 5 + 2, the left-recursive grammar groups it as (9 - 5) + 2. The digits are printed as they are reduced and each operator after its right operand, so the output is 9 5 - 2 +, the postfix form. Moving the print actions to the front of the bodies would instead print the operators earlier, which is why the position of an action changes the output.

Worked example (a GATE-style evaluation). Consider this SDT, in which the symbols have unusual meanings.

E→E1#T{E.val=E1.val×T.val}E \to E_1 \# T \quad \{E.\mathit{val} = E_1.\mathit{val} \times T.\mathit{val}\}
T→T1 & F{T.val=T1.val+F.val}T \to T_1 \,\&\, F \quad \{T.\mathit{val} = T_1.\mathit{val} + F.\mathit{val}\}
E→T,T→F,F→num{values passed up}E \to T, \quad T \to F, \quad F \to \mathbf{num} \quad \{\text{values passed up}\}

Evaluate 2 # 3 & 5 # 6 & 4. The operator & sits lower in the grammar, so it binds tighter, even though it means addition. So the input groups as 2 # (3 & 5) # (6 & 4), and both operators group from the left.

E.val=2×(3+5)×(6+4)=2×8×10=160E.\mathit{val} = 2 \times (3 + 5) \times (6 + 4) = 2 \times 8 \times 10 = 160

Why it matters. GATE likes SDTs with strange operators precisely because students use the usual school precedence. Precedence comes only from the grammar's levels, and associativity from the side of the recursion.

Three-address code and its representations

Most compilers translate the syntax tree into three-address code, in which each instruction has at most one operator on its right side. A long expression is broken into steps, and the compiler invents temporaries t1,t2,…t_1, t_2, \dots to hold the partial results. The name comes from the general form x=y op zx = y \ \mathit{op}\ z, which mentions three addresses.

The usual instruction kinds are few. They are binary assignment x = y op z, unary assignment x = minus y, copy x = y, unconditional jump goto L, conditional jump if x relop y goto L, procedure calls with param x and call p, n, indexed assignments x = a[i] and a[i] = x, and address and pointer assignments x = &y, x = *p and *p = x.

Worked example (a loop). The C loop s = 0; for (i = 0; i < n; i++) s = s + a[i];, with 4-byte integers, becomes the code below.

1: s = 0
2: i = 0
3: if i >= n goto 9
4: t1 = 4 * i
5: t2 = a[t1]
6: s = s + t2
7: i = i + 1
8: goto 3
9: return s

Three-address code can be stored in three ways. Take a = b * -c + b * -c, whose code is t1 = minus c, t2 = b * t1, t3 = minus c, t4 = b * t3, t5 = t2 + t4 and a = t5.

Position op arg1 arg2 Quadruple result Triple arguments
(0) minus c t1 c
(1) times b t1 t2 b, (0)
(2) minus c t3 c
(3) times b t3 t4 b, (2)
(4) plus t2 t4 t5 (1), (3)
(5) assign t5 a a, (4)

Quadruples have four fields, op, arg1, arg2 and result, and name every temporary explicitly. Triples drop the result field and refer to a value by the position of the triple that computes it, so (1) means "the result of instruction 1". Indirect triples add a separate list of pointers to triples, so the optimiser can reorder the list without touching the triples.

Why it matters. Optimisers move instructions around all the time. With plain triples, moving an instruction changes positions and breaks every reference to it, which is why quadruples and indirect triples are preferred in optimising compilers.

Syntax trees, DAGs and SSA form

A syntax tree is a compact parse tree. Its interior nodes are operators and its leaves are operands, and chains such as E→T→FE \to T \to F are dropped. A DAG, or directed acyclic graph, goes one step further and gives each distinct subexpression a single node, shared by every place that uses it.

To build a DAG, look up a node before creating it. If a node with the same operator and the same children already exists, reuse it; otherwise create a new one. This lookup, usually done with hashing, is what finds common subexpressions.

Worked example. Count nodes for a+a∗(b−c)+(b−c)∗da + a * (b - c) + (b - c) * d. The syntax tree has 7 leaves (aa, aa, bb, cc, bb, cc, dd) and 6 operator nodes, so 13 nodes. In the DAG the leaves aa, bb, cc and dd appear once each, and b−cb - c is built once and shared, so there are 4 leaves and 5 operator nodes, which is 9 nodes.

For a = b * -c + b * -c, the DAG shares both minus c and b * t1. Its code needs only four instructions: t1 = minus c, t2 = b * t1, t3 = t2 + t2 and a = t3. The six-line code of the last section shrinks because the DAG found the repetition.

Static single-assignment (SSA) form is an intermediate code in which every variable is assigned exactly once. Each new assignment creates a new version, so x = a + b; x = x * 2; y = x + 1 becomes x1 = a + b; x2 = x1 * 2; y1 = x2 + 1. Each use then names exactly one definition, which makes many optimisations simpler.

When two control paths meet, a variable may have different versions on each path. SSA joins them with a φ-function: if one branch sets x3=1x_3 = 1 and the other sets x4=2x_4 = 2, the join point gets x5=ϕ(x3,x4)x_5 = \phi(x_3, x_4). The φ-function picks the version from whichever path the program actually took.

Why it matters. GATE asks for the number of nodes in a DAG and for the minimum number of temporaries. The DAG is also the tool for local common-subexpression elimination, which the syllabus names directly.

Backpatching in brief

When a compiler translates if (x < 5 or y > 2) S, it must emit jumps to the start of SS and past it before it knows where those places are. One solution is two passes. Backpatching does it in one pass by leaving jump targets blank and filling them in later.

Each boolean expression BB carries two lists of instructions with blank targets. B.truelistB.\mathit{truelist} holds the jumps to take when BB is true, and B.falselistB.\mathit{falselist} the jumps for false. Three functions manage them: makelist(i)\mathit{makelist}(i) makes a new list containing instruction ii, merge(p1,p2)\mathit{merge}(p_1, p_2) joins two lists, and backpatch(p,i)\mathit{backpatch}(p, i) writes target ii into every jump on list pp.

B→B1 or M B2:backpatch(B1.falselist,M.instr), B.truelist=merge(B1.truelist,B2.truelist), B.falselist=B2.falselistB \to B_1 \ \mathbf{or}\ M\, B_2: \quad \mathit{backpatch}(B_1.\mathit{falselist}, M.\mathit{instr}),\ B.\mathit{truelist} = \mathit{merge}(B_1.\mathit{truelist}, B_2.\mathit{truelist}),\ B.\mathit{falselist} = B_2.\mathit{falselist}

The marker M→εM \to \varepsilon records M.instrM.\mathit{instr}, the number of the next instruction, which is where B2B_2 begins. If B1B_1 is false, control must go on to test B2B_2, so B1B_1's false jumps are patched to M.instrM.\mathit{instr}. For and, the roles swap: B1B_1's true jumps are patched to the start of B2B_2, and the false lists are merged.

Worked example. Starting at instruction 100, the condition gives the code below. The truelist is {100,102}\{100, 102\}, patched to 104 where SS begins, and the falselist is {103}\{103\}, patched to the first instruction after SS.

100: if x < 5 goto _      (true: patched to 104)
101: goto 102             (false of x < 5: patched to start of y > 2)
102: if y > 2 goto _      (true: patched to 104)
103: goto _               (false: patched to after S)

Why it matters. Backpatching is how one-pass compilers produce correct jump code for conditions and loops. Exam questions usually ask what a list contains, or which target fills a blank.

Descriptive lens: how written papers ask this

Written papers for scientist posts and university examinations ask about this topic in four ways:

  1. Define and contrast synthesised and inherited attributes, and S-attributed and L-attributed definitions, with an example of each.
  2. Draw an annotated parse tree and a dependency graph for an input, and give an evaluation order.
  3. Translate a statement or a loop into three-address code, and show its quadruples, triples and indirect triples.
  4. Construct the DAG of an expression or a basic block, and use it to remove common subexpressions.

Practice questions (our own, not previous-year questions).

  1. Write an SDD for a desk calculator and draw the annotated parse tree for (4 + 2) * 3. Is your SDD S-attributed? (10 marks)
  2. Translate x = (a + b) * (a + b) - c into three-address code, and represent it as quadruples, triples and indirect triples. (15 marks)
  3. Distinguish S-attributed and L-attributed definitions. Show, with the declaration int p, q, r, why inherited attributes are needed. (10 marks)

Answer plan for question 3.

  • Begin by defining synthesised and inherited attributes, with the direction in which each flows in the parse tree.
  • Define an S-attributed SDD as one with only synthesised attributes, evaluated bottom-up in post-order during LR parsing.
  • Define an L-attributed SDD by its condition that inherited attributes depend only on the parent's inherited attributes and on left siblings.
  • Write the four declaration rules, with L.inh=T.typeL.\mathit{inh} = T.\mathit{type} passed from TT to LL and down the list.
  • Draw the annotated tree for int p, q, r, and show addtype\mathit{addtype} placing the type integer in each symbol-table entry.
  • Conclude that the type is known only to the left sibling, so a purely synthesised scheme cannot pass it to the names without extra work.

Quick revision

  • An SDD attaches attributes and semantic rules to a grammar, while an SDT places actions inside production bodies.
  • Synthesised attributes come from children, inherited ones come from the parent or siblings, and terminals have only synthesised ones.
  • S-attributed SDDs use only synthesised attributes and suit LR parsing, while L-attributed SDDs also allow inheritance from the parent and left siblings.
  • Every S-attributed SDD is L-attributed, and a cycle in the dependency graph makes evaluation impossible.
  • Precedence in an SDT comes from grammar levels, and associativity from the side of the recursion.
  • Three-address code has at most one operator on the right side of each instruction.
  • Quadruples have four fields, triples have three and refer by position, and indirect triples add a pointer list.
  • A DAG gives one node to each distinct subexpression, so a+a∗(b−c)+(b−c)∗da + a * (b - c) + (b - c) * d needs 9 nodes against 13.
  • SSA gives each variable one assignment and uses φ-functions where paths meet.
  • Backpatching leaves jump targets blank on truelists and falselists and fills them in later.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. In a syntax-directed translation scheme, semantic actions are:

  2. An attribute of a node computed from the attributes of its children is:

  3. Terminals in an SDD can have:

  4. For A→B CA \to B\,C, which rule makes the SDD NOT L-attributed?

  5. Which statement is TRUE?

  6. A valid order for evaluating the attributes of an SDD is given by:

  7. With print actions at the right ends, the SDT for E→E+T∣E−T∣TE \to E + T \mid E - T \mid T, T→digitT \to \mathbf{digit} prints what for 9 - 5 + 2?

  8. With E→E1#TE \to E_1 \# T meaning multiply and T→T1 & FT \to T_1 \,\&\, F meaning add, the value of 2 # 3 & 5 # 6 & 4 is:

  9. Which instruction is NOT valid three-address code?

  10. Which representation lets the optimiser reorder instructions without changing references?

  11. How many fields does a quadruple have?

  12. How many nodes are in the DAG of a+a∗(b−c)+(b−c)∗da + a * (b - c) + (b - c) * d?

  13. In SSA form, the ϕ\phi-function is placed:

  14. In backpatching for B→B1 or M B2B \to B_1 \ \mathbf{or}\ M\, B_2, which list is patched to M.instrM.\mathit{instr}?

  15. Which topic is listed under Compiler Design in the GATE 2026 CS syllabus?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is the difference between S-attributed and L-attributed SDDs?

S-attributed SDDs use only synthesised attributes. L-attributed SDDs also allow inherited attributes that depend on the parent's inherited attributes and on left siblings.

What is three-address code?

It is intermediate code in which each instruction has at most one operator on its right side, such as t1 = b * c, using compiler-made temporaries.

How do quadruples differ from triples?

Quadruples have four fields including an explicit result. Triples have three fields and refer to results by position, which makes reordering harder.

Why is a DAG used for expressions?

A DAG gives each distinct subexpression one shared node, so repeated work is found and computed once.

More in this module: Compiler design

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Compiler Design (IIT Kharagpur, 106105190): syntax-directed translation and intermediate code generation