Algorithmadvanced
Variable type analysis
Also called VTA.
Prune a sound call graph by pushing the classes of new along the assignments of a type propagation graph and keeping the targets that reach each receiver.
- Solves
- Call graph construction
- Time
- O((n + P) K) worst
- Space
- O((n + P) K) extra
- Where
- K = the number of classes; P = the number of edges of the initial call graph; n = the size of the program
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Vijay Sundaresan, Laurie Hendren, Chrislain Razafimahefa, Raja Vallee Rai, Patrick Lam, Etienne Gagnon, Charles Godin, 2000
Variable type analysis (VTA) is a solution of call graph construction that tracks, for each variable and each field, the set of classes whose objects may reach it. It starts from a sound call graph, such as the one of rapid type analysis or class hierarchy analysis. It builds a graph with an edge for each assignment and for each argument and result passing along the initial call edges. It puts the class of each new into its variable, and pushes the classes along the edges after collapsing the cycles. A call y.m(z) then keeps only the initial edges that a class reaching y explains. The result is sound, and it is inside the initial graph.
In plain words
Rapid type analysis keeps one list of created classes for the whole program. So if the program creates a Circle in one place and a Square in another, every variable of type Shape may hold both. Variable type analysis keeps one list per variable. When the code says a = new Circle(), it writes Circle into the list of a. When the code says b = a, everything in the list of a also goes into the list of b. Calls pass lists into parameters and back out of results, along the calls that an earlier, rougher call graph found. When the lists stop growing, a call a.grow() keeps only the methods that the classes in the list of a really run.
The problem
The input is a program in the model of class hierarchy analysis, with the dispatch function , and a sound initial call graph whose edges start in methods of and end in methods of . The type propagation graph has a node for each variable of each method and a node for each field name. Its edges are for x = y, for x = y.f, for y.f = z, and for each with : x = y.m(z) in , the edges , and . The seed of is the set of classes with x = new C() in .
The types are the least with and for every edge . The output keeps the edges , : x = y.m(z) in , for which some has , and then the part of them reachable from main.
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may |
| domain | maps from the nodes of to sets of classes |
| order | pointwise inclusion (bottom is precise) |
| join | pointwise union |
| bottom and top | every node maps to , and every node maps to all classes |
| boundary value | the seeds from the new statements |
| initial value | the seeds |
| transfer | for each edge ; distributive, since it copies sets |
The algorithm
VTA(P, R0, E0)- 1
make a node M.v for each variable v of each method M in R0, and a node f for each field - 2
for each x = y in a method M of R0 do add the edge M.y -> M.x - 3
for each x = y.f do add f -> M.x; for each y.f = z do add M.z -> f - 4
for each (s, T) in E0 with s: x = y.m(z) in M do add M.y -> T.this, M.z -> T.p, T.ret -> M.x - 5
for each x = new C() in a method M of R0 do add C to types(M.x) - 6
find the strongly connected components of the graph with Tarjan's algorithm - 7
for each component c in topological order do - 8
for each edge from c to another component d do types(d) <- types(d) ∪ types(c) - 9
E <- {(s, T) in E0 : s: x = y.m(z) in M, and some C in types(M.y) has LOOKUP(C, m) = T} - 10
R <- the methods reachable from main along E; drop from E the edges of sites outside R - 11
return (R, E)
Line L6 uses Tarjan's algorithm. All nodes of one component get the same types, the union of their seeds. Line L7 visits the components so that every component comes after all components with an edge into it. So when line L8 pushes the types of a component, they are final, and each edge is used once. Line L10 removes the methods that only pruned edges reached.
Example
The program of the call graph construction page, with the initial graph of rapid type analysis:
class Shape { Shape grow() { return this; } }
class Circle : Shape { Shape grow() { return new Square(); } }
class Square : Shape { Shape grow() { return this; } }
class Oval : Circle { }
main() {
Shape a = new Circle();
Shape b = new Square();
Shape c = a.grow(); // site s1
Shape d = b.grow(); // site s2
Shape e = c.grow(); // site s3
}
is main, Circle.grow and Square.grow, and links each of s1, s2 and s3 to both grow methods. The graph has these edges: from each receiver a, b and c to Circle.this and Square.this; from Circle.ret and Square.ret to each result c, d and e; and Square.this to Square.ret for return this. The seeds are for a, for b and for Circle.ret.
| node | types | why |
|---|---|---|
a |
Circle | seed |
b |
Square | seed |
Circle.ret |
Square | seed |
c, Square.this, Square.ret |
Circle, Square | one component: c to Square.this to Square.ret to c; it gets Circle from a, and Square from b and Circle.ret |
Circle.this |
Circle, Square | from a, b and c |
d, e |
Circle, Square | from both results |
Line L9 keeps s1 to Circle.grow (the types of a), s2 to Square.grow (the types of b), and s3 to both methods (the types of c). That is 4 edges, against 6 for RTA and 9 for CHA. The run makes 3 calls: s1 to Circle.grow, and s2 and s3 to Square.grow. The edge from s3 to Circle.grow is spurious. It comes from the spurious RTA edge from s1 to Square.grow: along it, the Circle of a flows into Square.this, then to Square.ret and back into c. Starting from the CHA graph gives the same 4 edges here.
Correctness
The types. The least solution maps each node to the union of the seeds of the nodes that reach . Nodes of one component reach each other, so they share their types. Taking the components in topological order, each component receives the final types of all components with an edge into it, so it ends with the union of the seeds of all nodes that reach it.
Soundness. Take a well-typed program without reflection or native code, and a sound initial graph. By induction over the steps of a run, if a variable of a frame of holds an object of class , then , and the same holds for fields. A new is a seed. A copy, a load and a store follow an edge of , because all objects share the one node of each field. A call from to is an edge of , since is sound, so line L4 made the edges that carry the receiver, the argument and the result. So at a call, the class of the receiver is in , the target is , and line L9 keeps the edge. The caller is in by induction, so line L10 keeps it too.
Nesting. Line L9 keeps a subset of , so when the initial graph is the RTA graph. A larger initial graph gives a larger graph , larger types and a larger result. The full proofs are in the proof file.
Proof: Variable type analysis computes the least type assignment of its graph, and its pruned call graph is sound and inside the initial graphfull
Setting. The program, , , and well typed are as in the proof of class hierarchy analysis. The program has no reflection, no native code and no classes loaded at run time. The initial graph is sound: every method that a run enters is in , and every call of a run from site to method has . It is also closed under targets: , every site of an edge of lies in a method of , and every target of an edge of is in . The results of class hierarchy analysis and of rapid type analysis have both properties.
The graph has a node for each variable of each method , and a node for each field name. Its edges come from lines L2 to L4: for x = y in ; for x = y.f; for y.f = z; and for each edge with : x = y.m(z) in , the edges , and . The seed of a node is the set of classes with x = new C() in (line L5); other seeds are empty. A type assignment maps each node to a set of classes. It is a solution if for every node and for every edge .
Lemma 1 (the least solution). Let , where every node reaches itself. Then is the least solution.
Proof. is a solution: , and for an edge , every node that reaches also reaches . Let be any solution, and let reach along a path . Then . So .
Lemma 2 (lines L6 to L8 compute it). Lines L6 to L8 stop and give every node the set .
Proof. Tarjan's algorithm gives the strongly connected components, each as a list, in an order where a component comes after all components that it reaches. Line L7 takes them in the reverse order, which is a topological order of the component graph. Two nodes of one component reach each other, so they reach the same nodes and are reached by the same nodes, and is the same on both. Let be a component and the union of the seeds of its nodes. We show by induction in the topological order that when line L7 reaches , the set of is . Every component that reaches reaches it through a last edge with in a component that reaches and in . The component comes before , so line L8 has already added its set, which by induction holds . Line L8 only adds sets of components that reach , so nothing more enters. The set of never changes after is processed, because no later component has an edge into . Each loop is over a finite list, so the lines stop.
Lemma 3 (the run invariant). In every run, at every moment: if a variable of a live frame of method holds an object of class , then ; and if the field of any object holds an object of class , then .
Proof. By induction over the steps of the run. At the start, all variables and fields hold null. Every frame belongs to a method that the run entered, which is in by soundness of the initial graph, so its nodes exist. x = new C() in puts into , and . x = y copies a value of , and the edge carries its class. x = y.f reads the field of some object, whose class is in by the induction hypothesis, and the edge carries it. y.f = z writes the value of into a field , and the edge carries its class. A call at : x = y.m(z) in that enters has by soundness. It binds in the new frame to the value of and to the value of , and the edges and carry their classes. When it returns, it writes the value of into , and the edge carries its class. Since is a solution, each class lands in the set of the node that receives it.
Theorem 1 (soundness). Let be the result of lines L9 and L10. Every method that a run enters is in , and every call of a run from site to has .
Proof. By induction over the calls of the run. The run starts in . Take a call at site : x = y.m(z) in a frame of method , on a receiver of class , that enters . The frame of was entered earlier, so by the induction hypothesis. By soundness of the initial graph, . By Lemma 3, , and by type safety (Lemma 4 of the proof of class hierarchy analysis), . So line L9 keeps . Line L10 searches from along the kept edges, and lies in , so the search adds to and to .
Theorem 2 (inside the initial graph, and monotone). and . If and , then the result for is inside the result for .
Proof. Line L9 keeps a subset of . Line L10 starts at and follows edges of , whose targets are in . For the second part, the graph for contains every node, edge and seed of the graph for , so by Lemma 1 its least solution is pointwise larger. Then line L9 keeps a superset, and the search of line L10 reaches a superset. With the initial graph of rapid type analysis, this gives , where the second inclusion is Theorem 3 of the proof of rapid type analysis.
Theorem 3 (cost). Let be the size of the program, the number of classes and . The algorithm runs in time.
Proof. has at most nodes, for field names, and at most edges, since each statement gives at most one edge and each edge of gives at most three. Lines L1 to L5 build it in . Tarjan's algorithm takes . Line L8 runs once per edge, and each union of sets of at most classes takes with bit vectors. Line L9 checks at most classes per edge of , with a dispatch table, in . Line L10 is a graph search over at most edges. The total is .
Complexity
Proved. The graph has nodes and at most edges, for . Building it and running Tarjan's algorithm take . Line L8 takes one union of sets of at most classes per edge, in with bit vectors. Line L9 checks at most classes per edge of . So the time is , and the space for the types is , plus for the graph.
Measured, not proved. On 400 random well-typed programs (seed 2000), the result equals that of a plain iteration of the edges until nothing changes. On 300 random programs with 5 concrete runs each (seed 79), every call that a run makes is in . On 300 random programs (seed 7), , and VTA is strictly smaller than RTA on some of them. On 300 random programs (seed 8), the result from the RTA graph is inside the result from the CHA graph.
Properties
- Sound only if the initial graph is sound. A call edge missing from means a missing parameter edge in line L4, so the types of the callee are too small.
- Field-based. One node per field name merges the field of all objects. This is what makes stores and loads sound without any alias information.
- Context-insensitive and flow-insensitive. All calls of a method share its parameter nodes, and the order of statements does not matter.
- Monotone in the initial graph. A smaller sound initial graph never gives a larger result. So running VTA again with its own result as the initial graph is sound and may prune more.
- Classes, not objects. The sets hold classes, so two objects of the same class are never told apart. A points-to analysis with allocation sites can tell them apart.
Variants and improvements
- Declared type analysis. Sundaresan and others also describe a coarser variant with one node per declared type instead of one per variable. It is cheaper and less precise.
- On-the-fly pruning. Pass a class along only if , and add call edges as types arrive instead of starting from . This is a type-based form of Andersen's analysis with an on-the-fly call graph. On the example it removes the spurious edge from s3 and gives the exact 3 edges.
- Per-method and per-field sets. Tip and Palsberg propagate classes with one set per method, per field or per class. These lie between RTA and VTA.
- Field-sensitive versions. One node per field of each abstract object needs alias information, which leads to field-sensitive points-to analysis.
When to use it
Use VTA when RTA leaves too many targets and you want a sound graph without a full points-to analysis. It costs one graph build, one pass of Tarjan's algorithm and one propagation pass, and it scales to large Java programs. It is a good input for devirtualization and for an interprocedural analysis that needs a tighter graph. When the precision of classes per variable is not enough, for example for collections that hold many classes, use a points-to analysis with context.
Pitfalls
- A field node per base variable. Making a node for
x.finstead of one nodefin line L3 is unsound. Withx.f = a; y = x; b = y.f, the class ofagoes tox.fand never reachesb. Line L3 must use one node per field name, unless an alias analysis says which bases share objects. - Pruning with the declared type. A version of line L9 that keeps the targets of every class is just CHA. Line L9 must test the classes in .
- An unsound initial graph. If comes from a guess, such as the edges seen in a profile, line L4 misses parameter flows, and line L9 may drop real edges. must be sound, for example the result of line L12 of RTA.
- Forgetting the result edge. A version of line L4 without leaves
cin the example with no types, and the real call from s3 toSquare.growis lost. - Claiming soundness with reflection. Objects from reflection, deserialization or native code do not come from a
newof the text, so line L5 has no seed for them.
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
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small object-oriented program model, for the call graph pages.
A program is a dict with these keys:
"classes" dict from each class name to its parent, None for the root.
"methods" dict from each method name m to (decl, ptype, rtype): the
class that introduces m, the declared type of its parameter
p and the declared type of its result.
"fields" dict from each field name f to (decl, ftype): the class that
declares f and the declared type of f.
"bodies" dict from each method id (C, m), the method m as class C
defines it, to (locals, stmts). The root is MAIN, a static
method with no this, p or ret. locals maps each variable to
its declared class. Every other body has the variables
"this" (of type C), "p" and "ret" among its locals.
The statements are tuples:
("new", x, C) x = new C()
("copy", x, y) x = y
("load", x, y, f) x = y.f
("store", y, f, z) y.f = z
("call", s, x, y, m, z) x = y.m(z) at call site s; x or z may be None
A method returns the value of its variable ret. The programs of
random_program are well typed in the sense of Java: a variable or field only
receives objects of its declared class or of a subclass, and a call y.m(z)
has decl(y) <= decl(m), so the dispatch always finds a method.
lookup(prog, C, m) is the method that runs for m on an object of class C.
run(prog, rng) runs the program concretely and returns the call edges and
the methods that the run saw. cha_spec and rta_spec are slow reference
versions of class hierarchy analysis and rapid type analysis: they apply
their rules to every reachable method, round after round, until nothing
changes.
"""
MAIN = ("Main", "main")
def is_sub(prog, c, d):
"""True if class c is d or a subclass of d."""
while c is not None:
if c == d:
return True
c = prog["classes"][c]
return False
def subclasses(prog):
"""A dict from each class d to the set of classes c with c <= d."""
below = {d: set() for d in prog["classes"]}
for c in prog["classes"]:
a = c
while a is not None:
below[a].add(c)
a = prog["classes"][a]
return below
def lookup(prog, c, m):
"""The method id that runs when m is called on an object of class c."""
while c is not None:
if (c, m) in prog["bodies"]:
return (c, m)
c = prog["classes"][c]
raise KeyError(f"no method {m} above the class")
def call_sites(prog, mid):
"""The call statements of the body of mid."""
return [st for st in prog["bodies"][mid][1] if st[0] == "call"]
def all_sites(prog):
"""A dict from each call site to (method id, statement)."""
out = {}
for mid, (_, stmts) in prog["bodies"].items():
for st in stmts:
if st[0] == "call":
out[st[1]] = (mid, st)
return out
def shapes():
"""The example of the call graph pages: Shape, Circle, Square, Oval."""
S = "Shape"
return {
"classes": {S: None, "Circle": S, "Square": S, "Oval": "Circle"},
"methods": {"grow": (S, S, S)},
"fields": {},
"bodies": {
(S, "grow"): ({"this": S, "p": S, "ret": S}, [("copy", "ret", "this")]),
("Circle", "grow"): ({"this": "Circle", "p": S, "ret": S}, [("new", "ret", "Square")]),
("Square", "grow"): ({"this": "Square", "p": S, "ret": S}, [("copy", "ret", "this")]),
MAIN: (
{"a": S, "b": S, "c": S, "d": S, "e": S},
[
("new", "a", "Circle"),
("new", "b", "Square"),
("call", "s1", "c", "a", "grow", None),
("call", "s2", "d", "b", "grow", None),
("call", "s3", "e", "c", "grow", None),
],
),
},
}
def random_program(rng, nclasses=5, nmethods=3, nfields=2, nstmts=6):
"""A random well-typed program. rng is a random.Random."""
names = ["K%d" % i for i in range(nclasses)]
classes = {names[0]: None}
for i in range(1, nclasses):
classes[names[i]] = names[rng.randrange(i)]
prog = {"classes": classes, "methods": {}, "fields": {}, "bodies": {}}
below = subclasses(prog)
for i in range(nmethods):
prog["methods"]["m%d" % i] = (rng.choice(names), rng.choice(names), rng.choice(names))
for i in range(nfields):
prog["fields"]["f%d" % i] = (rng.choice(names), rng.choice(names))
sites = [0]
def body(this, ptype, rtype, count):
local = {"v%d" % i: rng.choice(names) for i in range(3)}
if this is not None:
local.update({"this": this, "p": ptype, "ret": rtype})
allv = list(local)
dest = [v for v in allv if v != "this"]
def sub_vars(t):
return [v for v in allv if is_sub(prog, local[v], t)]
def super_vars(t):
return [v for v in dest if is_sub(prog, t, local[v])]
stmts = []
if this is None: # main starts by making objects for two variables
stmts = [("new", x, rng.choice(sorted(below[local[x]]))) for x in rng.sample(dest, 2)]
while len(stmts) < count:
kind = rng.choices(["new", "copy", "load", "store", "call"], (3, 3, 2, 2, 4))[0]
if kind == "new":
x = rng.choice(dest)
stmts.append(("new", x, rng.choice(sorted(below[local[x]]))))
elif kind == "copy":
x = rng.choice(dest)
ys = sub_vars(local[x])
if ys:
stmts.append(("copy", x, rng.choice(ys)))
elif kind in ("load", "store"):
if not prog["fields"]:
continue
f = rng.choice(sorted(prog["fields"]))
fdecl, ftype = prog["fields"][f]
ys = sub_vars(fdecl)
if not ys:
continue
if kind == "load":
xs = super_vars(ftype)
if xs:
stmts.append(("load", rng.choice(xs), rng.choice(ys), f))
else:
zs = sub_vars(ftype)
if zs:
stmts.append(("store", rng.choice(ys), f, rng.choice(zs)))
else:
m = rng.choice(sorted(prog["methods"]))
mdecl, pt, rt = prog["methods"][m]
ys = sub_vars(mdecl)
if not ys:
continue
zs = sub_vars(pt)
xs = super_vars(rt)
z = rng.choice(zs) if zs and rng.random() < 0.8 else None
x = rng.choice(xs) if xs and rng.random() < 0.8 else None
sites[0] += 1
stmts.append(("call", "s%d" % sites[0], x, rng.choice(ys), m, z))
return local, stmts
for m, (mdecl, pt, rt) in sorted(prog["methods"].items()):
for c in sorted(below[mdecl]):
if c == mdecl or rng.random() < 0.4:
prog["bodies"][(c, m)] = body(c, pt, rt, rng.randint(1, nstmts))
prog["bodies"][MAIN] = body(None, None, None, nstmts + 2)
return prog
class _Stop(Exception):
pass
def run(prog, rng, steps=300, depth=6, skip=0.25):
"""One concrete run from MAIN. Variables start as null. Each statement is
skipped with probability skip, and each body runs once or twice, which
stands for branches and loops. A call on null or a field access on null
is skipped, as if the program caught the exception. Returns (edges,
entered): the pairs (site, method id) that the run executed and the
methods it entered."""
heap = []
edges, entered = set(), {MAIN}
budget = [steps]
def execute(mid, env, level):
stmts = prog["bodies"][mid][1]
for _ in range(rng.randint(1, 2)):
for st in stmts:
budget[0] -= 1
if budget[0] < 0:
raise _Stop
if rng.random() < skip:
continue
kind = st[0]
if kind == "new":
heap.append((st[2], {}))
env[st[1]] = len(heap) - 1
elif kind == "copy":
env[st[1]] = env.get(st[2])
elif kind == "load":
o = env.get(st[2])
if o is None:
continue
env[st[1]] = heap[o][1].get(st[3])
elif kind == "store":
o = env.get(st[1])
if o is None:
continue
heap[o][1][st[2]] = env.get(st[3])
else:
_, s, x, y, m, z = st
o = env.get(y)
if o is None:
continue
target = lookup(prog, heap[o][0], m)
edges.add((s, target))
entered.add(target)
result = None
if level < depth:
callee = {"this": o, "p": env.get(z) if z is not None else None}
execute(target, callee, level + 1)
result = callee.get("ret")
if x is not None:
env[x] = result
try:
execute(MAIN, {}, 0)
except _Stop:
pass
return edges, entered
def _fixpoint(prog, targets):
"""The least (R, E) closed under: MAIN in R, and for each site s of a
method of R and each T in targets(s, R), (s, T) in E and T in R."""
reach, edges = {MAIN}, set()
changed = True
while changed:
changed = False
for mid in sorted(reach):
for st in call_sites(prog, mid):
for t in targets(mid, st, reach):
if (st[1], t) not in edges:
edges.add((st[1], t))
changed = True
if t not in reach:
reach.add(t)
changed = True
return reach, edges
def cha_spec(prog):
"""Class hierarchy analysis by plain iteration."""
def targets(mid, st, reach):
decl = prog["bodies"][mid][0][st[3]]
return {lookup(prog, c, st[4]) for c in prog["classes"] if is_sub(prog, c, decl)}
return _fixpoint(prog, targets)
def rta_spec(prog):
"""Rapid type analysis by plain iteration."""
def targets(mid, st, reach):
made = {s[2] for r in reach for s in prog["bodies"][r][1] if s[0] == "new"}
decl = prog["bodies"][mid][0][st[3]]
return {lookup(prog, c, st[4]) for c in made if is_sub(prog, c, decl)}
return _fixpoint(prog, targets)
def show(prog):
"""The program in a short text form, for messages of failed tests."""
out = []
for c, p in prog["classes"].items():
out.append(f"class {c}" + (f" : {p}" if p else ""))
for m, sig in prog["methods"].items():
out.append(f"method {m} {sig}")
for f, sig in prog["fields"].items():
out.append(f"field {f} {sig}")
for mid, (local, stmts) in prog["bodies"].items():
out.append(f"{mid[0]}.{mid[1]} {local}")
out.extend(f" {st}" for st in stmts)
return "\n".join(out)
variable_type_analysis.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variable-type-analysis/. The authors are listed in prov/5D67PN.jsonl.
"""Variable type analysis (VTA): prune a call graph with the classes that
reach each variable.
variable_type_analysis(prog, initial) takes a program of the oomodel form and
a sound initial call graph initial = (R0, E0), by default the one of rapid
type analysis. It builds the type propagation graph: one node per variable
of each method of R0 and one node per field name, with an edge for each
assignment and for each parameter and result passing along E0. It seeds the
nodes with the classes of the new statements, collapses the strongly
connected components, and propagates the classes in topological order. A
call y.m(z) keeps the edges of E0 to LOOKUP(C, m) for the classes C that
reach y. Returns (R, E), with R the methods reachable from the root along E.
graph_and_seeds and prune are shared with the plain iteration of the tests.
Cost: O((n + |E0|) * K) for a program of size n and K classes.
"""
from oomodel import MAIN, lookup, subclasses
def graph_and_seeds(prog: dict, initial: tuple) -> tuple[dict, dict]:
"""The type propagation graph as successor sets, and the seed classes."""
reach0, edges0 = initial
succ, seed = {}, {}
def edge(a, b):
succ.setdefault(a, set()).add(b)
succ.setdefault(b, set())
by_site = {}
for s, t in edges0:
by_site.setdefault(s, []).append(t)
for mid in reach0: # @line L1
local, stmts = prog["bodies"][mid]
for v in local:
succ.setdefault((mid, v), set())
for st in stmts:
kind = st[0]
if kind == "new":
seed.setdefault((mid, st[1]), set()).add(st[2]) # @line L5
elif kind == "copy":
edge((mid, st[2]), (mid, st[1])) # @line L2
elif kind == "load":
edge(("field", st[3]), (mid, st[1])) # @line L3
elif kind == "store":
edge((mid, st[3]), ("field", st[2])) # @line L3
else:
_, s, x, y, m, z = st
for t in by_site.get(s, []): # @line L4
edge((mid, y), (t, "this"))
if z is not None:
edge((mid, z), (t, "p"))
if x is not None:
edge((t, "ret"), (mid, x))
return succ, seed
def prune(prog: dict, initial: tuple, types: dict) -> tuple[set, set]:
"""Keep the edges of E0 that some class reaching the receiver explains,
then keep what is reachable from the root."""
below = subclasses(prog)
reach0, edges0 = initial
sites = {}
for mid in reach0:
for st in prog["bodies"][mid][1]:
if st[0] == "call":
sites[st[1]] = (mid, st)
keep = {}
for s, t in edges0: # @line L9
mid, (_, _, _, y, m, _) = sites[s]
mdecl = prog["methods"][m][0]
if any(c in below[mdecl] and lookup(prog, c, m) == t for c in types.get((mid, y), ())):
keep.setdefault(mid, set()).add((s, t))
reach, stack, edges = {MAIN}, [MAIN], set() # @line L10
while stack:
mid = stack.pop()
for s, t in keep.get(mid, ()):
edges.add((s, t))
if t not in reach:
reach.add(t)
stack.append(t)
return reach, edges
def components(succ: dict) -> list[list]:
"""Tarjan's strongly connected components, without recursion. The list
comes in reverse topological order: sinks first."""
index, low, on, stack, out = {}, {}, set(), [], []
counter = 0
for root in succ:
if root in index:
continue
index[root] = low[root] = counter
counter += 1
stack.append(root)
on.add(root)
work = [(root, iter(succ[root]))]
while work:
v, it = work[-1]
pushed = False
for w in it:
if w not in index:
index[w] = low[w] = counter
counter += 1
stack.append(w)
on.add(w)
work.append((w, iter(succ[w])))
pushed = True
break
if w in on:
low[v] = min(low[v], index[w])
if pushed:
continue
work.pop()
if work:
u = work[-1][0]
low[u] = min(low[u], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop()
on.discard(w)
comp.append(w)
if w == v:
break
out.append(comp)
return out
def variable_type_analysis(prog: dict, initial: tuple | None = None) -> tuple[set, set]:
if initial is None:
from oomodel import rta_spec
initial = rta_spec(prog)
succ, seed = graph_and_seeds(prog, initial)
comps = components(succ) # @line L6
rep = {v: i for i, comp in enumerate(comps) for v in comp}
ctypes = [set() for _ in comps]
for v, cs in seed.items():
ctypes[rep[v]] |= cs
for i in range(len(comps) - 1, -1, -1): # @line L7
for v in comps[i]:
for w in succ[v]: # @line L8
if rep[w] != i:
ctypes[rep[w]] |= ctypes[i]
types = {v: ctypes[rep[v]] for v in succ}
return prune(prog, initial, types) # @line L11
test_variable_type_analysis.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variable-type-analysis/. The authors are listed in prov/5D67PN.jsonl.
import random
import oomodel
from oomodel import MAIN
from variable_type_analysis import components, graph_and_seeds, prune, variable_type_analysis
def plain_vta(prog, initial):
"""The same graph, solved by pushing classes along every edge until
nothing changes."""
succ, seed = graph_and_seeds(prog, initial)
types = {v: set(seed.get(v, ())) for v in succ}
changed = True
while changed:
changed = False
for v in succ:
for w in succ[v]:
if not types[v] <= types[w]:
types[w] |= types[v]
changed = True
return prune(prog, initial, types)
def programs(seed, count):
rng = random.Random(seed)
for _ in range(count):
yield rng, oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
def test_page_example():
reach, edges = variable_type_analysis(oomodel.shapes())
circle, square = ("Circle", "grow"), ("Square", "grow")
assert reach == {MAIN, circle, square}
assert edges == {("s1", circle), ("s2", square), ("s3", circle), ("s3", square)}
def test_page_example_from_cha_graph():
prog = oomodel.shapes()
assert variable_type_analysis(prog, oomodel.cha_spec(prog)) == variable_type_analysis(prog)
def test_class_flows_through_a_field():
prog = {
"classes": {"A": None, "B": "A", "H": None},
"methods": {"m": ("A", "A", "A")},
"fields": {"f": ("H", "A")},
"bodies": {
("A", "m"): ({"this": "A", "p": "A", "ret": "A"}, []),
("B", "m"): ({"this": "B", "p": "A", "ret": "A"}, []),
MAIN: (
{"a": "A", "o": "A", "h": "H", "x": "A"},
[
("new", "a", "B"),
("new", "o", "A"),
("new", "h", "H"),
("store", "h", "f", "a"),
("load", "x", "h", "f"),
("call", "s1", None, "x", "m", None),
("call", "s2", None, "o", "m", None),
],
),
},
}
reach, edges = variable_type_analysis(prog)
assert edges == {("s1", ("B", "m")), ("s2", ("A", "m"))}
assert len(oomodel.rta_spec(prog)[1]) == 4
def test_components_match_mutual_reachability():
rng = random.Random(3)
for _ in range(200):
n = rng.randint(1, 12)
succ = {v: {w for w in range(n) if rng.random() < 0.15} for v in range(n)}
comps = components(succ)
assert sorted(v for c in comps for v in c) == list(range(n))
reach = {}
for v in range(n):
seen, stack = {v}, [v]
while stack:
for w in succ[stack.pop()]:
if w not in seen:
seen.add(w)
stack.append(w)
reach[v] = seen
where = {v: i for i, c in enumerate(comps) for v in c}
for v in range(n):
for w in range(n):
assert (where[v] == where[w]) == (w in reach[v] and v in reach[w])
if w in succ[v] and where[v] != where[w]:
assert where[w] < where[v] # sinks come first
def test_same_as_plain_iteration():
for _, prog in programs(2000, 400):
initial = oomodel.rta_spec(prog)
assert variable_type_analysis(prog, initial) == plain_vta(prog, initial), oomodel.show(prog)
def test_sound_against_concrete_runs():
for rng, prog in programs(79, 300):
reach, edges = variable_type_analysis(prog)
for _ in range(5):
seen_edges, entered = oomodel.run(prog, rng)
assert seen_edges <= edges, oomodel.show(prog)
assert entered <= reach
def test_nested_inside_rta_inside_cha():
smaller = 0
for _, prog in programs(7, 300):
cha = oomodel.cha_spec(prog)
rta = oomodel.rta_spec(prog)
vta = variable_type_analysis(prog, rta)
assert vta[0] <= rta[0] <= cha[0]
assert vta[1] <= rta[1] <= cha[1]
smaller += vta[1] != rta[1]
assert smaller > 0
def test_monotone_in_the_initial_graph():
for _, prog in programs(8, 300):
from_rta = variable_type_analysis(prog, oomodel.rta_spec(prog))
from_cha = variable_type_analysis(prog, oomodel.cha_spec(prog))
assert from_rta[0] <= from_cha[0] and from_rta[1] <= from_cha[1]
History
Sundaresan, Hendren, Razafimahefa, Vallee-Rai, Lam, Gagnon and Godin introduced variable type analysis and declared type analysis in 2000, as part of the Soot framework for Java. They built the type propagation graph on a conservative initial call graph, collapsed its strongly connected components, and used the result to resolve virtual calls. In the same year, Tip and Palsberg described a family of propagation-based algorithms that keep fewer sets. Grove and Chambers (2001) placed such algorithms in a general framework of call graph construction.
References
- Vijay Sundaresan, Laurie Hendren, Chrislain Razafimahefa, Raja Vallee-Rai, Patrick Lam, Etienne Gagnon and Charles Godin, Practical virtual method call resolution for Java, Proceedings of OOPSLA 2000, 264 to 280, the type propagation graph, the collapse of strongly connected components, and the pruning of a conservative initial call graph
- Frank Tip and Jens Palsberg, Scalable propagation-based call graph construction algorithms, Proceedings of OOPSLA 2000, 281 to 293, the related propagation-based algorithms with one set of classes per method, per field or per class
- David Grove and Craig Chambers, A framework for call graph construction algorithms, ACM Transactions on Programming Languages and Systems 23(6), 685 to 746, 2001, the lattice of call graph algorithms and the place of flow-insensitive type propagation in it
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 5D67PN Edit this page History Report an error Markdown