You are on page 1of 36

CS2352 PRINCIPLES OF COMPILER DESIGN L T P C 3 0 2 4

OBJECTIVES
To understand, design and implement a lexical analyzer.
To understand, design and implement a parser.
To understand, design code generation schemes.
To understand optimization of codes and runtime environment.
UNIT I LEXICAL ANALYSIS 9
Introduction to Compiling- Compilers-Analysis of the source program-The phases-
Cousins-The grouping of phases-Compiler construction tools. The role of the lexical
analyzer- Input buffering-Specification of tokens-Recognition of tokens-A language for
specifying lexical analyzer.
UNIT II SYNTAX ANALYSIS and RUN-TIME ENVIRONMENTS 9
Syntax Analysis- The role of the parser-Context-free grammars-riting a grammar-
Topdo!n parsing-"ottom-up #arsing-$R parsers-Constructing an S$R%&' parsing table.
Type Checking- Type Systems-Specification of a simple type checker. Run-Time
(n)ironments-Source language issues-Storage organization-Storage-allocation
strategies.
UNIT III INTERMEDIATE CODE GENERATION 9
Intermediate languages-*eclarations-Assignment statements - "oolean expressions-
Case statements- "ackpatching-#rocedure calls
UNIT IV CODE GENERATION 9
Issues in the design of a code generator- The target machine-Run-time storage
management-"asic blocks and flo! graphs- +ext-use information-A simple code
generator-Register allocation and assignment-The dag representation of basic blocks -
,enerating code from dags.
UNIT V CODE OPTIMIZATION 9
Introduction-The principle sources of optimization-#eephole optimization- -ptimization of
basic blocks-$oops in flo! graphs- Introduction to global data-flo! analysis-Code
impro)ing transformations.
TOTAL: 75 PERIODS
TEXT BOOK:
&. Alfred .. Aho/ Ra)i Sethi 0effrey *. 1llman/ 2Compilers- #rinciples/ Techni3ues/ and
Tools4/ #earson (ducation Asia/ 5667.
R(8(R(+C(S9
&. *a)id ,alles/ 2:odern Compiler *esign4/ #earson (ducation Asia/ 5667
5. Ste)en S. :uchnick/ 2Ad)anced Compiler *esign ; Implementation4/:organ
<aufmann #ulishers/ 5666.
=. C. +. 8isher and R. 0. $e"lanc 2Crafting a Compiler !ith C4/ #earson (ducation/
5666.
1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
THIRD YEAR (SIXTH SEMESTER)
PRINCIPLES OF COMPILER DESIGN CS1352
UNIT I
PART-A
1. What is a Translator?
Translator is a program which converts a program written in any source Language into
any other Destination language. The source and destination languages may e any !igh Level
Language or Low Level Languages li"e assemly language or machine language.
#. What is $rror !andler?
The error handler invo"es error diagnostic routines and also generates error messages. %t
wor"s in con&unction with all the phases to handle the errors at the respective phases.
'. Define To"ens.
The to"en can e defined as a meaningful group of characters over the character set of the
programming language li"e identifiers, "eywords, constants and others.
(. Define )ymol Tale.
* )ymol Tale is a data structure containing a record for each identifier, with fields for
the attriutes of the identifier.
+. Define lexeme?
The character se,uence forming a to"en is called lexeme for the to"en.
-. .ame minimum ( compiler construction tools.
L$/
0*1123arser generator
)yntax directed translation scheme.
*utomatic code generator
Data flow engines
4. Write a short note on L$/.
* L$/ source program is a specification of lexical analyzer consisting of set of
regular expressions together with an action for each regular expression. The action is a piece
of code, which is to e executed whenever a to"en specified y the corresponding regular
#
expression is recognized. The output of a L$/ is a lexical analyzer program constructed from
the L$/ source specification.
5. What is the role of lexical analysis phase?
Lexical analyzer reads the source program one character at a time, and
grouped into a se,uence of atomic units called to"ens. %dentifiers, "eywords,
constants, operators and punctuation symols such as commas, parenthesis, are
typical to"ens.
6. 7ention the role of semantic analysis?
)emantic analysis chec"s the source program for semantic errors and
gathers information for the suse,uent code2generation phase.
%t uses hierarchical structure to identify the operators and operands of
expressions and statements.
*n important component of semantic analysis is type chec"ing .%n type
chec"ing the compiler chec"s that each operator has operands that are permitted
y the source language specification.
%n such cases, certain programming language supports operand coercion or
type coercion also.
18. .ame some variety of intermediate forms.
3ostfix notation or polish notation.
)yntax tree
Three address code
9uadruple
Triple
11. What are the techni,ues ehind code optimization phase?
1onstant folding
Loop constant code motion
%nduction variale elimination
1ommon su expression elimination
)trength reduction
7athematical identities
1#. Write the syntax for three2address code statement, and mention its properties.
'
)yntax: *; < op 1
Three2address instruction has at most one operator in addition to the
assignment symol. The compiler has to decide the order in which
operations are to e done.
The compiler must generate a temporary name to hold the value
computed y each instruction.
)ome three2address instructions can have less than three operands.
1'. What are the various phases of a compiler?
The different phases of a compiler are lexical analyzer, syntax analyzer, semantic
analyzer, intermediate code generator, code optimizer, code generator, symol tale manager,
error handler.
1(. Define prefix of ).
* string otained y removing zero or more trailing symols of string s= $x.,an is a
prefix of anana.
1+. Define suffix of ).
* string otained y removing zero or more leading symols of string s= $x.,nana is a
suffix of anana.
1-. Write notational shorthand.
1. >ne or more instances ?@A
#. Bero or one instance ??A
'. Bero or more instances ?CA
14. What is Dinite *utomata?
These are language recognizers. Eenerally a recognizer will identify an entity which is
familiar to that and say it is the same entity or it is not that entity. )imilarly the automata will ta"e the
input to"en and say FyesF if it is a sentence of the language and FnoF if it is not a sentence of the
language.
14. Define character class.
G*2Ba2zHG*2Ba2z826HC
15. Define nonregular set.
Iepeating strings cannot e descried y regular expression. The set
Jwcw K w is a string of aLs and LsM
16. Define identifier.
(
letter* K < K NNK B K a K K N..K z
digit 8 K 1 KNN.K6
id letter ?letter K digit A C
#8. Define num.
digit 8 K 1 KNN.K6
digits digit digitC
optionalOfraction .digits K P
optionalOexponent ?$?@K2K P AdigitsA K P
num digits optionalOfraction optionalOexponent
id letter ?letter K digit A C
PART B Text Book:Alfred Aho,Ravi Sethi,V.1effery Ullman]
1. $xplain the various phases of a compiler. (Page No.10)
#. $xplain the various 1ompiler 1onstruction Tools. (Page No.22)
'. $xplain Iole of Lexical *nalyzer. (Page No.84)
(. $xplain To"ens with its attriutes.(Page No.85)
+. $xplain %nput <uffering with example. (Page No.88)
UNIT II
PART A
1. What is )yntax *nalyzer?
This receives valid to"ens from the scanner and chec"s them against the Erammar and
produces the valid syntactical constructs. This is also called 3arser.
#. What are the categories of 3arsers?
The two road categories of parsers are Top down 3arsers and <ottom up 3arsers.
'. What is Top Down 3arser?
These are the parsers which constructs the parse tree from the root to the leaves in pre2
order for the given input string.
(. What is <ottom Qp 3arser?
+
These are the parsers which constructs the parse tree from the leaves to the root for the
given input string.
+. What is Left Iecursion?
* grammar is left recursive if it has a non terminal F*F such that, there is a derivation as
follows * */ for some input string, where / is a grammar symol.
-. What are the steps involved in .on Iecursive predictive parsing?
The steps involved are:
%nput uffer is filled with input string with as the right end mar"er.
)tac" is initially pushed with
1onstruction of 3arsing Tale T
3arsing y parsing routine
4. What is LL?1A Erammar?
* grammar FEF whose parsing tale has no multiply defined entries, can e called as LL?1A
grammar.
5. What is a )hift 2 Ieduce 3arser?
%t is a ottom up parser. The parsing is done from the leaves to the root. The parse tree is
constructed from the ottom to top, for an input string.
6. Define !andles.
* handle of a string is a sustring that matches the right side of a production. This
reduction helps in constructing the parse tree or right most derivation.
18. What are >perator 3recedence relations?
There are three operator precedence relations and they are represented y R. , ; and
.SThese have the following meanings:
T1 R. T# t1 yields precedence to t#
T1 ; t# t1 has the same precedence as t#
T1 .S t# t1 ta"es precedence over t#
Where t1,t# are terminals.
11. What is recursive descent parsing?
This is a top down method of syntax analysis in which we execute a set of recursive
procedures to process the input.
1#. What are the two functions of parser?
%t chec"s the to"ens appearing in its input, which is output of the lexical analyzer.
-
%t involves grouping the to"ens of source program into grammatical phrases
that are used y the compiler to synthesize the output. Qsually grammatical phrases of the source
program are represented y tree li"e structure called parse tree.
1'. Define amiguous grammar, and specify it demerits.
%f a grammar produces more than one parse tree for the given input
string then it is called amiguous grammar. It's demerit is
%t is difficult to select or determine which parse tree is suitale for an input
string.
1(. 7ention the properties of parse tree.
The root is laeled y the start symol.
$ach leaf is laeled y a to"en or yTT
$ach interior node is laeled y a non terminal
%f * is the .on terminal, laeling some interior node and x1, x#, x' .xn
are the laels of the children.
1+. What do you mean y a syntax tree?
)yntax tree is a variant of a parse tree in which each leaf represents an operand and each
interior node represents an operator.
1-. Define !andle pruning.
* techni,ue to otain the rightmost derivation in reverse ?called canonical reduction
se,uenceA is "nown as handle pruning ?i.e.A starting with a string of terminals w to e parsed. %f w
is the sentence of the grammar thenT ;T n whereT T n is the nth right sentential form of un"nown
right most derivation.
14. What are the demerits of )LI?
%t will not produce uni,uely defined parsing action tales for all grammars.
)hift2Ieduce conflict.
15. Why LI parsing is good and attractive?
LI parsers can e constructed for all programming language constructs for which 1DE
can e written.
LI parsing is .on2ac"trac"ing )hift2Ieduce parsing.
Erammars parsed using LI parsers are super set of the class of grammar.
LI parser can detect syntactic error as soon as possile, when left2to2right
4
)can of the input.
16. What are the rules for U 1losure operationV in )LI parsing?
%f W%L is a set of items for grammar E then 1losure ?%A is the set of items constructed from % y
the following # rules.
%nitially every item in % is added to 1losure ?%A
%f * .< is in 1losure?%A and <X to % , then add the item <X. to %, if it is not
*lready there. *pply this until no more new items can e added to 1losure ?%A.
#8. 7ention the demerits of L*LI parser.
7erger will produce reduce Y reduce conflict.
>n erroneous input, L*LI parser may proceed to do some reductions
*fter the LI parser has declared an error, ut L*LI parser never shift a
)ymol after the LI parser declares an error.
#1. What are Terminals and .on Terminals?
Terminals are symols which are used to ma"e strings in any language. .on terminals are
the symols which are used to specify the strings.
##. What is a production rule?
3roduction rules define the way in which the syntactical constructs may e uilt, from the
terminals. $ach 3roduction rule consists of non terminal followed y a string of non terminals and
terminals.
#'. What is amiguous grammar?
%f a grammar produces more than one parse tree for the given input string, then it can e
called as amiguous grammar.
PART B Text Book:Alfred Aho,Ravi Sethi,V.1effery Ullman]
1. $xplain Top2 Down 3arsing. (Page No.181)
#. $xplain the role of Lexical analyzer. (Page No.84)
'. Differentiate Deterministic and .ondeterministic Dinite *utomata. (Page No.114)
(. !ow do you design Lexical *nalyser Eenerator. (Page No.128)
+. !ow do you reduce the numer of states of a DD*. (Page No.142)
-. $xplain $rror Iecovery in 3redictive 3arsing. (Page No.192)
5
4. !ow do you a predictive 3arsing Tale. (Page No.190)
UNIT III
PART A
1. What are the ways of constructing LI parsing tales?
The different ways of constructing LI 3arsing tales are:
)LI ?)imple LIA
1LI ?1anonical LIA
L*LI ?loo" ahead LIA
#. What are viale prefixes?
The set of prefixes of right sentential forms that can appear on the stac" of a shift reduce
parser are called viale prefixes.
'. What are the conflicts during )hift reduce parsing?
There are context free grammars for which shift reduce parsing cannot e used. $very
shift reduce parser for such a grammar can reach a configuration in which the parser "nowing
the entire stac" contents and the next input symol cannot decide whether to shift or to reduce
a shiftYreduce conflict or cannot decide which of several reductions to ma"e a reduceYreduce
conflict.
(. What are the components involved in the construction of )LI 3arsing Tale?
The components involved are:
1onstruction of sets of LI?>A items collection using 1L>)QI$ function and goto
function.
1onstruction of parsing tale using LI?>A items
+. What are the actions performed on a )LI 3arsing Tale?
The 3arsing tale has two parts. They are *ction entries and Eoto $ntries. The actions
performed are shift, reduce, accept and error. The Eoto entries will e having state numers
li"e 1,#,' etc.
-. What are Iational preprocessors?
These processors augment older languages with more modern flow of control and data
structuring facilities.
4. What are loaders?
6
The process of loading consists of ta"ing relocatale machine code, altering the
relocatale addresses and placing the altered instructions and data in memory at the proper
locations.
5. What are the different compiler construction tools?
The different compiler construction tools are 3arser generators, )canner generators,
)yntax directed translation engines, *utomatic code generators and Data Dlow engines.
6. What is Data flow engine?
7uch of the information needed to perform good code optimization involves Zdata flow
analysis,V the gathering of information aout how values are transmitted from one part of a
program to each other part. This is handled y the data flow engines.
18. What are )yntax directed translation engines?
These produce collections of routines that wal" the parse tree generating intermediate
code.
11. What is the syntax for 0*11 source specification program?
Declarations
[[
Translation rules
[[
)upporting 12routines
1#. !ow 0*11 resolves parsing action conflicts?
* reduceYreduce conflict is resolved y choosing the conflicting production listed first
in the 0*11 specification.
* shiftYreduce conflict is resolved y shifting action or introduces associativity and
precedence.
1'. What is the new production added to the 0*11 on error recovery?
When parser generated y 0*11 encounters errors, then 0*11
pops symol from its stac" until it finds the topmost state on its stac" whose
underlying set of items includes an item of the form * $rror TTT
1(. What do you mean y D*E?
%t is Directed *cyclic Eraph. %n this common su expressions are
eliminated. )o it is a compact way of representation.
1+. $xplain postfix notation.
%t is the linearized representation of syntax tree .%t is a list of nodes of the syntax tree in which a
18
node appears immediately after its children.
$.g., for the aove syntax tree, a c uminus C c uminus C @ ;
1-. What are the different types of three address statements?
*ssignment statements of the form x;y op z.
*ssignment statements of the form x; op y.
1opy statements of the form x;y.
*n unconditional &ump, goto L.
1onditional &umps, if x relop y goto L.
3rocedure call statements, param x and call p , n.
%ndexed assignments of the form, x;yGiH , xGiH;y.
*ddress and pointer assignments.
14. %n compiler how three address statements can e represented as records with fields
for the operator and operands.
9uadruples.
Triples.
%ndirect triples.
15. Define ,uadruple and give one example.
* ,uadruple is a data structure with ( fields li"e operator, argument21 ,
argument2# and result.
Example: a;C2c
>perator *rgument 21 *rgument 21 Iesult
?8A Qminus c T
1
?1A C T
1
T2
(2) = a
16. What is the merit of ,uadruples?
%f we move a statement computing a variale, W*L then the statements using F*F
re,uires no change. That is W*L can e computed anywhere efore the utilization of
*.
#8. Eenerate three address code for U if *R< then 1 else 8U, using numerical method.
?1A if *R< goto ?(A
?#A T
1
;8
?'A goto ?+A
?(A T
1
;1
?+A
11
PART B Text Book:Alfred Aho,Ravi Sethi,V.1effery Ullman]
1. $xplain the )tac" %mplementation of )hift Ieduce 3arsing. (Page No.198)
#. $xplain >perator \3recedence 3arsing. (Page No.203)
'. $xplain error recovery in >perator2 3recedence 3arsing. (Page No.210)
(. $xplain LI 3arsing *lgorithm. (Page No.216)
+. $xplain 3arser Eenerators. (Page No.257)
UNIT - IV
PART A
1. What are the types of intermediate representations?
The types of intermediate representations are )yntax trees, postfix notation, three address
code.
#. What is a symolic lael?
* symolic lael represents the index of a three address statement in the array holding
intermediate code.
'. What is 9uadruple?
* 9uadruple is a record structure with four fields, which we call op, arg1, arg# and result.
The op field contains an internal code for the operator.
(. What are the functions used for manipulating the list of laels in <ac"patching?
The lists of functions are
aA ma"elist?iA 2 creates a new list containing only %,an index into the array of
,uadruples.
A merge?p1,p#A \ concatenates the lists pointed to y p1 and p#
cA ac"patch?p,iA \ inserts % as the target lael for each of the statements on the list
pointed to y p.
+. What is type system?
The type system is a collection of rules for assigning type expressions in the program. The
type chec"er implements the type system.
-. Define lifetime.
The life time of any procedure refers to the consecutive se,uence of steps from eginning
to end of that procedure during the execution of the program.
1#
4. What is *ctivation Tree?
The activation of a procedure is nothing ut the execution of the procedure. The program
can roadly e called as a collection of procedures. The activations of procedures in a program
can e represented in a tree called activation tree.
5. What is control stac"?
This is a stac", which "eeps trac" of live procedure activations.
6. What is activation record?
*n activation record is a record which "eeps the information necessary for an activation
of a procedure and also manages that information.
18. What are the different fields of an activation record?
The different fields of an activation record are temporaries, local data, saved machine status,
optional access lin", optional control lin", actual parameters and returned value.
11. What is mean y syntax directed definition.
%t is a generalization of a 1DE in which each grammar symol has an associated set of
attriutes li"e, synthesized attriute and inherited attriute.
1#. !ow the value of synthesized attriute is computed?
%t was computed from the values of attriutes at the children of that node in the
parse tree.
1'. !ow the value of inherited attriute is computed?
%t was computed from the value of attriutes at the silings and parent of that node.
1(. Define ac"patching.
To generate three address code, # passes are necessary. %n first pass, laels
are not specified. These statements are placed in a list. %n second pass, these
laels are properly filled, is called ac"patching.
1+. What are the three functions used for ac"patching?
7a"elist ?iA
7erge ?p1, p#A
<ac"patch ?p, iA
1-. When procedure call occurs, what are the steps to e ta"es placed?
o )tate of the calling procedure must e saved, so that it can resume after completion of
procedure.
1'
o Ieturn address is saved, in this location called routine must transfer after completion of
procedure
14. What are the demerits in generating '2address code for procedure calls?
1onsider, ;ac ?%, ]A .%t is very difficult to identify whether it is array
reference or it is a call to the procedure ac.
15. )tate the prolems in code generation.
Three main prolems in code generation are,
Deciding what machine instructions to generate.
Deciding in what order the computations should e done and
Deciding which registers to use.
16. Define code generation.
The code generation is the final phase of the compiler. %t ta"es an
intermediate representation of the source program as the input and produces an
e,uivalent target program as the output.
#8. Define ac"patch.
ac"patch?p,iA \ inserts % as the target lael for each of the statements on the list pointed to
y p.
PART B Text Book:Alfred Aho,Ravi Sethi,V.1effery Ullman]
1. $xplain )ymol tales. (Page No.429)
#. $xplain the different types of Three \ address )tatements. (Page No.467)
'. $xplain )yntax Directed Translation into Three *ddress 1ode. (Page No.468)
(. $xplain the operations used in Declarations. (Page No.476)
+. $xplain 3rocedure 1alls. (Page No.506)
UNIT - V
PART A
1. Define asic loc"s.
a. * asic loc" is a se,uence of consecutive statements in which flow of control enters
at the eginning and leaves at the end without halt or possiility of ranching except at
the end.
#. What are the structure preserving transformations?
The structure preserving transformations are:
1(
1ommon su expression elimination
Dead code elimination
Ienaming of temporary variales
%nterchange of two independent ad&acent statements
'. What is a register descriptor?
* register descriptor "eeps trac" of what is currently in each register. %t is consulted
whenever a new register is needed.
(. What are the nodes on a directed acylic graph?
The nodes are:
Leaves are laeled y uni,ue identifiers, either variale names or constants.
%nterior nodes are laeled y an operator symol.
.odes are also optionally given a se,uence of identifiers for laels.
+. What is local and gloal program?
* transformation of a program is called local if it can e performed y loo"ing only at the
statements in a asic loc"= otherwise it is called gloal.
-. What is dead code elimination?
* variale is live at a point in a program if its value can e used suse,uently= otherwise it
is dead at that point.
4. What is dominator tree?
%n a dominator tree, the initial node is the root and each node dominates only to its
descendants.
5. When is a flow graph reducile?
* flow graph is reducile if and only if we can partition the edges into two dis&oint groups
often called the forward edges and ac" edges.
6. What is induction variale?
* variale is called an induction variale of a loop if every time the variale changes
values, it is incremented or decremented y some constant.
18. What is static memory allocation?
This allocation is done at the compile time and the data for the procedure can e in
advance "nown and the sizes are also "nown at compile time, so these memories can e
allocated statically.
11.7ention some of the ma&or optimization techni,ues.
1+
Local optimization
Loop optimization
Data flow analysis
Dunction preserving transformations
*lgorithm optimization.
1#. What are the methods availale in loop optimization?
1ode movement
)trength reduction
Loop test replacement
%nduction variale elimination
1'. What is the step ta"es place in peephole optimization?
%t improves the performance of the target program y examining a short se,uence of
target instructions. %t is called peephole. Ieplace this instructions y a shorter or faster
se,uence whenever possile. %t is very useful for intermediate representation.
14. What are the characteristics of peephole optimization?
a. Iedundant instruction elimination.
. Dlow of control optimization
c. *lgeraic simplifications
d. Qse of machine idioms
1+. What are the rules to find leader in basic block?
%t is the first statement in a asic loc" is a leader.
*ny statement which is the target of a conditional or unconditional goto is a leader.
*ny statement, which immediately follows a conditional goto, is a leader.
16. Define flow graph.
Ielationships etween asic loc"s are represented y a directed graph called flow
graph.
14. What are the principle sources of optimization?
The principle sources of optimization are,
>ptimization consists of detecting patterns in the program and replacing these
patterns y e,uivalent ut more efficient constructs.
The richest source of optimization is the efficient utilization of the registers and
instruction set of a machine.
1-
15. What is a cross complier?
A cross compiler is a compiler capale of creating executale code for a platform
other than the one on which the compiler is run. ?ieA. * compier may run on one machine and
produce target code for another machine.
16. What are the properties of optimizing compilers?
1ompilers that apply code2 improving transformations are called optimizing
compilers. The properties of optimizing compilers are:
Transformation must preserve the meaning of programs.
Transformation must, on the average, speed up programs y a measurale amount.
Transformation must e worth the effect.
20. What does the runtime storage hold?
Iuntime storage holds
1A The generated target code
#A Data o&ects
'A * counter part of the control stac" to "eep trac" of procedure activations.
PART B Text Book:Alfred Aho,Ravi Sethi,V.1effery Ullman]
1. $xplain the issues in the design of a 1ode Eenerator. (Page No.514)
#. $xplain the 1ode Eeneration *lgorithm. (Page No.537)
'. !ow do you construct a directed *cyclic Eraph? (Page No.546)
(. $xplain 3eephole >ptimization. (Page No.554)
+. $xplain the principle sources of >ptimization. (Page No.592)
-. $xplain loops in Dlow Eraph. (Page No.602)
14
B.E/B.Tech.DEGREE EXAMINATION, MAY/1UNE 2007
Sixth semester
Computer Science and Engineering
CS337-PRINCIPLES OF COMPILER DESIGN
(Regulation 2004)
Time : Three hours Maximum : 100 marks
Part A --(10`220 marks)
Answer All questions
1. Define 1ompiler.
1ompiler is a program that can read a program in one language?source languageA and
translate it into an e,uivalent program in another language?target languageA.
#. What is Iegular $xpression?
* regular expression, often called a pattern, is an expression that descries a set of
strings.
'. What are !andles?
* handle of a string is a sustring 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.
(. List out the actions involved in shift reduce parsing.
a. )hift.
. Ieduce.
c. *ccept.
d. $rror.
15
+. $liminate Left Iecursion for the given grammar.
E E + T K T
T T ` F K F
F ( E )K id
E TE'
E' +TE' |
T FT'
T' *FT' |
F ( E ) | id
-. What is three address code?T*1A and generate T*1 for the statement:
a;#C@'Cc
Three-address code ?often areviated to T*1 or '*1A is a form of representing
intermediate code used y compilers to aid in the implementation of code2improving
transformations. $ach instruction in three2address code can e descried as a (2tuple:
?operator, operand1, operand#, resultA.
t1;'Cc
t#;#C
t';t1@t#
4. What is )DT?
Syntax-directed translation ?)DTA is a method of translating a string into a se,uence
of actions y attaching one such action to each rule of a grammar. Thus, parsing a string of
the grammar produces a se,uence of rule applications. *nd )DT provides a simple way to
attach semantics to any such syntax.
5. Define Directed *cyclic Eraph?
* directed acyclic graph ?commonly areviated to DAGA, is a directed graph with
no directed cycles. That is, it is formed y a collection of vertices and directed edges, each
edge connecting one vertex to another. %n this common su expressions are eliminated.
)o it is a compact way of representation.
16
6. >ptimize following the code y eliminating common su expression:
0;*@<Cx@1C?xCC#A@DC?xCC'A
(Refer Book)
18. What is peephole optimization?
Peephole optimization is a "ind of optimization performed over a very small set of
instructions in a segment of generated code. The set is called a UpeepholeU or a UwindowU. %t
wor"s y recognizing sets of instructions that donFt actually do anything, or that can e
replaced y a leaner set of instructions.
PART B (5 X 16 80 MARKS)
11. ?aA $xplain the various phases of compiler in detail with neat s"etch. (Page No:5 )
OR]
?A ?iA $xplain with neat s"etch implementation of Lexical analyzer. (Page No:76 )
?iiA Descrie in detail aout any three compiler construction tools. (Page No:12)
1#. ?aA ?iA $xplain the wor"ing model of top down parsing and ottom up parsing?
(Page No:217,233 )
?iiA Descrie the error detection and recovery process involved in the lexical phase.
(Page No:195 )
OR]
?A Write the algorithm for predictive parser and parse the input expression: x2#Cy using the
elow given grammar E: (Page No:217 )
$$@T^$2T ^T
TTCD ^TYD ^D
#8
Dnum ^id
1'. ?aA ?iA 3erform LI parsing and drive the input a ? a , a ? a , a A A using the elow given
grammar: (Page No:242 )
))
)a ?LA
)a
L), L
L)
?iiA 3erform shift reduce parsing for the input # C ?1@'A usin the grammar:
E E + T K T
T T ` F K F
F ( E )K id
OR]
?A ?iA Write an algorithm for generating LI item sets and constructing )LI 3arsing tale.
(Page No:245, 253 )
?iiA Write aout L*LI 3arser. (Page No:270 )
1(. ?aA <rief %ntermediate code generation for <asic loc", 1ontrol flow and <oolean expressions.
(Page No:399 )
OR]
?A ?iA $xplain the data structure used for implementing symol tale. (Page No:85 )
?iiA Write aout 9uadruple and Triple with its structure. (Page No:366 )
1+. ?aA ?iA $xplain various code optimization techni,ues in detail. (Page No:533 )
?iiA Eenerate target code for the given program segment:
main?A
J
#1
int i,&= i;(= &;i@+=
M
OR]
?A ?iA $xplain the various issues involved in the design of 1ode generation.
(Page No:506 )
?iiA Descrie in detail aout Iun time storage 7anagement. (Page No:427 )
B.E/B.Tech.DEGREE EXAMINATION, NOVEMBER/DECEMBER 2007
Sixth semester
Computer Science and Engineering
CS1352-PRINCIPLES OF COMPILER DESIGN
Time : Three hours Maximum : 100 marks
Part A --(10`220 marks)
1. What is an ambiguous grammar?
%f a grammar produces more than one parse tree for the given input string, then it can e
called as amiguous grammar.
#. Draw a transition diagram to represent relational operators.
)tart R ; return? relop, L$A
S
>ther return?relop, .$A
; C
return?relop,$9A return?relop,LTA
S ;
return?relop,E$A
>ther C
Ieturn?relop, ETA
3. What is left factoring? Give an example.
Left factoring is a grammar transformation that is useful for producing a grammar
suitale for predictive parsing.
##
-
+
5
8
4
(
1 #
'
4. What is a predictive parser?
3redictive parser is a program ased on a transition diagram attempts to match the
terminal symols against the input.
+. What are the goals of error handler in a parser?
The goals of error handler in a parser are
To maximize input text
To report actual and presence of errors clearly and accurately.
To recover from each error ,uic"ly enough to e ale to detect \ suse,uent errors.
.ot to significantly slow down the processing of correct programs.
-. State the parts of a Yacc source program.
The 0acc source program has ' parts:
Declarations
[[
Translation rules
[[
)upporting 12routines
7. What are the notations used to represent an intermediate languages?
The notations used to represent intermediate languages are
)yntax trees.
3ostfix notation
Three \ address code
5. What is the sequence of actions taking place on entry to a procedure?
The se,uence of actions ta"ing place on entry to a procedure includes calling se,uence,
translation for a call. * call se,uence allocates an activation record and enters information
into its fields. The code in calling se,uence is often divided etween the calling procedure
?the callerA and the procedure it calls ?the calleeA
9. What is a cross complier?
A cross compiler is a compiler capale of creating executale code for a platform
other than the one on which the compiler is run. ?ieA. * compier may run on one machine and
produce target code for another machine.
18. What are the properties of optimizing compilers?
1ompilers that apply code2 improving transformations are called optimizing
compilers. The properties of optimizing compilers are:
Transformation must preserve the meaning of programs.
#'
Transformation must, on the average, speed up programs y a measurale
amount.
Transformation must e worth the effect.
PART B (5 X 16 80 MARKS)
11. a. ?iA What is a compiler? $xplain the various phases of compiler in detail.
Complier is a program that reads a program written in one language ?source
languageA2 and translates it into an e,uivalent program in another language2?target languageA.
%n this translation process, the complier reports to its user the presence of the errors in the
source program.
Refer. Page. No. 10
?iiA What is a regular expression? $xplain the rules with an example.
Refer. Page. No. 94
. ?iA Eive a detailed note on the compiler2 construction tools.
Refer. Page. No. 22
?iiA $xplain riefly aout input uffering in reading the source program for finding the
to"ens.
Refer. Page. No. 88
1#. a. ?iA $xplain in detail aout design of a lexical analyzer generator.
Refer. Page. No. 198
?iiA $xplain the non2recursive predictive parsing with its algorithm.
Refer. Page. No. 187
. ?iA 1onstruct a minimum state DD* for the regular expression:
?a A C a c
Refer. Page. No. 136
?iiA List and explain the different types of error recovery strategies.
Refer. Page. No. 192
1'. a. ?iA Dor the operators given elow, calculate the operator precedence relations
and operator2precedence function.
id, @, C,_
Refer. Page. No. 204 & 205
?iiA $xplain the LI parsing algorithm in detail.
#(
Refer. Page. No. 218
. 1onstruct a canonical parsing tale for the grammar given elow.
) 11 1 c1 K d
Refer. Page. No. 231 -235
1( a. ?iA $xplain the various implementation of three address statements.
Refer. Page. No. 466 & 467
?iiA $xplain the operations that are used to define the semantic rules.
Refer. Page. No. 286 & 287
. ?iA Descrie the method of generating syntax2directed definition for control
statements.
Refer. Page. No. 280
?iiA $xplain the various methods for implementing symol tale and compare them.
Refer. Page. No. 429
1+. a. $xplain the various issues involved in the design of a code generator.
Refer. Page. No. 514
. $xplain the following regarding runtime storage management:
?iA )tatic allocation
Refer. Page. No. 522
?iiA )tac" allocation
Refer. Page. No. 524
B.E/B.Tech.DEGREE EXAMINATION, APRIL/MAY 2005
Sixth semester
Computer Science and Engineering
CS1352-PRINCIPLES OF COMPILER DESIGN
Time : Three hours Maximum : 100 marks
PART A (10 X 2 20 Marks)
1. What are the cousins of the compiler?
The cousins of the compiler are
3reprocessors
7acro processing.
#+
Dile inclusion.
Iational preprocessors
Language $xtensions.
*ssemlers.
Loaders and Lin" editors
2. What are the error recovery actions in a lexical analyzer?
3anic mode recovery.
Deleting an extraneous character
%nserting a missing character.
Ieplacing an incorrect character y a correct character.
Transposing two ad&acent characters.
3. What are the algebraic properties of regular expressions?
Qnion
`leene 1losure
3ositive 1losure
4. What is a finite automation?
Finite automation are language recognizers. Eenerally a recognizer will identify an
entity, which is familiar to that, and say it is the same entity or it is not that entity. )imilarly
the automata will ta"e the input to"en and say FyesF if it is a sentence of the language and FnoF
if it is not a sentence of the language.
5. What are the goals of error handler in a parser?
The goals of error handler in a parser are
To maximize input text
To report actual and presence of errors clearly and accurately.
To recover from each error ,uic"ly enough to e ale to detect \ suse,uent errors.
.ot to significantly slow down the processing of correct programs.
6. Define Handle.
* handle of a string is a su string that matches the right side of a production. This
reduction helps in constructing the parse tree or right most derivation.
7. What is a basic block?
* asic loc" is a se,uence of consecutive statements in which flow of control enters at
the eginning and leaves at the end without halt or possiility of ranching except at the end.
#-
8. What are the various ways to pass parameters in a function?
1all y value
1all y reference
9. How would you calculate the cost of an instruction?
10. How would you map names to values?
PART-B(5 X 16 80 Marks)
11. (i) What are the arious !hases of the co"!iler? #$!lain each !hase
in detail. Write do%n the out!ut of each !hase for the e$!ression. a& = b '
c ( )0.
Refer. Page. No. 10
?iiA <riefly explain the 1ompiler2 1onstruction tools.
Refer. Page. No. 22
12. a. (i) #$!lain the !rocess of constructin* an +,- fro" a re*ular
e$!ression. ,ind +,- for the e$!ression (a.b) ( a(a / b) (a / b). 0onert the
obtained +,- into 1,-.
Refer. Page. No. 117,118,121 - 123
?iiA What are the issues of the lexical analyzer?
Refer. Page. No. 84 & 85
. ?iA !ow would you construct a DD* directly from a regular expression? $xplain with a
suitale example.
Refer. Page. No. 135 & 136
?iiA What are the preliminary steps that are to e carried out during parsing? $xplain with
suitale example.
12. a. 0onstruct the !redictie !arser for the follo%in* *ra""ar&
) a K K ? T A
T T , ) K )
Write down the necessary algorithms and define D%I)T and D>LL>W. )how the
ehavior of the parser in the sentences=
?iA ?a, ?a, aAA
?iiA ???a, aA, , ?aA ,aA.
#4
Refer. Page. No. 182 & 188
. ?iA 1hec" whether the following grammar is a LL?1A grammar.
) i$t) K i$t)e) K a
$
Refer. Page. No. 191
?iiA. $xplain the error recovery strategies on 3redictive parsing.
Refer. Page. No. 192
?iiiA $xplain the LI parsing algorithm with an example.
Refer. Page. No. 218 - 220
1(. a. ?iA What is a three address code? What are its types? !ow it is implemented?
Refer. Page. No. 466 & 467
?iiA $xplain how declarations are done in a procedure using syntax directed translation.
Refer. Page. No. 468
. $xplain the various data structures used for implementing the symol tale and compare
them.
Refer. Page. No. 429
1). a. #$!lain the !rinci!le sources of code o!ti"i3ation in detail.
Refer. Page. No. 592
. ?iA What are the issues in the design of the code generator? $xplain.
Refer. Page. No. 514
?iiA $xplain the D*E representation of the asic loc" with an example.
Refer. Page. No. 598
B.E/B.Tech.DEGREE EXAMINATION, MAY/1UNE 2009
Sixth semester
Computer Science and Engineering
CS1352-PRINCIPLES OF COMPILER DESIGN
Time : Three hours Maximum : 100 marks
Part A --(10`220 marks)
1. What are the issues to e considered in the design of lexical analyzer?
!ow to 3recisely 7atch )trings to To"ens
!ow to %mplement a Lexical *nalyzer
2. Define concrete and astract syntax with example.
The grammar is mainly used for parsing only 2 the "ey is to resolve all amiguities. This
grammar is called Concrete Syntax.
#5
a Abstract Syntax is used to characterize the essential structure of the program 2 the
"ey
is to e as simple as possile= it may contain amiguities.
Traditional Compilers do semantic analysis on 1oncrete )yntax
a Modern Compilers do the semantic analysis on *stract )yntax tree
3. Derive the string and construct a syntax tree for the input string ceaede using
the grammar )2S)a*K*,*2S*<K<,<2Sc)dKe
Iefer class notes.
4. List the factors to e considered for top2down parsing.
We egin with the start symol and at each step,
expand one of the remaining nonterminals y replacing it with the right side of one of its
productions. We repeat until only terminals remain. The top2down parse produces a
leftmost derivation of the sentence.
5. Why is it necessary to generate intermediate code instead of generating target
program itself?
%ntermediate code is simple enough to e easily converted to any target code.
1omplex enough to represent the entire complex structure of high level language
6. Define back patching.
Backpatch (X , Y) : replace the line numers listed in W/L with the value W0L
7. List the issues in code generation.
1ode generator tries to optimize the generated code in some way. The generator may try to use
faster instructions, use fewer instructions, exploit availale registers, and avoid redundant
computations.
8. Write the steps for constructing leaders in basic blocks.
Determine leaders ?first statements of <<sA
The first statement is a leader
The target of a conditional is a leader
* statement following a ranch is a leader
Dor each leader, its asic loc" consists of the leader and all the statements up to ut not
including the next leader
9. What are the issues in static allocation?
Iesources needed to meet the deadlines of safety2critical tas"s are typically preallocated. *lso,
these tas"s are usually statically scheduled such that their deadlines will e met even under worst2
case conditions. <esides periodicity constraints, algorithms that do allocation and scheduling must e
ale to handle the resource, precedence, communication, and fault etc.
10. What is meant by copy-restor?
Refer class notes.
3*IT <22?+C1-;58A
11. ?aA ?iA $xplain the need for dividing the compilation process into various phases
and explain its functions.

#6
Answer the following with an example,

?iiA $xplain how astract stac" machine can e used as translators.
Refer Principles of compiler design -aho , Page No.62
?orA
?A What is syntax directed translation? !ow it is used for translation of expresions?
?1-A
Refer Principles of compiler design -aho , Page No.33

1#. ?aA Eiven the following grammar )2S*)K,*2S)*Ka 1onstruct a )LI parsing tale for
the string aa ?1-A
Refer class notes.
?orA
?A 1onsider the grammar $2S$@T,T2STCD,D2S?$Abid.Qsing predictive parsing the string
id@idCid. ?1-A
Refer class notes.
1'. ?aA $xplain in detail how three address code are generated and implemented.
Highlight the following
Quadraples, Binary Operator,Unary Operator, Move Operator,
Unconditional 1umps, Conditional 1umps, Procedure Parameters, Procedure Calls,
Indexed Assignments, Address and Pointer Assignments, Syntax-Directed Translation into
Three-Address Code.
?orA
?A $xplain the role of declaration statements in intermediate code generation.
Highlights the important of declaration part in a program
Nested Procedure Declarations
1(. ?aA Design a simple code generator and explain with example.
Refer Principles of compiler design -aho , Page No.535

?orA
?A Write short notes on:
1: 3eep hole optimization Refer Principles of compiler design -aho , Page No.554
#: %ssues in code generation Refer Principles of compiler design -aho , Page No.514
1+. ?aA $xplain with an example how asic loc"s are optimized.
Refer Principles of compiler design -aho , Page No.598
Lexical
*nalyzer
)emantic
*nalyzer
)yntax
*nalyzer
%ntermediate
1ode Eenerator
1ode
>ptimizer
1ode
Eenerator
'8
?orA
?A $xplain the storage allocation strategies used in run time environments.
Refer Principles of compiler design -aho , Page No.522


<.$Y<.Tech.D$EI$$ $/*7%.*T%>.,*3I%LY7*0 #885
1)1'+#23I%.1%3L$) >D 1>73%L$I D$)%E.
*nswer *ll ,uestions
3art * 22?18C#;#8 mar"sA
1. Differentiate compiler and interpreter
An interpreter is a translator of high level language program.The function of these translator is to
convert high level program into machine code.These translators translate one instruction at a time.A
Compiler is a translator which is used to translate the whole source of a program at a time.
2.Write short notes on buffer pair.
Refer class notes.
3.Construct a parse tree of (a+b)`c for the grammer E->E+E/E`E/(E)/id.
Refer class notes
4.Eliminate immediate left recursion for the following grammer
E->E+T/T,T->T`F,F->(E)/id.
Refer class notes
5.Write short notes on global data flow analysis.
1ata4flo% anal5sis is a collection of techni6ues for co"!ile4ti"e reasonin* about the run4
ti"e flo% of alues
6.Define back patching with an example.
Backpatch (X , Y) : replace the line numers listed in W/L with the value W0L
7.Give syntax directed translation for the following statement Call p1(int a, int b).
Refer class notes
8.How can you find the leaders in basic block.
Determine leaders ?first statements of <<sA
The first statement is a leader
The target of a conditional is a leader
* statement following a ranch is a leader
'1
Dor each leader, its asic loc" consists of the leader and all the statements up to ut not
including the next leader
9.Define code motion.
%n computer programming, loop-invariant code consists of statements ?in an imperative
programming languageA which can e moved outside the ody of a loop without affecting the
semantics of the program.
Loop-invariant code motion ?also called hoisting or scalar promotionA is a compiler optimization
which performs this movement automatically.
10.Define basic block and flow graph.
* basic block is code that has one entry point ?i.e., no code within it is the destination of a &ump
instructionA, one exit point and no &ump instructions contained within it. The start of a asic loc"
may e &umped to from more than one location. The end of a asic loc" may e a &ump instruction
or the statement efore the destination of a &ump instruction. <asic loc"s are usually the asic unit to
which compiler optimizations are applied.
%n a control flow graph each node in the graph represents a asic loc", i.e. a straight2line piece of
code without any &umps or &ump targets= &ump targets start a loc", and &umps end a loc". Directed
edges are used to represent &umps in the control flow. There are, in most presentations, two specially
designated loc"s: the entry block, through which control enters into the flow graph, and the exit
block, through which all control flow leaves.
3*IT <22?+C1-;58A
11. aA iA $xplain the phases of compiler with the neat schematic.
Answer the following with an example,
iiA Write short notes on compiler construction tools.
Refer Principles of compiler design -aho , Page No.22

?orA
A iA $xplain grouping of phases.
Refer Principles of compiler design -aho , Page No.20
Lexical
*nalyzer
)emantic
*nalyzer
)yntax
*nalyzer
%ntermediate
1ode Eenerator
1ode
>ptimizer
1ode
Eenerator
'#
iiA $xplain specification of to"ens.
Refer Principles of compiler design -aho , Page No.92
1#. aA Dind the )LI parsing tale for the given grammer and parse the sentence ?a@ACc.
$2S$@$Y$C$Y?$AYid.
Refer class notes
?orA
A Dind the predictive parser for the given grammer and parse the sentence ?a@ACc.
$2S$@TYT,T2STCDYD,D2S?$AYid.
Refer class notes
1'. aA Eenerate intermediate code for the following code segment along with the re,uired syntax
directed translation scheme.
iA if?aSA
x;a@
else
x;a2
where a c x are of real and of int type data.
iiA int a,=
float c=
a;18=
switch?aA
J
case 18: c;1=
case #8: c;#=
M
Refer class notes
?orA
A iA Eenerate intermediate code for the following code segment along with the re,uired syntax
directed translation scheme.
%;1=s;8=
While?iR;18A
s;s@aGiHGiHGiH
i;i@1= Refer class notes
iiA Write short notes on ac"2patching.
Refer Principles of compiler design -aho , Page No.500
''
1(. aA iA $xplain the various issues in the design of code generation,
Refer Principles of compiler design -aho , Page No.514
iiA $xplain code generation phase with simple code generation algorithm.
Refer Principles of compiler design -aho , Page No.535

?orA
A iA Eenerate D*E representation of the following code and list out the applications of D*E
representation.
i;=s;8=
while?iR;18A
s;s@aGiHGiH=
i;i@1=
Refer class notes and Refer Principles of compiler design -aho , Page No.550
iiA Write short notes on next2use information with suitale example.
Refer Principles of compiler design -aho , Page No.534
1+. aA iA $xplain principle sources of optimization.
Refer Principles of compiler design -aho , Page No.592
iiA Write short notes on.
1A )torage >rganization
Refer Principles of compiler design -aho , Page No.396
#A 3arameter 3assing.
Refer Principles of compiler design -aho , Page No.424
?orA
A iA >ptimize the following code using various optimization techni,ue.
i;1=s;8=
for?i;1=iR;'=i@@A
for?&;1=&R;'=&@@A
cGiHG&H;cGiHG&H@aGiHG&H@GiHG&H Refer Class notes
iiA Write short notes on access to non2local names. Refer Class notes
'(
B.E/B.Tech. DEGREE EXAMINATION, APRIL/MAY 2010.
Eighth semester
Information Technology
CS1352 PRINCIPLES OF COMPILER DESIGN
(Common to Sixth Semester Computer Science and Engineering)
(Regulation 2004)
(Also Common to B.E.(Part Time) Fifth Semester, Regulation 2005)
Time : Three Hours Maximum : 100 Marks
PART A (10 X 2 20 MARKS)
1. What are the two types of analysis of the source programs y compiler?
#. !ow is the to"en structure is specified?
'. Eive two examples for each of top down parser and ottom up parser?
(. What is the significance of loo" ahead in LI?1A items?
+. What is the meaning of inherited translation?
-. What is meant y short circuit code?
4. What is meant y a asic loc"?
5. Which variale is to e made live and why?
6. Eive any two examples for strength reduction.
18. What are the fields availale in activation records?
PART B (5 X 16 80 MARKS)
11. ?aA ?iA Discuss any four compiler construction tools. ?5A
?iiA Write down the exclusive functions carried out y the analysis phases of any
compiler. ?5A
OR]
?A ?iA Write riefly on the issues in input uffering and how they are
handled. ?5A
?iiA Eive the rules for generating regular expressions for descriing
languages. ?5A
1#. ?aA 1onstruct predictive parsing tale for the following grammar. )how
how the string ?a, aA is parsed y the predictive parser? ?1-A
) a K d K ?TA
'+
T T,))
OR]
?A 1onstruct the 1LI parsing tale for the following Erammar. ?1-A
) 11
1 c1
1 d
1'. ?aA Descrie the translation scheme for array translation and translate the following integer
array operation into three address code.
*Gi, &H ; <Gi, &H @ 1G"H where * and < are of 18 / #8 size and 1 contains +8 elements.
?1-A
OR]
?A Translate ?a or A and ?cRdA and ?dReA into three address statements using ac" patching.
?1-A
1(. ?aA Write on the issues in code generation and generate the assemly language for the
statement W:; ?* @ <A @ ?* @ 1A @ ?* @ 1A ?5@5A
OR]
?A ?iA 1onstruct D*E for the following asic loc". ?5A
T
1
:; * @ <
T
#
:; 1 @ D
T
'
:; $ 2 T
#
T
(
:; T
1
2 T
'
?iiA $xplain the techni,ues used in peephole optimization. ?5A
1+. ?aA Dor the following program segment construct the flow graph and apply the possile
optimizations.
sum :; 8
% :; 1=
do
sum :; prod @ *G%H C <G%H=
% :; % @ 1=
while % R; #8=
OR]
?A Discuss the various storage allocation strategies. ?1-A
'-

You might also like