Algorithm Search⌘K

Algorithmcore

Class hierarchy analysis

Also called CHA.

Build a call graph from declared types. A virtual call y.m() may reach the method m of every class at or below the declared class of y.

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
Jeffrey Dean, David Grove, Craig Chambers, 1995

Class hierarchy analysis (CHA) solves call graph construction for object-oriented programs from the class tree and the declared types alone. At a virtual call y.m(z), the object in y has a class at or below the declared class of y, so the call may reach the method that m dispatches to on any of those classes. The analysis starts at main, adds these targets as edges, and scans each newly reached method once. It runs in time close to linear in the size of the program, it is sound for any type-safe program without reflection, and it is the base that rapid type analysis and variable type analysis refine.

In plain words

When a program calls shape.area(), the variable shape is declared as a Shape. The language promises that the object in it is a Shape or an object of a class below Shape in the class tree. So the call can only run one of the area methods that those classes use. Class hierarchy analysis lists exactly those methods. It does this for each call in each method that main can reach, and it adds each new method it finds to a to-do list. When the list is empty, the result is a call graph. It never misses a real call, as long as the program does not use tricks such as reflection. It may list calls that never happen, because it does not ask which objects the program creates.

The problem

The input is a program in the model of the call graph construction page: a set of classes with single inheritance, where C≤DC \le D means that CC is DD or a class below it; for each method name mm the class decl(m)\mathrm{decl}(m) that introduces it; method bodies with the statements x = new C(), x = y, x = y.f, y.f = z and the virtual call x = y.m(z) at a site ss; a declared class decl(y)\mathrm{decl}(y) for each variable; and the root main. The program is well typed: an assignment puts a value of class CC into a variable or field of declared class DD only if C≤DC \le D, and a call y.m(z) has decl(y)≤decl(m)\mathrm{decl}(y) \le \mathrm{decl}(m).

LOOKUP(C,m)\mathrm{LOOKUP}(C, m) is the method that runs when mm is called on an object of class CC: the definition of mm in CC or in the nearest class above CC that defines it. The CHA targets of a site ss: x = y.m(z) are

TCHA(s)={LOOKUP(C,m):C≤decl(y)}.T_{CHA}(s) = \{\mathrm{LOOKUP}(C, m) : C \le \mathrm{decl}(y)\}.

The output is the least pair (R,E)(R, E) such that main∈Rmain \in R, and for each site ss in a method of RR and each T∈TCHA(s)T \in T_{CHA}(s), (s,T)∈E(s, T) \in E and T∈RT \in R.

item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain pairs (R,E)(R, E) of reachable methods and call edges
order inclusion of both parts (bottom is precise)
join union of both parts
bottom and top (∅,∅)(\emptyset, \emptyset) and all methods with all edges
boundary value main∈Rmain \in R
initial value R={main}R = \{main\}, E=∅E = \emptyset
transfer the closure rule above; monotone, and distributive since TCHAT_{CHA} does not depend on (R,E)(R, E)

The algorithm

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

Each method enters WW once, when it first enters RR (line L8), so each body is scanned once. Line L5 needs the set of classes below each class. The implementation builds it once, together with a table of LOOKUP(C,m)\mathrm{LOOKUP}(C, m) for every class CC below decl(m)\mathrm{decl}(m), so lines L5 and L6 cost O(1)O(1) per class. The loop of line L10 always stops, because C≤decl(y)≤decl(m)C \le \mathrm{decl}(y) \le \mathrm{decl}(m) and decl(m)\mathrm{decl}(m) defines mm.

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
}

The classes at or below Shape are Shape, Circle, Square and Oval. LOOKUP(Oval,grow)\mathrm{LOOKUP}(Oval, grow) walks up to Circle.grow. So TCHA(s)={Shape.grow,Circle.grow,Square.grow}T_{CHA}(s) = \{Shape.grow, Circle.grow, Square.grow\} for all three sites, since all three receivers are declared as Shape.

step method taken what happens WW after the step
1 main s1, s2 and s3 each get the 3 edges; the 3 grow methods enter RR Shape.grow, Circle.grow, Square.grow
2 Square.grow no call sites Shape.grow, Circle.grow
3 Circle.grow no call sites Shape.grow
4 Shape.grow no call sites empty

The result has 4 reachable methods and 9 edges. The only run makes 3 calls: s1 to Circle.grow, and s2 and s3 to Square.grow. Shape.grow is in RR although no code creates a Shape. Rapid type analysis removes it.

Correctness

Soundness. In a well-typed program without reflection, native callbacks or classes loaded at run time, every method that a run enters is in RR, and every call that a run makes is in EE. The key fact is type safety: at every moment of a run, each variable and field of declared class DD holds null or an object of a class C≤DC \le D. So when site ss: x = y.m(z) runs in a method of RR, the receiver has a class C≤decl(y)C \le \mathrm{decl}(y), and the method that runs is LOOKUP(C,m)∈TCHA(s)\mathrm{LOOKUP}(C, m) \in T_{CHA}(s). By induction over the calls of the run, the caller is in RR, so the edge is in EE and the callee is in RR.

Least solution. The algorithm adds only edges that the closure rule forces, and when WW is empty, every method of RR has been scanned, so the rule holds. So the result is the least closed pair. The full proof is in the proof file.

Proof: Class hierarchy analysis computes the least closed call graph, and it is sound for well-typed programsfull

Setting. The program has a finite set of classes with a parent function; C≤DC \le D means that CC is DD or below it. Each method name mm has a class decl(m)\mathrm{decl}(m) that defines it, and LOOKUP(C,m)\mathrm{LOOKUP}(C, m) is the definition of mm in the nearest class at or above CC that has one. Each variable yy of a method body has a declared class decl(y)\mathrm{decl}(y). A call site ss: x = y.m(z) has the target set T(s)={LOOKUP(C,m):C≤decl(y)}T(s) = \{\mathrm{LOOKUP}(C, m) : C \le \mathrm{decl}(y)\}. A pair (R,E)(R, E) is closed if main∈Rmain \in R and, for every site ss in a method of RR and every T∈T(s)T \in T(s), (s,T)∈E(s, T) \in E and T∈RT \in R.

The program is well typed: x = new C() has C≤decl(x)C \le \mathrm{decl}(x); x = y has decl(y)≤decl(x)\mathrm{decl}(y) \le \mathrm{decl}(x); a load x = y.f and a store y.f = z have decl(y)≤decl(f)\mathrm{decl}(y) \le \mathrm{decl}(f) for the class that declares ff, type(f)≤decl(x)\mathrm{type}(f) \le \mathrm{decl}(x) for the load and decl(z)≤type(f)\mathrm{decl}(z) \le \mathrm{type}(f) for the store; a call x = y.m(z) has decl(y)≤decl(m)\mathrm{decl}(y) \le \mathrm{decl}(m), decl(z)≤ptype(m)\mathrm{decl}(z) \le \mathrm{ptype}(m) and rtype(m)≤decl(x)\mathrm{rtype}(m) \le \mathrm{decl}(x); in the body of the definition of mm in class CC, decl(this)=C\mathrm{decl}(this) = C, decl(p)=ptype(m)\mathrm{decl}(p) = \mathrm{ptype}(m) and decl(ret)=rtype(m)\mathrm{decl}(ret) = \mathrm{rtype}(m). The program has no reflection, no native code that calls back and no classes loaded at run time: every call of a run is the execution of a call site of the text.

Lemma 1 (LOOKUP stops). For a site y.m(z) and C≤decl(y)C \le \mathrm{decl}(y), the loop of line L10 stops at a class that defines mm.

Proof. C≤decl(y)≤decl(m)C \le \mathrm{decl}(y) \le \mathrm{decl}(m), so decl(m)\mathrm{decl}(m) is on the path from CC to the root, and it defines mm. The loop stops at the first class on this path that defines mm, at the latest at decl(m)\mathrm{decl}(m). □\square

Lemma 2 (termination and the invariant). The loop of line L2 runs at most ∣Π∣|\Pi| times, where Π\Pi is the set of methods. At each test of line L2: (a) every method is in WW at most once, and W⊆RW \subseteq R; (b) for every method M∈R∖WM \in R \setminus W, every site ss of MM and every T∈T(s)T \in T(s), (s,T)∈E(s, T) \in E and T∈RT \in R.

Proof. A method enters WW only in line L1 or line L8, and line L8 adds it to RR at the same time, only if it was not in RR. Methods never leave RR. So each method enters WW at most once, and the loop runs at most ∣Π∣|\Pi| times. This gives (a). For (b): at the start, R∖W=∅R \setminus W = \emptyset. A method MM leaves WW in line L3, and lines L4 to L8 add (s,T)(s, T) to EE and TT to RR for every site ss of MM and every T∈T(s)T \in T(s), by Lemma 1. Sets only grow, so (b) stays true for the methods that left WW before. □\square

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

Proof. At the start, R={main}⊆R∗R = \{main\} \subseteq R^* and E=∅E = \emptyset. Line L7 adds (s,T)(s, T) for a site ss of a method MM taken from W⊆R⊆R∗W \subseteq R \subseteq R^* and a T∈T(s)T \in T(s), so (s,T)∈E∗(s, T) \in E^* and T∈R∗T \in R^* because (R∗,E∗)(R^*, E^*) is closed. Line L8 adds the same TT to RR. □\square

Theorem 1 (least closed pair). The algorithm stops and returns the least closed pair.

Proof. It stops by Lemma 2. At the end WW is empty, so by Lemma 2(b) the pair (R,E)(R, E) is closed. By Lemma 3 it is inside every closed pair. The intersection of all closed pairs is closed (each rule instance holds in each of them), so a least closed pair exists, and (R,E)(R, E) is it. □\square

Lemma 4 (type safety). In every run of a well-typed program, at every moment, every variable vv of a live frame holds null or an object of a class C≤decl(v)C \le \mathrm{decl}(v), and every field ff of every object holds null or an object of a class C≤type(f)C \le \mathrm{type}(f).

Proof. By induction over the steps of the run. At the start, all variables and fields hold null. x = new C() stores an object of class C≤decl(x)C \le \mathrm{decl}(x). x = y stores the value of yy, of a class C≤decl(y)≤decl(x)C \le \mathrm{decl}(y) \le \mathrm{decl}(x). A load stores a field value, of a class C≤type(f)≤decl(x)C \le \mathrm{type}(f) \le \mathrm{decl}(x). A store puts a value of class C≤decl(z)≤type(f)C \le \mathrm{decl}(z) \le \mathrm{type}(f) in a field. A call x = y.m(z) on a receiver of class C′≤decl(y)C' \le \mathrm{decl}(y) runs the body of LOOKUP(C′,m)\mathrm{LOOKUP}(C', m), defined in a class CC with C′≤CC' \le C; it binds this to the receiver, of class C′≤C=decl(this)C' \le C = \mathrm{decl}(this), and p to a value of class at most decl(z)≤ptype(m)\mathrm{decl}(z) \le \mathrm{ptype}(m). The return stores the value of ret, of a class at most rtype(m)≤decl(x)\mathrm{rtype}(m) \le \mathrm{decl}(x), in xx. □\square

Theorem 2 (soundness). In every run, every method that the run enters is in RR, and for every execution of a site ss that enters a method TT, (s,T)∈E(s, T) \in E.

Proof. By induction over the calls of the run, in the order in which they happen. The run starts in main∈Rmain \in R. Take a call at site ss: x = y.m(z) in a frame of method MM. That frame was entered earlier, so M∈RM \in R by the induction hypothesis. The receiver is an object of a class C≤decl(y)C \le \mathrm{decl}(y) by Lemma 4 (a null receiver makes no call). The method that runs is T=LOOKUP(C,m)∈T(s)T = \mathrm{LOOKUP}(C, m) \in T(s). Since (R,E)(R, E) is closed by Theorem 1, (s,T)∈E(s, T) \in E and T∈RT \in R. □\square

Theorem 3 (cost). With a dispatch table and the sets of classes below each class built first, the algorithm takes O(n+SK)O(n + S K) time after the table, where nn is the size of the program, SS the number of sites and KK the number of classes. The table takes O(KM)O(K M) time for MM method names when it is filled from the root down.

Proof. By Lemma 2, each method is taken from WW once, so lines L3 and L4 read each body once, in O(n)O(n) in total. For each site, line L5 visits at most KK classes, and lines L6 to L8 take O(1)O(1) each with the table and with hashing or direct indexing for RR and EE. That is O(SK)O(S K). The table: for each name mm, visit the classes below decl(m)\mathrm{decl}(m) from the top; the entry of a class is its own definition of mm if it has one, and else the entry of its parent. Each of the at most KMK M entries takes O(1)O(1). The sets of classes below each class have O(Kh)O(K h) elements in total for a tree of height hh, and the program reads one of them per site. ■\blacksquare

Complexity

Proved. Let hh be the height of the class tree. The table of LOOKUP has at most KMK M entries. Filled top-down, each entry copies the entry of the parent or takes the class's own method, so it takes O(KM)O(K M) time; the implementation calls LOOKUP for each entry, which takes O(KMh)O(K M h). Each method is scanned once, which costs O(n)O(n) over the program. Each call site loops over at most KK classes with O(1)O(1) work each, which costs O(SK)O(S K). So the time is O(n+SK+KM)O(n + S K + K M), with hash sets for RR and EE (in expectation) or arrays indexed by method and site (worst case). The space is O(KM)O(K M) for the table and O(SK)O(S K) for the edges.

Measured, not proved. On 500 random well-typed programs with up to 7 classes, the result equals that of a plain round-robin iteration of the closure rule. On 300 random programs with 5 concrete runs each (seed 77), every call that a run makes is in EE.

Properties

  • Sound under type safety. The proof uses only the declared types. A language with unchecked casts, such as C++ with static_cast on a wrong type, breaks it.
  • Independent of the values. TCHA(s)T_{CHA}(s) depends on the text of the site, not on what the program creates or assigns. So the transfer is distributive, and the answer for a site does not change when other code changes, as long as the class tree is the same.
  • Least precise of the classic three. For every program, the call graph of rapid type analysis and that of variable type analysis are subsets of the CHA graph. The proofs are on their pages.
  • Single target. If TCHA(s)T_{CHA}(s) has one method, the call can become a direct call (devirtualization) with no run-time test.

Variants and improvements

  • Name-based resolution. Keep every method called mm, whatever the class. This needs no class tree and is weaker than CHA.
  • Rapid type analysis. Keep only the classes that some reachable method creates (rapid type analysis).
  • Type propagation. Track the classes that reach each variable (variable type analysis), or the abstract objects of a points-to analysis.
  • Interfaces and multiple inheritance. For a Java interface, the classes below it are the classes that implement it and their subclasses. For C++ with multiple inheritance, LOOKUP must search several paths and report an ambiguity.
  • Specialization. A compiler can make a copy of a method for a group of receiver classes. Inside the copy, this has a smaller set of classes below it, so more calls on this have one CHA target.
  • Guarded inlining in a JIT. A just-in-time compiler can use CHA on the classes loaded so far, inline the single target, and record a dependency. When a new subclass is loaded, it throws the code away. See inline caching for the run-time alternative.

When to use it

Use CHA when you need a sound call graph fast, for example as the first step of a whole-program optimizer, as the initial graph of variable type analysis, or in a tool that must answer at once. It needs no fixed point over values and scales to any program size. When the program creates few of the classes in its hierarchy, as with large libraries, use rapid type analysis, which costs almost the same. When the call graph feeds a precise analysis, such as an alias analysis, use a points-to based graph.

Pitfalls

  • Missing inherited methods. A version that, in line L5, loops only over the classes that define m misses calls of a method inherited from above decl(y)\mathrm{decl}(y). With Oval o and a call o.grow(), no class at or below Oval defines grow, but the call runs Circle.grow. Line L5 must loop over all classes below decl(y)\mathrm{decl}(y), and line L6 must walk up.
  • Scanning unreachable code. Taking every method of the program as a root, instead of main in line L1, makes a sound graph with more edges. That is right for a library, whose public methods are all roots, and wrong for a whole program.
  • Claiming soundness with reflection. A call through Method.invoke or a class loaded by name is not a call site of the text. The result of line L9 does not cover it. Treat such programs as unsound for CHA, or add the reflective targets by hand.
  • An open hierarchy. If code that the analysis did not see can add subclasses, the set in line L5 is not complete. A compiler that devirtualizes on CHA must then guard the call or recompile when a class is loaded.

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.

class_hierarchy_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/class-hierarchy-analysis/. The authors are listed in prov/M6WV8Z.jsonl.
"""Class hierarchy analysis (CHA): a call graph from declared types.

class_hierarchy_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 at or below the declared class of y. The worklist holds the
methods that are reachable but not yet scanned.

Precondition: the program is well typed, so a variable of declared class D
only holds objects of a class C <= D. Cost: O(K * M) for the dispatch table
of K classes and M method names, plus O(n + S * K) for a program of size n
with S call sites.
"""

from oomodel import MAIN, call_sites, lookup, subclasses


def class_hierarchy_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)  # @line L10 @line L11
    reach, work, edges = {MAIN}, [MAIN], set()  # @line L1
    while work:  # @line L2
        mid = work.pop()  # @line L3
        local = prog["bodies"][mid][0]
        for _, s, _, y, m, _ in call_sites(prog, mid):  # @line L4
            for c in below[local[y]]:  # @line L5
                t = table[(c, m)]  # @line L6
                edges.add((s, t))  # @line L7
                if t not in reach:  # @line L8
                    reach.add(t)
                    work.append(t)
    return reach, edges  # @line L9
oomodel.py 305 lines
# 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)
test_class_hierarchy_analysis.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/class-hierarchy-analysis/. The authors are listed in prov/M6WV8Z.jsonl.

import random

import oomodel
from class_hierarchy_analysis import class_hierarchy_analysis
from oomodel import MAIN


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


def test_lookup_walks_up_the_tree():
    prog = oomodel.shapes()
    assert oomodel.lookup(prog, "Oval", "grow") == ("Circle", "grow")
    assert oomodel.lookup(prog, "Square", "grow") == ("Square", "grow")


def test_no_calls():
    prog = {
        "classes": {"A": None},
        "methods": {},
        "fields": {},
        "bodies": {MAIN: ({"x": "A"}, [("new", "x", "A")])},
    }
    assert class_hierarchy_analysis(prog) == ({MAIN}, set())


def test_declared_type_limits_the_targets():
    # A receiver declared as Square cannot reach Circle.grow or Shape.grow.
    prog = oomodel.shapes()
    local, stmts = prog["bodies"][MAIN]
    local = dict(local, q="Square")
    prog["bodies"][MAIN] = (local, [("new", "q", "Square"), ("call", "s9", None, "q", "grow", None)])
    reach, edges = class_hierarchy_analysis(prog)
    assert edges == {("s9", ("Square", "grow"))}
    assert reach == {MAIN, ("Square", "grow")}


def test_unreachable_method_adds_no_edges():
    # The call in Shape.grow is never scanned when no site reaches Shape.grow.
    prog = oomodel.shapes()
    local, _ = prog["bodies"][MAIN]
    prog["bodies"][MAIN] = (local, [])
    prog["bodies"][("Shape", "grow")][1].append(("call", "s7", None, "this", "grow", None))
    assert class_hierarchy_analysis(prog) == ({MAIN}, set())


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


def test_sound_against_concrete_runs():
    rng = random.Random(77)
    for _ in range(300):
        prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
        reach, edges = class_hierarchy_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_contains_rapid_type_analysis():
    rng = random.Random(5)
    for _ in range(300):
        prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
        reach, edges = class_hierarchy_analysis(prog)
        rta_reach, rta_edges = oomodel.rta_spec(prog)
        assert rta_reach <= reach and rta_edges <= edges

History

Dean, Grove and Chambers described class hierarchy analysis in 1995, in their work on optimizing compilers for object-oriented languages, and used it to replace message sends with direct calls. Bacon and Sweeney (1996) measured it on C++ programs and showed that rapid type analysis removes many more virtual calls at almost the same cost. Grove, DeFouw, Dean and Chambers (1997), and Grove and Chambers (2001), placed CHA at the bottom of a lattice of call graph algorithms and measured the whole family on Cecil and Java programs. Sundaresan and others (2000) used CHA as the conservative initial call graph of the Soot framework for Java, on which variable type analysis builds.

References

  1. Jeffrey Dean, David Grove and Craig Chambers, Optimization of object-oriented programs using static class hierarchy analysis, ECOOP '95, LNCS 952, 77 to 101, 1995, the definition of class hierarchy analysis and its use to bind message sends statically
  2. David F. Bacon and Peter F. Sweeney, Fast static analysis of C++ virtual function calls, Proceedings of OOPSLA '96, 324 to 341, 1996, class hierarchy analysis for C++ and its measured comparison with rapid type analysis
  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, class hierarchy analysis as the cheapest point of the framework, and its measured precision
  4. 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, class hierarchy analysis as the conservative initial call graph of the Soot framework

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/M6WV8Z/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