Announcements. Project 2: released due this sunday! Midterm date is now set: check newsgroup / website. Chapter 7: Translation to IR

Size: px
Start display at page:

Download "Announcements. Project 2: released due this sunday! Midterm date is now set: check newsgroup / website. Chapter 7: Translation to IR"

Transcription

1 Announcements Project 2: released due this sunday! Midterm date is now set: check newsgroup / website. 1

2 Translation to Intermediate Code (Chapter 7) This stage converts an AST into an intermediate representation. Last stage of semantic analysis : the IR can be thought of as representation of the meaning of the program in more low-level terms (without committing to a specific target machine). 2

3 Translation to Intermediate Code (Chapter 7) It is also possible to go directly to target assembly code. Q: Why use intermediate representation? 3

4 Why Use IR? More portable compiler architecture Java ML Pascal C C++ IR Sparc MIPS PowerPC x86 4

5 Why Use IR? Better separation of concerns: Frontend not complicated with details of target architecture Backend not complicated with details of the language semantics. 5

6 Design of a good IR What do we seek from a good IR? convenient to produce by semantic analysis phase convenient to translate to machine language (for all desired architectures) clear and simple meaning so that optimizing transformations can be specified and implemented easily. 6

7 IR Trees Exp ::= CONST( int ) NAME( Label ) TEMP( Temp ) BINOP( Op, Exp, Exp) MEM(Exp) CALL( Exp fun, List<Exp> args) ESEQ( Stm, Exp ) Stm ::= MOVE(Exp dst, Exp src) EXP(Exp) JUMP(Label) CJUMP(RelOp, Exp, Exp, Label thn, Label els) SEQ( Stm, Stm) LABEL( Label ) Op ::= PLUS, MINUS, MUL, DIV, AND, OR, LSHIFT,... RelOp ::= EQ, NE, LT, GT, LE, GE, ULT, ULE,... 7

8 Translation to IR Relatively Straightforward but many cases: Trouble is a kind of combinatorial explosion: different kinds of expressions / statements x different kinds of usage context. To emit good code we may need to generate different code for an expression / statement based on its usage context. Examples on next slides 8

9 Translation to IR Example: assignment expression in C/Java (but not MiniJava) Exercise: draw an IRTree for the expression x = x + 1 9

10 Translation to IR Exercise 2: Assume the translator is compositional (i.e. it builds up IR for non-leaf AST nodes by generating IR snippets for its children recursively and then glueing these together. Use the code from exercise 1 to build IR trees for these two program fragments while (x<10) {...do stuff.. x = x+1; y = x = x+1; Could you do better? How? 10

11 Translation to IR Example 2: Boolean expressions and if-then-else. Consider these two boolean expressions (assume x is an int local variable and flag is a boolean local variable) Exercise 1: x < 5 flag Draw an IRExp tree that represents each of these. 11

12 Translation to IR Example 2: Boolean expressions and if-then-else. Exercise 2: Consider the following MiniJava statement if (E) T else F //statement //statement Assume you already generated IR code for E, T and F. Show the IRTree for the if (use symbols E, T, F as placeholder for their respective IR code). 12

13 Translation to IR Example 2: Boolean expressions and if-then-else. Exercise 3: Now put together the information from Exercise 1 and two to draw the IRTree for if (x<5) T else F if (flag) T else F Could you do better? How? 13

14 Context Dependent Translation To generate nice code, we need to be able to generate different code for some expressions depending on how they are used. We distinguish three kinds of usage contexts for an exp E contexts that need an explicit value: x = E f(e) return E contexts that discard the expression value: E; contexts that use E's value as a branching condition. if (E)... else... E &&... 14

15 Context Dependent Translation Instead of returning an actual IRExp (or IRStm) our translator returns an object that knows how to create good code for these three different kinds of contexts): public abstract class TRExp { /** * The expression is used in a context where an explicit result * value is required. */ abstract IRExp unex(); /** * The expression is used in a context that discards the value * (good compilation strategy may avoid producing it). */ abstract IRStm unnx(); /** * The expression is used as the condition for a CJUMP. */ abstract IRStm uncx(label iftrue, Label iffalse); 15

16 Example: Context dependent Assign Exp public TRExp visit(assign n) { final Access var = currentenv.lookup(n.name); TRExp val = n.value.accept(this); final IRStm stm = IR.MOVE( var.exp(frame.fp()), val.unex()); return new TRExp() { IRExp unex() { return ESEQ(stm, var.exp(frame.fp())); IRStm unnx() { return stm; IRStm uncx(label iftrue, Label iffalse) {... ; 16

17 The Ex class Many AST nodes naturally translate to expression that produce an explicit value. To use them as a statement we must discard that value. To use them as a branch condition we must generate an actual branch with a test of the expression's value. 17

18 The Ex class public class Ex extends TRExp { private final IRExp exp; public Ex(IRExp exp) { this.exp = IRStm uncx(label t, Label f) { return CJUMP(RelOp.NE, exp, CONST(0), t, IRExp unex() { return IRStm unnx() { return EXP(exp); 18

19 The Nx class Many AST nodes naturally translate to an IRStm that produces no value. It should be illegal to use them in a context that wants a value (including as a branc condition). If your type checker works, then the uncx and unex cases are illegal and needn't have a real implementation. 19

20 public class Nx extends TRExp { private final IRStm stm; public Nx(IRStm stm) { this.stm = stm; The Nx class public IRStm uncx(label iftrue, Label iffalse) { throw new Error("Bug in type checker?"); public IRExp unex() { throw new Error("Bug in type checker?"); public IRStm unnx() { return stm; 20

21 The Cx class Some AST expressions most naturally translate to a CJUMP (e.g. comparing numbers with < can only be done with a CJUMP!) We can convert them into an expression that returns an explicit value by using that branch to store an explicit value (typically 0 for false, and 1 for true). 21

22 The Cx class import static minijava.irtree.ir.*; public abstract class Cx extends TRExp { abstract IRStm uncx(label iftrue, Label iffalse); IRExp unex() { Label t = new Label(); Label f = new Label(); TEMP r = TEMP(new Temp()); return ESEQ( SEQ( MOVE(r, TRUE), uncx(t,f), LABEL(f), MOVE(r, FALSE), LABEL(t)), r); IRStm unnx() { Label end = new Label(); return SEQ( uncx(end, end), LABEL(end) ); 22

23 Next Now that we have seen the IR tree model that we are using and... the scaffolding we use to generate code for different types of expression contexts... Let's look at a series of specific language constructs and think about how to generate IR code for them. 23

24 1) Simple (Local) Variables Example: int f(int p) { int x; x = 4; return x + p; Problem: The layout of activation records is dependent on the target architecture. => address computations for local variables and formal parameters are dependent on target architecture. Q: How can we write our IR code generator to generate the right addressing calculations, without making the translator implementation specific to an architecture. 24

25 The Frame Class Problem: The layout of activation records is dependent on the target architecture. => address computations for local variables and formal parameters are dependent on target architecture. Q: How can we write our IR code generator to generate the right addressing calculations, without making the translator implementation specific to one architecture. 25

26 The Frame Class Frame Abstract class X86Frame PPCFrame MIPSFrame... Frame class has abstract methods to create an object to keep track of the current frame's layout. allocate variables / formals in the frame special temporaries (the FP and RV) other target architecture specific stuff. Designed to hide details such as frame layout and whether locals/formals are in registers or in the frame. 26

27 The Frame Class public abstract class Frame extends DefaultIndentable { /** Create a new frame for a the target architecture and * allocate space for the formal parameters according to the * target architecture's calling conventions. */ public abstract Frame newframe(label name, List<Boolean> formalsescape); /**A label that points to the beginning of the function's code.*/ public abstract Label getlabel(); /** fetch a list of abstract representations of the addresses of * the formal parameters.*/ public abstract List<Access> getformals(); /** Allocate space for a local variable in this frame.*/ public abstract Access alloclocal(boolean escapes); /** Frame pointer (e.g. a temp mapped to %ebp on x86) */ public abstract Temp FP(); /** Return value (e.g. a temp mapped to %eax on x86) */ public abstract Temp RV();... 27

28 The Access Class /** * An instance of this class represents a place to store a local, temp * or parameter. * * It may be a register or memory address relative to the current * stack frame. * * This class is abstract for two reasons. * * First, there are concrete subclasses * for the different cases (at least two: one for register and one for * inframe). * * Second, each architecture can provide its own concrete * implementations. */ public abstract class Access { /** * Translate into intermediate representation (returns an IRExp * that can be used either as an L-value or an R-value */ public abstract IRExp exp(temp fp); 28

29 package minijava.ir.frame.x86; import static minijava.ir.tree.ir.*; class InFrame extends Access { private int offset; InFrame(int offset) {... The Access public IRExp exp(temp fp) { return MEM(PLUS(TEMP(fp), offset)); class InReg extends Access { private Temp name; InReg(Temp name) {... Note: these classes are not public IRExp exp(temp frameptr) { return TEMP(name); 29

30 X86Frame Implementation Formals: always allocated as InFrame (recall our exercise with the gcc assembly code for exact details about the offset computations) Locals: allocated as InFrame when escapes is true. allocated as InReg when escapes is false. for MiniJava escapes is always false. Since the Frame stuff is supposed to be reusable for other programming languages, we should implement the escapes = true case however. Running out of Registers (i.e. Temps)? don't worry now, this phase assumes infinite # of Temps => worry later: Register Allocation phase. 30

31 2) Array Variables Two different styles of array variables (in different languages) Example: (PASCAL) var a : array [1..10] of integer begin... b := a; // copies contents of array a -> b end Example: (C) int a[10], *b;... b = a; // copies address of array a[0] -> b 31

32 2) Array Variables MiniJava has pointer arrays. (So an array variable is always a pointer to some (dynamically allocated) array. Example: (MiniJava) int[] a, b; a = new int[10]; b = new int[10]; b = a; // copies pointer to an array from a -> b // (The original b array becomes garbage) // a and b now both point to the same array. 32

33 2) Array Variables in MiniJava How to represent MiniJava arrays? How to compute IR code for array subscripting expressions? Example: (MiniJava) int[] a, b; int i; int i; a = new int[10]; b = new int[a.length];... i = 0 while (i < a.length) { a[i] = b[i]; i = i+1; Let's figure this out together 33

34 2) Pascal Style (Static) Arrays? How to represent Pascal arrays? How to compute IR code for array subscripting expressions? Example: (Pascal) var a : array [10..15] of integer; var i : integer;... a[i] = 20;... 34

35 3) Records / Structs How to represent Pascal style records (or C style structs)? How to compute IR code for accessing fields of a record. Example: (Pascal) type Point = record x : integer; y : integer; end; type Line = record st : Point en : Point end; var p : Point; var l : Line; p1.x := 10; p1.y := 20; l.st := p1; l.en := p1; l.en.x = l.st.x+10;... 35

36 3) Records / Structs How to represent Pascal style records (or C style structs)? How to compute IR code for accessing fields of a record. Example: (Pascal) type Point = record x : integer; y : integer; end; type Line = record st : Point en : Point end; var p : Point; var l : Line; p1.x := 10; p1.y := 20; l.st := p1; l.en := p1; l.en.x = l.st.x+10;... 36

37 4) && (lazy and) Examples (Java): if (x<5 && x>=0)... flag = x<5 && x>=0 flag = a && b if (a && b)... if (x!=null && x.isempty())... 37

38 Examples (Java): int x; int fac; x = 10; fac = 1; while (x>0) { fac = fac * x; x--; 5) while loops Other loops are similar (can convert to while loops!) Note: comments in the book about for loop would make more sense for Pascal style for loops: for i := low to high do... 38

39 These are easy... 6) (static) function calls We have an IR code to represent function calls directly. f(<a>,<b>,<c>) => CALL( NAME(f_label),list(<a>,<b>,<c>)) In MiniJava sans inheritance, methods are just like static functions. <r>.f(<a>,<b>,<c>) =>??? What about static links? What about MiniJava with inheritance? 39

40 7) Strings (and other big literals ) HL languages usually allow the inclusion of String literals inside of expressions. Example: System.out.println( Hello World ); How does this work? What kind of IR is generated? Where is this String stored? Note: This kind of idea also applies to other big literals (or even small ones). E.g. array constants in Java or quoted lists in Scheme. Q: What about mutation operations on these data? 40

41 Example: (MiniJava) 8) variable declarations int foo(int p1, boolean p2) { int x; boolean b;... Example: (Java) (allows nested scopes and init expressions) int x = 0; int y = x+20; { int z;

42 Example: (MiniJava) class Foo { 9) Procedure / Method decls int foo(int p1, boolean p2) { int x; boolean b;... Only body compiled into IR. Also: a ProcedureFragment is created and stored in a global list of fragments. Q: Besides the IR of the body, what else do we expect to find in the final assembly code? Can we produce all of this now? 42

43 10) Classes & Objects (sans inheritance) Example: (MiniJava) class Vehicle { int position; int gas; int move(int x) { position = position + x ; return position; int fill(int add) { gas = gas + add; return gas;... new Vehicle()... 43

Administration. Today

Administration. Today Announcements Administration Office hour today changed to 3:30 4:30 Class is cancelled next Monday I have to attend a Senate Curriculum Committee meeting Project Build a Functions compiler from the Expressions

More information

CPSC 411, Fall 2010 Midterm Examination

CPSC 411, Fall 2010 Midterm Examination CPSC 411, Fall 2010 Midterm Examination. Page 1 of 11 CPSC 411, Fall 2010 Midterm Examination Name: Q1: 10 Q2: 15 Q3: 15 Q4: 10 Q5: 10 60 Please do not open this exam until you are told to do so. But please

More information

7 Translation to Intermediate Code

7 Translation to Intermediate Code 7 Translation to Intermediate Code ( 7. Translation to Intermediate Code, p. 150) This chpater marks the transition from the source program analysis phase to the target program synthesis phase. All static

More information

CPSC 411, 2015W Term 2 Midterm Exam Date: February 25, 2016; Instructor: Ron Garcia

CPSC 411, 2015W Term 2 Midterm Exam Date: February 25, 2016; Instructor: Ron Garcia CPSC 411, 2015W Term 2 Midterm Exam Date: February 25, 2016; Instructor: Ron Garcia This is a closed book exam; no notes; no calculators. Answer in the space provided. There are 8 questions on 14 pages,

More information

Compilation 2013 Translation to IR

Compilation 2013 Translation to IR Compilation 2013 Erik Ernst Aarhus University Intermediate Representation Translation source/target uses IR as a bridge Simplification: n+m combinations, not n m Java SML Pascal C C++ SPARC MIPS Pentium

More information

Topic 7: Intermediate Representations

Topic 7: Intermediate Representations Topic 7: Intermediate Representations COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 2 Intermediate Representations 3 Intermediate Representations 4 Intermediate Representations

More information

Compiler Construction 2009/2010: Intermediate Representation

Compiler Construction 2009/2010: Intermediate Representation Compiler Construction 2009/2010: Intermediate Representation Annette Bieniusa November 24, 2009 Outline 1 Contexts 2 Canonical Trees Using Expressions in different Contexts Compare the translation for

More information

Compiler Internals. Reminders. Course infrastructure. Registering for the course

Compiler Internals. Reminders. Course infrastructure. Registering for the course Compiler Internals 15-745 Optimizing Compilers Spring 2006 Peter Lee Reminders Get on the course mailing list Check out the web site http://www.cs.cmu.edu/afs/cs/ academic/class/15745-s06/web subscribe

More information

Where we are. What makes a good IR? Intermediate Code. CS 4120 Introduction to Compilers

Where we are. What makes a good IR? Intermediate Code. CS 4120 Introduction to Compilers Where we are CS 4120 Introduction to Compilers Andrew Myers Cornell University Lecture 13: Intermediate Code 25 Sep 09 Source code (character stream) Token stream Abstract syntax tree Abstract syntax tree

More information

Translation. From ASTs to IR trees

Translation. From ASTs to IR trees Translation From ASTs to IR trees Copyright c 2010 by Antony L. Hosking. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target

More information

CSE 401 Final Exam. December 16, 2010

CSE 401 Final Exam. December 16, 2010 CSE 401 Final Exam December 16, 2010 Name You may have one sheet of handwritten notes plus the handwritten notes from the midterm. You may also use information about MiniJava, the compiler, and so forth

More information

We ve written these as a grammar, but the grammar also stands for an abstract syntax tree representation of the IR.

We ve written these as a grammar, but the grammar also stands for an abstract syntax tree representation of the IR. CS 4120 Lecture 14 Syntax-directed translation 26 September 2011 Lecturer: Andrew Myers We want to translate from a high-level programming into an intermediate representation (IR). This lecture introduces

More information

Languages and Compiler Design II IR Code Generation I

Languages and Compiler Design II IR Code Generation I Languages and Compiler Design II IR Code Generation I Material provided by Prof. Jingke Li Stolen with pride and modified by Herb Mayer PSU Spring 2010 rev.: 4/16/2010 PSU CS322 HM 1 Agenda Grammar G1

More information

IR trees: Statements. IR trees: Expressions. Translating MiniJava. Kinds of expressions. Local variables: Allocate as a temporary t

IR trees: Statements. IR trees: Expressions. Translating MiniJava. Kinds of expressions. Local variables: Allocate as a temporary t IR trees: Expressions CONST Integer constant i i NAME Symbolic constant n [a code label] n TEMP Temporary t [one of any number of registers ] t BINOP Application of binary operator: e 1 e 2 ADD, SUB, MUL,

More information

System Software Assignment 1 Runtime Support for Procedures

System Software Assignment 1 Runtime Support for Procedures System Software Assignment 1 Runtime Support for Procedures Exercise 1: Nested procedures Some programming languages like Oberon and Pascal support nested procedures. 1. Find a run-time structure for such

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation Rupesh Nasre. CS3300 Compiler Design IIT Madras Aug 2015 Character stream Lexical Analyzer Machine-Independent Code Optimizer F r o n t e n d Token stream Syntax Analyzer Syntax

More information

CMPT 379 Compilers. Anoop Sarkar. 11/13/07 1. TAC: Intermediate Representation. Language + Machine Independent TAC

CMPT 379 Compilers. Anoop Sarkar.  11/13/07 1. TAC: Intermediate Representation. Language + Machine Independent TAC CMPT 379 Compilers Anoop Sarkar http://www.cs.sfu.ca/~anoop 11/13/07 1 TAC: Intermediate Representation Language Specific Language + Machine Independent Machine Dependent Front End AST Intermediate Code

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation Rupesh Nasre. CS3300 Compiler Design IIT Madras July 2018 Character stream Lexical Analyzer Machine-Independent Code Code Optimizer F r o n t e n d Token stream Syntax Analyzer

More information

Compilers and computer architecture: A realistic compiler to MIPS

Compilers and computer architecture: A realistic compiler to MIPS 1 / 1 Compilers and computer architecture: A realistic compiler to MIPS Martin Berger November 2017 Recall the function of compilers 2 / 1 3 / 1 Recall the structure of compilers Source program Lexical

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Intermediate Representations

Intermediate Representations Intermediate Representations A variety of intermediate representations are used in compilers Most common intermediate representations are: Abstract Syntax Tree Directed Acyclic Graph (DAG) Three-Address

More information

CPSC 411: Introduction to Compiler Construction

CPSC 411: Introduction to Compiler Construction CPSC 411: to Compiler Construction Kris De Volder kdvolder@cs.ubc.ca http://www.ugrad.cs.ubc.ca/~cs411/ 1 This Lecture Course Organization and Policies Website Newsgroup Assignments General Information

More information

(Not Quite) Minijava

(Not Quite) Minijava (Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier

More information

CSE P 501 Exam 8/5/04

CSE P 501 Exam 8/5/04 Name There are 7 questions worth a total of 65 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. You may refer to the following references: Course

More information

Principles of Compiler Design

Principles of Compiler Design Principles of Compiler Design Intermediate Representation Compiler Lexical Analysis Syntax Analysis Semantic Analysis Source Program Token stream Abstract Syntax tree Unambiguous Program representation

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Fundamentals of Compilation

Fundamentals of Compilation PART ONE Fundamentals of Compilation 1 Introduction A compiler was originally a program that compiled subroutines [a link-loader]. When in 1954 the combination algebraic compiler came into use, or rather

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

Semantic Analysis and Type Checking

Semantic Analysis and Type Checking Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on

More information

Translation to Intermediate Code. Chapter 7

Translation to Intermediate Code. Chapter 7 Translation to Intermediate Code Chapter 7 1 Introduction The front end of a compiler parses the input program and creates Abstract Syntax Tree The back end is responsible to create Machine Code It is

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Agenda. CSE P 501 Compilers. Big Picture. Compiler Organization. Intermediate Representations. IR for Code Generation. CSE P 501 Au05 N-1

Agenda. CSE P 501 Compilers. Big Picture. Compiler Organization. Intermediate Representations. IR for Code Generation. CSE P 501 Au05 N-1 Agenda CSE P 501 Compilers Instruction Selection Hal Perkins Autumn 2005 Compiler back-end organization Low-level intermediate representations Trees Linear Instruction selection algorithms Tree pattern

More information

Where we are. Instruction selection. Abstract Assembly. CS 4120 Introduction to Compilers

Where we are. Instruction selection. Abstract Assembly. CS 4120 Introduction to Compilers Where we are CS 420 Introduction to Compilers Andrew Myers Cornell University Lecture 8: Instruction Selection 5 Oct 20 Intermediate code Canonical intermediate code Abstract assembly code Assembly code

More information

CSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall

CSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall CSE443 Compilers Dr. Carl Alphonce alphonce@buffalo.edu 343 Davis Hall http://www.cse.buffalo.edu/faculty/alphonce/sp17/cse443/index.php https://piazza.com/class/iybn4ndqa1s3ei shift/reduce conflict with

More information

CIS 341 Midterm February 28, Name (printed): Pennkey (login id): SOLUTIONS

CIS 341 Midterm February 28, Name (printed): Pennkey (login id): SOLUTIONS CIS 341 Midterm February 28, 2013 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this

More information

Topic 7: Activation Records

Topic 7: Activation Records Topic 7: Activation Records Compiler Design Prof. Hanjun Kim CoreLab (Compiler Research Lab) POSTECH 1 Storage Organization Stack Free Memory Heap Static Code 2 ELF file format example Executable Object

More information

Intermediate Representa.on

Intermediate Representa.on IR Intermediate Representa.on CMPT 379: Compilers Instructor: Anoop Sarkar anoopsarkar.github.io/compilers-class Intermediate Representation Language Specific Language + Machine Independent Machine Dependent

More information

Modules, Structs, Hashes, and Operational Semantics

Modules, Structs, Hashes, and Operational Semantics CS 152: Programming Language Paradigms Modules, Structs, Hashes, and Operational Semantics Prof. Tom Austin San José State University Lab Review (in-class) Modules Review Modules from HW 1 (in-class) How

More information

Compiler Construction D7011E

Compiler Construction D7011E Compiler Construction D7011E Lecture 8: Introduction to code generation Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 What is a Compiler? Compilers

More information

CSE 5317 Midterm Examination 4 March Solutions

CSE 5317 Midterm Examination 4 March Solutions CSE 5317 Midterm Examination 4 March 2010 1. / [20 pts] Solutions (parts a j; -1 point for each wrong answer, 0 points for each blank answer, 2 point for each correct answer. Therefore, the score for this

More information

CSE 401/M501 Compilers

CSE 401/M501 Compilers CSE 401/M501 Compilers Code Shape I Basic Constructs Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 K-1 Administrivia Semantics/type check due next Thur. 11/15 How s it going? Be sure to (re-)read

More information

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1 CSE P 501 Compilers Static Semantics Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Attribute grammars Representing types Symbol tables Note: this covers

More information

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking CSE450 Translation of Programming Languages Lecture 11: Semantic Analysis: Types & Type Checking Structure Project 1 - of a Project 2 - Compiler Today! Project 3 - Source Language Lexical Analyzer Syntax

More information

Code Generation. Dragon: Ch (Just part of it) Holub: Ch 6.

Code Generation. Dragon: Ch (Just part of it) Holub: Ch 6. Code Generation Dragon: Ch 7. 8. (Just part of it) Holub: Ch 6. Compilation Processes Again Choice of Intermediate Code Representation (IR) IR examples Parse tree Three address code (e.g., x := y op z)

More information

Compiler construction. x86 architecture. This lecture. Lecture 6: Code generation for x86. x86: assembly for a real machine.

Compiler construction. x86 architecture. This lecture. Lecture 6: Code generation for x86. x86: assembly for a real machine. This lecture Compiler construction Lecture 6: Code generation for x86 Magnus Myreen Spring 2018 Chalmers University of Technology Gothenburg University x86 architecture s Some x86 instructions From LLVM

More information

What is a Compiler? Compiler Construction SMD163. Why Translation is Needed: Know your Target: Lecture 8: Introduction to code generation

What is a Compiler? Compiler Construction SMD163. Why Translation is Needed: Know your Target: Lecture 8: Introduction to code generation Compiler Construction SMD163 Lecture 8: Introduction to code generation Viktor Leijon & Peter Jonsson with slides by Johan Nordlander Contains material generously provided by Mark P. Jones What is a Compiler?

More information

Intermediate Representations

Intermediate Representations Intermediate Representations Akim Demaille Étienne Renault Roland Levillain first.last@lrde.epita.fr EPITA École Pour l Informatique et les Techniques Avancées April 18, 2017 Intermediate Representations

More information

The compilation process is driven by the syntactic structure of the program as discovered by the parser

The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic Analysis The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on its syntactic structure

More information

PART ONE Fundamentals of Compilation

PART ONE Fundamentals of Compilation PART ONE Fundamentals of Compilation 1 Introduction A compiler was originally a program that compiled subroutines [a link-loader]. When in 1954the combination algebraic compiler came into use, or rather

More information

Operational Semantics. One-Slide Summary. Lecture Outline

Operational Semantics. One-Slide Summary. Lecture Outline Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:

More information

CIT Week13 Lecture

CIT Week13 Lecture CIT 3136 - Week13 Lecture Runtime Environments During execution, allocation must be maintained by the generated code that is compatible with the scope and lifetime rules of the language. Typically there

More information

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College CS5 Programming Languages Handout # 9 Prof. Lyn Turbak March, 00 Wellesley College Postfix: A Simple Stack Language Several exercises and examples in this course will involve the Postfix mini-language.

More information

CSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall

CSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall CSE443 Compilers Dr. Carl Alphonce alphonce@buffalo.edu 343 Davis Hall http://www.cse.buffalo.edu/faculty/alphonce/sp17/cse443/index.php https://piazza.com/class/iybn4ndqa1s3ei Announcements Be sure to

More information

Final CSE 131B Spring 2005

Final CSE 131B Spring 2005 Login name Signature Name Student ID Final CSE 131B Spring 2005 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (27 points) (24 points) (32 points) (24 points) (32 points) (26 points) (31 points)

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Implementing Subprograms

Implementing Subprograms 1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return

More information

Code Generation & Parameter Passing

Code Generation & Parameter Passing Code Generation & Parameter Passing Lecture Outline 1. Allocating temporaries in the activation record Let s optimize our code generator a bit 2. A deeper look into calling sequences Caller/Callee responsibilities

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

CS 415 Midterm Exam Spring SOLUTION

CS 415 Midterm Exam Spring SOLUTION CS 415 Midterm Exam Spring 2005 - SOLUTION Name Email Address Student ID # Pledge: This exam is closed note, closed book. Questions will be graded on quality of answer. Please supply the best answer you

More information

CSc 453. Compilers and Systems Software. 13 : Intermediate Code I. Department of Computer Science University of Arizona

CSc 453. Compilers and Systems Software. 13 : Intermediate Code I. Department of Computer Science University of Arizona CSc 453 Compilers and Systems Software 13 : Intermediate Code I Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2009 Christian Collberg Introduction Compiler Phases

More information

Compilation 2014 Activation Records

Compilation 2014 Activation Records Compilation 2014 Activation Records Aslan Askarov aslan@cs.au.dk Revised from slides by E. Ernst (Abstract) computer organization Program memory code segment contains program text data segment contains

More information

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Typical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout

Typical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout Tiger Runtime Environments Compile-time environments are just symbol tables; they are used to assist static semantic analysis, code generation and code optimization. Run-time environments are about how

More information

Operational Semantics of Cool

Operational Semantics of Cool Operational Semantics of Cool Key Concepts semantics: the meaning of a program, what does program do? how the code is executed? operational semantics: high level code generation steps of calculating values

More information

Recap: Functions as first-class values

Recap: Functions as first-class values Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

More information

This section provides some reminders and some terminology with which you might not be familiar.

This section provides some reminders and some terminology with which you might not be familiar. Chapter 3: Functions 3.1 Introduction The previous chapter assumed that all of your Bali code would be written inside a sole main function. But, as you have learned from previous programming courses, modularizing

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Autumn 2009 10/20/2009 2002-09 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Intermediate Representations & Symbol Tables

Intermediate Representations & Symbol Tables Intermediate Representations & Symbol Tables Copyright 2014, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University of Southern California have explicit permission

More information

Administration. Instruction Selection

Administration. Instruction Selection Project Administration Phase 3 out now, due Wednesday February 12 th Midterm Wednesday, February 26 th Sample questions on the web We might not get that far, but possibly will 1 Instruction Selection Idea:

More information

Semantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known.

Semantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known. SEMANTIC ANALYSIS: Semantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known. Parsing only verifies that the program consists of tokens

More information

Project Compiler. CS031 TA Help Session November 28, 2011

Project Compiler. CS031 TA Help Session November 28, 2011 Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level

More information

Acknowledgement. CS Compiler Design. Semantic Processing. Alternatives for semantic processing. Intro to Semantic Analysis. V.

Acknowledgement. CS Compiler Design. Semantic Processing. Alternatives for semantic processing. Intro to Semantic Analysis. V. Acknowledgement CS3300 - Compiler Design Intro to Semantic Analysis V. Krishna Nandivada IIT Madras Copyright c 2000 by Antony L. Hosking. Permission to make digital or hard copies of part or all of this

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

CSE 582 Autumn 2002 Exam 11/26/02

CSE 582 Autumn 2002 Exam 11/26/02 Name There are 8 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. You may refer to the following reference materials:

More information

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 4 Robert Grimm, New York University 1 Review Last week Control Structures Selection Loops 2 Outline Subprograms Calling Sequences Parameter Passing

More information

Code Generation. Lecture 12

Code Generation. Lecture 12 Code Generation Lecture 12 1 Lecture Outline Topic 1: Basic Code Generation The MIPS assembly language A simple source language Stack-machine implementation of the simple language Topic 2: Code Generation

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation Front-end intermediate code generation source program Lexical Analyzer Syntax Analyzer Semantic Analyzer Int. Code Generator intermediate representation Symbol Table Advantages

More information

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

More information

Announcements. My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM.

Announcements. My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM. IR Generation Announcements My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM. This is a hard deadline and no late submissions will be

More information

COS 126 General Computer Science Spring Written Exam 1

COS 126 General Computer Science Spring Written Exam 1 COS 126 General Computer Science Spring 2017 Written Exam 1 This exam has 9 questions (including question 0) worth a total of 70 points. You have 50 minutes. Write all answers inside the designated spaces.

More information

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem: Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd

More information

Implementing Functions at the Machine Level

Implementing Functions at the Machine Level Subroutines/Functions Implementing Functions at the Machine Level A subroutine is a program fragment that... Resides in user space (i.e, not in OS) Performs a well-defined task Is invoked (called) by a

More information

Code Generation II. Code generation for OO languages. Object layout Dynamic dispatch. Parameter-passing mechanisms Allocating temporaries in the AR

Code Generation II. Code generation for OO languages. Object layout Dynamic dispatch. Parameter-passing mechanisms Allocating temporaries in the AR Code Generation II Code generation for OO languages Object layout Dynamic dispatch Parameter-passing mechanisms Allocating temporaries in the AR Object Layout OO implementation = Stuff from last lecture

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Semantic actions for declarations and expressions. Monday, September 28, 15

Semantic actions for declarations and expressions. Monday, September 28, 15 Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Midterm 2. CMSC 430 Introduction to Compilers Fall 2018

Midterm 2. CMSC 430 Introduction to Compilers Fall 2018 Name: Directory ID: University ID: Midterm 2 CMSC 430 Introduction to Compilers Fall 2018 Instructions This exam contains 14 pages, including this one. Make sure you have all the pages. Write your name,

More information

Itree Stmts and Exprs. Back-End Code Generation. Summary: IR -> Machine Code. Side-Effects

Itree Stmts and Exprs. Back-End Code Generation. Summary: IR -> Machine Code. Side-Effects Back-End Code Generation Given a list of itree fragments, how to generate the corresponding assembly code? datatype frag = PROC of {name : Tree.label, function name body : Tree.stm, function body itree

More information

The remote testing experiment. It works! Code Generation. Lecture 12. Remote testing. From the cs164 newsgroup

The remote testing experiment. It works! Code Generation. Lecture 12. Remote testing. From the cs164 newsgroup The remote testing experiment. It works! Coverage - Score plot 0.9 Code Generation 0.7 0.6 Lecture 12 Coverage 0.5 0.4 0.3 Series1 Poly. (Series1) 0.2 0.1 0 0 10 20 30 40 50 Score CS 164 Lecture 14 Fall

More information

Writing Evaluators MIF08. Laure Gonnord

Writing Evaluators MIF08. Laure Gonnord Writing Evaluators MIF08 Laure Gonnord Laure.Gonnord@univ-lyon1.fr Evaluators, what for? Outline 1 Evaluators, what for? 2 Implementation Laure Gonnord (Lyon1/FST) Writing Evaluators 2 / 21 Evaluators,

More information

Intermediate Code Generation. Intermediate Representations (IR) Case Study : itree. itree Statements and Expressions

Intermediate Code Generation. Intermediate Representations (IR) Case Study : itree. itree Statements and Expressions Intermediate Code Generation Translating the abstract syntax into the intermediate representation. report all lexical & syntactic errors report all semantic errors Intermediate Representations (IR) What

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information