compiler-notes-of-unit-1-2
compiler-notes-of-unit-1-2
Syllabus CO BL
Module –I Introduction to compiling & Lexical Analysis CO-01, CO-02 2
Introduction of Compiler, Major data Structure in compiler, types
of Compiler, Front-end and Back- end of compiler, Compiler
structure: analysis-synthesis model of compilation, various phases of a
compiler, Lexical analysis: Input buffering , Specification &
Recognition of Tokens,Design of a Lexical Analyzer Generator, LEX.
Module –II Syntax Analysis &Syntax Directed Translation CO-02,CO-03, 3
Syntax analysis: CFGs, Top down parsing, Brute force approach,
recursive descent parsing, transformation on the grammars, predictive
parsing, bottom up parsing, operator precedence parsing, LR parsers
(SLR,LALR, LR),Parser generation. Syntax directed definitions:
Construction of Syntax trees, Bottom up evaluation of S-attributed
definition, L-attribute definition, Top down translation, Bottom Up
evaluation of inherited attributes Recursive Evaluation, Analysis of
Syntax directed definition.
Module –III Type Checking & Run Time Environment CO-03 2
Type checking: type system, specification of simple type checker,
equivalence of expression, types, type conversion, overloading of
functions and operations, polymorphic functions. Run time
Environment: storage organization, Storage allocation strategies,
parameter passing, dynamic storage allocation, Symbol table, Error
Detection & Recovery, Ad-Hoc and Systematic Methods.
Module –IV Code Generation CO-04 2
Intermediate code generation: Declarations, Assignment statements,
Boolean expressions, Case statements, Back patching, Procedure calls
Code Generation: Issues in the design of code generator, Basic block
and flow graphs, Register allocation and assignment, DAG
representation of basic blocks, peephole optimization, generating code
from DAG.
Module –V Code Optimization CO-05 2
Introduction to Code optimization: sources of optimization of basic
blocks, loops in flow graphs, dead code elimination, loop
optimization, Introduction to global data flow analysis, Code
Improving transformations ,Data flow analysis of structure flow graph
Symbolic debugging of optimized code.
TEXT BOOKS:
1 C. Siva Ram Murthy & B. S. Manoj: Ad-hoc Wireless Networks, 2nd Edition,
Pearson Education, 2011.
2 Deploying Wireless networks, Andy Wilton, Tim charity, Cambridge university
press
3 Fundamental of Wireless Networking, Ron Price, TMH.
4 3G Wireless Networks, Clint Smity, TMH.
REFERENCES:
1. Ozan K. Tonguz and Gianguigi Ferrari: Ad-hoc Wireless Networks, John Wiley,
2007.
2. Xiuzhen Cheng, Xiao Hung, Ding-Zhu Du: Ad-hoc Wireless Networking, Kluwer
Academic Publishers, 2004.
3. C.K. Toh: Ad-hoc Mobile Wireless Networks- Protocols and Systems, Pearson
Education, 2002.
Module -I
Introduction to Compiling:
1.1 INTRODUCTION OF LANGUAGE PROCESSING SYSTEM
A preprocessor produce input to compilers. They may perform the following functions.
1. Macro processing: A preprocessor may allow a user to define macros that are short hands
for longer constructs.
2. File inclusion: A preprocessor may include header files into the program text.
3. Rational preprocessor: these preprocessors augment older languages with more modern flow-
of- control and data structuring facilities.
4. Language Extensions: These preprocessor attempts to add capabilities to the language by
certain amounts to build-in macro
COMPILER
Compiler is a translator program that translates a program written in (HLL) the source program and
translate it into an equivalent program in (MLL) the target program. As an important part of a
compiler is error showing to the programmer.
Executing a program written n HLL programming language is basically of two parts. the source
program must first be compiled translated into a object program. Then the results object program
is loaded into a memory executed.
ASSEMBLER
Programmers found it difficult to write or read programs in machine language. They begin to use a
mnemonic (symbols) for each machine instruction, which they would subsequently translate into
machine language. Such a mnemonic machine language is now called an assembly language.
Programs known as assembler were written to automate the translation of assembly language in to
machine language. The input to an assembler program is called source program, the output is a
machine language translation (object program).
INTERPRETER
An interpreter is a program that appears to execute a source program as if it were machine language.
Languages such as BASIC, SNOBOL, LISP can be translated using interpreters. JAVA also uses
interpreter. The process of interpretation can be carried out in following phases.
1. Lexical analysis
2. Synatx analysis
3. Semantic analysis
4. Direct Execution
Advantages:
Modification of user program can be easily made and implemented as execution proceeds.
Type of object that denotes a various may change dynamically.
Debugging a program and finding errors is simplified task for a program used for interpretation.
The interpreter for the language makes it machine independent.
Disadvantages:
The execution of the program is slower.
Memory consumption is more.
Once the assembler procedures an object program, that program must be placed into memory and
executed. The assembler could place the object program directly in memory and transfer control to it,
thereby causing the machine language program to be execute. This would waste core by leaving the
assembler in memory while the user’s program was being executed. Also the programmer would
have to retranslate his program with each execution, thus wasting translation time. To over come this
problems of wasted translation time and memory. System programmers developed another
component called loader
“A loader is a program that places programs into memory and prepares them for execution.” It would
be more efficient if subroutines could be translated into object form the loader could”relocate”
directly behind the user’s program. The task of adjusting programs o they may be placed in arbitrary
core locations is called relocation. Relocation loaders perform four functions.
1.2 TRANSLATOR
A translator is a program that takes as input a program written in one language and produces as
output a program in another language. Beside program translation, the translator performs another
very important role, the error-detection. Any violation of d HLL specification would be detected and
reported to the programmers. Important role of translator are:
1 Translating the HLL program input into an equivalent ml program.
2 Providing diagnostic messages wherever the programmer violates specification of the HLL.
Syntax Analysis:-
The second stage of translation is called Syntax analysis or parsing. In this phase expressions,
statements, declarations etc… are identified by using the results of lexical analysis. Syntax analysis is
aided by using techniques based on formal grammar of the programming language.
Code Optimization :-
This is optional phase described to improve the intermediate code so that the output runs faster and
takes less space.
Code Generation:-
The last phase of translation is code generation. A number of optimizations to reduce the length of
machine language program are carried out during this phase. The output of the code generator is
the machine language program of the specified computer.
Table Management (or) Book-keeping:- This is the portion to keep the names used by the
program and records essential information about each. The data structure used to record this
information called a ‘Symbol Table’.
Error Handlers:-
It is invoked when a flaw error in the source program is detected. The output of LA is a stream of
tokens, which is passed to the next phase, the syntax analyzer or parser. The SA groups the tokens
together into syntactic structure called as expression. Expression may further be combined to form
statements. The syntactic structure can be regarded as a tree whose leaves are the token called as
parse trees.
The parser has two functions. It checks if the tokens from lexical analyzer, occur in pattern that are
permitted by the specification for the source language. It also imposes on tokens a tree-like structure
that is used by the sub-sequent phases of the compiler.
Example, if a program contains the expression A+/B after lexical analysis this expression might
appear to the syntax analyzer as the token sequence id+/id. On seeing the /, the syntax analyzer
should detect an error situation, because the presence of these two adjacent binary operators violates
the formulations rule of an expression. Syntax analysis is to make explicit the hierarchical structure
of the incoming token stream by identifying which parts of the token stream should be grouped.
Code Optimization
This is optional phase described to improve the intermediate code so that the output runs faster and
takes less space. Its output is another intermediate code program that does the some job as the
original, but in a way that saves time and / or spaces.
a. Local Optimization:-
There are local transformations that can be applied to a program to make an improvement.
For example,
If A > B goto L2
Goto L3
L2 :
T1 := B + C
A := T1 + D
E := T1 + F
Take this advantage of the common sub-expressions B + C.
b. Loop Optimization:-
Another important source of optimization concerns about increasing the speed of loops. A
typical loop improvement is to move a computation that produces the same result each
time around the loop to a point, in the program just before the loop is entered.
Code generator :-
Code Generator produces the object code by deciding on the memory locations for data, selecting
code to access each datum and selecting the registers in which each computation is to be done. Many
computers have only a few high speed registers in which computations can be performed quickly. A
good code generator would attempt to utilize registers as efficiently as possible.
Error Handing :-
One of the most important functions of a compiler is the detection and reporting of errors in the
source program. The error message should allow the programmer to determine exactly where the
errors have occurred. Errors may occur in all or the phases of a compiler.
Whenever a phase of the compiler discovers an error, it must report the error to the error handler,
which issues an appropriate diagnostic msg. Both of the table-management and error-Handling
routines interact with all phases of the compiler.
Example:
2.1 OVERVIEW
Language Definition
o Appearance of programming language :
Vocabulary : Regular expression
Syntax : Backus-Naur Form(BNF) or Context Free Form(CFG)
o Semantics : Informal language or some examples
list → list +
digit list → list -
digit list → digit
digit → 0|1|2|3|4|5|6|7|8|9
o list, digit : Grammar variables, Grammar symbols
o 0,1,2,3,4,5,6,7,8,9,-,+ : Tokens, Terminal symbols
Convention specifying grammar
o Terminal symbols : bold face string if, num, id
o Nonterminal symbol, grammar symbol : italicized names, list, digit ,A,B
Grammar G=(N,T,P,S)
o N : a set of nonterminal symbols
o T : a set of terminal symbols, tokens
o P : a set of production rules
o S : a start symbol, S∈N
o
Grammar G for a language L={9-5+2, 3-1, ...}
o G=(N,T,P,S)
N={list,digit}
T={0,1,2,3,4,5,6,7,8,9,-,+}
P : list -> list + digit
list -> list -
digit list ->
digit
digit -> 0|1|2|3|4|5|6|7|8|9
S=list
Parse Tree
o Example G:
list -> list + digit | list - digit | digit
digit -> 0|1|2|3|4|5|6|7|8|9
left most derivation for 9-5+2,
list ⇒ list+digit ⇒ list-digit+digit ⇒ digit-digit+digit ⇒ 9-digit+digit
⇒ 9-5+digit ⇒ 9-5+2
right most derivation for 9-5+2,
list ⇒ list+digit ⇒ list+2 ⇒ list-digit+2 ⇒ list-5+2
⇒ digit-5+2 ⇒ 9-5+2
Fig 2.2. Parse tree for 9-5+2 according to the grammar in Example
Ambiguity
A grammar is said to be ambiguous if the grammar has more than one parse tree for
a given string of tokens.
Example 2.5. Suppose a grammar G that can not distinguish between lists and digits as
in Example 2.1.
G : string → string + string | string - string |0|1|2|3|4|5|6|7|8|9
Associativity of operator
A operator is said to be left associative if an operand with operators on both sides of it is
taken by the operator to its left.
eg) 9+5+2≡(9+5)+2, a=b=c≡a=(b=c)
Left Associative Grammar :
list → list + digit | list - digit
digit →0|1|…|9
Right Associative Grammar :
right → letter = right | letter
letter → a|b|…|z
Precedence of operators
We say that a operator(*) has higher precedence than other operator(+) if the operator(*) takes
operands before other operator(+) does.
ex. 9+5*2≡9+(5*2), 9*5+2≡(9*5)+2
left associative operators : + , - , * , /
right associative operators : = , **
Syntax of statements
o stmt → id = expr ;
| if ( expr ) stmt ;
| if ( expr ) stmt else stmt ;
| while ( expr ) stmt ;
expr → expr + term | expr - term | term
term → term * factor | term / factor | factor
factor → digit | ( expr )
digit → 0 | 1 | … | 9
2.3 SYNTAX-DIRECTED TRANSLATION(SDT)
A formalism for specifying translations for programming language constructs.
( attributes of a construct: type, string, location, etc)
Syntax directed definition(SDD) for the translation of constructs
Syntax directed translation scheme(SDTS) for specifying translation
Postfix notation for an expression E
If E is a variable or constant, then the postfix nation for E is E itself ( E.t≡E ).
if E is an expression of the form E1 op E2 where op is a binary operator
o E1' is the postfix of E1,
o E2' is the postfix of E2
o then E1' E2' op is the postfix for E1 op E2
if E is (E1), and E1' is a postfix
then E1' is the postfix for E
eg) 9-5+2⇒95-2+
9 - (5 + 2) ⇒9 5 2 + -
Fig 2.7. Example of a depth-first traversal of a tree. Fig 2.8. An extra leaf is constructed for a semantic action.
Example 2.8.
SDD vs. SDTS for infix to postfix translation.
2.4 PARSING
if token string x ∈ L(G), then parse tree
else error message
Top-Down parsing
1. At node n labeled with nonterminal A, select one of the productions whose left part is
A and construct children of node n with the symbols on the right side of that
production.
2. Find the next node at which a sub-tree is to be
constructed. ex. G: type → simple
|↑id
|array [ simple ] of type
simple → integer
|char
|num dotdot num
Fig 2.10. Top-down parsing while scanning the input from left to right.
G : { S->aSb | c | ab }
According to topdown parsing procedure, acb , aabb∈L(G)?
S/acb⇒aSb/acb⇒aSb/acb⇒aaSbb/acb ⇒ X
(S→aSb) move (S→aSb) backtracking
⇒aSb/acb⇒acb/acb⇒acb/acb⇒acb/acb
(s→c) move move
so, acb∈ L(G)
Is is finished in 7 steps including one backtracking.
S/aabb⇒aSb/aabb⇒aSb/aabb⇒aaSbb/aabb⇒aaSbb/aabb⇒aaaSbbb/aabb ⇒ X
(S→aSb) move (S→aSb) move (S→aSb) backtracking
⇒aaSbb/aabb⇒aacbb/aabb ⇒ X
(S→c) backtracking
⇒aaSbb/aabb⇒aaabbb/aabb⇒ X
(S→ab) backtracking
⇒aaSbb/aabb⇒ X
backtracking
⇒aSb/aabb⇒acb/aabb
(S→c) bactracking
⇒aSb/aabb⇒aabb/aabb⇒aabb/aabb⇒aabb/aabb⇒aaba/aabb
(S→ab) move move move
so, aabb∈L(G)
but process is too difficult. It needs 18 steps including 5 backtrackings.
Left Factoring
If a grammar contains two productions of
form S→ aα and S → aβ
it is not suitable for top down parsing without backtracking. Troubles of this form can
sometimes be removed from the grammar by a technique called the left factoring.
In the left factoring, we replace { S→ aα, S→ aβ } by
{ S → aS', S'→ α, S'→ β } cf. S→ a(α|β)
(Hopefully α and β start with different symbols)
left factoring for G { S→aSb | c | ab }
S→aS' | c cf. S(=aSb | ab | c = a ( Sb | b) | c ) → a S' | c
S'→Sb | b
A concrete example:
<stmt> → IF <boolean> THEN <stmt> |
IF <boolean> THEN <stmt> ELSE
<stmt> is transformed into
<stmt>→ IF <boolean> THEN <stmt> S'
S' → ELSE <stmt> | ε
Example,
ofor G1 : { S→aSb | c | ab }
According to predictive parsing procedure, acb , aabb∈L(G)?
S/aabb⇒ unable to choose { S→aSb, S→ab ?}
o According for the feft factored gtrammar G1, acb ,
aabb∈L(G)? G1 : { S→aS'|c S'→Sb|b} <= {S=a(Sb|b) | c }
o S/acb⇒aS'/acb⇒aS'/acb ⇒ aSb/acb ⇒ acb/acb ⇒ acb/acb⇒ acb/acb
(S→aS') move (S'→Sb⇒aS'b) (S'→c) move move
so, acb∈ L(G)
It needs only 6 steps whithout any backtracking.
cf. General top-down parsing needs 7 steps and I backtracking.
o S/aabb⇒aS'/aabb⇒aS'/aabb⇒aSb/aabb⇒aaS'b/aabb⇒aaS'b/aabb⇒aabb/aabb⇒ ⇒
(S→aS') move (S'→Sb⇒aS'b) (S'→aS') move (S'→b) move move
so, aabb∈L(G)
but, process is finished in 8 steps without any backtracking.
cf. General top-down parsing needs 18 steps including 5 backtrackings.
Left Recursion
A grammar is left recursive iff it contains a nonterminal A, such
that A⇒+ Aα, where is any string.
o Grammar {S→ Sα | c} is left recursive because of S⇒Sα
o Grammar {S→ Aα, A→ Sb | c} is also left recursive because of S⇒Aα⇒ Sbα
If a grammar is left recursive, you cannot build a predictive top down parser for it.
1) If a parser is trying to match S & S→Sα, it has no idea how many times S must
be applied
2) Given a left recursive grammar, it is always possible to find another grammar
that generates the same language and is not left recursive.
3) The resulting grammar might or might not be suitable for RDP.
Example :
A → Aα∣β
=>
A → βR
R → αR | ε
Result: 9 5 – 2 +
Fig 2.14. Function for the nonterminals expr, rest, and term.
0
1 id count
2 id increment
3
Keywords are reserved, i.e., they cannot be used as identifiers.
Fig 2.15. Inserting a lexical analyzer between the input and the parser
A Lexical Analyzer
c=getchcar(); ungetc(c,stdin);
token representation
o #define NUM 256
Function lexan()
eg) input string 76 + a
input , output(returned value)
76 NUM, tokenval=76 (integer)
+ +
A id , tokeval="a"
...
factor() {
if(lookahead == '(' ) {
match('('); exor(); match(')');
} else if (lookahead == NUM) {
printf(" %f ",tokenval); match(NUM);
} else error();
}
The implementation of function lexan
1) #include <stdio.h>
2) #include <ctype.h>
3) int lino = 1;
4) int tokenval = NONE;
5) int lexan() {
6) int t;
7) while(1) {
8) t = getchar();
9) if ( t==' ' || t=='\t' ) ;
10) else if ( t=='\n' ) lineno +=1;
11) else if (isdigit(t)) {
12) tokenval = t -'0';
13) t = getchar();
14) while ( isdigit(t)) {
15) tokenval = tokenval*10 + t - '0';
16) t =getchar();
17) }
18) ungetc(t,stdin);
19) retunr NUM;
20) } else {
21) tokenval = NONE;
22) return t;
23) }
24) }
25) }
insert("mod", mod)
2. while parsing
whenever an identifier s is encountered.
if (lookup(s)'s token in {keywords} ) s is for a keyword; else s is for a identifier;
example
o preset
insert("div",div);
insert("mod",mod);
o while parsing
lookup("count")=>0 insert("count",id);
lookup("i") =>0 insert("i",id);
lookup("i") =>4, id
llokup("div")=>1,div
Stack Manipulation
Some instructions for assignment operation
o push v : push v onto the stack.
o rvalue a : push the contents of data location a.
o lvalue a : push the address of data location a.
o pop : throw away the top element of the stack.
o := : assignment for the top 2 elements of the stack.
o copy : push a copy of the top element of the stack.
Translation of Expressions
Infix expression(IE) → SDD/SDTS → Abstact macine codes(ASC) of postfix expression for
stack machine evaluation.
eg)
o IE: a + b, (⇒PE: a b + ) ⇒ IC: rvalue a
rvalue b
+
o day := (1461 * y) div 4 + (153 * m + 2) div 5 + d
(⇒ day 1462 y * 4 div 153 m * 2 + 5 div + d +
:=)
⇒1) lvalue day 6) div 11) push 5 16) :=
2) push 1461 7) push 153 12) div
3) rvalue y 8) rvalue m 13) +
4) * 9) push 2 14) rvalue d
5) push 4 10) + 15) +
A translation scheme for assignment-statement into abstract astack machine code e can
be expressed formally In the form as follows:
stmt → id := expr
{ stmt.t := 'lvalue' || id.lexeme || expr.t || ':=' }
eg) day :=a+b ⇒ lvalue day rvalue a rvalue b + :=
Control Flow
3 types of jump instructions :
o Absolute target location
o Relative target location( distance :Current ↔Target)
o Symbolic target location(i.e. the machine supports labels)
Control-flow instructions:
o label a: the jump's target a
o goto a: the next instruction is taken from statement labeled a
o gofalse a: pop the top & if it is 0 then jump to a
o gotrue a: pop the top & if it is nonzero then jump to a
o halt : stop execution
Translation of Statements
Translation scheme for translation if-statement into abstract machine
code. stmt → if expr then stmt1
{ out := newlabel1)
stmt.t := expr.t || 'gofalse' out || stmt1.t || 'label' out }
Emitting a Translation
Semantic Action(Tranaslation Scheme):
1. stmt → if
expr { out := newlabel; emit('gofalse', out) }
then
stmt1 { emit('label', out) }
2. stmt → id { emit('lvalue', id.lexeme) }
:=
expr { emit(':=') }
3. stmt → i
expr { out := newlabel; emit('gofalse', out) }
then
stmt1 { emit('label', out) ; out1 := newlabel; emit('goto', out`1); }
else
stmt2 { emit('label', out1) ; }
if(expr==false) goto out
stmt1 goto out1
out : stmt2
out1:
Implementation
procedure stmt()
var test,out:integer;
begin
o if lookahead = id then begin
emit('lvalue',tokenval);
match(id); match(':='); expr();
emit(':=');
o end
o else if lookahead = 'if' then begin
match('if');
expr();
out := newlabel();
emit('gofalse', out);
match('then');
stmt;
emit('label', out)
o end
o else error();
end
o gofalse OUT2
o code for S
o label OUT2
Exercise: How about if E1 and E2 then
S;
o if E1 and E2 then S1 else S2;
SDTS
|| ← left recursion elimination
New SDTS
Fig 2.20. Specification for infix to postfix translator & syntax directed translation scheme after
eliminating left-recursion.
3. Lexical Analysis:
Upon receiving a ‘get next token’ command form the parser, the lexical analyzer reads
the input character until it can identify the next token. The LA return to the parser representation
for the token it has found. The representation will be an integer code, if the token is a simple
construct such as parenthesis, comma or colon.
LA may also perform certain secondary tasks as the user interface. One such task is
striping out from the source program the commands and white spaces in the form of blank, tab
and new line characters. Another is correlating error message from the compiler with the source
program.
Here are the rules that define the regular expression over alphabet .
is a regular expression denoting { € }, that is, the language containing only the empty
string.
For each ‘a’ in Σ, is a regular expression denoting { a }, the language with only one string
consisting of the single symbol ‘a’ .
If R and S are regular expressions, then
Recognition of tokens:
We learn how to express pattern using regular expressions. Now, we must study how to take the
patterns for all the needed tokens and build a piece of code that examins the input string and
finds a prefix that is a lexeme matching one of the patterns.
Stmt →if expr then stmt
| If expr then else stmt
|є
Expr →term relop term
| term
Term →id
|number
For relop ,we use the comparison operations of languages like Pascal or SQL where = is “equals”
and < > is “not equals” because it presents an interesting structure of lexemes.
The terminal of grammar, which are if, then , else, relop ,id and numbers are the names of tokens
as far as the lexical analyzer is concerned, the patterns for the tokens are described using regular
definitions.
digit → [0,9]
digits →digit+
number →digit(.digit)?(e.[+-]?digits)?
letter → [A-Z,a-z]
id →letter(letter/digit)*
if → if
then →then
else →else
relop →< | > |<= | >= | = = | < >
In addition, we assign the lexical analyzer the job stripping out white space, by recognizing the
“token” we defined by:
WS → (blank/tab/newline)+
Here, blank, tab and newline are abstract symbols that we use to express the ASCII characters of
the same names. Token ws is different from the other tokens in that ,when we recognize it, we do
not return it to parser ,but rather restart the lexical analysis from the character that follows the
white space . It is the following token that gets returned to the parser.
The above TD for an identifier, defined to be a letter followed by any no of letters or digits.A
sequence of transition diagram can be converted into program to look for the tokens specified
by the diagrams. Each state gets a segment of code.
Example:
N(r1) and N(r2) are NFAs for regular expressions r1 and r2.
Example:
For a RE (a|b) * a, the NFA construction is shown below.
We can generalise both these functions to apply to sets of states by taking the union of the
application to individual states.
p1 {action 1}
p2 {action 2}
p3 {action 3}
……
……
Where, each p is a regular expression and each action is a program fragment describing
what action the lexical analyzer should take when a pattern p matches a lexeme. In Lex
the actions are written in C.
3. The third section holds whatever auxiliary procedures are needed by the
actions.Alternatively these procedures can be compiled separately and loaded with the
lexical analyzer.
Note: You can refer to a sample lex program given in page no. 109 of chapter 3 of the book:
Compilers: Principles, Techniques, and Tools by Aho, Sethi & Ullman for more clarity.
The LA scans the characters of the source pgm one at a time to discover tokens. Because of large
amount of time can be consumed scanning characters, specialized buffering techniques have been
developed to reduce the amount of overhead required to process an input character.
Buffering techniques:
1. Buffer pairs
2. Sentinels
The lexical analyzer scans the characters of the source program one a t a time to discover tokens.
Often, however, many characters beyond the next token many have to be examined before the
next token itself can be determined. For this and other reasons, it is desirable for thelexical
analyzer to read its input from an input buffer. Figure shows a buffer divided into two haves of,
say 100 characters each. One pointer marks the beginning of the token being discovered. A look
ahead pointer scans ahead of the beginning point, until the token is discovered .we view the
position of each pointer as being between the character last read and thecharacter next to be read.
In practice each buffering scheme adopts one convention either apointer is at the symbol last
read or the symbol it is ready to read.
Token beginnings look ahead pointerThe distance which the lookahead pointer may have to
travel past the actual token may belarge. For example, in a PL/I program we may see:
SYNTAX ANALYSIS
Ambiguity:
A grammar that produces more than one parse for some sentence is said to be ambiguous
grammar.
The sentence id+id*id has the following two distinct leftmost derivations:
E → E+ E E → E* E
E → id + E E→E+E*E
E → id + E * E E → id + E * E
E → id + id * E E → id + id * E
E → id + id * id E → id + id * id
Example:
To disambiguate the grammar E → E+E | E*E | E^E | id | (E), we can use precedence of
operators as follows:
^ (right to left)
/,* (left to right)
-,+ (left to right)
We get the following unambiguous grammar:
E → E+T | T
T → T*F | F
F → G^F | G
G → id | (E)
Consider this example, G: stmt → if expr then stmt |if expr then stmt elsestmt | other
This grammar is ambiguous since the string if E1 then if E2 then S1 else S2 has the
following
Left factoring:
Left factoring is a grammar transformation that is useful for producing a grammar suitable for
predictive parsing. When it is not clear which of two alternative productions to use to expand
a non-terminal A, we can rewrite the A-productions to defer the decision until we have seen
enough of the input to make the right choice.
If there is any production A → αβ1 | αβ2 , it can be rewritten as
A → αA’
A’ → β1 | β2
Consider the grammar , G : S→iEtS | iEtSeS | a
E→b
Left factored, this grammar becomes
S → iEtSS’ | a
S’ → eS | ε
E→b
TOP-DOWN PARSING
It can be viewed as an attempt to find a left-most derivation for an input string or an
attempt to construct a parse tree for the input starting from the root to the leaves.
Types of top-down parsing :
1. Recursive descent parsing
2. Predictive parsing
1. RECURSIVE DESCENT PARSING
Recursive descent parsing is one of the top-down parsing techniques that uses a set of
recursive procedures to scan its input.
This parsing method may involve backtracking, that is, making repeated scans of the
input.
Example for backtracking :
Consider the grammar G : S→cAd
A → ab | a
and the input string w=cad.
The parse tree can be constructed using the following top-down approach :
Step1:
Initially create a tree with single node labeled S. An input pointer points to ‘c’, the first
symbol of w. Expand the tree with the production of S.
Step2:
The leftmost leaf ‘c’ matches the first symbol of w, so advance the input pointer to the second
symbol of w ‘a’ and consider the next leaf ‘A’. Expand A using the first alternative.
Step3:
The second symbol ‘a’ of w also matches with second leaf of tree. So advance the input
pointer to third symbol of w ‘d’. But the third leaf of tree is b which does not match with the
input symbol d.
Hence discard the chosen production and reset the pointer to second position. This is called
backtracking.
Step4:
Now try the second alternative for A.
Procedure TPRIME( )
begin
If input_symbol=’*’ then
ADVANCE( );
F( );
TPRIME( );
end
Procedure F( )
begin
If input-symbol=’id’ then
ADVANCE( );
else if input-symbol=’(‘ then
ADVANCE( );
E( );
else if input-symbol=’)’ then
ADVANCE( );
end
else ERROR( );
Stack implementation:
PROCEDURE INPUT STRING
E( ) id+id*id
T( ) id+id*id
F( ) id+id*id
ADVANCE( ) id id*id
TPRIME( ) id id*id
EPRIME( ) id id*id
ADVANCE( ) id+id*id
T( ) id+id*id
F( ) id+id*id
ADVANCE( ) id+id*id
TPRIME( ) id+id*id
ADVANCE( ) id+id*id
F( ) id+id*id
ADVANCE( ) id+id*id
TPRIME( ) id+id*id
2. PREDICTIVE PARSING
Predictive parsing is a special case of recursive descent parsing where no
backtracking is required.
The key problem of predictive parsing is to determine the production to be applied
for a non-terminal in case of alternatives.
Non-recursive predictive parser
The table-driven predictive parser has an input buffer, stack, a parsing table and an output
stream.
Input buffer:
It consists of strings to be parsed, followed by $ to indicate the end of the input string.
Stack:
It contains a sequence of grammar symbols preceded by $ to indicate the bottom of the stack.
Initially, the stack contains the start symbol on top of $.
Parsing table:
It is a two-dimensional array M[A, a], where ‘A’ is a non-terminal and ‘a’ is a terminal.
Predictive parsing program:
The parser is controlled by a program that considers X, the symbol on top of stack, and a, the
current input symbol. These two symbols determine the parser action. There are three
possibilities:
1. If X = a = $, the parser halts and announces successful completion of parsing.
2. If X = a ≠ $, the parser pops X off the stack and advances the input pointer to
the next input symbol.
3. If X is a non-terminal , the program consults entry M[X, a] of the parsing table
M. This entry will either be an X-production of the grammar or an error entry.
FOLLOW(T) = { +, $, ) }
FOLLOW(T’) = { +, $, ) }
FOLLOW(F) = {+, * , $ , ) }
LL(1) grammar:
The parsing table entries are single entries. So each location has not more than one entry.
This type of grammar is called LL(1) grammar.
Consider this following grammar:
S → iEtS | iEtSeS | a
E→b
Since there are more than one production, the grammar is not LL(1) grammar.
Actions performed in predictive parsing:
1. Shift
2. Reduce
3. Accept
4. Error
Implementation of predictive parser:
1. Elimination of left recursion, left factoring and ambiguous grammar.
2. Construct FIRST() and FOLLOW() for all non-terminals.
3. Construct predictive parsing table.
4. Parse the given input string using stack and parsing table.
BOTTOM-UP PARSING
Constructing a parse tree for an input string beginning at the leaves and going towards the
root is called bottom-up parsing.
A general type of bottom-up parser is a shift-reduce parser.
SHIFT-REDUCE PARSING
Shift-reduce parsing is a type of bottom-up parsing that attempts to construct a parse tree for
an input string beginning at the leaves (the bottom) and working up towards the root (the
top).
Example:
Consider the grammar:
S → aABe
A → Abc | b
B→d
The sentence to be recognized is abbcde.
abbcde (A → b) S→ aABe
aAbcde (A → Abc) → aAde
aAde (B → d) → aAbcde
aABe(S → aABe) → abbcde
S
The reductions trace out the right-most derivation in reverse.
Handles:
A handle of a string is a substring that matches the right side of a production, and whose
reduction to the non-terminal on the left side of the production represents one step along the
reverse of a rightmost derivation.
Example:
E → E+E
E → E*E
E → (E)
E → id
E →E+E
→ E+E*E
→ E+E*id3
→ E+id2*id3
→id 1+id2*id3
Handle pruning:
$E +id2*id3 $ shift
$ E+ id2*id3 $ shift
$ E+E*E $ reduce by E→ E *E
$E $ accept
2. Reduce-reduce conflict: The parser cannot decide which of several reductions to make.
1. Shift-reduce conflict:
Example:
2. Reduce-reduce conflict:
M → R+R | R+c | R
R→c
and input c+c
$c +c $ Reduce by $c +c $ Reduce by
R→c R→c
$R +c $ Shift $R +c $ Shift
$ R+ c$ Shift $ R+ c$ Shift
Viable prefixes:
➢ a is a viable prefix of the grammar if there iswsuch that awis a right sentinel form.
➢ The set of prefixes of right sentinel forms that can appear on the stack of a shift-reduce parser
are called viable prefixes.
➢ The set of viable prefixes is a regular language.
OPERATOR-PRECEDENCE PARSING
Operator precedence parser can be constructed from a grammar called Operator-grammar. These
grammars have the property that no production on right side is ε or has two adjacent non-
terminals.
Example:
E → EAE | (E) | -E | id
A→+|-|*|/|↑
Since the right side EAE has three consecutive non-terminals, the grammar can be written as
follows:
Also make
( = ) , (< . ( , ) . >) , (< .
id , id . >) , $< .
id , id . >$ , $< .
( , ) . >$
Example:
E → E+E | E-E | E*E | E/E | E↑E | (E) | -E | id is given in the following table assuming
.
(9)else ifa >bthen /*reduce*/
(10)repeat
(11) pop the stack
.
(12)untilthe top stack terminal is related by <
to the terminal most recently popped
(13)elseerror( )
end
Example:
Consider the grammar E → E+E | E-E | E*E | E/E | E↑E | (E) | id. Input string isid+id*id.The
implementation is as follows:
LR PARSERS
An efficient bottom-up syntax analysis technique that can be used to parse a large class of
CFG is called LR(k) parsing. The ‘L’ is for left-to-right scanning of the input, the ‘R’ for
constructing a rightmost derivation in reverse, and the ‘k’ for the number of input symbols.
When ‘k’ is omitted, it is assumed to be 1.
Advantages of LR parsing:
✓ It recognizes virtually all programming language constructs for which CFG can be
written.
✓ It is an efficient non-backtracking shift-reduce parsing method.
✓ A grammar that can be parsed using LR method is a proper superset of a grammar that
can be parsed with predictive parser.
✓ It detects a syntactic error as soon as possible.
Drawbacks of LR method:
It is too much of work to construct a LR parser by hand for a programming language
grammar. A specialized tool, called a LR parser generator, is needed. Example: YACC.
INPUT a1 ai an $
… …
STACK
It consists of : an input, an output, a stack, a driver program, and a parsing table that has two
parts (actionandgoto).
➢ The parsing program reads characters from an input buffer one at a time.
➢ The program uses a stack to store a string of the form s 0 X1s1X2s2…Xmsm, where sm is on
top. Each Xi is a grammar symbol and each si is a state.
Action: The parsing program determines s m, the state currently on top of stack, and ai, the
current input symbol. It then consultsaction[s m,ai] in the action table which can have one of four
values :
Goto: The function goto takes a state and grammar symbol as arguments and produces a state.
LR Parsing algorithm:
Method: Initially, the parser has s 0 on its stack, where s0 is the initial state, andw$ in the input
buffer. The parser then executes the following program :
LR(O) items:
AnLR(O) itemof a grammar G is a production of G with a dot at some position of the
right side. For example, production A → XYZ yields the four items :
A →.XYZ
A → X.YZ
A → XY.Z
A → XYZ.
Closure operation:
If I is a set of items for a grammar G, then closure(I) is the set of items constructed from I
by the two rules:
Goto operation:
Goto(I, X) is defined to be the closure of the set of all items [A→ aX . β] such that
[A→ a . Xβ] is in I.
If any conflicting actions are generated by the above rules, we say grammar is not SLR(1).
3. Thegototransitions for stateiare constructed for all non-terminals A using the rule:
Ifgoto(I i,A) = Ij, thengoto[i,A] =j.
4. All entries not defined by rules (2) and (3) are made “error”
5. The initial state of the parser is the one constructed from the set of items containing
[S’→.S].
I0 : E’ →.E
E →.E + T
E →.T
T →.T * F
T →.F
F →.(E)
F →.id
GOTO ( I0 , E) GOTO ( I4 , id )
I1 : E’ → E. I5 : F → id.
E → E.+ T
GOTO ( I6 , T )
GOTO ( I0 , T) I9 : E → E + T.
I2 : E → T. T → T.* F
T → T.* F
GOTO ( I6 , F )
GOTO ( I0 , F) I3 : T → F.
I3 : T → F.
GOTO ( I6 , ( )
I4 : F → (.E )
GOTO ( I4 , T) GOTO ( I9 , *)
I2 : E →T. I7 : T → T *.F
T → T.* F F →.( E )
F →.id
GOTO ( I4 , F)
I3 : T → F.
GOTO ( I4 , ( )
I4 : F → (.E)
E →.E + T E →.T
T →.T * F T →.F
F →.(E)
F → id
FOLLOW (E) = { $ , ) , +)
FOLLOW (T) = { $ , + , ) , * }
FOOLOW (F) = { * , + , ) , $ }
ACTION GOTO
id + * ( ) $ E T F
IO s5 s4 1 2 3
I1 s6 ACC
I2 r2 s7 r2 r2
I3 r4 r4 r4 r4
I4 s5 s4 8 2 3
I5 r6 r6 r6 r6
I6 s5 s4 9 3
I7 s5 s4 10
I8 s6 s11
I9 r1 s7 r1 r1
I1O r3 r3 r3 r3
I11 r5 r5 r5 r5
Stack implementation:
0 id + id * id $ GOTO ( I0 , id ) = s5 ;shift
0F3 + id * id $ GOTO ( I0 , F ) = 3
GOTO ( I3 , + ) = r4 ;reduceby T → F
0T2 + id * id $ GOTO ( I0 , T ) = 2
GOTO ( I2 , + ) = r2 ;reduceby E → T
0E1 + id * id $ GOTO ( I0 , E ) = 1
GOTO ( I1 , + ) = s6 ;shift
0 E 1 + 6 id 5 * id $ GOTO ( I5 , * ) = r6 ;reduceby F → id
0E1+6F3 * id $ GOTO ( I6 , F ) = 3
GOTO ( I3 , * ) = r4 ;reduceby T → F
0E1+6T9 * id $ GOTO ( I6 , T ) = 9
GOTO ( I9 , * ) = s7 ;shift
0 E 1 + 6 T 9 * 7 id 5 $ GOTO ( I5 , $ ) = r6 ;reduceby F → id
0 E 1 + 6 T 9 * 7 F 10 $ GOTO ( I7 , F ) = 10
GOTO ( I10 , $ ) = r3 ;reduceby T → T * F
0E1+6T9 $ GOTO ( I6 , T ) = 9
GOTO ( I9 , $ ) = r1 ;reduceby E → E + T
0E1 $ GOTO ( I0 , E ) = 1
GOTO ( I1 , $ ) =accept
INTRODUCTION
The front end translates a source program into an intermediate representation from
which the back end generates target code.
1. Retargeting is facilitated. That is, a compiler for a different machine can be created
by attaching a back end for the new machine to an existing front end.
INTERMEDIATE LANGUAGES
Syntax tree
Postfix notation
The semantic rules for generating three-address code from common programming language
constructs are similar to those for constructing syntax trees or for generating postfix notation.
Graphical Representations:
Syntax tree:
A syntax tree depicts the natural hierarchical structure of a source program. Adag
(Directed Acyclic Graph)gives the same information but in a more compact way because
common subexpressions are identified. A syntax tree and dag for the assignment statementa : =
b * - c + b * - care as follows:
assign assign
a + a +
* * *
b uminus b uminus b uminus
c c c
Postfix notation:
Syntax-directed definition:
Syntax trees for assignment statements are produced by the syntax-directed definition.
Non-terminal S generates an assignment statement. The two binary operators + and * are
examples of the full operator set in a typical language. Operator associativities and precedences
are the usual ones, even though they have not been put into the grammar. This definition
constructs the tree from the input a : = b * - c + b* - c.
The tokenidhas an attributeplacethat points to the symbol-table entry for the identifier.
A symbol-table entry can be found from an attributeid.name, representing the lexeme associated
with that occurrence ofid.If the lexical analyzer holds all lexemes in a single array of
characters, then attributenamemight be the index of the first character of the lexeme.
Two representations of the syntax tree are as follows. In (a) each node is represented as a
record with a field for its operator and additional fields for pointers to its children. In (b), nodes
are allocated from an array of records and the index or position of the node serves as the pointer
to the node. All the nodes in the syntax tree can be visited by following pointers, starting from
the root at position 10.
aaaaaaaaaaaaa
assign
0 id b
1 id c
id a
2
2 uminus 1
3 * 0 2
+
4 id b
5 id c
*
*
6 uminus 5
id b id b 7 * 4 6
uminus uminus 8 + 3 7
id a
9
id c id c
assign 9 8
10
(b)
(a)
Three-Address Code:
x : = yopz
t1 : = y * z
t2 : = x + t1
The use of names for the intermediate values computed by a program allows three-
address code to be easily rearranged – unlike postfix notation.
Three-address code corresponding to the syntax tree and dag given above
t1 : = - c t1 : = -c
t2 : = b * t1 t2 : = b * t1
t3 : = - c t5 : = t2 + t2
t4 : = b * t3 a : = t5
t5 : = t2 + t4
a : = t5
(a) Code for the syntax tree (b) Code for the dag
The reason for the term “three-address code” is that each statement usually contains three
addresses, two for the operands and one for the result.
2. Assignment instructions of the formx : =opy, whereopis a unary operation. Essential unary
operations include unary minus, logical negation, shift operators, and conversion operators
that, for example, convert a fixed-point number to a floating-point number.
3.Copy statementsof the formx : = ywhere the value ofyis assigned tox.
4. The unconditional jump goto L. The three-address statement with label L is the next to be
executed.
5. Conditional jumps such asifx relop ygoto L. This instruction applies a relational operator (
<, =, >=, etc. ) toxandy, and executes the statement with label L next ifxstands in relation
relop to y. If not, the three-address statement following ifx relop ygoto L is executed next,
as in the usual sequence.
6.param xandcall p, nfor procedure calls andreturn y, where y representing a returned value
is optional. For example,
param x1
param x2
...
param xn
call p,n
generated as part of a call of the procedure p(x1, x2, …. ,xn ).
When three-address code is generated, temporary names are made up for the interior
nodes of a syntax tree. For example,id : =Econsists of code to evaluateEinto some temporary
t, followed by the assignmentid.place: =t.
E E E1 + E.place := newtemp;
E.code := E1.code||E 2.code||gen(E.place ‘:=’ E 1.place ‘+’ E2.place)
E2
E.place := newtemp;
E.code := E1.code || E2.code || gen(E.place ‘:=’ E1.place ‘*’ E2.place)
E E1 *
E.place := newtemp;
E.code := E1.code || gen(E.place ‘:=’ ‘uminus’ E1.place)
E2 E - E1
E.place : =
E1.place; E.code :
E ( E1 )
= E1.code
E.place : =
E id
id.place; E.code :
=‘‘
S.begin:
E.code
S1.code
goto S.begin
S.after:. . .
S whileEdoS 1 S.begin :=
newlabel; S.after :=
newlabel;
S.code := gen(S.begin ‘:’)
|| E.code ||
gen ( ‘if’ E.place ‘=’ ‘0’ ‘goto’
S.after)|| S1.code ||
gen ( ‘goto’ S.begin)
|| gen ( S.after ‘:’)
Quadruples
Triples
Indirect triples
Quadruples:
A quadruple is a record structure with four fields, which are,op, arg1, arg2andresult.
Theopfield contains an internal code for the operator. The three-address statementx : =
y op zis represented by placingyinarg1,zinarg2andxinresult.
The contents of fields arg1, arg2 and result are normally pointers to the symbol-table
entries for the names represented by these fields. If so, temporary names must be entered
into the symbol table as they are created.
Triples:
To avoid entering temporary names into the symbol table, we might refer to a temporary
value by the position of the statement that computes it.
If we do so, three-address statements can be represented by records with only three fields:
op, arg1andarg2.
The fieldsarg1andarg2, for the arguments ofop, are either pointers to the symbol table
or pointers into the triple structure ( for temporary values ).
Since three fields are used, this intermediate code format is known astriples.
A ternary operation like x[i] : = y requires two entries in the triple structure as shown as below
while x : = y[i] is naturally represented as two operations.
Indirect Triples:
For example, let us use an array statement to list pointers to triples in the desired
order. Then the triples shown above might be represented as follows:
DECLARATIONS
Declarations in a Procedure:
The syntax of languages such as C, Pascal and Fortran, allows all the declarations in a
single procedure to be processed as a group. In this case, a global variable, sayoffset, can
keep track of the next available relative address.
Before the first declaration is considered,offsetis set to 0. As each new name is seen ,
that name is entered in the symbol table with offset equal to the current value ofoffset,
andoffsetis incremented by the width of the data object denoted by that name.
The procedureenter( name, type, offset) creates a symbol-table entry forname, gives its
typetypeand relative addressoffsetin its data area.
The width of an array is obtained by multiplying the width of each element by the
number of elements in the array. The width of each pointer is assumed to be 4.
P D { offset : = 0 }
DD;D
D id : T { enter(id.name, T.type,
offset); offset : = offset +
T.width }
T integer { T.type : =
integer; T.width :
=4}
T ↑T 1 { T.type : = pointer
( T1.type); T.width : = 4 }
PD
One possible implementation of a symbol table is a linked list of entries for names.
A new symbol table is created when a procedure declarationD proc idD 1;Sis seen,
and entries for the declarations in D1 are created in the new table. The new table points back to
the symbol table of the enclosing procedure; the name represented by id itself is local to the
enclosing procedure. The only change from the treatment of variable declarations is that the
procedureenteris told which symbol table to make an entry in.
For example, consider the symbol tables for proceduresreadarray, exchange, and
quicksortpointing back to that for the containing proceduresort, consisting of the entire
program. Sincepartitionis declared withinquicksort, its table points to that ofquicksort.
sort
nil header
a
x
readarray
to
exchange readarray
quicksort to
exchange
readarra exchang quicksort
hd y hd e hd
k
v
par琀椀琀椀on
par琀椀琀椀o
hd n
i
j
1. mktable(previous)creates a new symbol table and returns a pointer to the new table. The
argumentpreviouspoints to a previously created symbol table, presumably that for the
enclosing procedure.
2. enter(table, name, type, offset)creates a new entry for namenamein the symbol table pointed
to bytable.Again,enterplaces typetypeand relative addressoffsetin fields within the entry.
3. addwidth(table, width)records the cumulative width of all the entries in table in the header
associated with this symbol table.
4. enterproc(table, name, newtable)creates a new entry for procedurenamein the symbol table
pointed to bytable. The argumentnewtablepoints to the symbol table for this procedure
name.
D D1 ; D2
The top element of stackoffsetis the next available relative address for a local of
the current procedure.
in ABC {action A}
are done beforeaction A at the end of the production occurs. Hence, the action associated
with the marker M is the first to be done.
Downloaded by Piryanshu Sharma ([email protected])
lOMoARcPSD|54605199
The action for nonterminal M initializes stacktblptrwith a symbol table for the
outermost scope, created by operationmktable(nil).The action also pushes relative
address 0 onto stack offset.
For each variable declarationid:T, an entry is created foridin the current symbol table.
The top of stack offset is incremented by T.width.
When the action on the right side ofD proc id; ND1; Soccurs, the width of all
declarations generated by D1 is on the top of stack offset; it is recorded
usingaddwidth. Stackstblptrandoffsetare then popped.
At this point, the name of the enclosed procedure is entered into the symbol table of its
enclosing procedure.
ASSIGNMENT STATEMENTS
Suppose that the context in which an assignment appears is given by the following grammar.
PM D
Mɛ
Nɛ
Nonterminal P becomes the new start symbol when these productions are added to those in the
translation scheme shown below.
ifp≠nilthen
E.place : = p
elseerror }
Temporaries can be reused by changingnewtemp. The code generated by the rules for E
E 1 + E2 has the general form:
evaluate E1 into t1
evaluate E2 into t2
t : = t1 + t2
The lifetimes of these temporaries are nested like matching pairs of balanced parentheses.
statement value of c
0
$0 := a * b 1
$1 := c * d 2
$0 := $0 + $1 1
$1 := e * f 2
$0 := $0 - $1 1
x := $0 0
Elements of an array can be accessed quickly if the elements are stored in a block of
consecutive locations. If the width of each array element isw, then theith element of array A
begins in location
wherelowis the lower bound on the subscript andbaseis the relative address of the storage
allocated for the array. That is,baseis the relative address of A[low].
ixw+ (base–lowxw)
The subexpressionc = base – lowxwcan be evaluated when the declaration of the array is seen.
We assume that c is saved in the symbol table entry for A , so the relative address of A[i] is
obtained by simply addingixwtoc.
Row-major (row-by-row)
Column-major (column-by-column)
A[ 1 1 ] A[11]
first column
first row A[ 1,2 ] A[21]
A[ 1 3 ] A [ 1,2 ]
A[ 2,1 ] A [ 2,2 ] second column
second row A[ 2 2 ] A[13]
A[ 2,3 ] A [ 2,3 ] third column
In the case of row-major form, the relative address of A[ i1 , i2] can be calculated by the formula
where,low 1 andlow 2 are the lower bounds on the values ofi 1 andi 2 andn 2 is the number of
values thati 2 can take. That is, ifhigh 2 is the upper bound on the value ofi 2, thenn 2 = high2 –
low2 +1.
Assuming that i1 and i2 are the only values that are known at compile time, we can rewrite the
above expression as
Generalized formula:
The expression generalizes to the following expression for the relative address of A[i1,i2,…,ik]
(1) S L:=E
(2) E E+E
(3) E (E)
(4) E L
(5) LElist]
(6) L id
(7) Elist Elist , E
(8) Elist id[E
We generate a normal assignment ifLis a simple name, and an indexed assignment into the
location denoted byLotherwise :
When an array referenceLis reduced toE, we want ther-value ofL. Therefore we use indexing
to obtain the contents of the locationL.place[L.offset] :
Elist.place : = t;
Elist.ndim : =
m}
Elist.place : =
E.place; Elist.ndim :
=1 }
Consider the grammar for assignment statements as above, but suppose there are two
types – real and integer , with integers converted to reals when necessary. We have another
attributeE.type, whose value is eitherrealorinteger. The semantic rule forE.typeassociated
with the productionE E + Eis :
E E + E{E.type: =
ifE 1.type = integerand
E2.type = integertheninteger
elsereal}
The entire semantic rule forE E + Eand most of the other productions must be
modified to generate, when necessary, three-address statements of the form x : = inttoreal y,
whose effect is to convert integer y to a real of equal value, called x.
E.place := newtemp;
ifE 1.type = integerandE 2.type = integerthen begin
emit( E.place ‘: =’ E1.place ‘int +’ E2.place);
E.type : = integer
end
else ifE 1.type = realandE 2.type = realthen begin
emit( E.place ‘: =’ E1.place‘real +’E
2.place); E.type : = real
end
else ifE 1.type = integerandE 2.type = realthen begin
u : = newtemp;
emit( u ‘: =’‘inttoreal’E 1.place);
emit( E.place ‘: =’ u‘ real +’E 2.place);
E.type : = real
end
else ifE 1.type = realandE 2.type =integerthen begin
u : = newtemp;
emit( u ‘: =’‘inttoreal’E 2.place);
emit( E.place ‘: =’ E1.place ‘real +’
u); E.type : = real
end
else
Downloaded by Piryanshu Sharma ([email protected])
lOMoARcPSD|54605199
E.type : = type_error;
t1 : = i int* j
t3 : = inttoreal t1
t2 : = y real+ t3
x : = t2
BOOLEAN EXPRESSIONS
Boolean expressions have two primary purposes. They are used to compute logical
values, but more often they are used as conditional expressions in statements that alter the flow
of control, such as if-then-else, or while-do statements.
Boolean expressions are composed of the boolean operators (and, or,andnot) applied
to elements that are boolean variables or relational expressions. Relational expressions are of the
formE 1 relopE 2, where E1 and E2 are arithmetic expressions.
There are two principal methods of representing the value of a boolean expression. They are :
To implement boolean expressions byflow of control, that is, representing the value of a
boolean expression by a position reached in a program. This method is particularly
convenient in implementing the boolean expressions in flow-of-control statements, such
as the if-then and while-do statements.
Numerical Representation
Here, 1 denotes true and 0 denotes false. Expressions will be evaluated completely from
left to right, in a manner similar to arithmetic expressions.
For example :
which can be translated into the three-address code sequence (again, we arbitrarily start
statement numbers at 100) :
Short-Circuit Code:
We can also translate a boolean expression into three-address code without generating
code for any of the boolean operators and without having the code necessarily evaluate the entire
expression. This style of evaluation is sometimes called “short-circuit” or “jumping” code. It is
possible to evaluate boolean expressions without generating code for the boolean operatorsand,
or,andnotif we represent the value of an expression by a position in the code sequence.
Flow-of-Control Statements
We now consider the translation of boolean expressions into three-address code in the
context of if-then, if-then-else, and while-do statements such as those generated by the following
grammar:
SifEthenS 1
|ifEthenS 1 elseS 2
| whileEdoS 1
E.true is the label to which control flows if E is true, and E.false is the label to which
control flows if E is false.
The semantic rules for translating a flow-of-control statement S allow control to flow
from the translation S.code to the three-address instruction immediately following
S.code.
S.next is a label that is attached to the first three-address instruction to be executed after
the code for S.
toE.true
E.code
toE.fals
E.code S1.code
e
E.false:
S.next:
E.true: S1.code
gotoS.begin
E.false:. .
.
Downloaded by Piryanshu Sharma ([email protected])
lOMoARcPSD|54605199
SifEthenS 1 E.true : =
newlabel; E.false :
= S.next; S1.next :
= S.next;
S.code : = E.code || gen(E.true ‘:’) || S1.code
SifEthenS 1 elseS 2
E.true : = newlabel;
E.false : =
newlabel; S1.next :
= S.next; S2.next : =
S.next;
S.code : = E.code || gen(E.true ‘:’) || S1.code ||
gen(‘goto’ S.next) ||
SwhileEdoS 1
gen( E.false ‘:’) || S2.code
S.begin : =
newlabel; E.true : =
newlabel; E.false : =
S.next; S1.next : =
S.begin;
S.code : = gen(S.begin ‘:’)|| E.code
|| gen(E.true ‘:’) || S1.code
|| gen(‘goto’ S.begin)
= E1.code
E( E1 ) E1.true : = E.true;
E1.false : =
E.false; E.code : =
E1.code
Eid 1 relop id2
E.code : = gen(‘if’id 1.placerelop.opid 2.place
‘goto’E.true) || gen(‘goto’E.false)
Etrue
E.code : = gen(‘goto’E.true)
Efalse
E.code : = gen(‘goto’ E.false)
CASE STATEMENTS
switchexpressio
n begin
casevalue:statemen
t
casevalue:statemen
t
...
casevalue:statemen
t default :statement
end
imin and the label for the default in entries not filled otherwise. To perform switch,
evaluate the expression to obtain the value ofj, check the value is within range and
transfer to the table entry at offset j-imin .
switchE
begin
caseV 1 :S 1
caseV 2 :S 2
...
caseV n-1 :S n-1
default :S n
end
This case statement is translated into intermediate code that has the following form :
code to evaluateEinto t
goto test
L1 : code forS 1
goto next
L2 : code forS 2
goto next
. . .
Ln-1 : code forS n-1
goto next
Ln : code forS n
goto next
test : if t =V 1 goto L1
if t =V 2 goto L2
. . .
if t =V n-1 goto Ln-1
goto Ln
next :
As eachcasekeyword occurs, a new label L is created and entered into the symbol table.
i
A pointer to this symbol-table entry and the valueV i of case constant are placed on a
stack (used only to store cases).
Each statementcaseV i: Si is processed by emitting the newly created label Li, followed
by the code forS i , followed by the jumpgoto next.
Then when the keywordendterminating the body of the switch is found, the code can be
generated for the n-way branch. Reading the pointer-value pairs on the case stack from
the bottom to the top, we can generate a sequence of three-address statements of the form
caseV 1 L1
caseV 2 L2
...
caseV n-1 Ln-1
case t Ln
label next
where t is the name holding the value of the selector expressionE, and L n is the label for
the default statement.
BACKPATCHING
The easiest way to implement the syntax-directed definitions for boolean expressions is
to use two passes. First, construct a syntax tree for the input, and then walk the tree in depth-first
order, computing the translations. The main problem with generating code for boolean
expressions and flow-of-control statements in a single pass is that during one single pass we may
not know the labels that control must go to at the time the jump statements are generated. Hence,
a series of branching statements with the targets of the jumps left unspecified is generated. Each
statement will be put on a list of goto statements whose labels will be filled in when the proper
label can be determined. We call this subsequent filling in of labelsbackpatching.
1. makelist(i) creates a new list containing onlyi, an index into the array of quadruples;
makelistreturns a pointer to the list it has made.
2. merge(p 1,p2) concatenates the lists pointed to byp 1 andp 2,and returns a pointer to the
concatenated list.
3. backpatch(p,i)inserts i as the target label for each of the statements on the list pointed to
byp.
Boolean Expressions:
We now construct a translation scheme suitable for producing quadruples for boolean
expressions during bottom-up parsing. The grammar we use is the following:
(2) |E 1 andM E 2
(3) |notE 1
(4) | (E 1)
(5) |id 1 relop id2
(6) |true
(7) |false
(8)Mɛ
Consider productionEE 1 andM E 2.IfE 1 is false, thenEis also false, so the statements on
E1.falselistbecome part ofE.falselist. IfE 1 is true, then we must next testE 2, so the target for the
statementsE 1.truelistmust be the beginning of the code generated forE 2. This target is obtained
using marker nonterminalM.
AttributeM.quadrecords the number of the first statement ofE 2.code. With the production M
ɛwe associate the semantic action
{M.quad : = nextquad}
The variablenextquadholds the index of the next quadruple to follow. This value will be
backpatched onto theE 1.truelistwhen we have seen the remainder of the productionE E1 and
M E2. The translation scheme is as follows:
(6)Etrue{E.truelist: =makelist(nextquad);
emit(‘goto_’) }
(7)Efalse{E.falselist: =makelist(nextquad);
emit(‘goto_’) }
(8)Mɛ{M.quad: =nextquad}
Flow-of-Control Statements:
(1)SifEthenS
(2) |ifEthenSelseS
(3) |whileEdoS
(4) |beginLend
(5) |A
(6) LL ; S
(7) |S
(1)SifEthenM 1 S1 NelseM 2 S2
{backpatch(E.truelist,M 1.quad);
backpatch(E.falselist,M 2.quad);
S.nextlist: =merge(S 1.nextlist,merge(N.nextlist,S 2.nextlist)) }
We backpatch the jumps whenEis true to the quadrupleM 1.quad, which is the beginning of the
code for S1. Similarly, we backpatch jumps whenEis false to go to the beginning of the code for
S2. The listS.nextlistincludes all jumps out of S 1 and S2, as well as the jump generated byN.
(2)Nɛ{N.nextlist: =makelist(nextquad);
emit(‘goto_’) }
(3)Mɛ{M.quad: =nextquad}
(6)SbeginLend{S.nextlist: =L.nextlist}
(7)SA{S.nextlist: =nil}
L.nextlist: =S.nextlist}
The statement followingL 1 in order of execution is the beginning ofS. Thus theL1.nextlistlist is
backpatched to the beginning of the code forS, which is given byM.quad.
(9)LS{L.nextlist: =S.nextlist}
PROCEDURE CALLS
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 argument passing, calls and returns are part of the run-time
support package.
Calling Sequences:
The translation for a call includes a calling sequence, a sequence of actions taken on
entry to and exit from each procedure. The falling are the actions that take place in a calling
sequence :
When a procedure call occurs, space must be allocated for the activation record of the
called procedure.
The arguments of the called procedure must be evaluated and made available to the
called procedure in a known place.
Environment pointers must be established to enable the called procedure to access data in
enclosing blocks.
The state of the calling procedure must be saved so it can resume execution after the call.
Also saved in a known place is the return address, the location to which the called
routine must transfer after it is finished.
Finally a jump to the beginning of the code for the called procedure must be generated.
emit(‘call’id.place) }
(2)Elist Elist , E
(3)ElistE
{ initializequeueto contain onlyE.place}
Here, the code for S is the code forElist, which evaluates the arguments, followed by a
parampstatement for each argument, followed by acallstatement.
queueis emptied and then gets a single pointer to the symbol table location for the name
that denotes the value of E.
INTRODUCTION