SlideShare a Scribd company logo
CSE 420
Lecture 12
Compiler Architecture
Parser
Static
Checker
Intermediate
Code generator
Code
Generator
Intermediate
Code
Target
language
Front End Back End
• m  n compliers can be built by writing m front ends
and n back ends – save considerable amount of effort
• We assume parsing, static checking and IC
generation is done sequentially
– These can be combined and done during parsing
• Static checking
– Operator operand compatibility
– Proper placement of break/continue keywords etc.
2
Intermediate Code (IC)
• The given program in a source language is converted
to an equivalent program in an intermediate language
by the IC generator.
• Ties the front and back ends together
• Language and Machine neutral
• Many forms
• Level depends on how being processed
• More than one intermediate language may be used by
a compiler
3
• Intermediate language can be many different languages, and the
designer of the compiler decides this intermediate language.
– syntax trees can be used as an intermediate language.
– postfix notation can be used as an intermediate language.
– three-address code (Quadraples) can be used as an
intermediate language
• we will use quadraples to discuss intermediate code
generation
• quadraples are close to machine instructions, but they are
not actual machine instructions.
– some programming languages have well defined
intermediate languages.
• java – java virtual machine
• prolog – warren abstract machine
• In fact, there are byte-code emulators to execute instructions
in these intermediate languages.
Intermediate Code (IC)
4
Intermediate language levels
5
Intermediate Languages Types
• Graphical IRs:
– Abstract Syntax trees
– Directed Acyclic Graphs (DAGs)
– Control Flow Graphs
• Linear IRs:
– Stack based (postfix)
– Three address code (quadruples)
6
Graphical IRs
• Abstract Syntax Trees (AST) – retain essential
structure of the parse tree, eliminating unneeded
nodes.
• Directed Acyclic Graphs (DAG) – compacted AST to
avoid duplication – smaller footprint as well
• Control flow graphs (CFG) – explicitly model control
flow
7
ASTs and DAGs:
:=
a +
**
b - (uni)
c
:=
a +
b - (uni) b
*
- (uni)
c c
a := b *-c + b*-c
AST DAG
8
Implementation of DAG/AST: Value Number
Method
9
Three-Address Code
• A three-address code is:
x := y op z
where x, y and z are names, constants or compiler-
generated temporaries; op is any operator.
• But we may also the following notation for three-address
code (it looks like a machine code instruction)
op y,z,x
apply operator op to y and z, and store the result in x.
• We use the term “three-address code” because each
statement usually contains three addresses (two for
operands, one for the result).
10
Linearized Representation of DAG/AST
• Source Code
– a = b * -c + b * -c
• Three address code
• Tree Representation
11
Three-Address Statements
Binary Operator: op y,z,result or
result := y op z
where op is a binary arithmetic or logical operator. This binary
operator is applied to y and z, and the result of the operation is
stored in result.
Ex:
add a,b,c
gt a,b,c
addr a,b,c
addi a,b,c
Unary Operator: op y,,result or
result := op y
where op is a unary arithmetic or logical operator. This unary
operator is applied to y, and the result of the operation is stored
in result.
Ex: uminus a,,c
12
Three-Address Code
• Two concepts
– Address
– Instruction
• Address
– Name: source-program names to appear as addresses
– Constant: Different types of constants
– Compiler Generated temporary:
13
Three-Address Instruction
Assignment Type 1: x := y op z
op is a binary arithmetic or logical operation
x, y and z are addresses
Assignment Type 2: x := op z
op is a unary arithmetic or logical operation
x and z are addresses
Copy Instruction:x := y
x and z are addresses and x is assigned the value of y
14
Three-Address Instructions
Unconditional Jump: goto L
We will jump to the three-address code with the label L, and the
execution continues from that statement.
Ex: goto L1
jmp 7
Conditional Jump 1: if
// jump to L1
// jump to the statement 7
x goto L and if False x goto L
We will jump to the three-address code with the label L if x is TRUE
and FALSE, respectively. Otherwise, the following three-address
instruction in sequence is executed next.
Conditional Jump 2: if x relop y goto L
We will jump to the three-address code with the label L if the result of y
relop z is true, and the execution continues from that statement. If the result is
false, the execution continues from the statement following this conditional
jump statement.
15
Three-Address Statements (cont.)
Procedure Parameters: param x
Procedure Calls: call p,n
where x is an actual parameter, we invoke the procedure p with
n parameters.
16
Three-Address Statements (cont.)
Indexed Assignments:
x := y[i]
sets x to the value in location i memory units beyond location y
y[i] := x
sets contents of the location i memory units beyond location y to
the value of x
Address and Pointer Assignments:
x := &y
sets the r-value of x to l-value of y
x := *y where y is a pointer whose r-value is a location
sets the r-value of x equal to the contents of that location
*x := y
sets the r-value of the object pointed by x to the r-value of y
17
Three address code example
do i=i+1; while (a[i] < v)
L: t1=i+1 100: t1 = i +1
i=t1 101: i = t1
t2=i*8 102: t2=i*8
t3=a[t2] 103: t3=a[t2]
if t3 < v goto L 104: if t3 < v goto 100
(A) Symbolic Labels (B) Position Numbers
18
Representing 3-Address Statements
op, arg1, arg2, result
• x = minus y
– Does not use arg2
• x = y
– Op is =
• param a1
– Uses neither arg2 nor result
• Conditional/Unconditional jumps
– Put the target label in result
19
Quadruples
• a = b * -c + b * -c
Quadruples
• Store each fields directly
21
Triples
op arg1 arg2
[ ]= x i
:= 0 y
0
1
22
Indirect Triples
23
Translating Expression
24
Goal
25
Synthesized Code and Place Attributes
26
Evaluating the attributes for code generation
27
Three-address code for expression
28
Incremental Translation
• ‘code’ attribute can be long string
• Instead of building up ‘E.code’
– We arrange to generate new three-address instructions
– ‘code’ attribute is not used
– ‘gen’ method is used instead of ‘IR’
• ‘gen’ constructs a three address instruction and appends
it to the sequence of instructions generated so far
29
Syntax-Directed Translation into Three-Address Code
S  id := E
E  E1 + E2
E  E1 * E2
E  - E1
E  ( E1 )
{gen(ID.svalue ‘:=’ E.place)}
{E.place := NewTemp();
gen(E.place ‘:=’ E1.place ‘+’ E2.place )}
{E.place = NewTemp();
gen(E.place ‘:=’ E1.place ‘*’ E2.place ‘,’)}
{E.place = NewTemp();
gen(E.place ‘:=’ ‘minus’ E1.place)}
{E.place = E1.place;}
E  id {E.place = ID.svalue;}
30
Addressing Array Elements
• Elements of arrays can be accessed quickly if the elements are
stored in a block of consecutive locations.
A one-dimensional array A:
baseA low i width
baseA is the address of the first location of the array A,
width is the width of each array element.
low is the index of the first array element
… …
31
Addressing Array Elements (cont.)
baseA+(i-low)*width
can be re-written as i*width + (baseA-low*width)
should be computed
at run-time
can be computed
at compile-time
• So, the location of A[i] can be computed at the run-time by
evaluating the formula i*width+c where c is (baseA-
low*width) which is evaluated at compile-time.
• Intermediate code generator should produce the code to
evaluate this formula i*width+c (one multiplication and
one addition operation).
32
Two-Dimensional Arrays
• A two-dimensional array can be stored in
– either row-major (row-by-row) or
– column-major (column-by-column).
• Most of the programming languages use row-major method.
• Row-major representation of a two-dimensional array:
row1 row2 rown
33
Two-Dimensional Arrays (cont.)
• The location of A[i1,i2] is
baseA+ ((i1-low1)*n2+i2-low2)*width
baseA is the location of the array A.
low1
low2
is the index of the first row
is the index of the first column
n2 is the number of elements in each row
width is the width of each array element
• Again, this formula can be re-written as
((i1*n2)+i2)*width + (baseA-((low1*n1)+low2)*width)
should be computed
at run-time
can be computed
at compile-time
34
Multi-Dimensional Arrays
• In general, the location of A[i1,i2,...,ik] is
(( ... ((i1*n2)+i2) ...)*nk+ik)*width + (baseA-
((...((low1*n1)+low2)...)*nk+lowk)*width)
• So, the intermediate code generator should produce the codes
to evaluate the following formula (to find the location of
A[i1,i2,...,ik]) :
(( ... ((i1*n2)+i2) ...)*nk+ik)*width + c
• To evaluate the (( ... ((i1*n2)+i2) ...)*nk+ik portion of this formula,
we can use the recurrence equation:
e1 = i1
em = em-1 * nm + im
35
Translation of Array Elements
• One dimensional
base + i  w
w: width of each array element
• Two Dimensional
base + i1  w1 + i2  w2
w1: width of a row
w2: width of an element in a row
• k dimensional (generalized)
base + i1  w1 + i2  w2 + … + ik  wk
36
Translation of Array References
• Need to relate the address calculation formulas to a
grammar for array references
• Consider the non-terminal L to generate an array
L € L [E] | id [E]
• Nonterminal L has three synthesized attributes
– L.addr denotes a temporary used to compute the offset
for array reference ij x wj
– L.array is a pointer to the symbol-table entry
• L.array.base is used to determine the actual l-value of it
– L.type is the type of sub-array generated by L
• L.type.width gives the width of the type
37
Syntax-Directed Translation into Three-Address Code
S  id := E;
| L := E;
{gen(ID.svalue ‘:=’ E.place)}
{gen(L.array.base ‘[’ L.addr ‘]’ ‘:=’ E.place)}
E  E1 + E2
| id
| L
{E.place := NewTemp();
gen(E.place ‘:=’ E1.place ‘+’ E2.place )}
{E.place = ID.svalue;}
{E.place = NewTemp();
gen(E.place ‘:=’ L.array.base ‘[’ L.addr ‘]’);}
L  id [E]
| L1 [E]
{L.array = ID.svalue;
L.type = L.array.type.elem;
L.addr = NewTemp();
gen(L.addr ‘:=’ E.place ‘*’ L.type.width)}
{L.array = L1.array;
L.type = L1.type.elem;
t = NewTemp();
L.addr = NewTemp();
gen(t ‘:=’ E.place ‘*’ L.type.width);
gen(L.addr ‘:=’ L1.addr ‘+’ t)}
38
Thank You
39

More Related Content

What's hot (20)

PPTX
Peephole Optimization
United International University
 
PDF
Syntax analysis
Akshaya Arunan
 
PPTX
Abstract Data Types
karthikeyanC40
 
PPT
Intermediate code generation (Compiler Design)
Tasif Tanzim
 
PPT
Intermediate code generation
Dr.DHANALAKSHMI SENTHILKUMAR
 
PDF
Compiler Construction | Lecture 1 | What is a compiler?
Eelco Visser
 
PPTX
Intermediate code- generation
rawan_z
 
PPTX
Unit iv(simple code generator)
Kalaimathi Vijayakumar
 
PPTX
Basic of compiler
Abhishek Singh
 
PPTX
Lexical analyzer generator lex
Anusuya123
 
PPTX
Control Flow Statements
Tarun Sharma
 
PDF
Code generation in Compiler Design
Kuppusamy P
 
PPTX
Code generation
Aparna Nayak
 
PPTX
Basic blocks - compiler design
hmnasim15
 
PDF
Symbol table in compiler Design
Kuppusamy P
 
PDF
Final_DSPRAC (1).pdf
Siddhant Pal
 
PDF
Python exception handling
Mohammed Sikander
 
PPTX
Peephole optimization techniques in compiler design
Anul Chaudhary
 
PPTX
Register Transfer Language,Bus and Memory Transfer
lavanya marichamy
 
PPT
Query optimization and processing for advanced database systems
meharikiros2
 
Peephole Optimization
United International University
 
Syntax analysis
Akshaya Arunan
 
Abstract Data Types
karthikeyanC40
 
Intermediate code generation (Compiler Design)
Tasif Tanzim
 
Intermediate code generation
Dr.DHANALAKSHMI SENTHILKUMAR
 
Compiler Construction | Lecture 1 | What is a compiler?
Eelco Visser
 
Intermediate code- generation
rawan_z
 
Unit iv(simple code generator)
Kalaimathi Vijayakumar
 
Basic of compiler
Abhishek Singh
 
Lexical analyzer generator lex
Anusuya123
 
Control Flow Statements
Tarun Sharma
 
Code generation in Compiler Design
Kuppusamy P
 
Code generation
Aparna Nayak
 
Basic blocks - compiler design
hmnasim15
 
Symbol table in compiler Design
Kuppusamy P
 
Final_DSPRAC (1).pdf
Siddhant Pal
 
Python exception handling
Mohammed Sikander
 
Peephole optimization techniques in compiler design
Anul Chaudhary
 
Register Transfer Language,Bus and Memory Transfer
lavanya marichamy
 
Query optimization and processing for advanced database systems
meharikiros2
 

Similar to Lecture 12 intermediate code generation (20)

PDF
Intermediate code generation
Akshaya Arunan
 
PPT
Chapter 6 Intermediate Code Generation
Radhakrishnan Chinnusamy
 
PPTX
Three address code In Compiler Design
Shine Raj
 
PPTX
Compiler Design_Intermediate code generation new ppt.pptx
RushaliDeshmukh2
 
PPT
458237.-Compiler-Design-Intermediate-code-generation.ppt
PalaniSamyB3
 
PDF
INTERMEDIATE CODE GENERTION-CD UNIT-3.pdf
Ranjeet Reddy
 
PPTX
Compiler Design_Code generation techniques.pptx
RushaliDeshmukh2
 
DOC
Compiler notes--unit-iii
Sumathi Gnanasekaran
 
PPTX
Syntax directed definition and intermediate code generation
JananiRamannachetty1
 
PPTX
UNIT - III Compiler.pptx power point presentation
KowsalyaG17
 
PDF
Project presentation PPT.pdf this is help for student who doing this complier...
AmitSingh395981
 
PDF
Chapter 11 - Intermediate Code Generation.pdf
RAnwarpasha
 
PPT
Chapter Eight(2)
bolovv
 
PPTX
Assignment statements
Divya Devan
 
PDF
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
venkatapranaykumarGa
 
PPT
Interm codegen
Anshul Sharma
 
PDF
Presentation1.pdf
GauravChaudhary531452
 
PDF
12IRGeneration.pdf
SHUJEHASSAN
 
PPTX
complier design unit 4 for helping students
aniketsugandhi1
 
Intermediate code generation
Akshaya Arunan
 
Chapter 6 Intermediate Code Generation
Radhakrishnan Chinnusamy
 
Three address code In Compiler Design
Shine Raj
 
Compiler Design_Intermediate code generation new ppt.pptx
RushaliDeshmukh2
 
458237.-Compiler-Design-Intermediate-code-generation.ppt
PalaniSamyB3
 
INTERMEDIATE CODE GENERTION-CD UNIT-3.pdf
Ranjeet Reddy
 
Compiler Design_Code generation techniques.pptx
RushaliDeshmukh2
 
Compiler notes--unit-iii
Sumathi Gnanasekaran
 
Syntax directed definition and intermediate code generation
JananiRamannachetty1
 
UNIT - III Compiler.pptx power point presentation
KowsalyaG17
 
Project presentation PPT.pdf this is help for student who doing this complier...
AmitSingh395981
 
Chapter 11 - Intermediate Code Generation.pdf
RAnwarpasha
 
Chapter Eight(2)
bolovv
 
Assignment statements
Divya Devan
 
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
venkatapranaykumarGa
 
Interm codegen
Anshul Sharma
 
Presentation1.pdf
GauravChaudhary531452
 
12IRGeneration.pdf
SHUJEHASSAN
 
complier design unit 4 for helping students
aniketsugandhi1
 
Ad

More from Iffat Anjum (20)

PPTX
Fog computing ( foggy cloud)
Iffat Anjum
 
PPTX
Cognitive radio network_MS_defense_presentation
Iffat Anjum
 
PPTX
Lecture 15 run timeenvironment_2
Iffat Anjum
 
PPT
Lecture 16 17 code-generation
Iffat Anjum
 
PPTX
Lecture 14 run time environment
Iffat Anjum
 
PPT
Lecture 13 intermediate code generation 2.pptx
Iffat Anjum
 
PPTX
Lecture 11 semantic analysis 2
Iffat Anjum
 
PPTX
Lecture 09 syntax analysis 05
Iffat Anjum
 
PPTX
Lecture 10 semantic analysis 01
Iffat Anjum
 
PPTX
Lecture 07 08 syntax analysis-4
Iffat Anjum
 
PPT
Lecture 06 syntax analysis 3
Iffat Anjum
 
PPT
Lecture 05 syntax analysis 2
Iffat Anjum
 
PPT
Lecture 03 lexical analysis
Iffat Anjum
 
PPT
Lecture 04 syntax analysis
Iffat Anjum
 
PPTX
Lecture 02 lexical analysis
Iffat Anjum
 
PPT
Compiler Design - Introduction to Compiler
Iffat Anjum
 
PPTX
Distributed contention based mac protocol for cognitive radio
Iffat Anjum
 
PPT
On qo s provisioning in context aware wireless sensor networks for healthcare
Iffat Anjum
 
PPT
Data link control
Iffat Anjum
 
PPT
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Iffat Anjum
 
Fog computing ( foggy cloud)
Iffat Anjum
 
Cognitive radio network_MS_defense_presentation
Iffat Anjum
 
Lecture 15 run timeenvironment_2
Iffat Anjum
 
Lecture 16 17 code-generation
Iffat Anjum
 
Lecture 14 run time environment
Iffat Anjum
 
Lecture 13 intermediate code generation 2.pptx
Iffat Anjum
 
Lecture 11 semantic analysis 2
Iffat Anjum
 
Lecture 09 syntax analysis 05
Iffat Anjum
 
Lecture 10 semantic analysis 01
Iffat Anjum
 
Lecture 07 08 syntax analysis-4
Iffat Anjum
 
Lecture 06 syntax analysis 3
Iffat Anjum
 
Lecture 05 syntax analysis 2
Iffat Anjum
 
Lecture 03 lexical analysis
Iffat Anjum
 
Lecture 04 syntax analysis
Iffat Anjum
 
Lecture 02 lexical analysis
Iffat Anjum
 
Compiler Design - Introduction to Compiler
Iffat Anjum
 
Distributed contention based mac protocol for cognitive radio
Iffat Anjum
 
On qo s provisioning in context aware wireless sensor networks for healthcare
Iffat Anjum
 
Data link control
Iffat Anjum
 
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Iffat Anjum
 
Ad

Recently uploaded (20)

PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Controller Request and Response in Odoo18
Celine George
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Introduction presentation of the patentbutler tool
MIPLM
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Difference between write and update in odoo 18
Celine George
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
infertility, types,causes, impact, and management
Ritu480198
 

Lecture 12 intermediate code generation

  • 2. Compiler Architecture Parser Static Checker Intermediate Code generator Code Generator Intermediate Code Target language Front End Back End • m  n compliers can be built by writing m front ends and n back ends – save considerable amount of effort • We assume parsing, static checking and IC generation is done sequentially – These can be combined and done during parsing • Static checking – Operator operand compatibility – Proper placement of break/continue keywords etc. 2
  • 3. Intermediate Code (IC) • The given program in a source language is converted to an equivalent program in an intermediate language by the IC generator. • Ties the front and back ends together • Language and Machine neutral • Many forms • Level depends on how being processed • More than one intermediate language may be used by a compiler 3
  • 4. • Intermediate language can be many different languages, and the designer of the compiler decides this intermediate language. – syntax trees can be used as an intermediate language. – postfix notation can be used as an intermediate language. – three-address code (Quadraples) can be used as an intermediate language • we will use quadraples to discuss intermediate code generation • quadraples are close to machine instructions, but they are not actual machine instructions. – some programming languages have well defined intermediate languages. • java – java virtual machine • prolog – warren abstract machine • In fact, there are byte-code emulators to execute instructions in these intermediate languages. Intermediate Code (IC) 4
  • 6. Intermediate Languages Types • Graphical IRs: – Abstract Syntax trees – Directed Acyclic Graphs (DAGs) – Control Flow Graphs • Linear IRs: – Stack based (postfix) – Three address code (quadruples) 6
  • 7. Graphical IRs • Abstract Syntax Trees (AST) – retain essential structure of the parse tree, eliminating unneeded nodes. • Directed Acyclic Graphs (DAG) – compacted AST to avoid duplication – smaller footprint as well • Control flow graphs (CFG) – explicitly model control flow 7
  • 8. ASTs and DAGs: := a + ** b - (uni) c := a + b - (uni) b * - (uni) c c a := b *-c + b*-c AST DAG 8
  • 9. Implementation of DAG/AST: Value Number Method 9
  • 10. Three-Address Code • A three-address code is: x := y op z where x, y and z are names, constants or compiler- generated temporaries; op is any operator. • But we may also the following notation for three-address code (it looks like a machine code instruction) op y,z,x apply operator op to y and z, and store the result in x. • We use the term “three-address code” because each statement usually contains three addresses (two for operands, one for the result). 10
  • 11. Linearized Representation of DAG/AST • Source Code – a = b * -c + b * -c • Three address code • Tree Representation 11
  • 12. Three-Address Statements Binary Operator: op y,z,result or result := y op z where op is a binary arithmetic or logical operator. This binary operator is applied to y and z, and the result of the operation is stored in result. Ex: add a,b,c gt a,b,c addr a,b,c addi a,b,c Unary Operator: op y,,result or result := op y where op is a unary arithmetic or logical operator. This unary operator is applied to y, and the result of the operation is stored in result. Ex: uminus a,,c 12
  • 13. Three-Address Code • Two concepts – Address – Instruction • Address – Name: source-program names to appear as addresses – Constant: Different types of constants – Compiler Generated temporary: 13
  • 14. Three-Address Instruction Assignment Type 1: x := y op z op is a binary arithmetic or logical operation x, y and z are addresses Assignment Type 2: x := op z op is a unary arithmetic or logical operation x and z are addresses Copy Instruction:x := y x and z are addresses and x is assigned the value of y 14
  • 15. Three-Address Instructions Unconditional Jump: goto L We will jump to the three-address code with the label L, and the execution continues from that statement. Ex: goto L1 jmp 7 Conditional Jump 1: if // jump to L1 // jump to the statement 7 x goto L and if False x goto L We will jump to the three-address code with the label L if x is TRUE and FALSE, respectively. Otherwise, the following three-address instruction in sequence is executed next. Conditional Jump 2: if x relop y goto L We will jump to the three-address code with the label L if the result of y relop z is true, and the execution continues from that statement. If the result is false, the execution continues from the statement following this conditional jump statement. 15
  • 16. Three-Address Statements (cont.) Procedure Parameters: param x Procedure Calls: call p,n where x is an actual parameter, we invoke the procedure p with n parameters. 16
  • 17. Three-Address Statements (cont.) Indexed Assignments: x := y[i] sets x to the value in location i memory units beyond location y y[i] := x sets contents of the location i memory units beyond location y to the value of x Address and Pointer Assignments: x := &y sets the r-value of x to l-value of y x := *y where y is a pointer whose r-value is a location sets the r-value of x equal to the contents of that location *x := y sets the r-value of the object pointed by x to the r-value of y 17
  • 18. Three address code example do i=i+1; while (a[i] < v) L: t1=i+1 100: t1 = i +1 i=t1 101: i = t1 t2=i*8 102: t2=i*8 t3=a[t2] 103: t3=a[t2] if t3 < v goto L 104: if t3 < v goto 100 (A) Symbolic Labels (B) Position Numbers 18
  • 19. Representing 3-Address Statements op, arg1, arg2, result • x = minus y – Does not use arg2 • x = y – Op is = • param a1 – Uses neither arg2 nor result • Conditional/Unconditional jumps – Put the target label in result 19
  • 20. Quadruples • a = b * -c + b * -c
  • 21. Quadruples • Store each fields directly 21
  • 22. Triples op arg1 arg2 [ ]= x i := 0 y 0 1 22
  • 26. Synthesized Code and Place Attributes 26
  • 27. Evaluating the attributes for code generation 27
  • 28. Three-address code for expression 28
  • 29. Incremental Translation • ‘code’ attribute can be long string • Instead of building up ‘E.code’ – We arrange to generate new three-address instructions – ‘code’ attribute is not used – ‘gen’ method is used instead of ‘IR’ • ‘gen’ constructs a three address instruction and appends it to the sequence of instructions generated so far 29
  • 30. Syntax-Directed Translation into Three-Address Code S  id := E E  E1 + E2 E  E1 * E2 E  - E1 E  ( E1 ) {gen(ID.svalue ‘:=’ E.place)} {E.place := NewTemp(); gen(E.place ‘:=’ E1.place ‘+’ E2.place )} {E.place = NewTemp(); gen(E.place ‘:=’ E1.place ‘*’ E2.place ‘,’)} {E.place = NewTemp(); gen(E.place ‘:=’ ‘minus’ E1.place)} {E.place = E1.place;} E  id {E.place = ID.svalue;} 30
  • 31. Addressing Array Elements • Elements of arrays can be accessed quickly if the elements are stored in a block of consecutive locations. A one-dimensional array A: baseA low i width baseA is the address of the first location of the array A, width is the width of each array element. low is the index of the first array element … … 31
  • 32. Addressing Array Elements (cont.) baseA+(i-low)*width can be re-written as i*width + (baseA-low*width) should be computed at run-time can be computed at compile-time • So, the location of A[i] can be computed at the run-time by evaluating the formula i*width+c where c is (baseA- low*width) which is evaluated at compile-time. • Intermediate code generator should produce the code to evaluate this formula i*width+c (one multiplication and one addition operation). 32
  • 33. Two-Dimensional Arrays • A two-dimensional array can be stored in – either row-major (row-by-row) or – column-major (column-by-column). • Most of the programming languages use row-major method. • Row-major representation of a two-dimensional array: row1 row2 rown 33
  • 34. Two-Dimensional Arrays (cont.) • The location of A[i1,i2] is baseA+ ((i1-low1)*n2+i2-low2)*width baseA is the location of the array A. low1 low2 is the index of the first row is the index of the first column n2 is the number of elements in each row width is the width of each array element • Again, this formula can be re-written as ((i1*n2)+i2)*width + (baseA-((low1*n1)+low2)*width) should be computed at run-time can be computed at compile-time 34
  • 35. Multi-Dimensional Arrays • In general, the location of A[i1,i2,...,ik] is (( ... ((i1*n2)+i2) ...)*nk+ik)*width + (baseA- ((...((low1*n1)+low2)...)*nk+lowk)*width) • So, the intermediate code generator should produce the codes to evaluate the following formula (to find the location of A[i1,i2,...,ik]) : (( ... ((i1*n2)+i2) ...)*nk+ik)*width + c • To evaluate the (( ... ((i1*n2)+i2) ...)*nk+ik portion of this formula, we can use the recurrence equation: e1 = i1 em = em-1 * nm + im 35
  • 36. Translation of Array Elements • One dimensional base + i  w w: width of each array element • Two Dimensional base + i1  w1 + i2  w2 w1: width of a row w2: width of an element in a row • k dimensional (generalized) base + i1  w1 + i2  w2 + … + ik  wk 36
  • 37. Translation of Array References • Need to relate the address calculation formulas to a grammar for array references • Consider the non-terminal L to generate an array L € L [E] | id [E] • Nonterminal L has three synthesized attributes – L.addr denotes a temporary used to compute the offset for array reference ij x wj – L.array is a pointer to the symbol-table entry • L.array.base is used to determine the actual l-value of it – L.type is the type of sub-array generated by L • L.type.width gives the width of the type 37
  • 38. Syntax-Directed Translation into Three-Address Code S  id := E; | L := E; {gen(ID.svalue ‘:=’ E.place)} {gen(L.array.base ‘[’ L.addr ‘]’ ‘:=’ E.place)} E  E1 + E2 | id | L {E.place := NewTemp(); gen(E.place ‘:=’ E1.place ‘+’ E2.place )} {E.place = ID.svalue;} {E.place = NewTemp(); gen(E.place ‘:=’ L.array.base ‘[’ L.addr ‘]’);} L  id [E] | L1 [E] {L.array = ID.svalue; L.type = L.array.type.elem; L.addr = NewTemp(); gen(L.addr ‘:=’ E.place ‘*’ L.type.width)} {L.array = L1.array; L.type = L1.type.elem; t = NewTemp(); L.addr = NewTemp(); gen(t ‘:=’ E.place ‘*’ L.type.width); gen(L.addr ‘:=’ L1.addr ‘+’ t)} 38