Algorithmadvanced
Type-based alias analysis
Also called TBAA.
Decides that two references cannot alias when their declared types are incompatible under the rules of a type-safe language.
- Solves
- Alias analysis
- Time
- O(t^2 h + m log t) worst
- Space
- O(t^2) extra
- Where
- h = the height of the type tree; m = the number of statements; t = the number of types
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Amer Diwan, Kathryn S. McKinley, J. Eliot B. Moss, 1998
Type-based alias analysis answers alias analysis queries from the types of a program alone. In a type-safe language, a reference of declared type can only reach objects whose class is or a subtype of . So two references can touch the same memory only if their types share a subtype. The analysis needs no points-to analysis, costs almost nothing, and works on a part of a program. Diwan, McKinley and Moss (1998) gave three forms of growing precision: TypeDecl compares the declared types, FieldTypeDecl also compares the field names, and SMTypeRefs also looks at which types the program assigns to each other. C compilers use a form of the same idea, based on the rule of the C standard about the types through which an object may be accessed.
In plain words
In a language where the types cannot lie, a variable that is declared to hold a car can never hold a house. So a write through a car variable cannot change a house. A compiler can use this fact to keep a value in a register, or to move a read past a write, without a costly study of the whole program. The basic form only asks whether the two declared types could describe the same object. A better form also says that two different fields of objects never overlap. The best form also notes which types the program really mixes: if the program never puts a sports car into a car variable, then a car variable and a sports car variable never meet, even though one type is a kind of the other.
The problem
The input is a well-typed program in a language with classes and fields, and two memory references and , each the field of the object that a variable holds. The question is whether some run can make them touch the same field of the same object. A "no" must be true for every run; a "yes" may be wrong. The analysis is flow-insensitive: it ignores the order of the statements, but not the statements that the control flow gives.
The toy language has a tree of classes, with when is or a descendant of , and . Each variable has a declared class , and each field has a declared type . The statements are p = new C, p = q, p = q.f and q.f = p, each allowed only if the type of the value is a subtype of the type of the place: an upcast is fine, a downcast is not. SMTypeRefs as a data-flow analysis:
| item | value |
|---|---|
| direction | none: one answer for the whole program |
| may or must | may |
| domain | partitions of the set of types into groups |
| order | a finer partition is lower (bottom is precise) |
| join | the finest partition coarser than both |
| bottom and top | every type in its own group, and one group for all types |
| boundary value | none, there is no entry or exit point |
| initial value | every type in its own group |
| transfer | each statement that moves a value from type to a place of type merges the groups of and ; monotone, and the result does not depend on the order |
The algorithm
TypeDecl says that and may alias if . FieldTypeDecl says so only if and , since different fields never overlap in a type-safe language. SMTypeRefs, or selective merging, puts the types in groups with a disjoint-set forest, and replaces by , the subtypes of that the program can really store in a place of type .
TYPE-REFS(P)- 1
for each class C do make a group with C alone - 2
for each statement of P that moves a value of type A into a place of type B do - 3
if A is not B then UNION(A, B) - 4
for each class D do TypeRefs[D] <- {C in Sub(D) : FIND(C) = FIND(D)} - 5
return TypeRefs SM-MAY-ALIAS(q1.f1, q2.f2)- 6
if f1 is not f2 then return false - 7
return true if TypeRefs[T(q1)] and TypeRefs[T(q2)] have a common class, else false
In line L2, p = new C moves a value of type into , p = q moves into , p = q.f moves into , and q.f = p moves into . Lines L6 and L7 are the field test of FieldTypeDecl with in place of ; Diwan, McKinley and Moss call this combination SMFieldTypeRefs.
Example
A program in a Java-like notation. The class Object has a field val of type Object, the class A has a field next of type A, and A1 and A2 extend A, and B extends Object.
A1 x; A2 y; A a; Object o; A t;
x = new A1; // 0
y = new A2; // 1
a = y; // 2
x.next = a; // 3
y.next = a; // 4
o = new B; // 5
o.val = o; // 6
t = a.next; // 7
Line L3 merges A2 with A (statement 2) and B with Object (statement 5); the other statements move a value between equal types. So , and . The memory references are in statements 3, 4, 6 and 7.
| references | TypeDecl | FieldTypeDecl | SMTypeRefs | some run |
|---|---|---|---|---|
x.next, y.next (3, 4) |
yes | no: and share no subtype | no | no |
x.next, a.next (3, 7) |
yes | yes: | no: | no |
y.next, a.next (4, 7) |
yes | yes | yes: is in both | yes |
o.val and any next (6 with 3, 4, 7) |
yes | no: different fields | no | no |
The pair (4, 7) really aliases, since a = y. Every form says yes for it. SMTypeRefs is exact here. FieldTypeDecl says yes for (3, 7) because a could hold an A1 by its type, but no statement ever puts one there.
Correctness
The full proof is in the proof file. Its steps:
- The run invariant. At every moment of every run, an object of class held by a variable has and in the group of , and the same for the fields. The proof is by induction over the steps: each statement moves an object from a place of type to a place of type , the typing rule gives , and line L3 put and in one group.
- Soundness. If two references touch the field of one object of class , then is in of both base types, so SMTypeRefs answers yes.
- Each form refines the one before. , and equal fields have equal declared types.
So the three answers are sound, and SMTypeRefs is the most precise of them.
Proof: Type-based alias analysis is sound for every run of a well-typed program, and each of its three forms refines the one beforefull
Setting. A program has a tree of classes, where means that is or a descendant of , and . Each field is declared in one class and has a declared type ; field names are unique. Each variable has a declared class . The statements are p = new C, p = q, p = q.f and q.f = p, with the typing rules , , with declared in an ancestor of , and with declared in an ancestor of . The type of the source and the type of the target of a statement are , , and , in the four forms. Lines L1 to L3 put each class in its own group and merge the groups of the two types of every statement where they differ. is the final group of , and line L4 sets .
A run executes the statements in any order, any number of times, from a state where no variable and no field holds an object. This covers every path of the control flow graph. A statement that reads a variable or field with no object does not run. A reference touches the field of the object that holds when its statement runs. The three answers for two references and are:
- TypeDecl: ;
- FieldTypeDecl: and ;
- SMTypeRefs (lines L6 and L7): and .
Lemma 1 (the run invariant). At every state of every run, for every variable that holds an object of class , and ; and for every object whose field holds an object of class , the field is declared in an ancestor of the class of the holder, , and .
Proof. By induction over the steps of the run. At the start nothing holds an object. Take a step.
p = new Cmakes an object of class , and by the typing rule. If , line L3 merged their groups, so .p = qmoves an object of class from to . By the hypothesis, , and , since line L3 merged the two groups if the types differ.p = q.freads the field of the object in , which exists by the hypothesis and holds an object of class with and .q.f = pwrites the object of class in into the field of the object in . The class of has , and is declared in an ancestor of , so also of . Then , and .
No other holder changes, so the invariant holds after the step.
Theorem 1 (soundness). If the references and touch the same field of the same object in some run, then SMTypeRefs, FieldTypeDecl and TypeDecl all answer that they may alias.
Proof. They touch the field of one object of class , held by and by at the two moments. By Lemma 1, and for , so , and SMTypeRefs answers yes. The other two answer yes by Theorem 2.
Theorem 2 (each form refines the one before). If SMTypeRefs answers yes, FieldTypeDecl does; if FieldTypeDecl answers yes, TypeDecl does.
Proof. , so a common element of the two sets of TypeRefs is a common subtype. If FieldTypeDecl answers yes, then , so , and .
The same argument shows that a points-to analysis that respects the typing rules is at least as precise as SMTypeRefs: if the abstract flow of an allocation site of class reaches both and along statements of the program, every holder on the way has below its type and in its group, so is in both sets of TypeRefs.
Theorem 3 (time). With classes of a tree of height , statements and a union-find forest with path compression in lines L1 to L3, the groups take time, and time with union by rank as well; and the table of TypeRefs takes time and space. Each query then takes time, or with a table of the answers built in time.
Proof. Lines L1 to L3 make groups and at most unions. Line L4 tests for every pair, each by a walk up the tree of at most steps, and one find per pair. A query compares two subsets of the classes.
The analysis does not look at the statements again for each query, and it does not depend on the order of the statements, so it is flow-insensitive in the same sense as the points-to analyses: it ignores the order, not the statements that the control flow gives.
Complexity
Proved. With types in a tree of height and statements, lines L1 to L3 take time with path compression, and with union by rank as well. Line L4 takes time and space. A query takes time with sets, or with a table of all pairs of types. TypeDecl and FieldTypeDecl need no pass over the statements at all.
Stated in the paper, not proved here. Diwan, McKinley and Moss measured the three forms on Modula-3 programs with redundant load elimination. They report that FieldTypeDecl and SMTypeRefs are much more precise than TypeDecl, that the optimization based on them removes a useful share of the loads, and, by a limit study, that a more precise alias analysis would remove few more loads in their programs. They also discuss its use on incomplete programs, where a part of the code is not known.
Measured, not proved. On 200 seeded random well-typed programs of 30 statements over six classes and four fields, with 5967 pairs of references in all, TypeDecl says yes for all 5967, FieldTypeDecl for 2860, SMTypeRefs for 2852, and the runs of the test file touched one field of one object from 1950 of the pairs. The random programs mix their types a lot, so selective merging finds little to separate there.
Properties
- Sound for type-safe programs. In any run, two references that touch the same location get "may alias".
- Flow-insensitive and context-insensitive. It uses no order of statements and no calling context.
- Cheap and modular. TypeDecl and FieldTypeDecl need only the declarations. SMTypeRefs needs one linear pass over the assignments.
- Coarse for one type. Two references of the same type and field always may alias. To tell apart two lists of the same type, a points-to analysis is needed.
- A filter. Points-to analyses for typed languages often use the types to drop facts that the type rules forbid, which gives both precision and speed.
Variants and improvements
- C and strict aliasing. C is not type-safe, but the standard (C11, 6.5, paragraph 7) lets an object be accessed only through an lvalue of a compatible type, a signed or unsigned variant of it, a qualified version, an aggregate or union that contains such a member, or a character type. A program that breaks the rule has undefined behavior, so a compiler may assume that an
int *and afloat *do not point to the same object. Character types are the exception: achar *may alias anything. GCC and Clang use this rule, and the flag-fno-strict-aliasingturns it off. - Type trees in a compiler. LLVM attaches type descriptors to loads and stores as metadata, in a tree whose root is the character type, and answers queries by the ancestor relation in the tree. Access to a field of a structure carries the structure type and the offset, which gives a form of FieldTypeDecl.
- Combined with points-to analysis. Field sensitivity gives the field test of FieldTypeDecl inside a points-to analysis, and a type filter in Steensgaard's analysis or in Andersen's analysis keeps apart the targets of pointers of unrelated types.
- Class hierarchy analysis. The same subtype sets that TypeDecl uses also give the possible targets of a virtual call in class hierarchy analysis.
When to use it
Use it as the first and cheapest alias analysis in a compiler for a type-safe language, or for C and C++ code that follows the strict aliasing rule. It helps loop-invariant code motion, scalar replacement of aggregates, redundant load elimination and instruction scheduling, which need to know that a store does not change a value in a register. When many references have the same type, add a points-to analysis.
Pitfalls
- Code that breaks the type rules. In C, code that reads a
floatthrough anint *, or that uses a cast to reinterpret memory, has undefined behavior, and type-based alias analysis can turn it into a wrong result. Use a union,memcpy, or a character type for such access, or compile with strict aliasing off. - Forgetting the character types. A C alias analysis that treats
charlike any other type misses the aliases ofmemcpyand of byte-wise code. - Implicit assignments. Selective merging must see every move of a value between types: parameters and return values, array stores, and the values that a library or unknown code writes. A missing merge makes the answer unsound.
- Downcasts. A checked downcast moves a value from type to a subtype and must also merge and ; the toy language of this page has no downcasts.
- Same type, different objects. The analysis cannot tell apart two objects of one type. Do not use it to show that two
nextfields of different lists never alias.
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/.
"""Points-to constraints in the four basic forms, for the pointer analysis pages.
A program is a list of statements. Each statement is a tuple with the same
shape as the pointer instructions of the toy IR (toyir.py):
("addr", p, a) p = &a
("copy", p, q) p = q
("load", p, q) p = *q
("store", p, q) *p = q
Every name is a pointer variable, and every variable is also a memory
location whose address the program may take. A points-to solution is a dict
from each variable to a set of variables. The order of the statements does
not matter to a flow-insensitive analysis.
parse(text) and show(stmts) convert to and from the toy IR notation.
random_program(rng, nvars, nstmts) builds a random program.
least_solution(stmts) is a slow reference: it applies the four rules to
every statement, round after round, until nothing changes.
is_solution(stmts, pts) checks that pts meets every constraint.
concrete_facts(stmts, rng, runs, steps) runs the program concretely, with
the statements in random order, and returns the facts (p, a) that some run
saw: p held the address of a.
"""
import re
_NAME = r"[A-Za-z_][A-Za-z0-9_]*"
_FORMS = [
("addr", re.compile(r"(%s) = &(%s)" % (_NAME, _NAME))),
("load", re.compile(r"(%s) = \*(%s)" % (_NAME, _NAME))),
("store", re.compile(r"\*(%s) = (%s)" % (_NAME, _NAME))),
("copy", re.compile(r"(%s) = (%s)" % (_NAME, _NAME))),
]
def parse(text):
"""Parse lines such as "p = &a", "p = q", "p = *q" and "*p = q".
The k-th "p = alloc" becomes "p = &hk", one location per allocation
site. Blank lines, lines that start with #, block labels and the
terminators jump, br and ret are skipped, so a toy IR program with only
pointer instructions can be read as it is. A flow-insensitive analysis
ignores the order of the statements, so the blocks do not matter."""
stmts = []
sites = 0
for raw in text.splitlines():
line = " ".join(raw.split())
if not line or line.startswith("#") or line.endswith(":"):
continue
if line.split()[0] in ("jump", "br", "ret"):
continue
m = re.fullmatch(r"(%s) = alloc" % _NAME, line)
if m:
sites += 1
stmts.append(("addr", m.group(1), "h%d" % sites))
continue
for kind, rx in _FORMS:
m = rx.fullmatch(line)
if m:
stmts.append((kind, m.group(1), m.group(2)))
break
else:
raise ValueError("not a pointer statement: %r" % raw)
return stmts
def show(stmts):
out = []
for kind, x, y in stmts:
if kind == "addr":
out.append("%s = &%s" % (x, y))
elif kind == "copy":
out.append("%s = %s" % (x, y))
elif kind == "load":
out.append("%s = *%s" % (x, y))
else:
out.append("*%s = %s" % (x, y))
return "\n".join(out)
def variables(stmts):
"""All names, in the order of their first use."""
seen = {}
for _, x, y in stmts:
seen.setdefault(x, None)
seen.setdefault(y, None)
return list(seen)
def random_program(rng, nvars=8, nstmts=30, weights=(3, 4, 2, 2)):
"""A random list of nstmts statements over the names v0 .. v(nvars-1).
weights gives the relative number of addr, copy, load and store forms."""
names = ["v%d" % i for i in range(nvars)]
kinds = ["addr", "copy", "load", "store"]
return [
(rng.choices(kinds, weights)[0], rng.choice(names), rng.choice(names))
for _ in range(nstmts)
]
def least_solution(stmts):
"""The least solution of the inclusion constraints, by plain iteration."""
pts = {v: set() for v in variables(stmts)}
changed = True
while changed:
changed = False
for kind, x, y in stmts:
if kind == "addr":
new = {y}
targets = [x]
elif kind == "copy":
new = pts[y]
targets = [x]
elif kind == "load":
new = set()
for a in pts[y]:
new |= pts[a]
targets = [x]
else:
new = pts[y]
targets = list(pts[x])
for t in targets:
if not new <= pts[t]:
pts[t] |= new
changed = True
return pts
def is_solution(stmts, pts):
"""True if pts satisfies every constraint of stmts."""
for kind, x, y in stmts:
if kind == "addr" and y not in pts[x]:
return False
if kind == "copy" and not pts[y] <= pts[x]:
return False
if kind == "load" and any(not pts[a] <= pts[x] for a in pts[y]):
return False
if kind == "store" and any(not pts[y] <= pts[a] for a in pts[x]):
return False
return True
def concrete_facts(stmts, rng, runs=20, steps=120):
"""Run the program concretely. Each variable holds no value at the start.
A run is a sequence of statements in any order, with repeats, which is the
semantics that a flow-insensitive analysis must cover; every path of a
real control flow graph over these statements is such a sequence. A
statement that reads a variable with no value, or goes through one,
cannot run, so the run picks another. Returns the set of pairs (p, a)
such that p held the address of a at some moment of some run."""
seen = set()
for _ in range(runs):
val = {v: None for v in variables(stmts)}
for _ in range(steps):
kind, x, y = stmts[rng.randrange(len(stmts))]
if kind == "addr":
val[x] = y
dst = x
elif kind == "copy":
if val[y] is None:
continue
val[x] = val[y]
dst = x
elif kind == "load":
if val[y] is None or val[val[y]] is None:
continue
val[x] = val[val[y]]
dst = x
else:
if val[x] is None or val[y] is None:
continue
dst = val[x]
val[dst] = val[y]
seen.add((dst, val[dst]))
return seen
type_based_alias_analysis.py 232 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/type-based-alias-analysis/. The authors are listed in prov/FMJ8XA.jsonl.
"""Type-based alias analysis for a small type-safe language with classes.
A program has a class tree (each class has one parent, the root has none),
fields (each declared in one class, with a declared class as its type),
variables (each with a declared class), and statements in four forms:
("new", p, C) p = new C needs C <= T(p)
("copy", p, q) p = q needs T(q) <= T(p)
("load", p, q, f) p = q.f needs f in T(q), FT(f) <= T(p)
("store", q, f, p) q.f = p needs f in T(q), T(p) <= FT(f)
The memory references are the loads and stores, written q.f. The three
analyses of Diwan, McKinley and Moss answer whether two references may
touch the same field of the same object:
* type_decl: the declared types of the two locations, FT(f1) and FT(f2),
have a common subtype;
* field_type_decl: the fields are the same and the declared types of the
two bases have a common subtype;
* SMTypeRefs (selective merging), used here with fields as in their
SMFieldTypeRefs: the fields are the same and TypeRefs(T(q1)) meets
TypeRefs(T(q2)), where TypeRefs(T) holds the subtypes of T that are in
the same group as T after merging the two types of every assignment
between different types.
run(prog, rng) executes the program with the statements in random order and
reports the pairs of references that touched the same field of the same
object, and the dynamic types that each variable held.
"""
class Program:
def __init__(self, parent, fields, types, stmts):
self.parent = dict(parent) # class -> parent class or None
self.fields = dict(fields) # field -> (declaring class, field type)
self.types = dict(types) # variable -> declared class
self.stmts = list(stmts)
def is_sub(self, c, d):
while c is not None:
if c == d:
return True
c = self.parent[c]
return False
def subtypes(self, t):
return {c for c in self.parent if self.is_sub(c, t)}
def has_field(self, t, f):
return self.is_sub(t, self.fields[f][0])
def field_type(self, f):
return self.fields[f][1]
def check(self):
"""Raise TypeError if a statement breaks the typing rules."""
T = self.types
for s in self.stmts:
kind = s[0]
if kind == "new":
ok = self.is_sub(s[2], T[s[1]])
elif kind == "copy":
ok = self.is_sub(T[s[2]], T[s[1]])
elif kind == "load":
_, p, q, f = s
ok = self.has_field(T[q], f) and self.is_sub(self.field_type(f), T[p])
else:
_, q, f, p = s
ok = self.has_field(T[q], f) and self.is_sub(T[p], self.field_type(f))
if not ok:
raise TypeError("ill-typed statement: %r" % (s,))
def references(self):
"""The memory references: (statement index, base variable, field)."""
out = []
for i, s in enumerate(self.stmts):
if s[0] == "load":
out.append((i, s[2], s[3]))
elif s[0] == "store":
out.append((i, s[1], s[2]))
return out
def type_refs(prog):
"""TypeRefs(T) for each class T, by selective merging."""
group = {c: c for c in prog.parent} # @line L1
def find(c):
while group[c] != c:
group[c] = group[group[c]]
c = group[c]
return c
def union(a, b):
a, b = find(a), find(b)
if a != b:
group[max(a, b)] = min(a, b)
T = prog.types
for s in prog.stmts: # @line L2
kind = s[0]
if kind == "new":
src, dst = s[2], T[s[1]]
elif kind == "copy":
src, dst = T[s[2]], T[s[1]]
elif kind == "load":
src, dst = prog.field_type(s[3]), T[s[1]]
else:
src, dst = T[s[3]], prog.field_type(s[2])
if src != dst:
union(src, dst) # @line L3
return {t: {c for c in prog.subtypes(t) if find(c) == find(t)} # @line L4
for t in prog.parent} # @line L5
def type_decl(prog, r1, r2):
(_, _, f1), (_, _, f2) = r1, r2
return bool(prog.subtypes(prog.field_type(f1)) & prog.subtypes(prog.field_type(f2)))
def field_type_decl(prog, r1, r2):
(_, q1, f1), (_, q2, f2) = r1, r2
if f1 != f2:
return False
return bool(prog.subtypes(prog.types[q1]) & prog.subtypes(prog.types[q2]))
def sm_type_refs(prog, r1, r2, refs=None):
(_, q1, f1), (_, q2, f2) = r1, r2
if f1 != f2: # @line L6
return False
refs = refs if refs is not None else type_refs(prog)
return bool(refs[prog.types[q1]] & refs[prog.types[q2]]) # @line L7
def may_alias_pairs(prog, method):
"""All pairs (i, j), i <= j, of reference sites that method says may
alias. A site may alias itself when it can run on one object twice."""
rs = prog.references()
refs = type_refs(prog) if method is sm_type_refs else None
out = set()
for a in range(len(rs)):
for b in range(a, len(rs)):
if method is sm_type_refs:
hit = method(prog, rs[a], rs[b], refs)
else:
hit = method(prog, rs[a], rs[b])
if hit:
out.add((rs[a][0], rs[b][0]))
return out
def run(prog, rng, runs=20, steps=100):
"""Execute the program with the statements in random order. A statement
that reads a variable or field with no value cannot run. Returns the set
of pairs (i, j), i <= j, of reference sites that touched the same field
of the same object, and the set of pairs (variable, dynamic class)."""
touched_pairs, seen_types = set(), set()
for _ in range(runs):
val = {v: None for v in prog.types}
heap = [] # object id -> (class, {field: object id})
touched = {} # (object id, field) -> set of sites
for _ in range(steps):
i = rng.randrange(len(prog.stmts))
s = prog.stmts[i]
kind = s[0]
if kind == "new":
heap.append((s[2], {}))
val[s[1]] = len(heap) - 1
dst = s[1]
elif kind == "copy":
if val[s[2]] is None:
continue
val[s[1]] = val[s[2]]
dst = s[1]
elif kind == "load":
_, p, q, f = s
if val[q] is None or heap[val[q]][1].get(f) is None:
continue
touched.setdefault((val[q], f), set()).add(i)
val[p] = heap[val[q]][1][f]
dst = p
else:
_, q, f, p = s
if val[q] is None or val[p] is None:
continue
touched.setdefault((val[q], f), set()).add(i)
heap[val[q]][1][f] = val[p]
dst = None
if dst is not None:
seen_types.add((dst, heap[val[dst]][0]))
for sites in touched.values():
for a in sites:
for b in sites:
if a <= b:
touched_pairs.add((a, b))
return touched_pairs, seen_types
HIERARCHY = {"Object": None, "A": "Object", "B": "Object",
"A1": "A", "A2": "A", "B1": "B"}
FIELDS = {"val": ("Object", "Object"), "next": ("A", "A"),
"left": ("A1", "A1"), "link": ("B", "A")}
def random_program(rng, nvars=8, nstmts=30):
"""A random well-typed program over the fixed class tree HIERARCHY and
the fields FIELDS."""
classes = list(HIERARCHY)
types = {"x%d" % i: rng.choice(classes) for i in range(nvars)}
prog = Program(HIERARCHY, FIELDS, types, [])
names = list(types)
fields = list(FIELDS)
while len(prog.stmts) < nstmts:
kind = rng.choice(["new", "new", "copy", "copy", "load", "store", "store"])
p, q = rng.choice(names), rng.choice(names)
if kind == "new":
s = ("new", p, rng.choice(sorted(prog.subtypes(types[p]))))
elif kind == "copy":
s = ("copy", p, q)
elif kind == "load":
s = ("load", p, q, rng.choice(fields))
else:
s = ("store", q, rng.choice(fields), p)
prog.stmts.append(s)
try:
prog.check()
except TypeError:
prog.stmts.pop()
return prog
test_type_based_alias_analysis.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/type-based-alias-analysis/. The authors are listed in prov/FMJ8XA.jsonl.
import random
import ptsgen
from type_based_alias_analysis import (
Program,
field_type_decl,
may_alias_pairs,
random_program,
run,
sm_type_refs,
type_decl,
type_refs,
)
METHODS = [type_decl, field_type_decl, sm_type_refs]
PAGE = Program(
{"Object": None, "A": "Object", "B": "Object", "A1": "A", "A2": "A"},
{"next": ("A", "A"), "val": ("Object", "Object")},
{"x": "A1", "y": "A2", "a": "A", "o": "Object", "t": "A"},
[
("new", "x", "A1"), # 0
("new", "y", "A2"), # 1
("copy", "a", "y"), # 2
("store", "x", "next", "a"), # 3: x.next = a
("store", "y", "next", "a"), # 4: y.next = a
("new", "o", "B"), # 5
("store", "o", "val", "o"), # 6: o.val = o
("load", "t", "a", "next"), # 7: t = a.next
],
)
def test_page_example():
PAGE.check()
refs = type_refs(PAGE)
assert refs["A"] == {"A", "A2"} and refs["A1"] == {"A1"}
assert refs["Object"] == {"Object", "B"}
r = {i: (i, q, f) for i, q, f in PAGE.references()}
other = [(3, 4), (3, 7), (4, 7), (3, 6), (4, 6), (6, 7)]
def answers(method):
return [(i, j) for i, j in other if method(PAGE, r[i], r[j])]
assert answers(type_decl) == other
assert answers(field_type_decl) == [(3, 7), (4, 7)]
assert answers(sm_type_refs) == [(4, 7)]
# The run agrees: y.next and a.next touch one object, as a = y.
touched, _ = run(PAGE, random.Random(1), runs=30, steps=40)
assert (4, 7) in touched and (3, 7) not in touched and (3, 4) not in touched
def rejected(stmt):
try:
Program(PAGE.parent, PAGE.fields, PAGE.types, [stmt]).check()
except TypeError:
return True
return False
def test_ill_typed_programs_are_rejected():
assert rejected(("copy", "x", "a")) # a downcast from A to A1
assert rejected(("load", "t", "o", "next")) # Object has no field next
assert not rejected(("copy", "a", "x")) # an upcast is fine
def test_each_method_refines_the_one_before():
rng = random.Random(7100)
for trial in range(200):
prog = random_program(rng, rng.randint(3, 10), 30)
td, ftd, sm = (may_alias_pairs(prog, m) for m in METHODS)
assert sm <= ftd <= td
def test_sound_against_concrete_runs():
rng = random.Random(7200)
for trial in range(200):
prog = random_program(rng, rng.randint(3, 10), 30)
touched, seen_types = run(prog, rng, runs=15, steps=100)
refs = type_refs(prog)
for m in METHODS:
assert touched <= may_alias_pairs(prog, m), (m.__name__, prog.stmts)
# Every dynamic class that a variable held is in TypeRefs of its type.
for v, c in seen_types:
assert c in refs[prog.types[v]]
def test_runs_do_find_aliases():
rng = random.Random(7300)
found = 0
for trial in range(100):
prog = random_program(rng, 4, 30)
touched, _ = run(prog, rng, runs=10, steps=100)
found += sum(1 for i, j in touched if i != j)
assert found > 100
def to_points_to(prog):
"""The program in the four forms of ptsgen, with one location per
allocation site and one location F_f for each field f, shared by all
objects (a field-based model)."""
out = []
for i, s in enumerate(prog.stmts):
if s[0] == "new":
out.append(("addr", s[1], "site%d" % i))
elif s[0] == "copy":
out.append(("copy", s[1], s[2]))
elif s[0] == "load":
out.append(("copy", s[1], "F_" + s[3]))
else:
out.append(("copy", "F_" + s[2], s[3]))
return out
def test_points_to_analysis_is_at_least_as_precise():
# If Andersen's analysis says that the bases of two references with the
# same field may point to one object, SMTypeRefs says so too.
rng = random.Random(7400)
for trial in range(200):
prog = random_program(rng, rng.randint(3, 10), 30)
pts = ptsgen.least_solution(to_points_to(prog))
sm = may_alias_pairs(prog, sm_type_refs)
rs = prog.references()
for a in range(len(rs)):
for b in range(a, len(rs)):
(i, q1, f1), (j, q2, f2) = rs[a], rs[b]
if f1 == f2 and pts.get(q1, set()) & pts.get(q2, set()):
assert (i, j) in sm
History
Type information was used for alias questions in compilers for typed languages before 1998, but Diwan, McKinley and Moss (1998) gave the first careful study: three forms of the analysis, with their soundness argument for Modula-3, and their effect on redundant load elimination, measured against a limit. The C89 and later C standards had the rule about the types through which an object may be accessed, and GCC and other compilers began to use it for alias analysis around the same time, which made the strict aliasing rule widely known to C programmers. LLVM later made type-based alias information part of its intermediate representation, as metadata that the front end attaches to each memory access.
References
- Amer Diwan, Kathryn S. McKinley and J. Eliot B. Moss, Type-based alias analysis, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '98), 106 to 117, 1998, whole paper (TypeDecl, FieldTypeDecl, the selective merging of SMTypeRefs, and the evaluation with redundant load elimination on Modula-3 programs)
- ISO/IEC 9899:2011, Programming languages, C, 6.5, paragraph 7 (the types through which the stored value of an object may be accessed, the rule that C compilers use for type-based alias analysis)
- Yannis Smaragdakis and George Balatsouras, Pointer Analysis, Foundations and Trends in Programming Languages 2(1), 1 to 69, 2015, the discussion of type information as a filter on points-to facts
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 FMJ8XA Edit this page History Report an error Markdown