Algorithmadvanced
Escape analysis
Also called escape analysis for objects.
Finds objects that do not outlive their method or thread, so they can be put on the stack and their locks removed.
- Time
- O(n^2 h + s h) worst
- Space
- O(n^2 + n h + s) extra
- Where
- h = the number of allocation sites; n = the number of nodes of the constraint graph; s = the total size of the statements
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Jong Deok Choi, Manish Gupta, Mauricio Serrano, Vugranam C. Sreedhar, Samuel Midkiff, Bruno Blanchet, John Whaley, Martin Rinard, 1999
Escape analysis finds the objects that cannot outlive the method that creates them, and the objects that only one thread can ever see. An object escapes its method when some path of references from outside the method's activation can reach it: through a global, a parameter object of the caller, or the return value. An object escapes its thread when another thread can reach it, through a global or through the arguments of a thread start. The first fact lets a compiler put the object in the method's stack frame, or break it into local variables with scalar replacement. The second lets it remove the locks on the object. The algorithm on this page follows Choi and colleagues (1999): it gives each allocation site one of three states, NONE, ARG or GLOBAL, from a points-to graph of the whole program. Here the graph comes from a field-sensitive Andersen analysis.
In plain words
Many objects in object-oriented code live only for a moment: an iterator in a loop, a small result object, a temporary string builder. If no one outside the method can ever get a reference to such an object, the method can keep it in its own stack frame, and the garbage collector never sees it. Escape analysis checks this. It follows every way a reference can leave a method: it can be stored in a global, written into an object that the caller gave, returned, or handed to a new thread. If none of these ways can reach the object, it stays inside. If only the thread start and global ways are closed, the object stays in one thread, so locking it is not needed. The check is safe: when it says an object stays inside, that is true for every run.
The problem
The input is a program of methods with the statements $x = $ new at site , , , , and for a global , , start in a new thread, and ret y. The output is a state for each allocation site in method : GLOBAL if an object of may be reachable from a global or from a thread other than the one that made it, ARG if not, but it may be reachable from a parameter or the return value of , and NONE otherwise.
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may: GLOBAL and ARG mean "may escape" |
| domain | points-to sets of the locals, globals, return values and fields of sites, then one state for each site |
| order | inclusion of sets, and NONE below ARG below GLOBAL (bottom is precise) |
| join | union of sets, and maximum of states |
| bottom and top | empty sets and every site NONE, and every set full and every site GLOBAL |
| boundary value | the objects of globals and of thread start arguments are GLOBAL, and those of parameters and return values of are at least ARG for the sites of |
| initial value | every set empty |
| transfer | Andersen's inclusion rules for each statement, then reachability through the field sets |
The algorithm
ESCAPE(P)- 1
pts = ANDERSEN(P), with fields, globals, calls, returns and thread starts as copies - 2
roots = the sites in pts(g) for every global g, and in pts(a) for every argument a of every start - 3
shared = all sites reachable from roots through the field sets pts(s.f) - 4
for each method m do - 5
out = the sites in pts(p) for every parameter p of m, and in the return value of m - 6
out = all sites reachable from out through the field sets - 7
for each allocation site s in m do - 8
if s is in shared then state(s) = GLOBAL - 9
else if s is in out then state(s) = ARG - 10
else state(s) = NONE - 11
return state
Line L1 builds one points-to graph for the whole program. A call adds the copies from each argument to the callee's parameter and from the callee's return value. A start adds the parameter copies only. A field of the objects of site is one node , so a store adds to for every in , and a load reads it.
Lines L2 and L3 find what other threads may see. Every object that a global may hold, or that is passed to a new thread, is shared, and so is everything reachable from it. Lines L5 and L6 do the same for one method: its parameter objects belong to its callers, and its return value goes to its caller. A site of in neither set is NONE. Its objects are reachable only from the activation that made them and from the methods that activation calls, and they are garbage when it returns.
Example
main(): make(): worker(p):
a = new // s1 d = new // s4 q = new // s7
b = new // s2 e = new // s5 p.f = q
a.f = b d.f = e r = new // s8
c = make() w = new // s6 G = r
t = new // s3 w.f = d
start worker(t) ret d
| site | state | why |
|---|---|---|
| , | NONE | only locals of main reach them |
| GLOBAL | it is the argument of a thread start | |
| ARG | make returns it |
|
| ARG | it is reachable from the return value through | |
| NONE | it points to , but nothing points to it | |
| GLOBAL | it is stored into , and is shared | |
| GLOBAL | it is stored in the global |
So , and can live in the stack frame of their method. The objects of and outlive make, but no other thread sees them, so their locks can go. If the compiler inlines make into main, they become NONE in main too. The other three need the heap and their locks. Note that is made by worker and never stored in a global, but the thread that started worker can reach it through .
Correctness
The proof file shows three facts. First, the points-to stage is sound for every run, including every interleaving of threads: each value that a local, a field, a global or a return slot holds has its site in the matching set. Second, a frontier lemma: split the frames into inside and outside. If every object that both sides reach has its site in a set that is closed under the field sets, and every way across the frontier, a global or a start argument, only carries sites of , then this stays true, and an object made inside with its site outside never becomes reachable from outside. Third, two uses of the lemma. With the frames of one thread inside and = shared, objects of non-GLOBAL sites are never seen by another thread. With one activation of and its callees inside and = shared plus out of , objects of NONE sites are never reachable from the caller, and when the activation returns, its return value does not reach them, so no root does.
Proof: An object of a NONE site is unreachable from outside its activation, and an object of a site that is not GLOBAL is never seen by another threadfull
Setting. A program is a set of methods. Each method has parameters, locals and a list of statements of the forms of the page: new, copy, load, store, global load, global store, call, start and ret. A run starts with one thread whose stack holds one frame of the main method. A frame is an activation of a method: it holds the values of its locals and parameters, and a return slot that ret y sets. A step picks a thread and either runs the next statement of its top frame, skips it, or pops the top frame when its body is done and puts the return slot into the destination local of the frame below. A call pushes a frame with the argument values as parameters. A start makes a new thread with one such frame. Skipping models branches, so the runs include every path of every control flow of the bodies. Each object has the site of the new that made it. An object is reachable from if a chain of fields leads from to , and reachable from a frame or a global if it is reachable from a value it holds.
is the least solution of the inclusion constraints of the points-to stage (line L1): for $x = $ new at in ; for a copy; for , for every ; for , for every ; and for the global forms; for each argument of a call or start of ; for ; and for ret y in . The heap closure of a set of sites is the least superset of that contains for every in it and every field . Let
Lines L2 to L10 set $state(s) = $ GLOBAL if , ARG if for the method of , and NONE otherwise.
Lemma 1 (the points-to stage is sound). At every moment of every run: if a local of a frame of holds , then ; if field of holds , then ; if global holds , then ; and if the return slot of a frame of holds , then . So if is reachable from , then .
Proof. By induction on the steps. At the start nothing holds an object. Each step writes one place, and the value written is covered by the constraint of its statement, using the induction hypothesis for the place it was read from: a call writes parameters, covered by the argument constraints; a pop writes the destination local, covered by the return constraint; a load reads with , and a store writes with . A skipped step writes nothing. The claim about reachability follows by induction on the length of the chain of fields.
The frontier argument. Fix a run, a time interval , a set of frames called inside, and a set of sites with . At each moment let be the objects reachable from inside frames, and the objects reachable from globals or from frames that are not inside. Assume:
- a frame joins only when an inside frame calls, the new frame is the callee, and no frame leaves except by its return;
- at , every object in has its site in ;
- for every global , and for every argument of every start in every method;
- no inside frame returns into a frame that is not inside before .
Lemma 2 (frontier). Under these assumptions, at every moment of : (P) every object in has its site in ; and (Q) every object in that an inside frame made during the interval has its site in .
Proof. Both hold at : (P) by assumption 2, and (Q) because nothing is made yet. Consider one step. A step that only removes references, such as a skip, a pop or the overwrite of a value, can only shrink and , which keeps both claims, with one exception: a pop that writes the return value, treated below. For the other steps, note first that adding a reference from an object or root outside does not change .
A step of an inside frame. A new adds a fresh object to only. A copy, a load or a ret writes into an inside frame a value that is already in , so neither set changes. A call pushes an inside frame with values already in (assumption 1). A pop of an inside frame into an inside frame writes a value of into (assumption 4 excludes the other case). A store writes into the object . If , does not change. If , then by (P), the new objects of are reachable from after the step, and by Lemma 1 their sites are in . A global load brings the object of , and the objects reachable from it, into ; they have sites in by Lemma 1 and assumption 3. A global store and a start make the objects reachable from the value or the arguments reachable from a global or from a new frame that is not inside, and their sites are in or by assumption 3. In every case each object that joins or has its site in .
A step of a frame that is not inside. It is a frame of another thread, or a frame below the inside frames that is not on top, and only top frames run. A new adds a fresh object to , not made by an inside frame. A copy, a load, a global load or a global store moves values that are already in , so does not grow, and does not change. A call, a start or a pop puts values of into frames that are not inside. A store with does not grow , and if , the new objects of are reachable from , whose site is in by (P), so their sites are in by Lemma 1.
Theorem 1 (threads). If GLOBAL, then no object of site is ever reachable from a global or from a frame of a thread other than the thread that made it.
Proof. Let thread make with . Take = all frames of , from the start of to the end of the run, and , which is closed. Assumption 1 holds, since frames of come only from calls in . Assumption 3 holds by the definition of . Assumption 4 holds, since the first frame of has no frame below it. For assumption 2, at the start of the inside objects are those reachable from the start arguments, whose sites are in . By (Q) of Lemma 2, at every moment, and is exactly the set of objects reachable from globals or from other threads.
Theorem 2 (activations). If NONE for a site of method , then each object of site , made by an activation of , is reachable only from and the frames that calls while runs, and from no root at all after returns. So can be allocated in the frame of .
Proof. Here . Let be the push of and the moment just before its pop. Take = and every frame pushed above while is on the stack, and , which is closed as a union of closed sets. Assumption 1 holds because only the top frame of calls. Assumption 3 holds since . Assumption 4 holds since only returns into a frame below , and that happens after . For assumption 2, at the inside objects are those reachable from the parameters of , with sites in by Lemma 1. Every object of site is made by a frame of , and is inside, so by (Q), during : no global, no other thread and no frame below reaches it.
At the pop of , the return slot holds an object with , and the objects reachable from have sites in by Lemma 1, so is not among them. After the pop, every root is a root that was outside before, or the destination local that now holds . So no root reaches . A step can only create a reference to an object that some root reaches, so stays unreachable for the rest of the run.
Theorem 3 (termination and cost). Let be the number of nodes of the constraint graph (locals, return values, globals and pairs of a site and a field), the number of sites and the total size of the statements, counting each argument. The analysis stops and takes time and space.
Proof. Each node's set only grows inside the sites, so there are at most insertions, and the worklist stops. With difference propagation each pair of a node and a site is sent along each out-edge of the node once, and there are at most distinct edges, so propagation costs . Each new edge first sends the whole set of its source, , for in total. Each pair of a load or store statement and a site of its base pointer is handled once, for edge requests. The heap closure of a set of sites visits each site once and each element of each set once, which is . It runs once for and once for each method, and there are at most methods, since each has a return node, so this part is . The space holds the edges, the sets and the statements.
Complexity
Proved. Let be the number of nodes of the constraint graph (locals, return values, globals and pairs of a site and a field), the number of sites and the total size of the statements. The Andersen stage with difference propagation takes time. Each closure of lines L3 and L6 takes , once for the shared set and once per method, and there are at most methods. So the whole analysis takes time and space.
Stated in the literature. Choi and colleagues report, for a set of Java benchmarks in a static compiler, that a large share of the objects could be allocated on the stack in some programs and that many lock operations could be removed, with a measurable speedup. Stadler, Würthinger and Mössenböck report that a partial escape analysis in a just-in-time compiler removes more allocations and locks than an analysis that decides once per method.
Measured, not proved. On 250 random programs with up to 4 methods, threads, globals, recursion and two fields (seed 2024), the 2608 sites got 1608 NONE, 431 ARG and 569 GLOBAL states. Three random interleaved runs of each program, with each statement skipped with probability 0.2 to model branches, checked the claims of both theorems after every step, 575103 checks in all, with no failure. Dropping the globals, the start arguments, the return values or the parameters from lines L2 and L5 made the same check fail in 138, 33, 99 and 17 of the 750 runs.
Properties
- Sound, not exact. A NONE object never escapes in any run, but an object marked ARG or GLOBAL may never escape in a real run.
- Context-insensitive. All activations of a method share one set per variable, so a method that sometimes receives an escaping object makes its parameter objects escape for all callers. Object sensitivity or method summaries reduce this.
- Flow-insensitive. An object that escapes only on one branch, or only at the end of a method, escapes everywhere.
- Thread-aware. Thread starts are roots of escape, like globals. An analysis that ignores them would remove locks from objects that two threads share.
- Whole program. The answer for one method depends on its callers and callees, so loading a new class can change it. A just-in-time compiler that uses the result must be able to undo it.
Variants and improvements
- Connection graphs. Choi and colleagues build a summary graph for each method that records which parameter fields may reach which objects, and combine summaries at call sites, without a whole-program points-to analysis. This gives some context sensitivity, since each call site maps the summary to its own arguments.
- Escape by types. Blanchet's analysis abstracts each value by an integer that says how much of its type may escape, and computes it by abstract interpretation. It is fast and handles recursion over lists and trees.
- Points-to escape graphs. Whaley and Rinard separate inside edges, made by the method, from outside edges, which stand for unknown objects of the caller. A method's summary can then be reused, and objects captured by a method or a thread are found compositionally.
- Partial escape analysis. In a just-in-time compiler, Stadler, Würthinger and Mössenböck decide escape per control flow branch. An object that escapes only on a rare path is created only on that path, and is replaced by local values on the others.
- Regions. Region-based memory management generalizes stack allocation: an object goes into the region of the outermost activation that it cannot escape.
When to use it
Use it in a compiler for a language where every object is on the heap and every object can be locked, such as Java. The common clients are stack allocation, scalar replacement after inlining, and removing locks from thread-local objects. A just-in-time compiler runs it per compiled method after inlining, where most temporary objects become NONE. For languages that already let the programmer choose stack allocation, the same analysis checks that a pointer to a stack object does not outlive the frame.
Pitfalls
- Forgetting threads. A version of line L2 that uses only the globals as roots treats and in the example as thread-local and removes locks that two threads need. The right line L2 also adds every argument of every thread start.
- Forgetting the return value. A version of line L5 with only the parameters marks and as NONE, and stack allocation would leave
mainwith a pointer into a dead frame. The right line L5 adds the return value. - Forgetting the parameters. A version of line L5 without the parameters misses an object stored into a field of a parameter object, which the caller can then reach. The right line L5 adds the sites of every parameter.
- Stopping at direct references. A version of lines L3 and L6 that takes only the sets themselves, without the closure, marks as NONE, although it is reachable from the shared through a field. The right lines close over the field sets.
- Allocation in a loop. A NONE site in a loop makes one object per iteration. One fixed slot in the frame is enough only if the object of the last iteration is dead when the next one is made. Otherwise the frame needs space per iteration, or the object stays on the heap.
- Claiming soundness with reflection or native code. Reflection, native methods and serialization can store a reference where the analysis does not see it. Such calls must be treated as making their arguments GLOBAL.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/escape-analysis/. The authors are listed in prov/JVVDBX.jsonl.
"""Escape analysis with threads, on top of a field-sensitive Andersen analysis.
A program is a dict from method names to (params, body). params is a list of
parameter names, and body is a list of statements in these forms:
("new", x, s) x = new object at allocation site s
("copy", x, y) x = y
("load", x, y, f) x = y.f
("store", x, f, y) x.f = y
("gload", x, g) x = global g
("gstore", g, y) global g = y
("call", x, m, args) x = m(args), args is a list of local names
("start", m, args) start a new thread that runs m(args)
("ret", y) the method will return the value of y
Each allocation site appears in one "new" statement. Names are local to their
method; globals have their own name space.
escape(program) returns a dict from each allocation site to one of
GLOBAL an object from the site may be reachable from a global or from a
thread other than the one that made it;
ARG not GLOBAL, but an object may be reachable from a parameter or
the return value of the method that made it, so it may outlive
the activation that made it;
NONE an object never leaves the activation that made it and the
methods it calls: it can live on the stack, and its locks can go.
"""
from collections import deque
NONE, ARG, GLOBAL = "none", "arg", "global"
def points_to(program):
"""Andersen's analysis with fields, globals, calls, returns and thread
starts, by a constraint graph with difference propagation. The nodes are
("v", m, x) for a local, ("r", m) for the return value of m, ("g", g) for
a global and ("f", s, f) for field f of the objects of site s."""
pts, succ, delta, loads, stores = {}, {}, {}, {}, {}
work = deque()
queued = set()
def node(n):
if n not in pts:
pts[n], succ[n], delta[n] = set(), set(), set()
loads[n], stores[n] = [], []
return n
def push(n):
if n not in queued:
queued.add(n)
work.append(n)
def propagate(s, n):
new = s - pts[n]
if new:
pts[n] |= new
delta[n] |= new
push(n)
def add_edge(u, v):
node(u)
node(v)
if v not in succ[u]:
succ[u].add(v)
propagate(pts[u], v)
def var(m, x):
return node(("v", m, x))
for m, (params, body) in program.items():
node(("r", m))
for p in params:
var(m, p)
for st in body:
kind = st[0]
if kind == "new":
propagate({st[2]}, var(m, st[1]))
elif kind == "copy":
add_edge(var(m, st[2]), var(m, st[1]))
elif kind == "load":
loads[var(m, st[2])].append((st[3], var(m, st[1])))
elif kind == "store":
stores[var(m, st[1])].append((st[2], var(m, st[3])))
elif kind == "gload":
add_edge(node(("g", st[2])), var(m, st[1]))
elif kind == "gstore":
add_edge(var(m, st[2]), node(("g", st[1])))
elif kind in ("call", "start"):
callee, args = (st[2], st[3]) if kind == "call" else (st[1], st[2])
for p, a in zip(program[callee][0], args):
add_edge(var(m, a), var(callee, p))
if kind == "call":
add_edge(node(("r", callee)), var(m, st[1]))
elif kind == "ret":
add_edge(var(m, st[1]), node(("r", m)))
while work:
n = work.popleft()
queued.discard(n)
d = delta[n]
delta[n] = set()
for a in d:
for f, x in loads[n]:
add_edge(node(("f", a, f)), x)
for f, y in stores[n]:
add_edge(y, node(("f", a, f)))
for w in list(succ[n]):
propagate(d, w)
return pts
def heap_graph(pts):
"""Site s -> the sites that some field of an object of s may point to."""
heap = {}
for n, s in pts.items():
if n[0] == "f":
heap.setdefault(n[1], set()).update(s)
return heap
def closure(heap, start):
seen = set(start)
stack = list(start)
while stack:
s = stack.pop()
for t in heap.get(s, ()):
if t not in seen:
seen.add(t)
stack.append(t)
return seen
def escape(program):
pts = points_to(program) # @line L1
heap = heap_graph(pts)
roots = set()
for n, s in pts.items():
if n[0] == "g":
roots |= s
for m, (_, body) in program.items():
for st in body:
if st[0] == "start":
for a in st[2]:
roots |= pts[("v", m, a)] # @line L2
shared = closure(heap, roots) # @line L3
state = {}
for m, (params, body) in program.items(): # @line L4
out = set(pts[("r", m)])
for p in params:
out |= pts[("v", m, p)] # @line L5
out = closure(heap, out) # @line L6
for st in body:
if st[0] == "new": # @line L7
s = st[2]
if s in shared:
state[s] = GLOBAL # @line L8
elif s in out:
state[s] = ARG # @line L9
else:
state[s] = NONE # @line L10
return state # @line L11
test_escape_analysis.py 257 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/escape-analysis/. The authors are listed in prov/JVVDBX.jsonl.
import random
from escape_analysis import ARG, GLOBAL, NONE, escape, points_to
PAGE = {
"main": ([], [
("new", "a", "s1"),
("new", "b", "s2"),
("store", "a", "f", "b"),
("call", "c", "make", []),
("new", "t", "s3"),
("start", "worker", ["t"]),
]),
"make": ([], [
("new", "d", "s4"),
("new", "e", "s5"),
("store", "d", "f", "e"),
("new", "w", "s6"),
("store", "w", "f", "d"),
("ret", "d"),
]),
"worker": (["p"], [
("new", "q", "s7"),
("store", "p", "f", "q"),
("new", "r", "s8"),
("gstore", "G", "r"),
]),
}
def test_page_example():
assert escape(PAGE) == {
"s1": NONE, "s2": NONE, "s3": GLOBAL, "s4": ARG,
"s5": ARG, "s6": NONE, "s7": GLOBAL, "s8": GLOBAL,
}
def test_storing_into_a_parameter_escapes_to_the_caller():
prog = {
"main": ([], [("new", "a", "s1"), ("call", "x", "fill", ["a"])]),
"fill": (["p"], [("new", "q", "s2"), ("store", "p", "f", "q")]),
}
assert escape(prog) == {"s1": NONE, "s2": ARG}
def test_passing_to_a_callee_that_keeps_it_local_does_not_escape():
prog = {
"main": ([], [("new", "a", "s1"), ("call", "x", "use", ["a"])]),
"use": (["p"], [("load", "y", "p", "f")]),
}
assert escape(prog) == {"s1": NONE}
def test_reading_a_global_and_writing_into_it():
prog = {
"main": ([], [("gload", "x", "G"), ("new", "a", "s1"), ("store", "x", "f", "a")]),
"init": ([], [("new", "b", "s2"), ("gstore", "G", "b")]),
}
assert escape(prog) == {"s1": GLOBAL, "s2": GLOBAL}
def test_recursion_that_passes_its_object_on():
prog = {"main": (["p"], [("new", "a", "s1"), ("call", "x", "main", ["a"])])}
assert escape(prog) == {"s1": ARG}
# Random programs and a concrete interpreter with threads.
FIELDS = ["f0", "f1"]
GLOBALS = ["G0", "G1"]
LOCALS = ["l0", "l1", "l2"]
def random_program(rng, nmethods, nstmts):
methods = ["m%d" % i for i in range(nmethods)]
params = {m: ["p%d" % j for j in range(0 if m == "m0" else rng.randint(0, 2))] for m in methods}
kinds = ["new", "copy", "load", "store", "gload", "gstore", "call", "start", "ret"]
weights = [4, 2, 2, 3, 1, 1, 3, 1, 2]
site = 0
prog = {}
for m in methods:
names = params[m] + LOCALS
body = []
for x in LOCALS:
site += 1
body.append(("new", x, "s%d" % site))
for _ in range(nstmts):
kind = rng.choices(kinds, weights)[0]
if kind == "new":
site += 1
body.append(("new", rng.choice(LOCALS), "s%d" % site))
elif kind == "copy":
body.append(("copy", rng.choice(LOCALS), rng.choice(names)))
elif kind == "load":
body.append(("load", rng.choice(LOCALS), rng.choice(names), rng.choice(FIELDS)))
elif kind == "store":
x = rng.choice(params[m] if params[m] and rng.random() < 0.5 else names)
body.append(("store", x, rng.choice(FIELDS), rng.choice(names)))
elif kind == "gload":
body.append(("gload", rng.choice(LOCALS), rng.choice(GLOBALS)))
elif kind == "gstore":
body.append(("gstore", rng.choice(GLOBALS), rng.choice(names)))
elif kind in ("call", "start"):
callee = rng.choice(methods)
args = [rng.choice(names) for _ in params[callee]]
if kind == "call":
body.append(("call", rng.choice(LOCALS), callee, args))
else:
body.append(("start", callee, args))
else:
body.append(("ret", rng.choice(names)))
prog[m] = (params[m], body)
return prog
class Frame:
def __init__(self, method, env, dest, ident):
self.method, self.env, self.dest, self.ident = method, env, dest, ident
self.pc = 0
self.ret = None
def reach(heap, start):
seen = set()
stack = [o for o in start if o is not None]
while stack:
o = stack.pop()
if o in seen:
continue
seen.add(o)
stack.extend(v for v in heap[o].values() if v is not None)
return seen
def frame_roots(fr):
return list(fr.env.values()) + [fr.ret]
def run_and_check(prog, state, pts, rng, steps=120, max_depth=4, max_threads=3):
"""Run the program from m0 with random interleaving of threads, and skip
each statement with probability 0.2, which models a branch. After every
step, check the escape claims and that the heap matches pts."""
heap, glob, made = {}, {}, {}
threads = [[Frame("m0", {}, None, 0)]]
idents = 1
checked = 0
for _ in range(steps):
live = [t for t in range(len(threads)) if threads[t]]
if not live:
break
t = rng.choice(live)
stack = threads[t]
fr = stack[-1]
params, body = prog[fr.method]
if fr.pc == len(body):
stack.pop()
if stack and fr.dest is not None:
stack[-1].env[fr.dest] = fr.ret
else:
st = body[fr.pc]
fr.pc += 1
env = fr.env
kind = st[0]
if rng.random() < 0.2:
pass
elif kind == "new":
o = len(heap)
heap[o] = {}
made[o] = (st[2], t, fr.ident)
env[st[1]] = o
elif kind == "copy":
env[st[1]] = env.get(st[2])
elif kind == "load":
if env.get(st[2]) is not None:
env[st[1]] = heap[env[st[2]]].get(st[3])
elif kind == "store":
if env.get(st[1]) is not None:
heap[env[st[1]]][st[2]] = env.get(st[3])
elif kind == "gload":
env[st[1]] = glob.get(st[2])
elif kind == "gstore":
glob[st[1]] = env.get(st[2])
elif kind == "call":
if len(stack) < max_depth:
cparams = prog[st[2]][0]
stack.append(Frame(st[2], {p: env.get(a) for p, a in zip(cparams, st[3])}, st[1], idents))
idents += 1
elif kind == "start":
if len(threads) < max_threads:
cparams = prog[st[1]][0]
threads.append([Frame(st[1], {p: env.get(a) for p, a in zip(cparams, st[2])}, None, idents)])
idents += 1
else:
fr.ret = env.get(st[1])
checked += check(prog, state, pts, heap, glob, made, threads)
return checked
def check(prog, state, pts, heap, glob, made, threads):
from_globals = reach(heap, glob.values())
per_frame = [[reach(heap, frame_roots(fr)) for fr in stack] for stack in threads]
# The heap and the variables are inside the points-to result.
for o, fields in heap.items():
for f, v in fields.items():
if v is not None:
assert made[v][0] in pts[("f", made[o][0], f)]
for stack in threads:
for fr in stack:
for x, v in fr.env.items():
if v is not None:
assert made[v][0] in pts[("v", fr.method, x)]
count = 0
for o, (site, t, ident) in made.items():
if state[site] != GLOBAL:
assert o not in from_globals, site
for u, frames in enumerate(per_frame):
if u != t:
assert all(o not in r for r in frames), site
count += 1
if state[site] == NONE:
idents = [fr.ident for fr in threads[t]]
below = idents.index(ident) if ident in idents else len(idents)
assert all(o not in r for r in per_frame[t][:below]), site
count += 1
return count
def test_escape_claims_hold_on_concrete_runs():
rng = random.Random(2024)
checked = 0
kinds = {NONE: 0, ARG: 0, GLOBAL: 0}
for _ in range(250):
prog = random_program(rng, rng.randint(1, 4), rng.randint(2, 9))
state = escape(prog)
pts = points_to(prog)
for s in state.values():
kinds[s] += 1
for _ in range(3):
checked += run_and_check(prog, state, pts, rng)
assert checked > 5000
assert min(kinds.values()) > 50
def test_a_returned_none_object_is_garbage():
"""After the activation that made a NONE object returns, no root reaches
the object, so it could have lived in that activation's stack frame."""
prog = {
"m0": ([], [("call", "x", "m1", []), ("new", "y", "s9")]),
"m1": ([], [("new", "a", "s1"), ("new", "b", "s2"), ("store", "a", "f0", "b"), ("ret", "b")]),
}
state = escape(prog)
assert state["s1"] == NONE and state["s2"] == ARG
rng = random.Random(7)
assert run_and_check(prog, state, points_to(prog), rng, steps=30) > 0
History
Escape analysis began in functional languages. Park and Goldberg (1992) found lists that do not escape a function, so that they could be allocated on the stack. For Java, three papers at OOPSLA 1999 appeared together: Choi, Gupta, Serrano, Sreedhar and Midkiff with connection graphs and the three escape states, Blanchet with an analysis by abstract interpretation over types, and Whaley and Rinard with compositional points-to escape graphs. All three used the result to allocate on the stack and to remove locks. Escape analysis then moved into just-in-time compilers for Java, where it drives scalar replacement and lock removal after inlining, and Stadler, Würthinger and Mössenböck (2014) made it partial, per control flow branch.
References
- Jong-Deok Choi, Manish Gupta, Mauricio Serrano, Vugranam C. Sreedhar and Samuel Midkiff, Escape analysis for Java, Proceedings of OOPSLA 1999, 1 to 19, the connection graph, the three escape states NoEscape, ArgEscape and GlobalEscape, objects reachable from threads as escaping, stack allocation and lock removal
- Bruno Blanchet, Escape analysis for object-oriented languages, application to Java, Proceedings of OOPSLA 1999, 20 to 34, escape analysis as an abstract interpretation over types, with stack allocation and synchronization elimination
- John Whaley and Martin Rinard, Compositional pointer and escape analysis for Java programs, Proceedings of OOPSLA 1999, 187 to 206, points-to escape graphs with inside and outside edges, method summaries, and objects captured by a method or a thread
- Lukas Stadler, Thomas Würthinger and Hanspeter Mössenböck, Partial escape analysis and scalar replacement for Java, Proceedings of CGO 2014, escape decided per control flow branch in a just-in-time compiler, with objects created only on the branches where they escape
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JVVDBX Edit this page History Report an error Markdown