Blog
Compiler Construction Past Paper 2015 – BSCS 6th Term UOS (CS-443)
University of Sargodha BS Computer Science 6th term Compiler Construction (CS-443) paper, 2015 exam (80 marks, 2:30 hours). The paper is retyped below, followed by solved answers for all 16 short questions and all six long questions: intermediate code, an LL(1) predictive parser with its table, a parse tree, postfix-to-infix translation, minimum DFAs, DAG value numbers, and quadruples/triples.
Solved answers
Q1 – Short answers (16 × 2)
1. Source, intermediate and object code. Source code is the program written by the programmer in a high-level language (e.g. C++). Intermediate code is a machine-independent form produced inside the compiler (e.g. three-address code). Object code is the machine-language output of the compiler/assembler, ready to be linked into an executable.
2. Components of a CFG. A context-free grammar G = (V, T, P, S): a set of non-terminals V, a set of terminals T (tokens), a set of productions P of the form A → α, and a start symbol S.
3. Lexical analyzer. The first phase of a compiler. It reads the source characters, groups them into lexemes and returns tokens (keyword, id, number, operator) to the parser, removes white space and comments, and enters identifiers in the symbol table.
4. Canonical-LR. Canonical LR(1) is the most powerful LR parsing method. It uses LR(1) items [A → α·β, a] that carry one lookahead symbol, so a reduction is made only on the exact lookahead. Its tables are large (many states); LALR merges states with the same core to reduce size.
5. Predictive parsing. A top-down parsing method without backtracking for LL(1) grammars. The next input symbol (lookahead) decides which production to apply, using a parsing table M[A, a] built from FIRST and FOLLOW sets (or recursive procedures).
6. Three-address code. An intermediate code in which each instruction has at most one operator on the right side and at most three addresses, e.g. t1 = b * c; t2 = a + t1. It can be stored as quadruples, triples or indirect triples.
7. Lexical errors. Errors found while forming tokens: an illegal character (e.g. @ or $ in C), a misspelled or too-long identifier, an unterminated string or comment, or a badly formed number such as 3.4.5.
8. Errors reported by the lexical analyzer. Only errors in the spelling of tokens: invalid characters, malformed numbers, unterminated strings/comments, identifiers longer than allowed. Example: int 2x = 5; or printf("hello); (string not closed). It cannot detect fi (a == b) as an error because fi is a valid identifier.
9. Where tokens are kept; creating lexemes. The lexer usually hands each token to the parser on demand (getNextToken); token attributes such as identifier names are stored in the symbol table and the token carries a pointer to that entry. Lexemes are created by reading characters into an input buffer (two-buffer scheme with lexemeBegin and forward pointers) until a pattern (regular expression / transition diagram) matches the longest possible lexeme.
10. Two functions of a pre-processor. (1) Macro processing – expands macros such as #define PI 3.14. (2) File inclusion – inserts header files (#include). It also does conditional compilation (#ifdef) and removes comments.
11. Compiler, language translator, cross compiler. A language translator is any program that converts code from one language to another (assembler, compiler, interpreter). A compiler translates a whole high-level program into target code before execution. A cross compiler runs on one machine but produces code for a different machine (e.g. compiling on a PC for an ARM microcontroller).
12. Principles of compilation. The compiler must preserve the meaning of the program (correctness), and should improve it in a measurable way (speed, size); compilation time should be reasonable and the compiler should give clear error messages. The work is divided into phases (analysis and synthesis).
13. Register allocation vs register assignment. Register allocation decides which variables will be kept in registers at each point of the program. Register assignment decides which specific register (R1, R2 …) each of those variables will occupy.
14. Dead code elimination. An optimization that removes statements whose results are never used or that can never be executed, e.g. x = 5; when x is not used afterwards, or code after return.
15. Retargetable compiler. A compiler designed so that its back end (code generator) can be changed easily to produce code for a new target machine, usually by using a machine description, e.g. GCC and LLVM.
16. Peephole optimization. A local optimization that looks at a small window (peephole) of target instructions and replaces it with a shorter/faster sequence: removing redundant loads/stores, unreachable code, jumps to jumps, algebraic simplification (x = x + 0), and using machine idioms (INC).
Q2 – (a) Intermediate code generation (b) Predictive parser
(a) After semantic analysis the front end translates the program into an intermediate representation (IR) that is easy to produce and easy to translate into machine code. Benefits: retargeting (same front end for many machines) and machine-independent optimization. Representations:
- Syntax tree / DAG: a tree of operators and operands; a DAG also shares common subexpressions.
- Postfix notation: a + b * c becomes a b c * +.
- Three-address code: x = y op z, x = op y, x = y, goto L, if x relop y goto L, param x, call p, n, x = y[i].
- Quadruples (op, arg1, arg2, result), triples (op, arg1, arg2; results referred to by position) and indirect triples (a list of pointers to triples, so statements can be reordered).
- Static Single Assignment (SSA): each name is assigned exactly once.
Example for a = b * −c + b * −c: t1 = minus c; t2 = b * t1; t3 = minus c; t4 = b * t3; t5 = t2 + t4; a = t5.
(b) Predictive (LL(1)) parser algorithm. It uses an input buffer ending with $, a stack initially holding $ S, and a table M[A, a].
push $ and S; a = first input symbol
repeat
X = top of stack
if X is a terminal or $:
if X == a: pop X; advance input
else error()
else if M[X, a] = X -> Y1 Y2 ... Yk:
pop X; push Yk ... Y2 Y1 (Y1 on top); output the production
else error()
until X == $Grammar (expression grammar without left recursion): E → T E′, E′ → + T E′ | ε, T → F T′, T′ → * F T′ | ε, F → ( E ) | id. FIRST(E) = FIRST(T) = FIRST(F) = { (, id }; FIRST(E′) = { +, ε }; FIRST(T′) = { *, ε }; FOLLOW(E) = FOLLOW(E′) = { ), $ }; FOLLOW(T) = FOLLOW(T′) = { +, ), $ }; FOLLOW(F) = { +, *, ), $ }.
| id | + | * | ( | ) | $ | |
|---|---|---|---|---|---|---|
| E | E→TE′ | E→TE′ | ||||
| E′ | E′→+TE′ | E′→ε | E′→ε | |||
| T | T→FT′ | T→FT′ | ||||
| T′ | T′→ε | T′→*FT′ | T′→ε | T′→ε | ||
| F | F→id | F→(E) |
Parsing id + id: $E → $E′T → $E′T′F → $E′T′id (match id) → $E′T′ → $E′ (T′→ε) → $E′T+ (match +) → $E′T′F → $E′T′id (match id) → $E′T′ → $E′ → $ → accept.
Q3 – (a) CFG and parse tree for ((4−8)*2(7*4)) (b) Structure of a compiler
(a) In the printed expression there is no operator between 2 and (7*4); in arithmetic this means multiplication, so it is read as ((4 − 8) * 2 * (7 * 4)). Grammar:
E -> E + T | E - T | T
T -> T * F | F
F -> ( E ) | digit
digit -> 0 | 1 | ... | 9
E
|
T
|
F
/ | \
( E )
|
T
______|_______
/ | \
T * F
/ | \ / | \
T * F ( E )
| | |
F digit T
/ | \ | / | \
( E ) 2 T * F
/ | \ | |
E - T F digit
| | | |
T F digit 4
| | |
F digit 7
| |
digit 8
|
4Value: (4 − 8) = −4; −4 × 2 = −8; 7 × 4 = 28; −8 × 28 = −224.
(b) See the phases below.
A compiler translates a program in a source language into an equivalent program in a target language and reports errors. It works in two parts: the analysis (front end) breaks the source into pieces, checks it and builds an intermediate representation; the synthesis (back end) builds the target program from that representation.
source program
|
[ Lexical analyzer ] -> tokens
|
[ Syntax analyzer ] -> parse / syntax tree
|
[ Semantic analyzer ] -> annotated tree (type checked)
|
[ Intermediate code gen ] -> three-address code
|
[ Code optimizer ] -> improved intermediate code
|
[ Code generator ] -> target (machine / assembly) code
Symbol table manager and error handler are used by all phases.
Front end (analysis) = first 4 phases; back end (synthesis) = last 2.- Lexical analysis (scanning): groups characters into lexemes and produces tokens such as <id,1> <=> <id,2> <+> <num,60>; removes blanks and comments.
- Syntax analysis (parsing): checks the token stream against the grammar and builds a parse tree / syntax tree.
- Semantic analysis: type checking, declarations before use, type conversions (e.g. inttofloat).
- Intermediate code generation: machine-independent code such as three-address code.
- Code optimization: makes the intermediate code faster/smaller (constant folding, common subexpressions, dead code removal).
- Code generation: chooses instructions and registers for the target machine.
- Symbol table: stores each identifier with its type, scope and location; error handler reports and recovers from errors in every phase.
Q4 – Syntax-directed translation: postfix → infix
Postfix grammar: E → E E op | digit. Each E gets a synthesized attribute t (a string). Parentheses are added so the infix result keeps the same meaning.
E -> E1 E2 + { E.t = "(" || E1.t || "+" || E2.t || ")" }
E -> E1 E2 - { E.t = "(" || E1.t || "-" || E2.t || ")" }
E -> E1 E2 * { E.t = "(" || E1.t || "*" || E2.t || ")" }
E -> E1 E2 / { E.t = "(" || E1.t || "/" || E2.t || ")" }
E -> digit { E.t = digit.lexval }Input 95−2*:
E.t = "((9-5)*2)"
/ | \
E.t = "(9-5)" E.t = "2" *
/ | \ |
E.t="9" E.t="5" - digit 2
| |
digit 9 digit 5Input 952*−:
E.t = "(9-(5*2))"
/ | \
E.t = "9" E.t = "(5*2)" -
| / | \
digit 9 E.t="5" E.t="2" *
| |
digit 5 digit 2Results: 95−2* → ((9−5)*2) = 8, and 952*− → (9−(5*2)) = −1.
Q5 – Minimum-state DFAs
A string matches (a|b)*a(a|b)k when the (k+1)-th symbol from the right end is a. The DFA therefore has to remember the last k+1 symbols, so the minimum DFA has 2k+1 states (all of them are distinguishable). This was checked with a Myhill–Nerode count in Python: 4, 8 and 16 states.
(a) (a|b)*a(a|b) – second symbol from the end is a. States are named by the last two symbols read (start = “bb”, i.e. nothing useful seen). Accepting states: ab and aa.
| State (last two) | on a | on b | Accepting? |
|---|---|---|---|
| → bb (start) | ba | bb | No |
| ba | aa | ab | No |
| aa | aa | ab | Yes |
| ab | ba | bb | Yes |
(b) (a|b)*a(a|b)(a|b) – third symbol from the end is a. 8 states named by the last three symbols; on input c the state xyz moves to yzc. Accepting states: those whose first letter is a.
| State | on a | on b | Accept |
|---|---|---|---|
| → bbb | bba | bbb | No |
| bba | baa | bab | No |
| bab | aba | abb | No |
| baa | aaa | aab | No |
| abb | bba | bbb | Yes |
| aba | baa | bab | Yes |
| aab | aba | abb | Yes |
| aaa | aaa | aab | Yes |
(c) (a|b)*a(a|b)(a|b)(a|b) – fourth symbol from the end is a. Same construction with the last four symbols: 16 states (bbbb … aaaa), start state bbbb, state wxyz goes to xyzc on input c, and the 8 states whose first letter is a are accepting. No two states can be merged, because for two different 4-symbol windows there is a suffix of b’s that brings the differing position to the 4th-from-last place, so one string is accepted and the other is not.
Q6 – DAGs and value numbers
Each node gets a value number; a new node is created only if (op, left, right) is not already in the table. + is left associative.
(a) a + b + (a + b) = ((a + b) + (a + b))
| Value no. | Node |
|---|---|
| 1 | id a |
| 2 | id b |
| 3 | + 1 2 (a + b) |
| 4 | + 3 3 (both children are node 3) |
(b) a + b + a + b = (((a + b) + a) + b)
| Value no. | Node |
|---|---|
| 1 | id a |
| 2 | id b |
| 3 | + 1 2 |
| 4 | + 3 1 |
| 5 | + 4 2 |
(c) a + a + ((a + a + a + (a + a + a + a)))
| Value no. | Node | Meaning |
|---|---|---|
| 1 | id a | a |
| 2 | + 1 1 | a + a (used for the first a + a and inside both inner sums) |
| 3 | + 2 1 | a + a + a |
| 4 | + 3 1 | a + a + a + a |
| 5 | + 3 4 | (a + a + a) + (a + a + a + a) |
| 6 | + 2 5 | whole expression |
(a) +(4) (b) +(5) (c) +(6)
// \ / \ / \
+(3) +(4) \ | +(5)
/ \ / \ \ | / \
a(1) b(2) +(3) a(1) b(2) | | +(4)
/ \ | | / \
a(1) b(2) | +(3) a(1)
| / \
+(2) a(1)
/ \
a(1) a(1)Q7 – a + −(b + c)
(a) Syntax tree
+
/ \
a minus
|
+
/ \
b cThree-address code: t1 = b + c; t2 = minus t1; t3 = a + t2.
(b) Quadruples
| op | arg1 | arg2 | result | |
|---|---|---|---|---|
| (0) | + | b | c | t1 |
| (1) | minus | t1 | t2 | |
| (2) | + | a | t2 | t3 |
(c) Triples
| op | arg1 | arg2 | |
|---|---|---|---|
| (0) | + | b | c |
| (1) | minus | (0) | |
| (2) | + | a | (1) |
(d) Indirect triples – a separate instruction list points to the triples above:
| Instruction | Points to |
|---|---|
| 35 | (0) |
| 36 | (1) |
| 37 | (2) |
