PL 12 CH 10
PL 12 CH 10
Implementing
Subprograms
ISBN 0- 0-321-49362-1
Chapter 10 Topics
• Call Semantics:
• Required storage:
– Status information, parameters, return address,
return value for functions, temporaries
• Caller Actions:
– Create an activation record instance
– Save the execution status of the current program unit
– Compute and pass the parameters
– Pass the return address to the called
– Transfer control to the called
• Prologue actions of the called:
– Save the old EP in the stack as the dynamic link and create
the new value
– Allocate local variables
void fun1(float r) {
int s, t;
...
fun2(s);
...
}
void fun2(int x) {
int y;
...
fun3(y);
main calls fun1
}
... fun1 calls fun2
void fun3(int q) { fun2 calls fun3
...
}
void main() {
float p;
...
fun1(p);
...
}
function main(){
var x;
function bigsub() {
var a, b, c;
function sub1 {
var a, d;
a = b + c; 🡨-------------------------------1
...
} // end of sub1
function sub2(x) {
var b, e;
function sub3() {
var c, e;
...
sub1();
...
e = b + a; 🡨------------------------------2
} // end of sub3 ...
sub3();
...
a = d + e; 🡨--------------------------------3
} // end of sub2
...
sub2(7);
...
} // end of bigsub
...
bigsub();
...
} // end of main
• At the call,
- The activation record instance must be built
- The dynamic link is just the old stack top pointer
- The static link must point to the most recent ari
of the static parent
- Two methods:
1. Search the dynamic chain
2. Treat subprogram calls and
definitions like variable references
and definitions
• Problems:
1. A nonlocal reference is slow if the
nesting depth is large
2. Time-critical code is difficult:
a. Costs of nonlocal references are
difficult to determine
b. Code changes can change the
nesting depth, and therefore the cost
• Two Methods:
1. Treat blocks as parameter-less subprograms
that are always called from the same location
– Every block has an activation record; an instance is
created every time the block is executed
2. Since the maximum storage required for a
block can be statically determined, this amount
of space can be allocated after the local
variables in the activation record
1-36
Using Shallow Access to Implement
Dynamic Scoping
void sub3() {
int x, z;
x = u + v;
…
}
void sub2() {
int w, x;
…
}
void sub1() {
int v, w;
…
}
void main() {
int v, u;
…
}