Algorithm Search⌘K

Algorithmcore

Rapid type analysis

Build a call graph like class hierarchy analysis, but let a virtual call reach only the classes that some reachable method creates with new.

Time
O(n + S K + K M) worst
Space
O(S K + K M) extra
Where
K = the number of classes; M = the number of method names; S = the number of call sites; n = the size of the program
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
David F. Bacon, Peter F. Sweeney, 1996

Rapid type analysis (RTA) is a solution of call graph construction for object-oriented programs that refines class hierarchy analysis with one global set: the classes that the program creates. A virtual call y.m(z) may reach the method m of a class only if that class is at or below the declared class of y and some reachable method contains new of that class. The graph is built on the fly from main, so a class created only in dead code does not count. RTA costs about the same as CHA, it is sound for type-safe programs without reflection, and its graph is always inside the CHA graph.

In plain words

Class hierarchy analysis assumes that a variable of type Shape can hold any kind of shape. But a program that never writes new Oval() can never hold an Oval. Rapid type analysis keeps a list of the classes that the program creates, and it only follows calls into methods of those classes. It starts at main and keeps a to-do list of methods to read. When a method creates a new class, the analysis goes back to the calls it has already seen and adds the new targets. When it sees a new call, it uses all the classes found so far. When the to-do list is empty, the graph is done.

The problem

The input is a program in the model of class hierarchy analysis: classes with single inheritance and the order C≤DC \le D, method bodies with x = new C(), x = y, x = y.f, y.f = z and virtual calls x = y.m(z) at sites ss, a declared class decl(y)\mathrm{decl}(y) for each variable, the dispatch function LOOKUP(C,m)\mathrm{LOOKUP}(C, m) and the root main. The program is well typed. The output is the pair (R,E)(R, E) of the least triple (R,I,E)(R, I, E) of methods, classes and edges with these rules:

  1. main∈Rmain \in R;
  2. if a method of RR contains x = new C(), then C∈IC \in I;
  3. if a method of RR contains the site ss: x = y.m(z), C∈IC \in I and C≤decl(y)C \le \mathrm{decl}(y), then (s,LOOKUP(C,m))∈E(s, \mathrm{LOOKUP}(C, m)) \in E and LOOKUP(C,m)∈R\mathrm{LOOKUP}(C, m) \in R.
item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain triples (R,I,E)(R, I, E) of reachable methods, created classes and call edges
order inclusion of all three parts (bottom is precise)
join union of all three parts
bottom and top (∅,∅,∅)(\emptyset, \emptyset, \emptyset) and all methods, all classes, all edges
boundary value main∈Rmain \in R
initial value R={main}R = \{main\}, I=∅I = \emptyset, E=∅E = \emptyset
transfer rules 2 and 3; monotone, not distributive, since rule 3 needs a site of RR and a class of II at once

The algorithm

  1. RTA(P)
  2. 1R <- {main}; W <- [main]; E <- {}; I <- {}; S <- {}
  3. 2while W is not empty do
  4. 3take a method M from W
  5. 4for each statement x = new C() in M do
  6. 5if C is not in I then add C to I
  7. 6for each site s: x = y.m(z) in S with C <= decl(y) do
  8. 7ADD(s, LOOKUP(C, m))
  9. 8for each call site s: x = y.m(z) in M do
  10. 9add s to S
  11. 10for each class C in I with C <= decl(y) do
  12. 11ADD(s, LOOKUP(C, m))
  13. 12return (R, E)
  14. ADD(s, T)
  15. 13add (s, T) to E
  16. 14if T is not in R then add T to R and to W

II holds the classes created so far, and SS holds the call sites seen so far. Lines L4 to L7 handle a class that appears late: every site seen before gets the targets for the new class. Lines L8 to L11 handle a site that appears late: it gets the targets for every class created before. So each pair of a site and a class is examined once, by whichever of the two arrives second. LOOKUP and the subclass test use tables built once, as in class hierarchy analysis.

Example

The program of the call graph construction page:

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
}
step method taken what happens WW after the step
1 main lines L4 to L7: I={Circle,Square}I = \{Circle, Square\}, no sites seen yet; lines L8 to L11: s1, s2 and s3 each get edges to Circle.grow and Square.grow Circle.grow, Square.grow
2 Square.grow no new, no sites Circle.grow
3 Circle.grow new Square(), but Square is already in II empty

The result has 3 reachable methods and 6 edges. Class hierarchy analysis gives 4 methods and 9 edges: RTA drops Shape.grow, because no reachable code creates a plain Shape, and it drops the 3 edges to it. The run makes 3 of the 6 edges: s1 to Circle.grow, and s2 and s3 to Square.grow. The edge from s1 to Square.grow is spurious, because RTA does not know that a holds only a Circle. Variable type analysis removes it.

Correctness

Least solution. Each class enters II once and each site enters SS once. The invariant is: for each site in SS and each class in II below its declared class, the edge is in EE. Line L7 keeps it when a class arrives, and line L11 keeps it when a site arrives. When WW is empty, SS holds all sites of RR and II holds all classes created in RR, so the three rules hold. Every edge that the algorithm adds is forced by the rules, so the result is the least solution.

Soundness. Take a well-typed program without reflection, native code or classes loaded at run time. By induction over the steps of a run: every object is created by a new in a method that the run entered, which is in RR, so its class is in II. At a call y.m(z), the receiver has a class C∈IC \in I, and type safety gives C≤decl(y)C \le \mathrm{decl}(y). So rule 3 puts the call in EE and the callee in RR.

Inside CHA. The CHA result with II set to all classes satisfies the three rules. The RTA result is the least triple that satisfies them, so it is inside the CHA result. The full proofs are in the proof file.

Proof: Rapid type analysis computes the least closed call graph, it is sound for well-typed programs, and it is inside class hierarchy analysisfull

Setting. The program, C≤DC \le D, decl\mathrm{decl}, LOOKUP\mathrm{LOOKUP} 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: every object of a run comes from the execution of a statement x = new C() of the text, and every call of a run is the execution of a call site of the text. A triple (R,I,E)(R, I, E) of methods, classes and edges is closed if

  1. main∈Rmain \in R;
  2. for every method M∈RM \in R and every statement x = new C() in MM, C∈IC \in I;
  3. for every method M∈RM \in R, every site ss: x = y.m(z) in MM and every C∈IC \in I with C≤decl(y)C \le \mathrm{decl}(y), the edge (s,LOOKUP(C,m))(s, \mathrm{LOOKUP}(C, m)) is in EE and LOOKUP(C,m)∈R\mathrm{LOOKUP}(C, m) \in R.

LOOKUP(C,m)\mathrm{LOOKUP}(C, m) is defined in rule 3, because C≤decl(y)≤decl(m)C \le \mathrm{decl}(y) \le \mathrm{decl}(m) and decl(m)\mathrm{decl}(m) defines mm.

Lemma 1 (termination). Each method enters WW at most once, so the loop of line L2 runs at most ∣Π∣|\Pi| times, for the set Π\Pi of methods. Each class enters II at most once, and each site enters SS at most once.

Proof. A method enters WW only in line L1 or line L14, and line L14 adds it to RR in the same step, only if it was not in RR. Methods never leave RR. A class enters II in line L5 only if it is not in II. A site enters SS in line L9 when its method is taken from WW, which happens once. □\square

Lemma 2 (the invariant). At each test of line L2: (a) W⊆RW \subseteq R; (b) II is the set of classes CC such that some method of R∖WR \setminus W has a statement x = new C(), and SS is the set of sites of the methods of R∖WR \setminus W; (c) for every site ss: x = y.m(z) in SS and every C∈IC \in I with C≤decl(y)C \le \mathrm{decl}(y), (s,LOOKUP(C,m))∈E(s, \mathrm{LOOKUP}(C, m)) \in E and LOOKUP(C,m)∈R\mathrm{LOOKUP}(C, m) \in R.

Proof. At the start, R∖WR \setminus W, II and SS are empty, so (b) and (c) hold, and W=R={main}W = R = \{main\}. Take one pass of the loop, with method MM. Part (a) holds because line L14 adds a method to RR and to WW together. Lines L4 and L5 add the classes created in MM to II, and line L9 adds the sites of MM to SS, while MM leaves WW in line L3. This gives (b). For (c), take a site ss in SS and a class CC in II with C≤decl(y)C \le \mathrm{decl}(y), after the pass. There are three cases. If both were there before the pass, (c) held before, and sets only grow. If ss was in SS before and CC entered II in this pass, line L6 visited ss when CC entered, and line L7 added the edge. If ss entered SS in this pass, lines L4 to L7 ran before, so CC was in II when line L10 ran for ss, and line L11 added the edge. In each case, ADD put the target in RR (line L14). □\square

Lemma 3 (every fact is forced). Let (R∗,I∗,E∗)(R^*, I^*, E^*) be any closed triple. At all times, R⊆R∗R \subseteq R^*, I⊆I∗I \subseteq I^* and E⊆E∗E \subseteq E^*.

Proof. At the start, R={main}⊆R∗R = \{main\} \subseteq R^* by rule 1, and II and EE are empty. Line L5 adds a class created in a method M∈R⊆R∗M \in R \subseteq R^*, which is in I∗I^* by rule 2. Lines L7 and L11 call ADD with a site ss of a method of RR, a class C∈IC \in I with C≤decl(y)C \le \mathrm{decl}(y) and T=LOOKUP(C,m)T = \mathrm{LOOKUP}(C, m). By the induction hypothesis the method is in R∗R^* and C∈I∗C \in I^*, so rule 3 gives (s,T)∈E∗(s, T) \in E^* and T∈R∗T \in R^*. □\square

Theorem 1 (least closed triple). The algorithm stops and returns (R,E)(R, E) of the least closed triple, and its II is the II of that triple.

Proof. It stops by Lemma 1. At the end WW is empty, so by Lemma 2 rule 2 holds (part (b)) and rule 3 holds (part (c), with SS the sites of all of RR). Rule 1 holds from line L1. So (R,I,E)(R, I, E) is closed, and by Lemma 3 it is inside every closed triple. The intersection of all closed triples is closed, because each rule instance holds in each of them, so the least closed triple exists, and it is (R,I,E)(R, I, E). □\square

Lemma 4 (type safety). In every run of a well-typed program, every variable of declared class DD and every field of type DD holds null or an object of a class C≤DC \le D.

Proof. This is Lemma 4 of the proof of class hierarchy analysis. It does not use any part of the analysis. □\square

Theorem 2 (soundness). In every run, every object has a class in II, every method that the run enters is in RR, and every call from a site ss to a method TT has (s,T)∈E(s, T) \in E.

Proof. By induction over the steps of the run. The run starts in main∈Rmain \in R. A step x = new C() runs in a frame of a method MM that the run entered, so M∈RM \in R by the induction hypothesis, and C∈IC \in I by rule 2. A call at site ss: x = y.m(z) runs in a frame of a method M∈RM \in R. Its receiver is an object that an earlier step created, so its class CC is in II, and C≤decl(y)C \le \mathrm{decl}(y) by Lemma 4. The method that runs is T=LOOKUP(C,m)T = \mathrm{LOOKUP}(C, m), so rule 3 gives (s,T)∈E(s, T) \in E and T∈RT \in R. □\square

Theorem 3 (inside class hierarchy analysis). Let (RC,EC)(R_C, E_C) be the result of class hierarchy analysis. Then R⊆RCR \subseteq R_C and E⊆ECE \subseteq E_C.

Proof. Let KK be the set of all classes. The triple (RC,K,EC)(R_C, K, E_C) is closed. Rule 1 holds since main∈RCmain \in R_C. Rule 2 holds since I=KI = K contains every class. For rule 3, take a site ss of a method of RCR_C and C≤decl(y)C \le \mathrm{decl}(y). Then LOOKUP(C,m)\mathrm{LOOKUP}(C, m) is in the CHA target set of ss, so the CHA closure rule puts the edge in ECE_C and the target in RCR_C. By Theorem 1 the RTA result is inside every closed triple, so it is inside this one. □\square

Theorem 4 (cost). After a dispatch table of LOOKUP\mathrm{LOOKUP} and a subclass test in O(1)O(1) are built, the algorithm runs in O(n+SK)O(n + S K) time, where nn is the size of the program, SS the number of sites and KK the number of classes.

Proof. By Lemma 1, each body is read once in lines L4 and L8, which costs O(n)O(n) in total. Each pair of a site ss and a class CC is examined at most once: in line L6 if ss entered SS before CC entered II, and in line L10 otherwise. Each class enters II once and each site enters SS once, so no pair is examined twice. Each examination is a subclass test, a table lookup and at most one ADD, all in O(1)O(1) with hashing or direct indexing for RR and EE. So lines L6, L7, L10 and L11 cost O(SK)O(S K) in total. The table takes O(KM)O(K M) time for MM method names, filled from the root down as in the proof of class hierarchy analysis, and a K×KK \times K bit matrix for the subclass test takes O(K2)O(K^2) time and space. A hash set of the classes below each class takes O(Kh)O(K h) for a class tree of height hh and gives the same test in expected O(1)O(1). ■\blacksquare

Complexity

Proved. Each body is read once, which costs O(n)O(n). Each pair of a site and a class is examined once, in line L6 or in line L10, with O(1)O(1) work, which costs O(SK)O(S K). The dispatch table costs O(KM)O(K M) time and space. So the time is O(n+SK+KM)O(n + S K + K M), with direct indexing for RR, II and EE (or hashing, in expectation). The space is O(SK)O(S K) for the edges and O(KM)O(K M) for the table. This is the same bound as CHA.

Measured, not proved. On 500 random well-typed programs with up to 7 classes (seed 1996), the result equals that of a plain round-robin iteration of the three rules. On 300 random programs with 5 concrete runs each (seed 78), every call that a run makes is in EE. On 300 random programs (seed 6), the RTA graph is inside the CHA graph, and it is strictly smaller on some of them.

Properties

  • Sound under type safety and a closed world. The proof needs every object to come from a new of the analysed text.
  • Inside CHA. For every program, RRTA⊆RCHAR_{RTA} \subseteq R_{CHA} and ERTA⊆ECHAE_{RTA} \subseteq E_{CHA}.
  • One set for the whole program. All variables share the same set II. A class created anywhere in reachable code is a possible receiver of every call whose declared type is above it.
  • Not distributive. An edge needs a site and a class, which may come from different paths. So the analysis has a real fixed point, but it is reached in one pass over each method because of lines L6 and L7.

Variants and improvements

  • Whole-program instantiation. Count the classes created anywhere in the program text, not only in reachable methods. This needs no on-the-fly graph and gives a graph between RTA and CHA.
  • One set per method or per field. Tip and Palsberg give each method, each field or each class its own set of classes and propagate classes along the call edges and field accesses. These variants lie between RTA and variable type analysis.
  • Type propagation per variable. Variable type analysis keeps a set of classes for each variable and field.
  • Points-to based graphs. A points-to analysis keeps sets of allocation sites instead of classes and builds the call graph at the same time.
  • Dead code removal. A method outside RR cannot run. A linker or a tree shaker can drop it (dead code elimination).

When to use it

Use RTA when you need a sound call graph for a whole program and CHA keeps too many targets, for example when the program uses a large library but creates few of its classes. RTA costs almost the same as CHA and has no per-variable state. It is a good initial graph for variable type analysis or for a points-to analysis. If you analyse a library without its clients, every class that client code may create must be in II from the start, and then RTA gains little over CHA.

Pitfalls

  • No back-patching of earlier sites. A version without lines L6 and L7 handles only the sites seen after a class is created. If main calls a.m() and only then reaches a method that creates a subclass B that overrides m, the edge to B.m is lost, and the graph is unsound. Lines L6 and L7 must revisit the sites in SS for each new class.
  • Objects that no new creates. Reflection (Class.newInstance), deserialization, clone and native code create objects without a new statement in the text. Their classes never enter II in line L5, and the calls on them are missing. Add these classes to II by hand or treat the program as outside the soundness claim.
  • Forgetting the constructor and static calls. In a real language, new C() also calls the constructor of CC and its superclasses, and the first use of CC may run its static initializer. These are direct calls. Add them to EE and their methods to RR when line L5 runs, or the methods they call are missed.
  • Testing the class of the declared type only. Line L10 must test C≤decl(y)C \le \mathrm{decl}(y) for every created class, not C=decl(y)C = \mathrm{decl}(y). A variable declared as Shape can hold a Circle.

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.

oomodel.pyI0RawGitHub
# 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)
rapid_type_analysis.py 55 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rapid-type-analysis/. The authors are listed in prov/D3EG6T.jsonl.
"""Rapid type analysis (RTA): a call graph from the classes that reachable
code creates.

rapid_type_analysis(prog) takes a program of the oomodel form and returns
(R, E): the methods reachable from the root, and the call edges as pairs
(site, method id). A virtual call y.m(z) may call LOOKUP(C, m) for every class
C that is at or below the declared class of y and that a reachable method
creates with new. The graph is built on the fly: a class created late adds
edges to the sites seen before, and a site seen late uses all classes created
before.

Precondition: the program is well typed. Cost: O(K * M) for the dispatch
table, plus O(n + S * K) for a program of size n with S call sites and K
classes.
"""

from oomodel import MAIN, lookup, subclasses


def rapid_type_analysis(prog: dict) -> tuple[set, set]:
    below = subclasses(prog)
    table = {}  # (C, m) -> LOOKUP(C, m), built once
    for m, (mdecl, _, _) in prog["methods"].items():
        for c in below[mdecl]:
            table[(c, m)] = lookup(prog, c, m)
    reach, work, edges = {MAIN}, [MAIN], set()  # @line L1
    made, seen = set(), []  # I and S of the pseudocode

    def add(s, t):
        edges.add((s, t))  # @line L13
        if t not in reach:  # @line L14
            reach.add(t)
            work.append(t)

    while work:  # @line L2
        mid = work.pop()  # @line L3
        local, stmts = prog["bodies"][mid]
        for st in stmts:  # @line L4
            if st[0] == "new" and st[2] not in made:
                c = st[2]
                made.add(c)  # @line L5
                for s, m, d in seen:  # @line L6
                    if c in below[d]:
                        add(s, table[(c, m)])  # @line L7
        for st in stmts:  # @line L8
            if st[0] == "call":
                _, s, _, y, m, _ = st
                d = local[y]
                seen.append((s, m, d))  # @line L9
                for c in made:  # @line L10
                    if c in below[d]:
                        add(s, table[(c, m)])  # @line L11
    return reach, edges  # @line L12
test_rapid_type_analysis.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rapid-type-analysis/. The authors are listed in prov/D3EG6T.jsonl.

import random

import oomodel
from oomodel import MAIN
from rapid_type_analysis import rapid_type_analysis


def test_page_example():
    reach, edges = rapid_type_analysis(oomodel.shapes())
    live = {("Circle", "grow"), ("Square", "grow")}
    assert reach == {MAIN} | live
    assert edges == {(s, t) for s in ("s1", "s2", "s3") for t in live}


def test_class_created_after_the_site_is_seen():
    # main calls a.m() on an A; A.m then creates a B, which overrides m.
    prog = {
        "classes": {"A": None, "B": "A"},
        "methods": {"m": ("A", "A", "A")},
        "fields": {},
        "bodies": {
            ("A", "m"): ({"this": "A", "p": "A", "ret": "A"}, [("new", "ret", "B")]),
            ("B", "m"): ({"this": "B", "p": "A", "ret": "A"}, []),
            MAIN: ({"a": "A"}, [("new", "a", "A"), ("call", "s1", "a", "a", "m", None)]),
        },
    }
    reach, edges = rapid_type_analysis(prog)
    assert edges == {("s1", ("A", "m")), ("s1", ("B", "m"))}
    assert reach == {MAIN, ("A", "m"), ("B", "m")}


def test_creation_in_unreachable_code_does_not_count():
    prog = oomodel.shapes()
    prog["bodies"][("Oval", "grow")] = ({"this": "Oval", "p": "Shape", "ret": "Shape"}, [])
    prog["bodies"][("Shape", "grow")][1].append(("new", "ret", "Oval"))
    reach, edges = rapid_type_analysis(prog)
    assert ("Oval", "grow") not in reach
    assert ("Shape", "grow") not in reach


def test_no_objects_no_edges():
    prog = oomodel.shapes()
    local, stmts = prog["bodies"][MAIN]
    prog["bodies"][MAIN] = (local, [st for st in stmts if st[0] == "call"])
    assert rapid_type_analysis(prog) == ({MAIN}, set())


def test_same_as_plain_iteration():
    rng = random.Random(1996)
    for _ in range(500):
        prog = oomodel.random_program(rng, rng.randint(1, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
        assert rapid_type_analysis(prog) == oomodel.rta_spec(prog), oomodel.show(prog)


def test_sound_against_concrete_runs():
    rng = random.Random(78)
    for _ in range(300):
        prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
        reach, edges = rapid_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_inside_class_hierarchy_analysis():
    rng = random.Random(6)
    smaller = 0
    for _ in range(300):
        prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
        reach, edges = rapid_type_analysis(prog)
        cha_reach, cha_edges = oomodel.cha_spec(prog)
        assert reach <= cha_reach and edges <= cha_edges
        smaller += edges != cha_edges
    assert smaller > 0

History

Bacon and Sweeney introduced rapid type analysis in 1996. They compared it with class hierarchy analysis and with name-based resolution on C++ programs, and found that keeping only the created classes resolves many more virtual calls at almost the same cost. Tip and Palsberg (2000) wrote RTA as a set of constraints and refined it with separate sets of classes per method, per field and per class. Grove and Chambers (2001) placed RTA in a framework of call graph algorithms between class hierarchy analysis and full type propagation.

References

  1. David F. Bacon and Peter F. Sweeney, Fast static analysis of C++ virtual function calls, Proceedings of OOPSLA '96, 324 to 341, 1996, the definition of rapid type analysis and its measured comparison with class hierarchy analysis on C++ programs
  2. Frank Tip and Jens Palsberg, Scalable propagation-based call graph construction algorithms, Proceedings of OOPSLA 2000, 281 to 293, the constraint form of rapid type analysis, and the refinements that keep one set of classes per method, per field or per class
  3. 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, rapid type analysis as a point of the framework between class hierarchy analysis and type propagation

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/D3EG6T/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example