Docsity

Compiler construction cs606 handouts, Essays (university) of Abnormal Psychology

Toggle sidebar
bg1
Sohail Aslam Compiler Construction Notes
1
L
Le
ec
ct
tu
ur
re
e
1
1
Course Organization
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%
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Compiler construction cs606 handouts and more Essays (university) Abnormal Psychology in PDF only on Docsity!

Le Leccttuurree 1 1

Course Organization

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%

Why Take this Course

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.

What are Compilers

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.

Issues in Compilation

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.

Le Leccttuurree 2 2

Two-pass Compiler

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.

Front End

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:

  1. Scanner
  2. Parser

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”.

Le Leccttuurree 3 3

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).

The Back End

<id,y>

<id,x>

<number,2>

Le Leccttuurree 4 4

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.

Three-pass Compiler

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:

Front

End

machine

code

errors

Middle

End

Back

End

IR IR

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:

  • Discover & propagate some constant value
  • Move a computation to a less frequently executed place
  • Specialize some computation based on context
  • Discover a redundant computation & remove it
  • Remove useless or unreachable code
  • Encode an idiom in some particularly efficient form

Role of Run-time System

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:

  • Memory management
  • Allocate and de-allocate memory
  • Garbage collection
  • Run-time type checking
  • Error/exception processing
  • Interface to OS – I/O
  • Support for parallelism
  • Parallel threads
  • Communication and synchronization

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 do not know what kind of token we are going to read from seeing first character.
  • If token begins with “i”, is it an identifier “i” or keyword “if”?
  • If token begins with “=”, is it “=” or “==”?

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

  • An input alphabet Σ
  • A set of states
  • A start (initial) state
  • A set of transitions
  • A set of accepting (final) states

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.

  • A FA that accepts only “1”
  • A FA that accepts any number of 1’s followed by a single 0

0

1

  • A FA that accepts ab*a (Σ: {a,b})

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.

A B 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:

  1. NFA for RE ab. The following figures show the construction steps. NFAs for RE a and RE b are made. These two are combined using an ε-move; the NFA for RE a appears on the left and is the source of the ε-transition.

s 0

a

NFA for a s 1

s 0^ a^ s 1

NFA for ab

s 3^ b^ s 4

s 3

b

NFA for b s 4

s^ ε

0

a

s 1

NFA for ab

s 3^ b^ s 4

  1. NFA for RE a|b

ε

s 0 s 5

s 1

a s 2

NFA for a | b

s 3 b ε s 4

ε

ε

  1. NFA for RE a*

ε s 0 s 1 s 4

a s 2

NFA for a*

ε

ε

ε