Code Generation and Optimisation. Local variables and procedures
|
|
- Lisa Lawrence
- 5 years ago
- Views:
Transcription
1 Code Generation and Optimisation Local variables and procedures
2 Motivation Procedures allow programmers to: abstract a general routine from a specific instance; reuse this routine many times. procedure factorial(n)(r) ( r := 1; while (n > 0) (r := n*r ; n := n-1) ); call factorial(3)(a); call factorial(2*2)(b); print a+b
3 LOCAL VARIABLES Before looking at procedures, it is useful to consider a simpler, related concept: local variables.
4 Local variables A declare statement declare v 1,, v n in s introduces n local variables v 1 v n within the scope of statement s. Modifications of v 1 v n inside s are observable only within s. Variables v 1 v n that are in scope outside s cannot be modified by s.
5 Exercise 1 What outputs are emitted when the following program is executed? x := 0; y := 0; declare x in ( x := 5; print x; y := y+1 ); print x; print y
6 Syntax Let v * denote a comma-separated list of v. s ::=... declare v * in s Concrete syntax data Stm =... Declare(String, Stm) Abstract syntax The abstract syntax allows only one variable to be introduced at a time, but: declare x, y, z in... declare x in ( declare y in ( declare z in... ))
7 Semantics To execute a statement declare v in s save the value of v, execute s, and then restore v to its original value. exec :: (Env, Stm) -> (Env, Output) exec(env, Declare(v, s)) = (env 2, out) where original = env!v (env 1, out) = exec(env, s) env 2 = insert(env 1, v, original) Semantics of declare statements
8 Run-time stack To implement the save and restore mechanism, the compiler uses a run-time stack with the following psuedo-instructions. push r subi $sp, $sp, 4 store r, $sp, 0 Push the value of a register r onto the stack. pop r load r, $sp, 0 addi $sp, $sp, 4 Pop the top stack item into register r. Register $sp points to the top stack item. The stack grows downwards.
9 Run-time stack The psuedo-instructions are easily encoded in the abstract syntax: push :: Reg -> [Instr] push(r) = [ OPI("$sp", "$sp", Sub, 4), STORE(r, "$sp", 0) ] Push the value of a register onto the stack. pop :: Reg -> [Instr] pop(r) = [ LOAD(r, "$sp", 0), OPI("$sp", "$sp", Add, 4) ] Pop the top stack item into a register.
10 Compilation To compile a statement declare v in s push v onto the stack, execute s, and then pop the stack into v. compilestm :: Stm -> [Instr] compilestm(declare(v, s)) = push(v) ++ compilestm(s) ++ pop(v) Compilation of declare statements.
11 Example Compiler x := 1; declare x in ( x := 2; print x ); print x li x, 1 push x li x, 2 print x pop x print x
12 Exercise 2 Give the contents of the run-time stack at lines 7 and 9. 1 x := 0; 2 y := 0; 3 declare x in ( 4 x := 1; 5 y := 2; 6 declare x, y in ( 7 x := 3 8 ); 9 skip 10 )
13 Possible optimisation The push and pop instructions can be discarded when the local variable being declared is not liveout of the declare statement. declare x in ( x := 2; print x ); x := 10; push x li x, 2 print x pop x li x, 10 But this is not implemented in the Tower compiler.
14 SEMANTICS OF PROCEDURES procedure: a set of instructions for a computer that has a name by which it can be called into action. Webster s Dictionary
15 Concrete syntax A procedure has a name p, input and output parameters, and a body. proc ::= procedure p ( v * ) ( v * ) ( s ) Ins Outs Body A program is a series of zero or more procedures, terminated by a main statement. prog ::= proc ; prog s
16 Abstract syntax A procedure is: a list of input parameters, a list of output parameters, and a body. type Proc = ([String], [String], Stm) A program is: a mapping from procedure names to procedures, and a main statement. type Prog = (Map String Proc, Stm)
17 Syntax of calls A procedure call provides a list of input expressions and a list of variables in which the outputs are to be stored. s ::=... call p ( e * ) ( v * ) Concrete syntax data Stm =... Call(String, [Exp], [String]) Abstract syntax
18 Informal semantics Consider a procedure p with m input parameters, n output parameters, and body s. procedure p(i 1,..., i m )(o 1,..., o n ) ( s ) Parameters i 1 i m and o 1 o n are local variables within the scope of the statement s.
19 Informal semantics When p is called, call p(e 1,..., e m )(v 1,..., v n ) the body of p is executed in a state where parameters i 1 i n contain the values of the expressions e 1 e n. When p returns, the caller continues in a state where variables v 1 v n have the values of p s output parameters o 1 o n.
20 Informal semantics From the caller's perspective, the only variables that may have been modified as a result of the call are: variables v 1 v n ; any variables that are not local to the body of p.
21 Exercise 3 What outputs are emitted when the following program is executed? procedure quad(a)(b) ( a := 2*a; b := 2*a ); a := 10; b := 20; call quad(2)(r); print a; print b; print r
22 Semantics of calls If procedure p is defined as procedure p(i 1,...,i m )(o 1,..., o n ) (s) then to execute a statement call p(e 1,, e m )(v 1 v n ) let locals be the set ({i 1 i m } {o 1 o n }) {v 1 v n }, and perform the following steps: save locals on the stack, bind i 1 i m to the values of e 1 e m, execute the body of p, bind v 1 v n to o 1 o n, restore locals from the stack.
23 COMPILING PROCEDURES
24 In-lining One way to compile a call to procedure p is to inline the body of p in the caller. procedure double(x)(y) ( y := x+x ); call double(2)(z) push x push y li x, 2 add y, x, x move z, y pop y pop x
25 Recursion However, a procedure may contain a call to itself. procedure fib(n)(r) ( declare a, b in ( if n <= 1 then ( r := 1 ) else ( call fib(n-1)(a); call fib(n-2)(b); r := a + b ) ) ); Therefore the in-lining method is only possible when compiling nonrecursive procedures.
26 Return addresses To call a procedure p, we can jump to the code for p, execute it, and then jump back (return) to the caller. Since p may be called from many different places, the return address is not constant. We need support for indirect jumps in our target language.
27 Indirect jumps instr ::=... la r, label (Load address) jumpr r (Indirect jump) Concrete syntax of indirect jumps. data Instr =... LA(Reg, Label) {- r a -} JUMPR(Reg) {- goto r -} Abstract syntax of indirect jumps.
28 Example revisited A convenient place to store the return address is on the stack. procedure double(x)(y) ( y := x+x ); call double(2)(z) Push and jump push x push y li x, 2 la tmp, return push tmp jump double return: move z, y pop y pop x halt double: add y, x, x pop ret jumpr ret Pop and return
29 Push and jump Generate code to push return address onto the stack and jump to target. pushandjump :: String -> [Instr] pushandjump(p) = [LA(tmp, return)] ++ push(tmp) ++ [JUMP(p)] ++ [LABEL(return)] where tmp = fresh() return = fresh()
30 Pop and return Generate code to pop return address and jump to it. compileproc :: (String, Proc) -> [Instr] compileproc(p, (ins, outs, body)) = [LABEL(p)] ++ compilestm(body) ++ pop(r) ++ [JUMPR(r)] where r = fresh() Compilation of procedures.
31 Simultaneous assignment Consider the following program. procedure p(x, y)(z) (...); x := 1; y := 2; call p(y, x)(r) We need to assign p's input parameters to the expressions supplied by the caller. Easy? x := y; y := x Wrong! Both input parameters are assigned value 2. The assignments must be simultaneous.
32 Simultaneous assignment Generate code to assign the values of e 1...e n to variables x 1...x n, simultaneously with the use of temporary variables. assign :: ([String], [Exp]) -> [Instr] Example: assign([x 1,x 2 ], [e 1,e 2 ]) gives code with the effect: t 1 := e 1 t 2 := e 2 x 1 := t 1 x 2 := t 2
33 Compiling calls compilestm(call(p, es, vs)) = {- Save p s locals -} concat([push(x) x <- locals]) {- Assign inputs -} ++ assign(ins, es) {- Push return address and jump -} ++ pushandjump(p) {- Assign outputs -} ++ assign(vs, [Var(o) o <- outs]) {- Restore p s locals -} ++ concat([pop(x) x <- reverse(locals)]) where (ins, outs, s) = procs!p locals = union(ins, outs) \\ vs Compilation of procedure calls.
34 Exercise 4 Show the run-time stack when execution reaches line (3). procedure fact(n)(x) ( (1) if n <= 1 then ( (2) x := 1 (3) ) else ( (4) call fact(n-1)(x); (5) x := n*x (6) ) (7) ); (8) n := 0; (9) x := 0; (10) call fact(3)(o) (11) Let Address(n) denote the return address of the call on line n.
35 Answer to Exercise 4 0 (n) 0 (x) Address(11) 3 (n) Address(5) 2 (n) Address(5) Bottom of stack Top of stack
36 Possible optimisation Saving and restoring variables local to a procedure p is not required when those variables are not live at the point where the p is called. procedure double(x)(y) ( y := x+x ); call double(2)(z); x := 0; y := 0 push x push y x := 2 z := y pop y pop x (The code for push and jump is elided.)
37 SUMMARY What have we learnt?
38 Summary Compiling local variables by save and restore to and from the runtime stack. Save and restore can often be avoided using liveness analysis. Compiling recursive procedures with in and out parameters.
39 Limitations and variations Some languages allow nested procedures. (Tower does not.) In some compilers, all parameters are passed via a stack. Tower tries to pass all parameters in registers, but accesses the stack when save and restore cannot be avoided; accesses spill-memory when registers are exhausted.
40 STATIC AND DYNAMIC SCOPING
41 Global variables What outputs are emitted when the following program is executed? procedure inc()() ( x := x + 1 ); x := 0; call inc()(); call inc()(); call inc()(); print x Variable x is a global variable.
42 Scoping What outputs are emitted when the following program is executed? procedure p()() ( declare x in ( x := 2; call q()() ) ); procedure q()() ( print x ); x := 1; call p()(); print x
43 Scoping Which x does the body of q refer to? procedure p()() ( declare x in ( x := 2; call q()() ) ); procedure q()() ( print x ); x := 1; call p()(); print x
44 Scoping Dynamic scoping: variable v refers to the most recently executed declaration of v at runtime. Static scoping: variable v refers to the innermost enclosing declaration of v in the source program.
45 Static renaming The Tower compiler implements dynamic scoping. However, static scoping semantics can be easily enforced by applying the static renaming transformation. declare v in s declare w in s[w/v] Where w is a fresh variable and s[x/y] is s with all in-scope occurrences of y replaced by x. Static renaming for declare statements.
46 Static renaming procedure p(v 1,, v m )(w 1,, w n ) (s) procedure p(a 1,, a m )(b 1,, b n ) ( s[a 1,,a m,b 1,,b n / v 1,,v m,w 1,,w n ] ) Where a 1,,a m,b 1,,b n are fresh variables and s[x 1,,x n /y 1,,y n ] is s with all in-scope occurrences of y 1,,y n replaced by x 1,,x n. Static renaming for procedures.
47 Example Static renaming transformation: procedure p()() ( declare x in ( x := 2; call q()() ) ); procedure q()() ( print x ); x := 1; call p()(); print x procedure p()() ( declare a in ( a:= 2; call q()() ) ); procedure q()() ( print x ); x := 1; call p()(); print x
48 APPENDIX Formal semantics of procedure calls
49 Semantics of binding Given environment env, variables v 1 v n and values x 1...x n, return a new environment where v i has value x i for all i in {1 n}. bind :: (Env, [String], [Int]) -> Env bind(env, vs, xs) = case (vs, xs) of (v:vs, x:xs) -> bind(insert(env, v, x), vs, xs) other -> env Binding variables to values.
50 Formal semantics of procedure calls exec :: (Env, Stm) -> (Env, Output) exec(env, Call(p, xs, ys)) = (env 4, out) where (ins, outs, body) = procs!p locals = union(ins, outs) \\ ys saved = [env!v v <- locals] env 1 = bind(env, ins, [eval(env, x) x <- xs]) (env 2, out) = exec(env 1, body) env 3 = bind(env 2, ys, [env 2!o o <- outs]) env 4 = bind(env 3, locals, saved) Semantics of procedure calls.
Scope, Functions, and Storage Management
Scope, Functions, and Storage Management Implementing Functions and Blocks cs3723 1 Simplified Machine Model (Compare To List Abstract Machine) Registers Code Data Program Counter (current instruction)
More informationCOMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture
COMP 303 Computer Architecture Lecture 3 Comp 303 Computer Architecture 1 Supporting procedures in computer hardware The execution of a procedure Place parameters in a place where the procedure can access
More informationCS153: Compilers Lecture 8: Compiling Calls
CS153: Compilers Lecture 8: Compiling Calls Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 2 out Due Thu Oct 4 (7 days) Project 3 out Due Tuesday Oct 9 (12 days) Reminder:
More informationImplementing Subroutines. Outline [1]
Implementing Subroutines In Text: Chapter 9 Outline [1] General semantics of calls and returns Implementing simple subroutines Call Stack Implementing subroutines with stackdynamic local variables Nested
More informationCompiler Theory. (Semantic Analysis and Run-Time Environments)
Compiler Theory (Semantic Analysis and Run-Time Environments) 005 Semantic Actions A compiler must do more than recognise whether a sentence belongs to the language of a grammar it must do something useful
More informationLecture08: Scope and Lexical Address
Lecture08: Scope and Lexical Address Free and Bound Variables (EOPL 1.3.1) Given an expression E, does a particular variable reference x appear free or bound in that expression? Definition: A variable
More informationProgramming Languages and Compiler Design
Programming Languages and Compiler Design Programming Language Semantics Compiler Design Techniques Yassine Lakhnech & Laurent Mounier {lakhnech,mounier}@imag.fr http://www-verimag.imag.fr/ lakhnech http://www-verimag.imag.fr/
More informationSeparate compilation. Topic 6: Runtime Environments p.1/21. CS 526 Topic 6: Runtime Environments The linkage convention
Runtime Environment The Procedure Abstraction and Separate Compilation Topics we will cover The procedure abstraction and linkage conventions Runtime storage convention Non-local data access (brief) These
More informationRun Time Environments
Run Time Environments ALSU Textbook Chapter 7.1 7.3 Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 Preliminaries During the execution of a program, the same name in the source
More information12/4/18. Outline. Implementing Subprograms. Semantics of a subroutine call. Storage of Information. Semantics of a subroutine return
Outline Implementing Subprograms In Text: Chapter 10 General semantics of calls and returns Implementing simple subroutines Call Stack Implementing subroutines with stackdynamic local variables Nested
More informationCENG3420 Computer Organization and Design Lab 1-2: System calls and recursions
CENG3420 Computer Organization and Design Lab 1-2: System calls and recursions Wen Zong Department of Computer Science and Engineering The Chinese University of Hong Kong wzong@cse.cuhk.edu.hk Overview
More informationSubroutines. int main() { int i, j; i = 5; j = celtokel(i); i = j; return 0;}
Subroutines Also called procedures or functions Example C code: int main() { int i, j; i = 5; j = celtokel(i); i = j; return 0;} // subroutine converts Celsius to kelvin int celtokel(int i) { return (i
More informationTopic 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 informationConcepts Introduced in Chapter 7
Concepts Introduced in Chapter 7 Storage Allocation Strategies Static Stack Heap Activation Records Access to Nonlocal Names Access links followed by Fig. 7.1 EECS 665 Compiler Construction 1 Activation
More informationG 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 informationInstruction Set Architectures (4)
Computer Architecture Week 06 Instruction Set Architectures (4) College of Information Science and Engineering Ritsumeikan University subroutines functions, procedures remember the next instruction s address
More informationG 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! Those values must be stored somewhere! Therefore, variables must somehow be bound. ! How?
A Binding Question! Variables are bound (dynamically) to values Subprogram Activation! Those values must be stored somewhere! Therefore, variables must somehow be bound to memory locations! How? Function
More informationLecture 9: Procedures & Functions. CS 540 George Mason University
Lecture 9: Procedures & Functions CS 540 George Mason University Procedures/Functions Control Abstraction call/return semantics, parameters, recursion Controlled Namespace Scope (local/non-local), binding,
More informationFunctions in MIPS. Functions in MIPS 1
Functions in MIPS We ll talk about the 3 steps in handling function calls: 1. The program s flow of control must be changed. 2. Arguments and return values are passed back and forth. 3. Local variables
More informationCSE 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 informationSystem 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 informationPrinciples of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004
Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?
More informationCode Generation. The Main Idea of Today s Lecture. We can emit stack-machine-style code for expressions via recursion. Lecture Outline.
The Main Idea of Today s Lecture Code Generation We can emit stack-machine-style code for expressions via recursion (We will use MIPS assembly as our target language) 2 Lecture Outline What are stack machines?
More informationCS 316: Procedure Calls/Pipelining
CS 316: Procedure Calls/Pipelining Kavita Bala Fall 2007 Computer Science Cornell University Announcements PA 3 IS out today Lectures on it this Fri and next Tue/Thu Due on the Friday after Fall break
More informationModule 27 Switch-case statements and Run-time storage management
Module 27 Switch-case statements and Run-time storage management In this module we will discuss the pending constructs in generating three-address code namely switch-case statements. We will also discuss
More informationWe can emit stack-machine-style code for expressions via recursion
Code Generation The Main Idea of Today s Lecture We can emit stack-machine-style code for expressions via recursion (We will use MIPS assembly as our target language) 2 Lecture Outline What are stack machines?
More informationTHEORY OF COMPILATION
Lecture 10 Activation Records THEORY OF COMPILATION EranYahav www.cs.technion.ac.il/~yahave/tocs2011/compilers-lec10.pptx Reference: Dragon 7.1,7.2. MCD 6.3,6.4.2 1 You are here Compiler txt Source Lexical
More informationArguments and Return Values. EE 109 Unit 16 Stack Frames. Assembly & HLL s. Arguments and Return Values
1 Arguments and Return Values 2 EE 109 Unit 16 Stack Frames MIPS convention is to use certain registers for this task used to pass up to 4 arguments. If more arguments, use the stack used for return value
More informationCompilation /15a Lecture 7. Activation Records Noam Rinetzky
Compilation 0368-3133 2014/15a Lecture 7 Activation Records Noam Rinetzky 1 Code generation for procedure calls (+ a few words on the runtime system) 2 Code generation for procedure calls Compile time
More informationProgramming Language Concepts, cs2104 Lecture 04 ( )
Programming Language Concepts, cs2104 Lecture 04 (2003-08-29) Seif Haridi Department of Computer Science, NUS haridi@comp.nus.edu.sg 2003-09-05 S. Haridi, CS2104, L04 (slides: C. Schulte, S. Haridi) 1
More informationFunctions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself
More informationMIPS function continued
MIPS function continued Review Functions Series of related instructions one after another in memory Called through the jal instruction Pointed to by a label like any other Returns by calling Stack Top
More informationVerified compilation of a first-order Lisp language
Verified compilation of a first-order Lisp language Lecture 7 MPhil ACS & Part III course, Functional Programming: Implementation, Specification and Verification Magnus Myreen Michaelmas term, 2013 Interpreter
More informationRun-Time Data Structures
Run-Time Data Structures Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers, it is used for:
More informationCSE Lecture In Class Example Handout
CSE 30321 Lecture 07-09 In Class Example Handout Part A: A Simple, MIPS-based Procedure: Swap Procedure Example: Let s write the MIPS code for the following statement (and function call): if (A[i] > A
More informationRun-Time Environments
CS308 Run-Time Environments Li Jiang Department of Computer Science and Engineering Shanghai Jiao Tong University Current Progress Source Language Lexical Analyzer Syntax Analyzer Semantic Analyzer Intermediate
More informationChapter 2A Instructions: Language of the Computer
Chapter 2A Instructions: Language of the Computer Copyright 2009 Elsevier, Inc. All rights reserved. Instruction Set The repertoire of instructions of a computer Different computers have different instruction
More informationTypical 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 informationCompilers and Code Optimization EDOARDO FUSELLA
Compilers and Code Optimization EDOARDO FUSELLA Contents Data memory layout Instruction selection Register allocation Data memory layout Memory Hierarchy Capacity vs access speed Main memory Classes of
More informationCS 61C: Great Ideas in Computer Architecture More MIPS, MIPS Functions
CS 61C: Great Ideas in Computer Architecture More MIPS, MIPS Functions Instructors: John Wawrzynek & Vladimir Stojanovic http://inst.eecs.berkeley.edu/~cs61c/fa15 1 Machine Interpretation Levels of Representation/Interpretation
More informationAssembly Programming (III) Lecturer: Sri Parameswaran Notes by: Annie Guo Dr. Hui Wu
Assembly Programming (III) Lecturer: Sri Parameswaran Notes by: Annie Guo Dr. Hui Wu 1 Lecture overview Stack and stack operations Functions and function calls Calling conventions 2 Stack What is stack?
More informationAn Overview to Compiler Design. 2008/2/14 \course\cpeg421-08s\topic-1a.ppt 1
An Overview to Compiler Design 2008/2/14 \course\cpeg421-08s\topic-1a.ppt 1 Outline An Overview of Compiler Structure Front End Middle End Back End 2008/2/14 \course\cpeg421-08s\topic-1a.ppt 2 Reading
More informationProcedures and Stacks
Procedures and Stacks Daniel Sanchez Computer Science & Artificial Intelligence Lab M.I.T. March 15, 2018 L10-1 Announcements Schedule has shifted due to snow day Quiz 2 is now on Thu 4/12 (one week later)
More informationMark Redekopp, All rights reserved. EE 352 Unit 6. Stack Frames Recursive Routines
EE 352 Unit 6 Stack Frames Recursive Routines Arguments and Return Values MIPS convention is to use certain registers for this task $a0 - $a3 used to pass up to 4 arguments. If more arguments, use the
More informationCompilers 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 informationControl Instructions. Computer Organization Architectures for Embedded Computing. Thursday, 26 September Summary
Control Instructions Computer Organization Architectures for Embedded Computing Thursday, 26 September 2013 Many slides adapted from: Computer Organization and Design, Patterson & Hennessy 4th Edition,
More informationControl Instructions
Control Instructions Tuesday 22 September 15 Many slides adapted from: and Design, Patterson & Hennessy 5th Edition, 2014, MK and from Prof. Mary Jane Irwin, PSU Summary Previous Class Instruction Set
More informationCS240: Programming in C
CS240: Programming in C Lecture 6: Recursive Functions. C Pre-processor. Cristina Nita-Rotaru Lecture 6/ Fall 2013 1 Functions: extern and static Functions can be used before they are declared static for
More informationCSCI 402: Computer Architectures. Instructions: Language of the Computer (3) Fengguang Song Department of Computer & Information Science IUPUI.
CSCI 402: Computer Architectures Instructions: Language of the Computer (3) Fengguang Song Department of Computer & Information Science IUPUI Recall Big endian, little endian Memory alignment Unsigned
More informationImplementing Procedure Calls
1 / 39 Implementing Procedure Calls February 18 22, 2013 2 / 39 Outline Intro to procedure calls Caller vs. callee Procedure call basics Calling conventions The stack Interacting with the stack Structure
More informationCompiling Code, Procedures and Stacks
Compiling Code, Procedures and Stacks L03-1 RISC-V Recap Computational Instructions executed by ALU Register-Register: op dest, src1, src2 Register-Immediate: op dest, src1, const Control flow instructions
More informationLecture 5. Announcements: Today: Finish up functions in MIPS
Lecture 5 Announcements: Today: Finish up functions in MIPS 1 Control flow in C Invoking a function changes the control flow of a program twice. 1. Calling the function 2. Returning from the function In
More informationCSE443 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 informationThe role of semantic analysis in a compiler
Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationCA Compiler Construction
CA4003 - Compiler Construction David Sinclair When procedure A calls procedure B, we name procedure A the caller and procedure B the callee. A Runtime Environment, also called an Activation Record, is
More informationMIPS Assembly (Functions)
ECPE 170 Jeff Shafer University of the Pacific MIPS Assembly (Functions) 2 Lab Schedule This Week Activities Lab work time MIPS functions MIPS Random Number Generator Lab 11 Assignments Due Due by Apr
More informationCS 314 Principles of Programming Languages. Lecture 13
CS 314 Principles of Programming Languages Lecture 13 Zheng Zhang Department of Computer Science Rutgers University Wednesday 19 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:
More informationDo-While Example. In C++ In assembly language. do { z--; while (a == b); z = b; loop: addi $s2, $s2, -1 beq $s0, $s1, loop or $s2, $s1, $zero
Do-While Example In C++ do { z--; while (a == b); z = b; In assembly language loop: addi $s2, $s2, -1 beq $s0, $s1, loop or $s2, $s1, $zero 25 Comparisons Set on less than (slt) compares its source registers
More informationFunctions and Procedures
Functions and Procedures Function or Procedure A separate piece of code Possibly separately compiled Located at some address in the memory used for code, away from main and other functions (main is itself
More informationVerification of an ML compiler. Lecture 3: Closures, closure conversion and call optimisations
Verification of an ML compiler Lecture 3: Closures, closure conversion and call optimisations Marktoberdorf Summer School MOD 2017 Magnus O. Myreen, Chalmers University of Technology Implementing the ML
More informationComputer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: MIPS Programming
Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: MIPS Programming We spent some time looking at the MIPS Instruction Set Architecture. We will now consider
More informationMIPS Datapath. MIPS Registers (and the conventions associated with them) MIPS Instruction Types
1 Lecture 08 Introduction to the MIPS ISA + Procedure Calls in MIPS Longer instructions = more bits to address registers MIPS Datapath 6 bit opcodes... 2 MIPS Instructions are 32 bits More ways to address
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages
More informationCompiler Construction
Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-17/cc/ Generation of Intermediate Code Conceptual Structure of
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of
More informationAn Elegant Weapon for a More Civilized Age
An Elegant Weapon for a More Civilized Age Solving an Easy Problem What are the input types? What is the output type? Give example input/output pairs Which input represents the domain of the recursion,
More informationToday. Putting it all together
Today! One complete example To put together the snippets of assembly code we have seen! Functions in MIPS Slides adapted from Josep Torrellas, Craig Zilles, and Howard Huang Putting it all together! Count
More informationLecture 7: Procedures and Program Execution Preview
Lecture 7: Procedures and Program Execution Preview CSE 30: Computer Organization and Systems Programming Winter 2010 Rajesh Gupta / Ryan Kastner Dept. of Computer Science and Engineering University of
More informationCS 61C: Great Ideas in Computer Architecture More RISC-V Instructions and How to Implement Functions
CS 61C: Great Ideas in Computer Architecture More RISC-V Instructions and How to Implement Functions Instructors: Krste Asanović and Randy H. Katz http://inst.eecs.berkeley.edu/~cs61c/fa17 9/14/17 Fall
More informationCS4215 Programming Language Implementation
CS4215 Programming Language Implementation You have 45 minutes to complete the exam. Use a B2 pencil to fill up the provided MCQ form. Leave Section A blank. Fill up Sections B and C. After finishing,
More informationEE 109 Unit 15 Subroutines and Stacks
1 EE 109 Unit 15 Subroutines and Stacks 2 Program Counter and GPRs (especially $sp, $ra, and $fp) REVIEW OF RELEVANT CONCEPTS 3 Review of Program Counter PC is used to fetch an instruction PC contains
More informationCompiler Construction
Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-17/cc/ Generation of Intermediate Code Outline of Lecture 15 Generation
More informationPrinciples of Programming Languages
Principles of Programming Languages Lecture 06 Implementation of Block Structured Languages 1 Activations and Environment Aspects of Subroutines: Static vs Dynamic! Static subroutine: code (``reentrant
More informationCS 61c: Great Ideas in Computer Architecture
MIPS Functions July 1, 2014 Review I RISC Design Principles Smaller is faster: 32 registers, fewer instructions Keep it simple: rigid syntax, fixed instruction length MIPS Registers: $s0-$s7,$t0-$t9, $0
More informationRun-time Environments - 2
Run-time Environments - 2 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time
More informationBranch Addressing. Jump Addressing. Target Addressing Example. The University of Adelaide, School of Computer Science 28 September 2015
Branch Addressing Branch instructions specify Opcode, two registers, target address Most branch targets are near branch Forward or backward op rs rt constant or address 6 bits 5 bits 5 bits 16 bits PC-relative
More informationProcedure Call and Return Procedure call
Procedures int len(char *s) { for (int l=0; *s!= \0 ; s++) l++; main return l; } void reverse(char *s, char *r) { char *p, *t; int l = len(s); reverse(s,r) N/A *(r+l) = \0 ; reverse l--; for (p=s+l t=r;
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationChapter 2. Computer Abstractions and Technology. Lesson 4: MIPS (cont )
Chapter 2 Computer Abstractions and Technology Lesson 4: MIPS (cont ) Logical Operations Instructions for bitwise manipulation Operation C Java MIPS Shift left >>> srl Bitwise
More informationThe plot thickens. Some MIPS instructions you can write cannot be translated to a 32-bit number
The plot thickens Some MIPS instructions you can write cannot be translated to a 32-bit number some reasons why 1) constants are too big 2) relative addresses are too big 3) absolute addresses are outside
More informationImplementing Subprograms
Implementing Subprograms In Text: Chapter 10 Slide 1 Implementing Subprograms Call - Save registers - provide storage for parameters - provide storage for locals - save execution status of caller - provide
More informationProgramming Languages
CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f -> fun x -> not (f x); # let
More informationCS 110 Computer Architecture Lecture 6: More MIPS, MIPS Functions
CS 110 Computer Architecture Lecture 6: More MIPS, MIPS Functions Instructor: Sören Schwertfeger http://shtech.org/courses/ca/ School of Information Science and Technology SIST ShanghaiTech University
More informationRun-time Environment
Run-time Environment Prof. James L. Frankel Harvard University Version of 3:08 PM 20-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Storage Organization Automatic objects are
More informationThe plot thickens. Some MIPS instructions you can write cannot be translated to a 32-bit number
The plot thickens Some MIPS instructions you can write cannot be translated to a 32-bit number some reasons why 1) constants are too big 2) relative addresses are too big 3) absolute addresses are outside
More informationECE260: Fundamentals of Computer Engineering
Supporting Nested Procedures James Moscola Dept. of Engineering & Computer Science York College of Pennsylvania Based on Computer Organization and Design, 5th Edition by Patterson & Hennessy Memory Layout
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #9: MIPS Procedures 2006-07-11 CS 61C L09 MIPS Procedures (1) Andy Carle C functions main() { int i,j,k,m;... i = mult(j,k);... m =
More informationInstruction Set Principles and Examples. Appendix B
Instruction Set Principles and Examples Appendix B Outline What is Instruction Set Architecture? Classifying ISA Elements of ISA Programming Registers Type and Size of Operands Addressing Modes Types of
More informationRecap: 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 informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationCourse Administration
Fall 2018 EE 3613: Computer Organization Chapter 2: Instruction Set Architecture Introduction 4/4 Avinash Karanth Department of Electrical Engineering & Computer Science Ohio University, Athens, Ohio 45701
More informationThe Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis
The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed
More informationPatterson PII. Solutions
Patterson-1610874 978-0-12-407726-3 PII 2 Solutions Chapter 2 Solutions S-3 2.1 addi f, h, -5 (note, no subi) add f, f, g 2.2 f = g + h + i 2.3 sub $t0, $s3, $s4 add $t0, $s6, $t0 lw $t1, 16($t0) sw $t1,
More informationDigital Forensics Lecture 3 - Reverse Engineering
Digital Forensics Lecture 3 - Reverse Engineering Low-Level Software Akbar S. Namin Texas Tech University Spring 2017 Reverse Engineering High-Level Software Low-level aspects of software are often the
More informationInformatica 3 Marcello Restelli
Informatica 3 Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Operational Semantics We describe the semantics of a programming language by means of an abstract semantic
More informationSummer 2003 Lecture 14 07/02/03
Summer 2003 Lecture 14 07/02/03 LAB 6 Lab 6 involves interfacing to the IBM PC parallel port Use the material on wwwbeyondlogicorg for reference This lab requires the use of a Digilab board Everyone should
More informationData Structures And Algorithms
Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:
More informationLectures 5. Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS
Lectures 5 Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS 1 OOPS - What does this C code do? int foo(char *s) { int L = 0; while (*s++) { ++L; } return L; } 2
More informationEE 361 University of Hawaii Fall
C functions Road Map Computation flow Implementation using MIPS instructions Useful new instructions Addressing modes Stack data structure 1 EE 361 University of Hawaii Implementation of C functions and
More information