Slide 1 Vitaly Shmatikov CS 345 Scope and Activation Records.

Slides:



Advertisements
Similar presentations
The University of Adelaide, School of Computer Science
Advertisements

Recap 1.Programmer enters expression 2.ML checks if expression is “well-typed” Using a precise set of rules, ML tries to find a unique type for the expression.
Prof. Necula CS 164 Lecture 141 Run-time Environments Lecture 8.
Slide 1 Vitaly Shmatikov CS 345 Functions. slide 2 Reading Assignment uMitchell, Chapter 7 uC Reference Manual, Chapters 4 and 9.
(1) ICS 313: Programming Language Theory Chapter 10: Implementing Subprograms.
Chapter 10 Implementing Subprograms. Copyright © 2012 Addison- Wesley. All rights reserved. 1-2 Chapter 10 Topics The General Semantics of Calls and Returns.
ISBN Chapter 10 Implementing Subprograms.
PSUCS322 HM 1 Languages and Compiler Design II Runtime System Material provided by Prof. Jingke Li Stolen with pride and modified by Herb Mayer PSU Spring.
Stacks and HeapsCS-3013 A-term A Short Digression on Stacks and Heaps CS-3013 Operating Systems A-term 2008 (Slides include materials from Modern.
1 Storage Registers vs. memory Access to registers is much faster than access to memory Goal: store as much data as possible in registers Limitations/considerations:
Cse321, Programming Languages and Compilers 1 6/12/2015 Lecture #17, March 12, 2007 Procedure Abstraction, Name Spaces, Scoping Rules, Activation Records,
Digression on Stack and Heaps CS-502 (EMC) Fall A Short Digression on Stacks and Heaps CS-502, Operating Systems Fall 2009 (EMC) (Slides include.
CS 536 Spring Run-time organization Lecture 19.
ISBN Chapter 10 Implementing Subprograms.
Dr. Muhammed Al-Mulhem ICS Chapter 7 Scope, Functions, and Storage Management.
Runtime Environments Source language issues Storage organization
Honors Compilers Addressing of Local Variables Mar 19 th, 2002.
Run-Time Storage Organization
Run time vs. Compile time
Catriel Beeri Pls/Winter 2004/5 environment 68  Some details of implementation As part of / extension of type-checking: Each declaration d(x) associated.
Semantics of Calls and Returns
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
Scope, Function Calls and Storage Management John Mitchell CS
Run-time Environment and Program Organization
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Stacks and HeapsCS-502 Fall A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
Scope, Function Calls and Storage Management John Mitchell CS
Recursion and Implementation of Functions
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
Runtime Environments What is in the memory? Runtime Environment2 Outline Memory organization during program execution Static runtime environments.
Runtime Environments Compiler Construction Chapter 7.
Chapter 10 Implementing Subprograms. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 10 Topics The General Semantics of Calls and Returns.
CSc 453 Runtime Environments Saumya Debray The University of Arizona Tucson.
Chapter 8 - Control II: Procedures and Environments
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 9 Def: The subprogram call and return operations of a language are together called its subprogram.
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
Slide 1 Vitaly Shmatikov CS 345 Imperative Programming.
Activation Records CS 671 February 7, CS 671 – Spring The Compiler So Far Lexical analysis Detects inputs with illegal tokens Syntactic analysis.
Midterm Review John Mitchell CS 242. Midterm uThurs Nov 7, 7-9PM Terman Aud Closed book uClass schedule Thurs Oct 31, Tues Nov 5 – topics not on midterm.
Subprograms - implementation
CSC 8505 Compiler Construction Runtime Environments.
1 Chapter 10 © 2002 by Addison Wesley Longman, Inc The General Semantics of Calls and Returns - Def: The subprogram call and return operations of.
RUNTIME ENVIRONMENT AND VARIABLE BINDINGS How to manage local variables.
Chapter 2 — Instructions: Language of the Computer — 1 Conditional Operations Branch to a labeled instruction if a condition is true – Otherwise, continue.
10-1 Chapter 10: Implementing Subprograms The General Semantics of Calls and Returns Implementing “Simple” Subprograms Implementing Subprograms with Stack-Dynamic.
ISBN Chapter 10 Implementing Subprograms.
Implementing Subprograms
Slide 1 Vitaly Shmatikov CS 345 Exceptions. slide 2 Reading Assignment uMitchell, Chapter 8.2.
ISBN Chapter 10 Implementing Subprograms.
Scope, Function Calls and Storage Management John Mitchell CS Reading: Chapter 7, Concepts in Programming Languages.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Run-Time Environments Chapter 7
Implementing Subprograms Chapter 10
Functions.
Implementing Subprograms
Procedures (Functions)
Implementing Subprograms
The University of Adelaide, School of Computer Science
Implementing Subprograms
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
UNIT V Run Time Environments.
Languages and Compilers (SProg og Oversættere)
Runtime Environments What is in the memory?.
Scope, Function Calls and Storage Management
Recursive Procedures and Scopes
RUN-TIME STORAGE Chuen-Liang Chen Department of Computer Science
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Presentation transcript:

slide 1 Vitaly Shmatikov CS 345 Scope and Activation Records

slide 2 Activation Records for Functions uBlock of information (“frame”) associated with each function call, including: Parameters Local variables Return address Location to put return value when function exits Control link to the caller’s activation record Saved registers Temporary variables and intermediate results (not always) Access link to the function’s static parent

slide 3 Activation Record Layout uReturn address Location of code to execute on function return uReturn-result address Address in activation record of calling block to receive returned value uParameters Locations to contain data from calling block Control link Local variables Intermediate results Environment pointer Parameters Return address Return-result addr

slide 4 Example uFunction fact(n) = if n<=1 then 1 else n * fact(n-1) Return result address: location to put fact(n) uParameter Set to value of n by calling sequence uIntermediate result Locations to contain value of fact(n-1) Control link Local variables Intermediate results Environment pointer Parameters Return address Return result addr

slide 5 Typical x86 Activation Record frame pointer stack pointer

slide 6 Run-Time Stack uActivation records are kept on the stack Each new call pushes an activation record Each completing call pops the topmost one Stack has all records of all active calls at any moment during execution (topmost record = most recent call) uExample: fact(3) Pushes one activation record on the stack, calls fact(2) This call pushes another record, calls fact(1) This call pushes another record, resulting in three activation records on the stack

slide 7 Control link fact(n-1) n Return-result addr 3 fact(3) Function Call Return address omitted; would be a pointer into code segment Control link fact(n-1) n Return-result addr 2 fact(2) fact(n) = if n<= 1 then 1 else n * fact(n-1) Control link fact(n-1) n Return-result addr k fact(k) Environment pointer Control link fact(n-1) n Return-result addr 1 fact(1)

slide 8 Function Return Control link fact(n-1) n Return-result addr 3 fact(3) Control link fact(n-1) n Return-result addr 1 2 fact(2) Control link fact(n-1) n Return-result addr 1 fact(1) fact(n) = if n<=1 then 1 else n * fact(n-1) Control link fact(n-1) n Return-result addr 2 3 fact(3) Control link fact(n-1) n Return-result addr 1 2 fact(2) High addresses Low addresses

slide 9 Scoping Rules uGlobal and local variables { int x=0; int y=x+1; { int z=(x+y)*(x-y); }; x, y are local to outer block z is local to inner bock x, y are global to inner block uStatic scope Global refers to declaration in closest enclosing block uDynamic scope Global refers to most recent activation record uDo you see the difference? (think function calls)

slide 10 Static vs. Dynamic Scope uExample var x=1; function g(z) { return x+z; } function f(y) { var x = y+1; return g(y*x); } f(3); x1 x4 y3 z12 outer block f(3) g(12) Which x is used for expression x+z ? static scope dynamic scope

slide 11 Activation Record For Static Scope uControl link Link to activation record of previous (calling) block Depends on dynamic behavior of the program uAccess link Link to activation record of closest lexically enclosing block in program text –Is this needed in C? (why?) Depends on the static program text Control link Local variables Intermediate results Environment pointer Parameters Return address Return result addr Access link

slide 12 Complex Nesting Structure var x=1; function g(z) { return x+z; } function f(y) { var x = y+1; return g(y*x); } f(3); function m(…) { var x=1; … function n( … ){ function g(z) { return x+z; } … { … function f(y) { var x = y+1; return g(y*x); } … f(3); … } … n( … ) …} … m(…) Simplify to Simplified code has same block nesting, if we follow convention that each declaration begins a new block

slide 13 Static Scope with Access Links var x=1; function g(z) = { return x+z; } function f(y) = { var x = y+1; return g(y*x); } f(3); x1 x4 y3 z12 outer block f(3) g(12) control link access link g…f… control link access link control link access link control link Use access link to find global variable: - Access link is always set to frame of closest enclosing lexical block - For function body, this is the block that contains function definition

slide 14 Variable Arguments (Redux) uSpecial functions va_start, va_arg, va_end compute arguments at run-time (how?)

slide 15 Activation Record for Variable Args va_start computes location on the stack past last statically known argument va_arg(ap,type) retrieves next arg from offset ap

slide 16 Tail Recursion (first-order case) uFunction g makes a tail call to function f if return value of function f is return value of g uExample fun g(x) = if x>0 then f(x) else f(x)*2 uOptimization: can pop current activation record on a tail call Especially useful for recursive tail call because next activation record has exactly same form tail callnot a tail call

slide 17 Example of Tail Recursion fun f(x,y) = if x>y then x else f(2*x, y); f(1,3) + 7; control return val x1 y3 control return val x1 y3 control return val x2 y3 control return val x4 y3 f(1,3) Optimization Set return value address to that of caller Can we do same with control link? Optimization Avoid return to caller Does this work with dynamic scope? Calculate least power of 2 greater than y

slide 18 Tail Recursion Elimination control return val x1 y3 f(4,3) Optimization pop followed by push - reuse activation record in place Tail recursive function is equivalent to iterative loop control return val x2 y3 f(1,3) control return val x4 y3 f(2,3) fun f(x,y) = if x>y then x else f(2*x, y); f(1,3) + 7;

slide 19 Tail Recursion and Iteration fun f(x,y) = if x>y then x else f(2*x, y); f(1,y); control return val x1 y3 f(4,3) control return val x2 y3 f(1,3) control return val x4 y3 f(2,3) function g(y) { var x = 1; while (!x>y) x = 2*x; return x; } initial value loop body test

slide 20 Higher-Order Functions uFunction passed as argument Need pointer to activation record “higher up” in stack uFunction returned as the result of function call Need to keep activation record of the returning function (why?) uFunctions that take function(s) as input and return functions as output are known as functionals

slide 21 Pass Function as Argument val x = 4; fun f(y) = x*y; fun g(h) = let val x=7 in h(3) + x; g(f); There are two declarations of x Which one is used for each occurrence of x? { var x = 4; { function f(y) {return x*y;} { function g(h) { var x = 7; return h(3) + x; } g(f); } } }

slide 22 Static Scope for Function Argument val x = 4; fun f(y) = x*y; fun g(h) = let val x=7 in h(3) + x; g(f); x4hy3fg Code for f Code for g g(f) h(3) x * y x7 follow access link local var How is access link for h(3) set?

slide 23 Closures uFunction value is pair closure =  env, code  Idea: statically scoped function must carry a link to its static environment with it Only needed if function is defined in a nested block (why?) uWhen a function represented by a closure is called… Allocate activation record for call (as always) Set the access link in the activation record using the environment pointer from the closure

slide 24 Function Argument and Closures val x = 4; fun f(y) = x*y; fun g(h) = let val x=7 in h(3) + x; g(f); x4 access link set from closure Code for f f access Run-time stack with access links Code for g h(3) y3 access g(f) h access x7 g

slide 25 Summary: Function Arguments uUse closure to maintain a pointer to the static environment of a function body uWhen called, set access link from closure uAll access links point “up” in stack May jump past activation records to find global vars Still deallocate activation records using stack (last-in- first-out) order

slide 26 Return Function as Result uLanguage feature (e.g., ML) uFunctions that return “new” functions Example: fun compose(f,g) = (fn x => g(f x)); Function is “created” dynamically –Expression with free variables; values determined at run-time Function value is closure =  env, code  Code not compiled dynamically (in most languages) Need to maintain environment of the creating function (why?)

slide 27 Return Function with Private State Function to “make counter” returns a closure How is correct value of count determined in c(2) ? fun mk_counter (init : int) = let val count = ref init fun counter(inc:int) = (count := !count + inc; !count) in counter end; val c = mk_counter(1); c(2) + c(2);

slide 28 fun mk_counter (init : int) = let val count = ref init fun counter(inc:int) = (count := !count + inc; !count) in counter end; val c = mk_counter(1); c(2) + c(2); Function Results and Closures c access Code for counter Code for mk_counter c(2) access inc2 mk_c 1 mk_counter(1) count init1 access counter Call changes cell value from 1 to 3 3

slide 29 Closures in Web Programming uUseful for event handlers function AppendButton(container, name, message) { var btn = document.createElement('button'); btn.innerHTML = name; btn.onclick = function(evt) { alert(message); } container.appendChild(btn); } uEnvironment pointer lets the button’s click handler find the message to display

slide 30 Managing Closures uClosures as used to maintain static environment of functions as they are passed around uMay need to keep activation records after function returns (why?) Stack (last-in-first-out) order fails! (why?) uPossible “stack” implementation: Put activation records on heap Instead of explicit deallocation, invoke garbage collector as needed –Not as totally crazy as is sounds (may only need to search reachable data)