runtime environments
DESCRIPTION
Runtime Environments. Support of Execution. Activation Tree Control Stack Scope Binding of Names Data object (values in storage) Environment (functions that map to stg) State (funct that maps a stg location to the value held there). Storage Allocation Strategies. Static - PowerPoint PPT PresentationTRANSCRIPT
Runtime EnvironmentsRuntime Environments
Support of ExecutionSupport of Execution
Activation TreeActivation Tree Control StackControl Stack ScopeScope Binding of NamesBinding of Names
– Data object (values in storage)Data object (values in storage)– Environment (functions that map to Environment (functions that map to stg)stg)
– State (funct that maps a stg State (funct that maps a stg location to the value held there)location to the value held there)
Storage Allocation StrategiesStorage Allocation Strategies
StaticStatic– Names are bound to storage at Names are bound to storage at compile timecompile time
Dynamic Dynamic – names are bound to storage at run names are bound to storage at run timetime
Storage OrganizationStorage Organization
CODECODE
STATIC DATASTATIC DATA
STACKSTACK
\/\/
/\/\
HEAPHEAP
StackStack
Allocate activation recordAllocate activation record Locals get new storageLocals get new storage Enters information into its Enters information into its fieldsfields
Activation Record (Stack Frames)Activation Record (Stack Frames)
Returned valueReturned value Actual parametersActual parameters Optional control linkOptional control link Optional access linkOptional access link Saved machine statusSaved machine status Local dataLocal data Temporary dataTemporary data
Calling SequenceCalling Sequence
Caller evaluates argumentsCaller evaluates arguments Caller stores return address in Caller stores return address in callee’s activation recordcallee’s activation record
Caller stores stack topCaller stores stack top Callee saves register values Callee saves register values and status information for and status information for callercaller
Return Sequence.Return Sequence.
Callee restores state of Callee restores state of machinemachine
Callee places return value next Callee places return value next to the activation record of the to the activation record of the callercaller
Restores top of stack pointerRestores top of stack pointer Caller copies return value Caller copies return value
Variable Length DataVariable Length Data
ArraysArrays– Stored after the activation recordStored after the activation record– The activation record does not The activation record does not have to allocate space for the have to allocate space for the
Dangling ReferenceDangling Reference #include <stdio.h>#include <stdio.h> int *dangle();int *dangle(); main(){main(){ int *p;int *p; p = dangle(); printf("p = %d\p = dangle(); printf("p = %d\n",*p);n",*p);
sub(); printf("p = %d\sub(); printf("p = %d\n",*p);n",*p);
}} int *dangle(){int *dangle(){ int i = 23;int i = 23; return &i;return &i; }} sub(){sub(){ int i,j,k;int i,j,k; }}
Heap vs Stack AllocationHeap vs Stack Allocation
Stack allocation cannot be used Stack allocation cannot be used ifif– Local names must be retained after Local names must be retained after activation endsactivation ends
– Activation outlives callerActivation outlives caller
Heap Management StrategiesHeap Management Strategies
free listfree list first fitfirst fit best fitbest fit worst fitworst fit
Garbage CollectionGarbage Collection
records not reachablerecords not reachable reclaim to allow reusereclaim to allow reuse performed by runtime systemperformed by runtime system
(support programs linked with (support programs linked with the compiled code)the compiled code)
Record TypesRecord Types
live – will be used in the live – will be used in the futurefuture
not live – will not be used in not live – will not be used in the futurethe future
reachable – able to be accessed reachable – able to be accessed via programsvia programs
Types of AlgorithmsTypes of Algorithms
Mark-And-Sweep CollectionMark-And-Sweep Collection Reference CountsReference Counts Copying CollectionCopying Collection Generational CollectionGenerational Collection Incremental CollectionIncremental Collection
Mark-And-Sweep CollectionMark-And-Sweep Collection
Program variables and heap Program variables and heap records form a directed graphrecords form a directed graph
Roots are the variablesRoots are the variables node n is reachable ifnode n is reachable if
r -> … -> nr -> … -> n Depth first search marks Depth first search marks reachable nodesreachable nodes
Any node not marked is garbageAny node not marked is garbage
Cost of Garbage CollectionCost of Garbage Collection
Depth first search takes time Depth first search takes time proportional to the number of proportional to the number of reachable nodesreachable nodes
Sweep phase takes time Sweep phase takes time proportional to the size of the proportional to the size of the heapheap
Maintaining Free SpaceMaintaining Free Space
Create a list of free spaceCreate a list of free space Search for a space of size N Search for a space of size N might be longmight be long
Maintain several free lists of Maintain several free lists of differing sizesdiffering sizes
External fragmentation a problemExternal fragmentation a problem Internal fragmentation can also Internal fragmentation can also be a problembe a problem
Reference CountsReference Counts
Count the number of pointers Count the number of pointers pointing to each recordpointing to each record
Store the reference count with Store the reference count with each recordeach record
If p addresses an alternate If p addresses an alternate record, decrement the old and record, decrement the old and increment the newincrement the new
If count reaches 0, free recordIf count reaches 0, free record
When to DecrementWhen to Decrement
Instead of decrementing the Instead of decrementing the counts a record references when counts a record references when the record is placed on the the record is placed on the free list, it is better to do free list, it is better to do this when the record is removed this when the record is removed from the free list.from the free list.
WhyWhy
Breaks the recursive Breaks the recursive decrementing work into shorter decrementing work into shorter piecespieces
Compiler emits code to check Compiler emits code to check whether the count has reached whether the count has reached 0, but the recursive 0, but the recursive decrementing will be done only decrementing will be done only in one place, in the allocatorin one place, in the allocator
Problems with Reference CountProblems with Reference Count
Cycles of garbage cannot be Cycles of garbage cannot be reclaimedreclaimed
Incrementing the reference Incrementing the reference counts is very expensivecounts is very expensive
Solutions-Cycles, ExpensiveSolutions-Cycles, Expensive
Require the programmer to break Require the programmer to break the cyclethe cycle
Combine reference counting with Combine reference counting with mark-sweepmark-sweep
No solution for it being No solution for it being expensiveexpensive
Problems outweigh advantages, Problems outweigh advantages, thus rarely usedthus rarely used
Copying CollectionCopying Collection
Reachable part is a directed Reachable part is a directed graph with records as nodes, graph with records as nodes, pointers as edges, and pointers as edges, and variables as rootsvariables as roots
Copy the graph from “from-Copy the graph from “from-space” to “to-space”space” to “to-space”
Delete all “from-space”qqDelete all “from-space”qq
Access to Nonlocal NamesAccess to Nonlocal Names
Lexical scope without nested Lexical scope without nested proceduresprocedures– Allows nonlocals to be found via Allows nonlocals to be found via static addressesstatic addresses
– Uses physical layoutUses physical layout– All storage locations known at All storage locations known at compile timecompile time
– Functions can be passed as Functions can be passed as parametersparameters
Lexical Scope ExampleLexical Scope Examplemain { /* main */ A.R. mainmain { /* main */ A.R. main p(); …p(); …} /* main */ A.R. p} /* main */ A.R. p p{ control p{ control
link mainlink main int n; no int n; no
access linkaccess link n = 1; …n = 1; … r(2); A.R. rr(2); A.R. r fun q{ /* inside of p */ contol link pfun q{ /* inside of p */ contol link p n = 5; /*n non-local non-global*/ access link pn = 5; /*n non-local non-global*/ access link p } …} … fun r(int n){ /* inside of p */ A.R. qfun r(int n){ /* inside of p */ A.R. q q(); q();
control link rcontrol link r }/* r */ access }/* r */ access
link plink p } …} …
Access Chaining ExampleAccess Chaining Examplemain{ A.R. mainmain{ A.R. main p(); …p(); … fun p{ A.R. pfun p{ A.R. p int x; ctl link main, int x; ctl link main, acc mainacc main
q(); A.R. q q(); A.R. q fun q{ ctl link p, acc fun q{ ctl link p, acc link plink p
r(); A.R. r r(); A.R. r fun r{ /* fun r */ ctl link q, acc link qfun r{ /* fun r */ ctl link q, acc link q x = 2; A.R. px = 2; A.R. p if ... then p(); ctl link r, acc if ... then p(); ctl link r, acc link main link main
} /* fun r */ A.R. q} /* fun r */ A.R. q } /* fun q */ ctl link p, acc link } /* fun q */ ctl link p, acc link pp
} /* fun p */ A.R. r} /* fun p */ A.R. r} /* fun main */ ctl link q, acc link q} /* fun main */ ctl link q, acc link q
Passing Function ExamplePassing Function Examplemain{ A.R. mainmain{ A.R. main q(); …q(); … fun p (fun a) { A.R. qfun p (fun a) { A.R. q a(); ctl link a(); ctl link main, acc mainmain, acc main
} /* end p */ A.R. p} /* end p */ A.R. p fun q { ctl link q, fun q { ctl link q, acc mainacc main
int x; A.R. aint x; A.R. a x = 2; ctl link p, x = 2; ctl link p, acc qacc q
p(r);p(r); fun r{fun r{ printf( x );printf( x ); } /* end r */} /* end r */ } /* end q */} /* end q */} /* end main */ } /* end main */
Dynamic ScopeDynamic Scopelisp, apl, snobol, spitbol, schemelisp, apl, snobol, spitbol, scheme
main(){main(){ float r; float r; r := .25;r := .25; show; small; show; small; show; small; show; small;
fun show{fun show{ printf(r); printf(r); } } fun small{fun small{ fun r;fun r; r := 0.125; r := 0.125; show;show; }}}} What is printed?What is printed?
Parameter PassingParameter Passing
Call by valueCall by value Call by reference (address)Call by reference (address) Call by copy restoreCall by copy restore Call by nameCall by name
Call by ValueCall by Value
Only the value is passedOnly the value is passed Storage is in the A.R. of Storage is in the A.R. of called functioncalled function
Caller evaluates and places the Caller evaluates and places the value in callee A.R.value in callee A.R.
Operations do not effect Operations do not effect original valueoriginal value
Call by ReferenceCall by Reference
Caller passes pointer to calleeCaller passes pointer to callee if a+b is passed, the address if a+b is passed, the address of a temporary is usedof a temporary is used
Consider swap(i,a[i])Consider swap(i,a[i])– Does indeed swapDoes indeed swap– Addresses are bound at time of Addresses are bound at time of callcall
Call by Copy-RestoreCall by Copy-Restore
Value of argument is given to Value of argument is given to calleecallee
Upon completion value is copied Upon completion value is copied back to callerback to caller
swap(i, a[i]) works correctlyswap(i, a[i]) works correctly
Copy-Restore/Reference ExampleCopy-Restore/Reference Example
int a = 1;int a = 1;main() {main() { unsafe(a);unsafe(a); print(a);print(a);}}fun unsafe( int x) {fun unsafe( int x) { x = 2;x = 2; a = 0;a = 0;}}
Copy-Restore/Reference ExampleCopy-Restore/Reference ExampleNested FunctionsNested Functions
main() {main() { int a = 1;int a = 1; unsafe(a);unsafe(a); print(a);print(a); fun unsafe( int x) {fun unsafe( int x) { x = 2;x = 2; a = 0;a = 0; }}}}
Call by NameCall by Name
A macroA macro Body of the function replaces Body of the function replaces the callthe call
Local values are protectedLocal values are protected swap(i, a[i]) does not work swap(i, a[i]) does not work since i will have changed valuesince i will have changed value
Call by Name ExampleCall by Name Example
#include <stdio.h>#include <stdio.h> int temp;int temp; #define swap(x,y) { temp = x, x = y, y = temp; }#define swap(x,y) { temp = x, x = y, y = temp; } main(){main(){ int i;int i; int a[5] ={1,2,3,4,5};int a[5] ={1,2,3,4,5}; for(i = 0; i < 5; i++)for(i = 0; i < 5; i++) printf("a[%d]=%d ",i,a[i]);printf("a[%d]=%d ",i,a[i]); i = 3;i = 3; swap(i,a[i]);swap(i,a[i]); for(i = 0; i < 5; i++ ) for(i = 0; i < 5; i++ ) printf("a[%d]=%d ",i,a[i]);printf("a[%d]=%d ",i,a[i]); }} Prints a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=3Prints a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=3