




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































The course is organized around theory and significant amount of practice. The practice will be in the form of home works and a project. The project is the highlight of the course: you will build a full compiler for subset of Java- like language. The implementation will in C++ and you will generate Intel x86 assembly language code. The project will be done in six parts; each will be a programming assignment.
The grade distribution will be
The primary text for the course is Compilers – Principles, Techniques and Tools by Aho, Sethi and Ullman. This is also called the Dragon Book; here is the image on the cover of the book:
Theory Homeworks 10% Exams 50% Practice Project 40%
There are number of reason for why you should take this course. Let’s go through a few
Reason #1: understand compilers and languages We all have used one or computer languages to write programs. We have used compilers to “compile” our code and eventually turn it into an executable. While we worry about data structures, algorithms and all the functionality that our application is supposed to provide, we perhaps overlook the programming language, the structure of the code and the language semantics. In this course, we will attempt to understand the code structure, understand language semantics and understand relation between source code and generated machine code. This will allow you to become a better programmer
Reason #2: nice balance of theory and practice We have studied a lot of theory in various CS courses related to languages and grammar. We have covered mathematical models: regular expressions, automata, grammars and graph algorithms that use these models. We will now have an opportunity to put this theory into practice by building a real compiler.
Reason #3: programming experience Creating a compiler entails writing a large computer program which manipulates complex data structures and implement sophisticated algorithm. In the process, we will learn more about C++ and Intel x86 assembly language. The experience, however, will be applicable if we desire to use another programming language, say Java, and generate code for architecture other than Intel.
Compilers translate information from one represent ation to another. Thus, a tool that translates, say, Russian into English could be labeled as a compiler. In this course, however, information = program in a computer language. In this context, we will talk of compilers such as VC, VC++, GCC, JavaC FORTRAN, Pascal, VB. Application that convert, for example, a Word file to PDF or PDF to Postscript will be called “translators”. In this course we will study typical compilation: from programs written in high- level languages to low- level object code and machine code.
The translation of code from some human readable form to machine code must be “correct”, i.e., the generated machine code must execute precisely the same computation as the source code. In general, there is no unique translation from source language to a destination language. No algorithm exists for an “ideal translation”.
Translation is a complex process. The source language and generated code are very different. To manage this complex process, the translation is carried out in multiple passes.
The figure above shows the structure of a two-pass compiler. The front end maps legal source code into an intermediate representation (IR). The back end maps IR into target machine code. An immediate advantage of this scheme is that it admits multiple front ends and multiple passes.
The algorithms employed in the front end have polynomial time complexity while majority of those in the backend are NP-complete. This makes compiler writing a challenging task.
Let us look at the details of the front and back ends.
source scanner parser code
tokens IR
errors
The front end recognizes legal and illegal programs presented to it. When it encounters errors, it attempts to report errors in a useful way. For legal programs, front end produces IR and preliminary storage map for the various data structures declared in the program. The front end consists of two modules:
T = { number, id, +, -} N = { goal , expr , term , op } P = { 1, 2, 3, 4, 5, 6, 7}
Given a CFG, we can derive sentences by repeated substitution. Consider the sentence
x + 2 – y
Production Result goal 1: goal? expr expr
2: expr? expr op term expr op term
5: term? id expr op y
7: op? – expr – y
2: expr? expr op term expr op term – y
4: term? number expr op 2 – y
6: op? + expr + 2 – y
3: expr? term term + 2 – y
5: term? id x + 2 – y
To recognize a valid sentence in some CFG, we reverse this process and build up a parse , thus the name “parser”.
A parse can be represented by a tree: parse tree or syntax tree. For example, here is the parse tree for the expression x+2-y
The parse tree captures all rewrite during the derivation. The derivation can be extracted by starting at the root of the tree and working towards the leaf nodes.
Abstract Syntax Trees
The parse tree contains a lot of unneeded information. Compilers often use an abstract syntax tree (AST). For example, the AST for the above parse tree is
This is much more concise; AST summarizes grammatical structure without the details of derivation. ASTs are one kind of intermediate representation (IR).
CISC architecture provided a rich set of instructions and addressing modes but it made the job of the compiler harder when it came to generate efficient machine code. The RISC architecture simplified this problem.
Register Allocation
Registers in a CPU play an important role for providing high speed access to operands. Memory access is an order of magnitude slower than register access. The back end attempts to have each operand value in a register when it is used. However, the back end has to manage a limited set of resources when it comes to the register file. The number of registers is small and some registers are pre-allocated for specialize used, e.g., program counter, and thus are not available for use to the back end. Optimal register allocation is NP-Complete.
Instruction Scheduling
Modern processors have multiple functional units. The back end needs to schedule instructions to avoid hardware stalls and interlocks. The generated code should use all functional units productively. Optimal scheduling is NP-Complete in nearly all cases.
There is yet another opportunity to produce efficient translation: most modern compilers contain three stages. An intermediate stage is used for code improvement or optimization. The topology of a three-pass compiler is shown in the following figure:
The middle end analyzes IR and rewrites (or transforms ) IR. Its primary goal is to reduce running time of the compiled code. This may also improve space usage, power consumption, etc. The middle end is generally termed the “Optimizer”. Modern optimizers are structured as a series of passes:
Opt 1
IR (^) IR
errors
Opt 2
Opt n
IR IR Opt 3
IR
Typical transformations performed by the optimizer are:
The executable code typically runs as a process in an Operating System Environment. The application will need a number of resources from the OS. For example, dynamic memory allocation and input output. The process may spawn more processes of threads. If the underline architecture has multiple processors, the application may want to use them. Processes communicate with other and may share resources. Compilers need to have an intimate knowledge of the runtime system to make effective use of the runtime environment and machine resources. The issues in this context are:
Ad-hoc Lexer
The task of writing a scanner is fairly straight forward. We can hand-write code to generate tokens. We do this by partitioning the input string by reading left-to-right, recognizing one token at a time. We will need to look-ahead in order to decide where one token ends and the next token begins. The following C++ code present is template for a Lexer class. An object of this class can produce the desired tokens from the input stream.
class Lexer { Inputstream s; char next; // look ahead Lexer(Inputstream _s) { s = _s; next = s.read(); }
Token nextToken() { if( idChar(next) )return readId(); if( number(next) )return readNumber(); if( next == ‘”’ ) return readString(); ... ... } Token readId() { string id = “”; while(true){ char c = input.read(); if(idChar(c) == false) return new Token(TID,id); id = id + string(c); } } boolean idChar(char c) { if( isAlpha(c) ) return true; if( isDigit(c) ) return true; if( c == ‘_’ ) return true;
return false; } Token readNumber(){ string num = “”; while(true){
next = input.read(); if( !isNumber(next)) return new Token(TNUM,num); num = num+string(next); } }
This works ok, however, there are some problem that we need to tackle.
We can extend the Lexer class but there are a number of other issues that can make the task of hand-writing a lexer tedious. We need a more principled approach. The most frequently used approach is to use a lexer generator that generates efficient tokenizer automatically.
Here are some Regular Expressions and the strings of the language denoted by the RE.
RE Strings in L(R) a “a” ab “ab” a|b “a” “b” (ab)* “” “ab” “abab” ... (a|ε)b “ab” “b”
Here are examples of common tokens found in programming languages.
digit ‘0’|’1’|’2’|’3’|’4’|’5’|’6’|’7’|’8’|’9’ integer digit digit* identifier [a-zA- Z_][a- zA-Z0-9_]*
Finite Automaton
We need mechanism to determine if an input string w belongs to L(R), the language denoted by regular expression R. Such a mechanism is called an acceptor.
input string
language
w
L
acceptor yes, if w ε L
no, if w ε L
The acceptor is based on Finite Automata (FA). A Finite Automaton consists of
A finite automaton accepts a string if we can follow transitions labeled with characters in the string from start state to some accepting state. Here are some examples of FA.
0
1
a
b
a
The actual algorithm actually builds N ondeterministic Finite Automaton (NFA) from RE. Each RE is converted into an NFA. NFA are joined together with ε-moves. The eventual NFA is then converted into a Deterministic Finite Automaton (DFA) which can be encoded as a transition table. Let us discuss how this happens.
Nondeterministic Finite Automaton (NFA)
An NFA can have multiple transitions for one input in a given state. In the following NFA, and input of 1 can cause the automaton to go to state B or C.
It can also have e–moves; the automaton machine can move from state A to state B without consuming input.
ε A (^) B
The operation of the automaton is not completely defined by input. A NFA can choose whether to make ε-moves and which of multiple transitions to take for a single input. The acceptance of NFA for a given string is achieved if it can get in a final state.
Deterministic Finite Automaton (NFA)
In Deterministic Finite Automata (DFA), on the other hand, there is only one transition per input per state. There are no ε-moves. Upon execution of the automaton, a DFA can take only one path through the state graph and is therefore completely determined by input.
NFAs and DFAs recognize the same set of languages (regular languages). DFAs are easier to implement – table driven. For a given language, the NFA can be simpler than the DFA. DFA can be exponentially larger than NFA. NFAs are the key to automating RE? DFA construction.
RE? NFA Construction
The algorithm for RE to DFA conversion is called Thompson’s Construction. The algorithm appeared in CACM 1968. The algorithm builds an NFA for each RE term. The NFAs are then combined using ε-moves. The NFA is converted into a DFA using the subset construction procedure. The number of states in the resulting DFA are minimized using the Hopcroft’s algorithm.
Given a RE, we first create NFA pattern for each symbol and each operator. We then join them with ε-moves in precedence order. Here are examples of such constructions:
0
ε
s 0 s 5
s 1
a s 2
NFA for a | b
s 3 b ε s 4
ε
ε
ε s 0 s 1 s 4
a s 2
NFA for a*
ε
ε
ε