Computer Science and IT‹›⌂ 0:00 studied

Module 8 · 18 min read · Free chapter

Runtime environments and optimisation

In short

Each call gets an activation record on the stack with parameters, links, return address and locals. Static scoping follows the program text, dynamic scoping follows the calls. Optimisation splits code into basic blocks at leaders, removes common subexpressions with a DAG, and uses data-flow analysis: liveness backward, reaching definitions and constant propagation forward.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: the pile of files on a clerk's desk

Picture a clerk in a district office. A file for a pension case is open on the desk, with a sticky note of working figures. Halfway through, the case needs a land record, so the clerk places that file on top and starts it, with a fresh note.

The land record in turn needs a birth certificate, and a third file goes on top. When the birth certificate is done, its file and note go away, and the clerk returns to the land record exactly where it was left. The newest file is always finished first.

A running program handles procedure calls in exactly this way. Each call gets an activation record on a stack, holding its parameters, local variables and the place to return to. The record is removed when the call returns, and the caller continues.

This chapter has two halves. The first is the runtime environment: how memory, scope and parameters work while a program runs. The second is optimisation: how a compiler studies the code it has produced and makes it faster without changing what it does.

Why it matters. GATE questions on scoping and parameter passing ask for the exact output of a program. Questions on optimisation ask you to count basic blocks, find live variables or fold constants, all of which need a clear picture of the code.

Memory layout and activation records

At run time, a program's memory has four areas. Code holds the instructions, and static data holds globals and constants whose size is known at compile time. The stack holds activation records, and the heap holds data created with malloc or new. The stack and heap usually grow towards each other from opposite ends of the free space.

An activation record, or stack frame, is pushed on each call and popped on return. Its usual fields, from the caller's side inwards, are listed below.

Field What it holds
Actual parameters Values or addresses passed by the caller
Returned value The result handed back to the caller
Control link Pointer to the caller's activation record
Access link Pointer to the record of the enclosing scope, for non-local names
Saved machine status Return address and saved registers
Local data Variables declared in the procedure
Temporaries Intermediate values of expressions

There are three ways to allocate storage. Static allocation fixes every address at compile time, which is fast but cannot support recursion, because two live calls of one procedure would share one set of locals. Stack allocation gives each call its own record, so recursion works, and the record vanishes on return.

Heap allocation is needed when data must outlive the call that created it, such as a linked-list node returned from a function. Heap blocks are freed explicitly, as with free in C, or reclaimed by a garbage collector. A pointer to a freed block is a dangling pointer, and a block nobody can reach but nobody freed is a memory leak.

Worked example. A recursive fact(n) that stops at n=1n = 1 is called from main as fact(3). At the deepest point the stack holds records for main, fact(3), fact(2) and fact(1), which is 4 records, and with depth nn the space used is O(n)O(n).

Why it matters. Questions on recursion depth, stack overflow and dangling pointers all reduce to this picture of the stack and heap. Knowing the fields of a record also explains how a procedure returns and finds non-local names.

Static and dynamic scoping

When a procedure uses a name it did not declare, which declaration does the name mean? There are two answers, and they can give different outputs for the same program.

Static or lexical scoping looks at the program text: the name refers to the declaration in the nearest enclosing block. The compiler can decide this before the program runs, and at run time it follows access links. C, C++ and Java use static scoping.

Dynamic scoping looks at the calls: the name refers to the most recent declaration that is still active in the chain of calls. It is decided only at run time, by following control links back through callers.

int x = 10;
void show() { print(x); }
void test() { int x = 20; show(); }
int main()  { test(); show(); }

Worked example. Under static scoping, show is written at the top level, where the only visible x is the global, so both calls print 10 and the output is 10 10. Under dynamic scoping, the first call to show comes from test, whose local x = 20 is the most recent active one, so it prints 20; the second call comes straight from main, so it prints 10. The output is 20 10.

Why it matters. GATE often gives a short program with a nested or global variable and asks for its output under both rules. Tracing the calls on paper, with a column for each active x, settles it quickly.

Parameter passing modes with outputs

How a parameter is passed decides whether the caller sees changes. There are four classic modes. Call by value copies the value, so the procedure works on its own copy. Call by reference passes the address, so the parameter is another name for the caller's variable.

Call by value-result, also called copy-in copy-out, copies the value in at the call and copies the final value back at the return. Call by name works like textual substitution: the argument expression replaces the parameter everywhere, and it is evaluated again at each use.

void f(int a, int b) { a = a + 1; b = b + a; }
int main() { int x = 5; f(x, x); print(x); }

int i = 1;
int arr[3] = {10, 20, 30};
void p(int y) { i = i + 1; print(y); }
int main2() { p(arr[i]); }
Mode f(x, x) prints p(arr[i]) prints
Value 5 20
Reference 12 20
Value-result, copied back left to right 11 20
Name 12 30

Working for f(x, x). By value, the procedure changes only its copies, so xx stays 5. By reference, aa and bb are both xx: the first line makes x=6x = 6, and the second makes x=6+6=12x = 6 + 6 = 12.

By value-result, aa and bb start as 5, then a=6a = 6 and b=5+6=11b = 5 + 6 = 11. At return aa is copied to xx and then bb is copied to xx, so x=11x = 11; if the copies were done right to left, the answer would be 6. By name, aa and bb both become the text x, which behaves like reference here and gives 12.

Working for p(arr[i]). By value and by reference, yy is fixed to arr[1], which is 20, before i changes. By name, yy stands for the text arr[i], which is evaluated only at the print, after i has become 2, so it prints arr[2], which is 30.

Why it matters. Output questions on parameter passing appear often in GATE and in scientist exams. The two programs above show the only real differences: aliasing, copy-back order and late evaluation.

Basic blocks, flow graphs and local optimisation

An optimiser first cuts the three-address code into basic blocks. A basic block is a straight run of instructions that is always entered at its first instruction and left at its last, with no jump into or out of the middle. To find blocks, first mark the leaders.

  • The first instruction of the program is a leader.
  • Every instruction that is the target of a jump is a leader.
  • Every instruction that comes right after a jump is a leader.

Each block runs from one leader up to, but not including, the next. In the flow graph, the blocks are nodes, and an edge joins B1B_1 to B2B_2 if B2B_2 can run right after B1B_1, by a jump or by falling through.

Worked example. Take the summing loop again.

1: s = 0
2: i = 0
3: if i >= n goto 9
4: t1 = 4 * i
5: t2 = a[t1]
6: s = s + t2
7: i = i + 1
8: goto 3
9: return s

The leaders are 1 (the first instruction), 3 (the target of 8), 4 (right after the jump at 3) and 9 (the target of 3, and right after 8). So there are 4 blocks: B1B_1 is lines 1 and 2, B2B_2 is line 3, B3B_3 is lines 4 to 8, and B4B_4 is line 9. The edges are B1→B2B_1 \to B_2, B2→B3B_2 \to B_3, B2→B4B_2 \to B_4 and the back edge B3→B2B_3 \to B_2, which marks the loop.

Local optimisation improves each block on its own. Constant folding computes constant expressions at compile time, so x = 4 * 2 becomes x = 8. Constant propagation replaces a variable known to hold a constant with that constant, and copy propagation replaces y with x after y = x.

Common subexpression elimination reuses a value already computed. Dead code elimination removes instructions whose results are never used. Algebraic simplification drops x + 0 and x * 1, and strength reduction replaces a costly operation by a cheaper one, such as x * 2 by x + x, or a multiplication in a loop by repeated addition.

Peephole optimisation slides a small window over the final instructions. It removes a load that follows a store to the same place, replaces a jump to a jump with a single jump, and deletes code that can never be reached.

Why it matters. Counting basic blocks is a direct GATE question, and the leader rules answer it in one pass. Every later analysis runs on the flow graph, so it must be right.

Common subexpressions and dead code with a DAG

Inside one basic block, a DAG finds repeated computations. Each variable's starting value is a leaf, marked with a subscript 0 such as b0b_0. Each instruction either reuses an existing node with the same operator and the same children, or creates a new one, and the variable assigned is attached to that node as a label.

Worked example. Build the DAG for this block.

a = b + c
b = a - d
c = b + c
d = a - d

The first line creates node n1=b0+c0n_1 = b_0 + c_0, labelled aa. The second creates n2=n1−d0n_2 = n_1 - d_0, labelled bb, and the third creates n3=n2+c0n_3 = n_2 + c_0, labelled cc; this is a new node, because bb now means n2n_2 and not b0b_0. The fourth line asks for a−da - d, and both aa and dd still mean n1n_1 and d0d_0, so it reuses n2n_2, and dd joins its labels.

a=b+cb=a−dc=b+cd=ba = b + c \qquad b = a - d \qquad c = b + c \qquad d = b

The rewritten block computes a−da - d once and replaces the fourth line with a copy. A careless reader might also merge the first and third lines because both look like b+cb + c, but the DAG shows they are different, because bb changed in between.

Dead code shows up in the same picture. If a node's labels are all variables that are not live at the block's exit, and no other node uses it, the instruction that computes it can be removed. Constant folding fits in too: a node whose children are constants is replaced by its value.

Worked example (folding and dead code). In x = 4; y = x * 2; z = y + x; if z > 10 goto L1, propagation and folding give y=8y = 8 and z=12z = 12. The test 12>1012 > 10 is always true, so the jump becomes goto L1, and the code that only ran when the test failed is now unreachable and can be deleted.

Why it matters. The syllabus names common subexpression elimination directly, and DAG questions on a block of four or five lines are common. Watch especially for variables reassigned in the middle of the block.

Data-flow analysis: reaching definitions and liveness

Local optimisation sees one block at a time. Data-flow analysis gathers facts across the whole flow graph by writing an equation for each block and solving all of them together. Each analysis has a direction, forward or backward, and a meet, union or intersection, for joining facts where paths meet.

Reaching definitions asks which assignments can reach a point without being overwritten. A block generates the definitions it makes, and kills other definitions of the same variables. It is a forward analysis with union as the meet.

OUT[B]=gen[B]∪(IN[B]−kill[B])\mathit{OUT}[B] = \mathit{gen}[B] \cup (\mathit{IN}[B] - \mathit{kill}[B])
IN[B]=⋃P∈pred(B)OUT[P]\mathit{IN}[B] = \bigcup_{P \in \mathit{pred}(B)} \mathit{OUT}[P]

Liveness asks which variables hold a value that may be used later. Here use[B]\mathit{use}[B] holds variables read in BB before any write in BB, and def[B]\mathit{def}[B] holds variables written before any read. Information flows from uses back to earlier points, so it is a backward analysis with union as the meet.

IN[B]=use[B]∪(OUT[B]−def[B])\mathit{IN}[B] = \mathit{use}[B] \cup (\mathit{OUT}[B] - \mathit{def}[B])
OUT[B]=⋃S∈succ(B)IN[S]\mathit{OUT}[B] = \bigcup_{S \in \mathit{succ}(B)} \mathit{IN}[S]

Both start with empty sets and repeat the equations until no set changes. Because sets only grow and are finite, the process always stops.

Worked example (liveness on the loop). For the four blocks of the summing loop, use[B1]=∅\mathit{use}[B_1] = \varnothing and def[B1]={s,i}\mathit{def}[B_1] = \{s, i\}; use[B2]={i,n}\mathit{use}[B_2] = \{i, n\}; use[B3]={i,a,s}\mathit{use}[B_3] = \{i, a, s\} and def[B3]={t1,t2}\mathit{def}[B_3] = \{t_1, t_2\}; and use[B4]={s}\mathit{use}[B_4] = \{s\}. In B3B_3, ss and ii are read before they are written, so they are in use, not def.

The first pass from the bottom gives IN[B4]={s}\mathit{IN}[B_4] = \{s\}, IN[B3]={a,i,s}\mathit{IN}[B_3] = \{a, i, s\} and IN[B2]={a,i,n,s}\mathit{IN}[B_2] = \{a, i, n, s\}. The second pass carries IN[B2]\mathit{IN}[B_2] around the back edge into OUT[B3]\mathit{OUT}[B_3], giving IN[B3]={a,i,n,s}\mathit{IN}[B_3] = \{a, i, n, s\}, and a third pass changes nothing. Finally IN[B1]={a,i,n,s}−{s,i}={a,n}\mathit{IN}[B_1] = \{a, i, n, s\} - \{s, i\} = \{a, n\}, so only aa and nn must be ready before the loop, and t1t_1 and t2t_2 are never live outside B3B_3.

Worked example (reaching definitions). Name the definitions d1d_1: s = 0, d2d_2: i = 0, and in B3B_3, d5d_5: s = s + t2 and d6d_6: i = i + 1. After the iteration settles, both d1d_1 and d5d_5 reach B4B_4, so the value of ss at the return is not a single constant, which is exactly the fact constant propagation needs.

Why it matters. The syllabus names liveness analysis directly, and GATE asks for the live variables at a point or for IN and OUT of a block. Writing the use and def sets carefully is half the work.

Constant propagation and register allocation

Constant propagation across blocks asks, for each variable at each point, whether it always holds the same constant. Each variable takes one of three values: UNDEF (no definition has reached yet), a constant cc, or NAC (not a constant). It is a forward analysis, and at a join point the values meet by these rules.

Meet of Result
UNDEF and a constant c c
c and the same c c
Two different constants NAC
NAC and anything NAC

For an instruction x=y+zx = y + z, if both yy and zz are constants, xx becomes their sum; if either is NAC, xx is NAC; otherwise xx is UNDEF. Worked example. If one branch sets x=3x = 3 and the other also sets x=3x = 3, then xx is 3 after the join and y = x * 2 folds to y = 6. If the other branch sets x=4x = 4 instead, then xx is NAC and nothing folds.

Analysis Direction Meet Used for
Reaching definitions Forward Union Use-definition chains, constant propagation
Liveness Backward Union Register allocation, dead code
Available expressions Forward Intersection Global common subexpressions
Constant propagation Forward Lattice meet Constant folding across blocks

Liveness leads directly to register allocation. Two variables interfere if they are live at the same point, so they cannot share a register. Draw an interference graph with a node per variable and an edge per interfering pair, and colour it so that no edge joins two nodes of the same colour; each colour is a register.

Worked example. In x = 2; y = x + 3; z = y * y; w = x + z, with only ww live at the end, the live sets after each line are {x}\{x\}, {x,y}\{x, y\}, {x,z}\{x, z\} and {w}\{w\}. The edges are xx–yy and xx–zz, and yy and zz never overlap, so they can share a register. Two colours suffice, and the code needs 2 registers, which matches the largest live set.

If the graph needs more colours than there are registers, some variable is spilled: it is kept in memory and loaded when needed. The compiler usually spills a variable that is used rarely and interferes with many others.

Why it matters. GATE asks for the minimum number of registers for a piece of code, and the answer comes from the largest live set. Constant propagation, liveness and common subexpressions are the three analyses the syllabus names, and this section completes them.

Descriptive lens: how written papers ask this

Written papers for scientist posts and university examinations ask about this topic in four ways:

  1. Describe the structure of an activation record and the storage allocation strategies, with a diagram of the stack during a recursive call.
  2. Trace a program under static and dynamic scoping, or under different parameter-passing modes, and give the output.
  3. Partition three-address code into basic blocks, draw the flow graph, and apply local optimisations.
  4. Set up and solve data-flow equations for reaching definitions, liveness or available expressions on a small flow graph.

Practice questions (our own, not previous-year questions).

  1. Draw the activation record of a procedure and explain each field. Why can static allocation not support recursion? (10 marks)
  2. For a procedure swap(int a, int b) called as swap(i, arr[i]), explain the result under call by value, reference and name. (10 marks)
  3. Write the data-flow equations for liveness analysis. Compute IN and OUT for each block of the summing loop given in this chapter. (15 marks)

Answer plan for question 3.

  • Begin by defining a live variable as one whose current value may be read on some path before it is overwritten.
  • Define use and def for a block, and note that a variable read before it is written belongs to use.
  • Write the two equations with IN[B]\mathit{IN}[B] from use and OUT[B]−def[B]\mathit{OUT}[B] - \mathit{def}[B], and OUT[B]\mathit{OUT}[B] as the union of the successors' IN sets.
  • Explain that the analysis is backward with union as the meet, and that all sets start empty.
  • List use and def for the four blocks, then show each pass of the iteration in a table until no set changes.
  • Conclude with the final sets, noting that only aa and nn are live on entry and that the temporaries are never live across blocks.

Quick revision

  • An activation record holds parameters, the returned value, control and access links, saved status, locals and temporaries.
  • Static allocation cannot support recursion, the stack holds call records, and the heap holds data that outlives a call.
  • Static scoping follows the program text through access links, while dynamic scoping follows the calls through control links.
  • For f(x, x) with a = a + 1; b = b + a and x=5x = 5, value prints 5, reference and name print 12, and value-result prints 11.
  • Leaders are the first instruction, every jump target and every instruction after a jump.
  • A DAG of a block reuses nodes for repeated computations only when no operand changed in between.
  • Reaching definitions is forward with union, liveness is backward with union, and available expressions is forward with intersection.
  • Constant propagation meets UNDEF with cc to give cc, and two different constants to give NAC.
  • The fewest registers for straight-line code equals the largest number of values live at once.
  • Spilling keeps a variable in memory when the interference graph needs more colours than registers.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. In an activation record, the control link points to:

  2. Which storage allocation cannot support recursion?

  3. A recursive fact(n) stopping at n=1n = 1 is called as fact(4) from main. The maximum number of activation records on the stack is:

  4. Global x = 10; show() prints x; test() declares x = 20 and calls show(); main calls test() then show(). The output under dynamic scoping is:

  5. f(a, b) does a = a + 1; b = b + a. With x = 5, after f(x, x) under call by reference, x is:

  6. p(y) does i = i + 1 and prints y; with i = 1 and arr = {10, 20, 30}, p(arr[i]) under call by name prints:

  7. Which instruction is NOT always a leader?

  8. The 9-line summing loop (s = 0, i = 0, test at line 3, body 4 to 8 ending in goto 3, return at 9) has how many basic blocks?

  9. Replacing x = 4 * 2 by x = 8 at compile time is:

  10. In the block a = b + c; b = a - d; c = b + c; d = a - d, the DAG shows that:

  11. Reaching definitions is a:

  12. The liveness equation for a block is:

  13. In constant propagation, x = 3 on one path and x = 4 on the other. After the join, x is:

  14. For x = 2; y = x + 3; z = y * y; w = x + z, with only w live at the end, the minimum number of registers without spilling is:

  15. Which data-flow analysis does the GATE 2026 CS syllabus name under Compiler Design?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is the difference between static and dynamic scoping?

Static scoping resolves a name by the program text, so the caller does not matter. Dynamic scoping uses the most recent active declaration in the call chain.

How are leaders of basic blocks found?

The first instruction, every jump target and every instruction right after a jump are leaders. Each block runs from a leader up to the next leader.

Is liveness a forward or backward analysis?

Liveness is backward with union: IN = use ∪ (OUT − def), and OUT is the union of the successors' IN sets.

What does call by name do?

It substitutes the argument expression for the parameter and evaluates it again at each use, so p(arr[i]) can read a different element after i changes.

More in this module: Compiler design

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Compiler Design (IIT Kharagpur, 106105190): run-time environments, code optimisation and data-flow analysis