29
slide 1 Vitaly Shmatikov CS 345 Scope and Activation Records

07 Activ Record

Embed Size (px)

DESCRIPTION

vvg

Citation preview

  • slide *Vitaly ShmatikovCS 345Scope and Activation Records

  • slide *Activation Records for FunctionsBlock of information (frame) associated with each function call, including:ParametersLocal variablesReturn addressLocation to put return value when function exitsControl link to the callers activation recordSaved registersTemporary variables and intermediate results(not always) Access link to the functions static parent

  • slide *Activation Record LayoutReturn addressLocation of code to execute on function returnReturn-result addressAddress in activation record of calling block to receive returned valueParametersLocations to contain data from calling blockControl linkLocal variablesIntermediate resultsEnvironment pointerParametersReturn addressReturn-result addr

  • slide *ExampleFunctionfact(n) = if n
  • slide *Typical x86 Activation Recordframe pointerstack pointer

  • slide *Run-Time StackActivation records are kept on the stackEach new call pushes an activation recordEach completing call pops the topmost oneStack has all records of all active calls at any moment during execution (topmost record = most recent call)Example: 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 *Function CallReturn address omitted; would be a pointer into code segmentfact(n) = if n
  • slide *Function ReturnControl linkfact(n-1)nReturn-result addr3fact(3)Control linkfact(n-1)nReturn-result addr12fact(2)Control linkfact(n-1)nReturn-result addr1fact(1)fact(n) = if n
  • slide *Scoping RulesGlobal and local variables

    x, y are local to outer block z is local to inner bockx, y are global to inner blockStatic scopeGlobal refers to declaration in closest enclosing blockDynamic scopeGlobal refers to most recent activation recordDo you see the difference? (think function calls)

  • slide *Static vs. Dynamic ScopeExamplevar x=1;function g(z) { return x+z; }function f(y) { var x = y+1; return g(y*x);}f(3);x1x4y3z12outer blockf(3)g(12)Which x is used for expression x+z ?static scopedynamic scope

  • slide *Activation Record For Static ScopeControl linkLink to activation record of previous (calling) blockDepends on dynamic behavior of the programAccess linkLink to activation record of closest lexically enclosing block in program textIs this needed in C? (why?)Depends on the static program textControl linkLocal variablesIntermediate resultsEnvironment pointerParametersReturn addressReturn result addrAccess link

  • slide *Complex Nesting Structurevar 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 toSimplified code has same block nesting, if we follow convention that each declaration begins a new block

  • slide *Static Scope with Access Linksvar x=1; function g(z) = { return x+z; } function f(y) = { var x = y+1; return g(y*x); } f(3);x4y3z12outer blockf(3)g(12)control linkaccess linkcontrol linkaccess linkcontrol linkaccess linkaccess linkcontrol linkUse 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 *Variable Arguments (Redux)Special functions va_start, va_arg, va_end compute arguments at run-time (how?)

  • slide *Activation Record for Variable Argsva_start computeslocation on the stackpast last staticallyknown argumentva_arg(ap,type) retrieves next arg from offset ap

  • slide *Tail Recursion (first-order case) Function g makes a tail call to function f if return value of function f is return value of gExamplefun g(x) = if x>0 then f(x) else f(x)*2Optimization: can pop current activation record on a tail callEspecially useful for recursive tail call because next activation record has exactly same form

  • slide *Example of Tail Recursionfun f(x,y) = if x>y then x else f(2*x, y);f(1,3) + 7;controlreturn valx1y3controlreturn valx1y3controlreturn valx2y3controlreturn valx4y3f(1,3)OptimizationSet return value address to that of callerCan we do same with control link?OptimizationAvoid return to callerDoes this work with dynamic scope?Calculate least power of 2 greater than y

  • slide *Tail Recursion Elimination controlreturn valx1y3f(4,3)Optimizationpop followed by push - reuse activation record in placeTail recursive function is equivalent to iterative loopcontrolreturn valx2y3f(1,3)controlreturn valx4y3f(2,3)fun f(x,y) = if x>y then x else f(2*x, y);f(1,3) + 7;

  • slide *Tail Recursion and Iteration fun f(x,y) = if x>y then x else f(2*x, y);f(1,y);function g(y) { var x = 1; while (!x>y) x = 2*x; return x;}

  • slide *Higher-Order FunctionsFunction passed as argumentNeed pointer to activation record higher up in stackFunction returned as the result of function callNeed to keep activation record of the returning function (why?)Functions that take function(s) as input and return functions as output are known as functionals

  • slide *Pass Function as Argumentval 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 xWhich 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 *Static Scope for Function Argumentval x = 4; fun f(y) = x*y; fun g(h) = let val x=7 in h(3) + x; g(f);

    Code for fCode for gg(f)h(3)x * yfollow access linklocal varHow is access link for h(3) set?

  • slide *ClosuresFunction value is pair closure = env, code Idea: statically scoped function must carry a link to its static environment with itOnly needed if function is defined in a nested block (why?)When a function represented by a closure is calledAllocate activation record for call (as always)Set the access link in the activation record using the environment pointer from the closure

  • slide *Function Argument and Closuresval x = 4; fun f(y) = x*y; fun g(h) = let val x=7 in h(3) + x; g(f);

    access link set from closureCode for fRun-time stack with access linksCode for g

  • slide *Summary: Function ArgumentsUse closure to maintain a pointer to the static environment of a function bodyWhen called, set access link from closureAll access links point up in stackMay jump past activation records to find global varsStill deallocate activation records using stack (last-in-first-out) order

  • slide *Return Function as ResultLanguage feature (e.g., ML)Functions that return new functionsExample: fun compose(f,g) = (fn x => g(f x));Function is created dynamicallyExpression with free variables; values determined at run-timeFunction value is closure = env, codeCode not compiled dynamically (in most languages)Need to maintain environment of the creating function (why?)

  • slide *Return Function with Private StateFunction to make counter returns a closureHow 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 *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 ClosuresCode for counterCode for mk_counter

  • slide *Closures in Web ProgrammingUseful 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);}

    Environment pointer lets the buttons click handler find the message to display

  • slide *Managing ClosuresClosures as used to maintain static environment of functions as they are passed aroundMay need to keep activation records after function returns (why?)Stack (last-in-first-out) order fails! (why?)Possible stack implementation:Put activation records on heapInstead of explicit deallocation, invoke garbage collector as neededNot as totally crazy as is sounds (may only need to search reachable data)