Algorithm Search⌘K

Algorithmadvanced

Dynamic slicing

Also called Korel-Laski dynamic slice, Agrawal-Horgan dynamic slicing.

Finds the statements that affected a value in one execution, from a trace of the dependences that actually occurred.

Time
O(T n) worst
Space
O((v + b) n) extra
Where
T = the number of statement instances the run executes; b = the number of blocks; n = the number of statements; v = the number of names
Properties
deterministicnot executable resultonlineiterative
Origin
Bogdan Korel, Janusz Laski, 1988

Dynamic slicing solves the program slicing problem for one run instead of all runs. The criterion names an input, a statement, which visit of that statement, and some variables. The answer is the set of statements whose executions in that run affected those values, through the data and control dependences that the run really had. Korel and Laski (1988) defined it for debugging. A static slice must cover every input and every path, so it keeps statements that this run never used; a dynamic slice drops them and is often much smaller. The price is that a dynamic slice holds for its one input only.

In plain words

Run the program once and watch. Each time a statement runs, write down which earlier steps it used: the step that last set each variable it reads, and the test that decided it would run at all. Each variable keeps a list of the statements its current value came from. When a statement runs, its list is the union of the lists of what it read, plus itself. When the run reaches the place you care about, the lists of the variables you care about are the answer. A statement that ran a thousand times but never fed those values is not in the answer. A statement that did not run at all is never in it.

The problem

Programs are in the toy IR, with x = k, x = y, x = a op b, jump, br and ret, and every block reaches a ret. A statement is an instruction or a block terminator. A dynamic criterion is ⟨I,p,q,V⟩\langle I, p, q, V \rangle: an input II, a statement pp, a count qq, and names VV. It asks for the values of VV just before the qq-th time the run on II reaches pp.

The run is a sequence of instances: executions of statements. Instance kk has two kinds of parents.

  • Dynamic data dependence. For each name yy that kk reads, the last earlier instance that wrote yy.
  • Dynamic control dependence. The most recent earlier branch instance jj, in a block XX, such that the run has not entered the block ipdom(X)\mathrm{ipdom}(X) since jj. The immediate post-dominator of XX is where the two arms of the branch join, so kk is still inside the region that jj decided.

The dynamic slice is the set of statements of all instances that reach the criterion by parent links. This is the slice of Agrawal and Horgan (1990), a set of statements. Korel and Laski (1988) also asked the slice to be a program that runs on II along the same path, which can force more statements in.

The algorithm

The method runs forward and keeps no trace. DS[x]DS[x] is the set of statements that the current value of xx depends on, the statement that wrote it included. OO is a list of the open branch instances, at most one per block, each with its own set.

  1. DYNAMIC-SLICE(P, I, p, q, V)
  2. 1DS[x] <- empty for every name x; O <- empty list; start the run of P on I
  3. 2for each statement instance s, in the order of the run do
  4. 3C <- the set of the last entry of O, or empty if O is empty
  5. 4if s is at p and the run reaches p for the q-th time then
  6. 5return C ∪ (the union of DS[x] over x in V)
  7. 6T <- {s} ∪ C ∪ (the union of DS[y] over the names y that s reads)
  8. 7if s writes x then DS[x] <- T
  9. 8if s is the branch of block X then remove the entry of X from O; append (X, ipdom(X), T) to O
  10. 9if s ends a block and the run goes to block Y then remove from O each entry whose ipdom is Y
  11. return none, because the run stopped before the q-th visit to p

Line L3 finds the dynamic control parent: the last open entry. Lines L8 and L9 keep the list right. An entry closes when the run enters its ipdom block. An older instance of the same block closes together with the newer one, so it can never again be the latest open entry, and line L8 drops it. This is the stack of Xin and Zhang (2007), and it keeps OO no longer than the number of blocks.

In the implementation, dynamic_slice is lines L1 to L9 and runs the program itself. The parameters start with an empty set, since no statement wrote them.

Example

The program counts ii from 0 to n−1n - 1 and adds ii to ss only when i=ki = k. The variable pp is never used for ss.

# params: n, k
B0:
  i = 0
  s = 0
  p = 1
  jump B1
B1:
  c = i < n
  br c B2 B5
B2:
  d = i == k
  br d B3 B4
B3:
  s = s + i
  jump B4
B4:
  p = p * 2
  i = i + 1
  jump B1
B5:
  ret s

The criterion is ss just before ret s, at its first visit.

Static slice. Every definition of ss can reach ret s, so the static slice is the 8 statements i = 0, s = 0, c = i < n, br c, d = i == k, br d, s = s + i and i = i + 1.

Input n=3n = 3, k=5k = 5. The loop runs 3 times and s = s + i never runs. The sets as the run goes:

instance what happens
i = 0 DS[i]={DS[i] = \{i = 0}\}
s = 0 DS[s]={DS[s] = \{s = 0}\}
c = i < n DS[c]={DS[c] = \{c = i < n, i = 0}\}
br c to B2 open entry (B1, ipdom B5) with the set DS[c]∪{DS[c] \cup \{br c}\}
d = i == k gets the open set, DS[i]DS[i] and itself
br d to B4 its entry (B2, ipdom B4) closes at once, because the run enters B4
i = i + 1 DS[i]DS[i] now also holds br c and c = i < n
two more trips, then br c to B5 entering B5 closes the B1 entry

At ret s the open list is empty and DS[s]DS[s] is still {\{s = 0}\}. The dynamic slice is the single statement s = 0, against 8 in the static slice. The loop ran, but nothing in it reached ss.

Input n=3n = 3, k=1k = 1. Now s = s + i runs once, at i=1i = 1. Its set holds s = 0, the set of ii (written by i = i + 1 in the first trip, which holds i = 0), and the set of the open br d, which holds d = i == k, the open br c and c = i < n. The dynamic slice is all 8 statements of the static slice.

For one input only. The slice {\{s = 0}\} of the first input is wrong for the second: on n=3n = 3, k=1k = 1 the value of ss comes from s = s + i, which is not in it.

Correctness

The full proof is in the proof file. Its steps:

  1. The open list. Before each instance, the list holds the open branch instances that are the latest of their block, in time order. An older instance of a block is open only while the newer one is, so the last entry is the dynamic control parent.
  2. The sets. Before each instance, DS[x]DS[x] is the set of statements reachable by parent links from the last writer of xx. The step for line L6 is the recursion: the closure of an instance is the instance plus the closures of its parents.
  3. The answer. Line L5 returns the union of the closures of the parents of the criterion instance, which is the dynamic slice by definition.
  4. The slice holds for its input. Run again on the same input, force every branch the way it went, and let every statement outside the slice write any value at all. The values of VV at the criterion do not change. The proof is induction over the instances in the closure: each one is a statement of the slice, and it reads values written by instances in the closure.
Proof: The forward method returns the closure of the dynamic dependence graph, and that closure holds for its inputfull

Setting. Fix a program, an input and a criterion (p,q,V)(p, q, V). The run is a finite sequence of statement instances 1,2,…,T1, 2, \ldots, T (it stops at a ret, a trap or the end of the fuel). Instance kk is an execution of statement sks_k, in a visit to block bkb_k. Let tt be the instance at which the run reaches pp for the qq-th time, if it exists.

For an instance kk and a name xx, let w(k,x)w(k, x) be the last instance before kk that writes xx, or none. For an instance kk, let c(k)c(k) be the latest branch instance j<kj < k such that the block ipdom(bj)\mathrm{ipdom}(b_j) is not entered by the run after instance jj, up to and including the visit of kk; or none. The parents of kk are w(k,y)w(k, y) for each name yy that sks_k reads, and c(k)c(k). The roots are w(t,x)w(t, x) for x∈Vx \in V, and c(t)c(t). Let KK be the set of instances reachable from the roots through parents, roots included. The dynamic slice is {sk:k∈K}\{ s_k : k \in K \}. For an instance kk, let K(k)K(k) be the set of instances reachable from kk through parents, kk included, and σ(k)={sj:j∈K(k)}\sigma(k) = \{ s_j : j \in K(k) \}.

Since K(k)={k}∪⋃m parent of kK(m)K(k) = \{k\} \cup \bigcup_{m \text{ parent of } k} K(m), we have σ(k)={sk}∪⋃mσ(m)\sigma(k) = \{s_k\} \cup \bigcup_{m} \sigma(m) over the parents mm of kk.

1. The open list

Lemma 1. Let j1<j2j_1 < j_2 be two branch instances of the same block XX. At every point after j2j_2, if j1j_1 is open (its ipdom block not entered since j1j_1), then j2j_2 is open too.

Proof. Both close when the run enters ipdom(X)\mathrm{ipdom}(X), and j2j_2 is later, so every entry of that block after j2j_2 is also after j1j_1. □\square

So at any point, the latest open branch instance is never an older instance of a block that has a later open instance. Line L8 removes exactly those older instances, and line L9 removes the instances that close when the run enters the next block.

Lemma 2. Before instance kk runs, the list holds, in time order, the open branch instances that are the latest instance of their block, each with the set σ(j)\sigma(j). Its last entry is c(k)c(k), or the list is empty and c(k)c(k) is none.

Proof. By induction on kk. At the start the list is empty and no branch has run. A non-branch instance changes nothing. A jump changes only the block; line L9 then drops the entries whose ipdom is the new block, and those are exactly the instances that close. For a branch instance jj of block XX, line L8 drops the older entry of XX, if there is one, and appends jj with the set TT of line L6, which is σ(j)\sigma(j) by Lemma 3 below, applied at jj; line L9 then closes entries as for a jump, jj included if its successor is its ipdom block. The list is in time order because entries are appended. Every open instance that is not on the list has a later open instance of its block, by Lemma 1, so the latest open instance is on the list and is its last entry. That is c(k)c(k) by definition. □\square

2. The sets per name

Lemma 3. Before instance kk runs, for every name xx: DS[x]=σ(w(k,x))DS[x] = \sigma(w(k, x)) if w(k,x)w(k, x) exists, and DS[x]=∅DS[x] = \emptyset if xx is a parameter not yet written. At line L6 for instance kk, T=σ(k)T = \sigma(k).

Proof. By induction on kk, together with Lemma 2. Line L1 gives the case k=1k = 1. At instance kk, line L3 sets CC to σ(c(k))\sigma(c(k)) by Lemma 2, or to ∅\emptyset. Line L6 sets T={sk}∪C∪⋃yDS[y]T = \{s_k\} \cup C \cup \bigcup_y DS[y] over the names yy that sks_k reads. By the induction hypothesis DS[y]=σ(w(k,y))DS[y] = \sigma(w(k, y)), or ∅\emptyset for a parameter not yet written, which has no parent instance. So T=σ(k)T = \sigma(k) by the recursion above. If sks_k writes xx, line L7 sets DS[x]=σ(k)DS[x] = \sigma(k), and w(k+1,x)=kw(k + 1, x) = k. The other names keep their last writer and their set. □\square

Theorem 1 (correctness). If the run reaches pp for the qq-th time, line L5 returns the dynamic slice. Otherwise the method returns none.

Proof. Lines L3 to L5 run at instance tt before it executes. By Lemmas 2 and 3, the returned set is σ(c(t))∪⋃x∈Vσ(w(t,x))\sigma(c(t)) \cup \bigcup_{x \in V} \sigma(w(t, x)), which is {sk:k∈K}\{ s_k : k \in K \}. If the run stops first, the loop ends without line L5. □\square

Termination and cost. The loop runs once per instance, so at most TT times. Let nn be the number of statements and bb the number of blocks. Every set holds statements, so it has at most nn elements, and a statement of the toy IR reads at most two names. So line L6 costs O(n)O(n). The list has at most one entry per block, so lines L8 and L9 cost O(b)O(b), and b≤nb \le n. The total time is O(Tn)O(T n). The method keeps one set per name and one per list entry, so the extra space is O((v+b)n)O((v + b) n) for vv names. It does not store the run.

3. What the slice means

Theorem 2 (the slice holds for its input). Run the program on the same input again, but make every branch instance go the way it went in the first run, and let every instance of a statement outside the slice write any value it likes. Then at instance tt the names of VV have the same values as in the first run.

Proof. The forced branches give the same sequence of instances, so ww is the same function in both runs. We show by induction on kk that every k∈Kk \in K that writes a name writes the same value in both runs. Since sks_k is in the slice, it computes its result from the values of the names it reads, as in the first run. Each such value was written by w(k,y)w(k, y), a parent of kk and so in KK, and earlier than kk; by induction it is the same, or it is the parameter value, which is the same. At tt, the value of x∈Vx \in V comes from w(t,x)w(t, x), a root, so it is the same. □\square

The proof needs the same input and the same path. For another input the parents are different instances, and a statement that is not in the slice can then write a value that reaches VV. For the same input, if a branch outside the slice goes the other way, a statement that never ran in the first run can overwrite a name that the slice reads. So the theorem does not give an executable program: to get one, Korel and Laski add statements, and their slices can be larger.

Complexity

Proved, for the method here. The loop runs once per instance, TT times. Each set holds at most nn statements and a statement reads at most two names, so line L6 costs O(n)O(n). The open list has at most one entry per block, so lines L8 and L9 cost O(b)O(b) with b≤nb \le n. The time is O(Tn)O(T n). The space is one set per name and one per open entry, O((v+b)n)O((v + b) n), independent of the length of the run.

Compared. The dynamic dependence graph of Agrawal and Horgan has one node per instance, so it takes O(T)O(T) space, and a slice is a backward search in it, linear in its size; once built, it answers any criterion of the run. The forward method answers one criterion, or all names at once, without storing the run. Zhang, Gupta and Zhang (2004) keep the sets as shared binary decision diagrams to cut the cost of the unions.

Properties

  • Holds for one input only. The guarantee is for the input of the criterion and its path. For another input the dependences are different instances, and the slice can miss statements.
  • Inside the static slice. Each dynamic dependence is also a static one, so the dynamic slice is a subset of the PDG slice for the same point and names. It is often much smaller, as in the example.
  • Exact dependences. The run knows which branch went which way and which definition was the last one. With pointers and arrays, it also knows the exact address read, which static analysis can only approximate.
  • Not a program. The result is a set of statements. If a statement of the slice runs several times, other instances of it may read values from statements outside the slice and change the path. Korel and Laski add statements to make the slice run; their slices can be larger.
  • Not minimal. A dependence counts even when it does not change the value, for example x = y - y depends on y.

Variants and improvements

  • Korel and Laski (1988). The slice must be a program that, run on the same input, follows the projection of the original path. If one instance of a statement is needed, all are, and more statements join to keep the path.
  • Agrawal and Horgan (1990). Four methods: mark the nodes of the static graph that ran; mark the edges that ran (both give slices that can be too large); build the full dynamic dependence graph, one node per instance; and the reduced dynamic dependence graph, which adds a node only when a new slice set appears.
  • Forward methods. Korel and Yalamanchili (1994) compute executable slices during the run. Zhang, Gupta and Zhang (2004) keep one set per name, as here, stored in binary decision diagrams.
  • Relevant slicing. Adds statements that did not run but could have changed the value had a branch gone the other way. This catches bugs of omission, such as a missing assignment in the arm that was skipped.
  • Interprocedural runs. Calls and returns need one control stack per frame. Xin and Zhang (2007) handle this online, and irregular control flow too.
  • Between static and dynamic. Conditioned slicing fixes a predicate on the inputs instead of one input.

When to use it

Use it to debug one failing run: start from the wrong value and read only the statements that produced it. It also serves fault localization over test suites, explaining a value seen in a log, and cutting down a run before delta debugging. When the slice must hold for all inputs, as for program understanding or refactoring, use a static slice. To follow untrusted data forward through runs, use taint analysis instead. When the cost of tracing is too high, a static slice of the failing path is a cheaper middle ground.

Pitfalls

  • Reusing a slice for another input. The slice of one input says nothing about other inputs. In the example, the slice of n=3n = 3, k=5k = 5 is one statement, and it is wrong for k=1k = 1.
  • Taking the most recent branch as the control parent. A branch whose arms have joined no longer controls anything. Without the ipdom check, every statement after an if depends on it.
  • Keeping old instances of a loop test on the control stack. Without line L8, every trip of a loop pushes one more entry and the stack grows with the run.
  • Expecting the set to run. A statement in the slice can run again with inputs that the slice does not compute and take another path. For a runnable slice, use the method of Korel and Laski.
  • Missing omission bugs. A statement that did not run is never in the slice, even when the bug is that it did not run. Relevant slicing addresses this.
  • Storing the whole trace. It grows with the run. Forward methods or compact graphs keep memory bounded by the program instead.

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.

dynamic_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-slicing/. The authors are listed in prov/1V18D7.jsonl.
"""Dynamic slicing on the toy IR, computed forward while the program runs.

A statement is a pair (label, i): instruction i of block label, or the
terminator of the block when i == len(instrs). A dynamic slicing criterion
is (label, i, q, V) together with an input: the values of the names in V
just before the q-th time the run on that input reaches statement
(label, i).

During the run, DS[x] is the set of statements that the current value of x
depends on, the statement that wrote it included. An open branch instance
keeps the same kind of set. A statement instance depends on the last write
of each name it reads (dynamic data dependence) and on the most recent
branch instance whose immediate post-dominator block has not been entered
since that branch ran (dynamic control dependence).

The programs use only x = k, x = y and x = a op b, with the terminators
jump, br and ret, and every block must reach a ret.
"""

import toyir

EXIT = "<exit>"


def statements(prog):
    return [(lab, i) for lab, b in prog.blocks.items() for i in range(len(b.instrs) + 1)]


def DEF(prog, node):
    lab, i = node
    b = prog.blocks[lab]
    if i == len(b.instrs):
        return set()
    ins = b.instrs[i]
    if ins[0] not in ("const", "copy", "op"):
        raise ValueError("unsupported instruction: %r" % (ins,))
    return {ins[1]}


def REF(prog, node):
    lab, i = node
    b = prog.blocks[lab]
    if i == len(b.instrs):
        return set(toyir.term_uses(b.term))
    return set(toyir.uses(b.instrs[i]))


def ipdom(prog):
    """Immediate post-dominator of each block, with a virtual EXIT after
    every ret."""
    labels = list(prog.blocks)
    succ = {lab: (toyir.succs(prog, lab) or [EXIT]) for lab in labels}
    full = set(labels) | {EXIT}
    pdom = {lab: set(full) for lab in labels}
    pdom[EXIT] = {EXIT}
    changed = True
    while changed:
        changed = False
        for lab in reversed(labels):
            new = {lab} | set.intersection(*(pdom[s] for s in succ[lab]))
            if new != pdom[lab]:
                pdom[lab] = new
                changed = True
    if any(EXIT not in pdom[lab] for lab in labels):
        raise ValueError("every block must reach a ret")
    return {lab: max(pdom[lab] - {lab}, key=lambda x: len(pdom[x])) for lab in labels}


def _value(env, a):
    return a if isinstance(a, int) else env[a]


def dynamic_slice(prog, args, crit, fuel=10000, ip=None):
    """The dynamic slice for criterion crit = (label, i, q, V) on the run of
    prog on args: a set of statements. Returns None if the run stops (ret,
    trap or no fuel left) before it reaches (label, i) for the q-th time."""
    plab, pi, q, V = crit
    if ip is None:
        ip = ipdom(prog)
    env = dict(zip(prog.params, args))
    empty = frozenset()
    DS = {x: empty for x in prog.params}  # @line L1
    open_br = []  # (block, its ipdom, slice of the branch instance)
    seen = 0
    lab = prog.entry
    while True:
        b = prog.blocks[lab]
        n = len(b.instrs)
        for i in range(n + 1):  # @line L2
            fuel -= 1
            if fuel < 0:
                return None
            C = open_br[-1][2] if open_br else empty  # @line L3
            if (lab, i) == (plab, pi):
                seen += 1
                if seen == q:  # @line L4
                    return set(C.union(*(DS.get(x, empty) for x in V)))  # @line L5
            node = (lab, i)
            T = C.union(*(DS[y] for y in REF(prog, node))) | {node}  # @line L6
            if i < n:
                ins = b.instrs[i]
                if ins[0] == "const":
                    v = ins[2]
                elif ins[0] == "copy":
                    v = _value(env, ins[2])
                elif ins[0] == "op":
                    try:
                        v = toyir._binop(ins[2], _value(env, ins[3]), _value(env, ins[4]))
                    except toyir._Trap:
                        return None
                else:
                    raise ValueError("unsupported instruction: %r" % (ins,))
                env[ins[1]] = v
                DS[ins[1]] = T  # @line L7
                continue
            t = b.term
            if t[0] == "ret":
                return None
            if t[0] == "br":
                nxt = t[2] if _value(env, t[1]) != 0 else t[3]
                open_br = [e for e in open_br if e[0] != lab]  # @line L8
                open_br.append((lab, ip[lab], T))
            else:
                nxt = t[1]
            open_br = [e for e in open_br if e[1] != nxt]  # @line L9
            lab = nxt
toyir.py 602 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/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
test_dynamic_slicing.py 336 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-slicing/. The authors are listed in prov/1V18D7.jsonl.
import random

import toyir
from dynamic_slicing import DEF, EXIT, REF, dynamic_slice, ipdom, statements

LOOP = """
# params: n, k
B0:
  i = 0
  s = 0
  p = 1
  jump B1
B1:
  c = i < n
  br c B2 B5
B2:
  d = i == k
  br d B3 B4
B3:
  s = s + i
  jump B4
B4:
  p = p * 2
  i = i + 1
  jump B1
B5:
  ret s
"""


# ------------------------------------------------- an independent recorder


def _eval(ins, env):
    def val(a):
        return a if isinstance(a, int) else env[a]

    if ins[0] == "const":
        return ins[2]
    if ins[0] == "copy":
        return val(ins[2])
    return toyir._binop(ins[2], val(ins[3]), val(ins[4]))


def _record(prog, args, fuel=10000):
    """Run prog and return the list of blocks it enters, in order, and the
    statement instances as (statement, index of its block visit)."""
    env = dict(zip(prog.params, args))
    blocks = []
    trace = []
    lab = prog.entry
    while fuel > 0:
        blocks.append(lab)
        b = prog.blocks[lab]
        for i, ins in enumerate(b.instrs):
            fuel -= 1
            trace.append(((lab, i), len(blocks) - 1))
            try:
                env[ins[1]] = _eval(ins, env)
            except toyir._Trap:
                return blocks, trace, "trap"
        fuel -= 1
        trace.append(((lab, len(b.instrs)), len(blocks) - 1))
        t = b.term
        if t[0] == "ret":
            return blocks, trace, "ret"
        if t[0] == "br":
            c = t[1] if isinstance(t[1], int) else env[t[1]]
            lab = t[2] if c != 0 else t[3]
        else:
            lab = t[1]
    return blocks, trace, "fuel"


def _reference(prog, args, crit):
    """Closure over the full graph of statement instances, built the naive
    way: for each instance, scan back for the last write of each name it
    reads and for the most recent branch instance whose ipdom block was not
    entered after it."""
    plab, pi, q, V = crit
    ip = ipdom(prog)
    blocks, trace, _ = _record(prog, args)
    occ = [k for k, (node, _) in enumerate(trace) if node == (plab, pi)]
    if len(occ) < q:
        return None
    target = occ[q - 1]

    def last_write(k, x):
        for j in range(k - 1, -1, -1):
            if x in DEF(prog, trace[j][0]):
                return j
        return None

    def ctrl(k):
        visit = trace[k][1]
        for j in range(k - 1, -1, -1):
            node, vj = trace[j]
            if node[1] == len(prog.blocks[node[0]].instrs) and prog.blocks[node[0]].term[0] == "br":
                if ip[node[0]] not in blocks[vj + 1 : visit + 1]:
                    return j
        return None

    def parents(k, names):
        out = {last_write(k, x) for x in names} | {ctrl(k)}
        return out - {None}

    roots = parents(target, V)
    seen = set(roots)
    stack = list(roots)
    while stack:
        k = stack.pop()
        for j in parents(k, REF(prog, trace[k][0])):
            if j not in seen:
                seen.add(j)
                stack.append(j)
    return {trace[k][0] for k in seen}


# --------------------------------------------------- an independent static slice


def _succ_stmts(prog, node):
    lab, i = node
    if i < len(prog.blocks[lab].instrs):
        return [(lab, i + 1)]
    return [(s, 0) for s in toyir.succs(prog, lab)]


def _postdominates(prog, y, x):
    """Every path from block x to the exit passes block y."""
    if x == y:
        return True
    seen = {x}
    stack = [x]
    while stack:
        a = stack.pop()
        nxt = toyir.succs(prog, a)
        if not nxt:
            return False
        for s in nxt:
            if s != y and s not in seen:
                seen.add(s)
                stack.append(s)
    return True


def _static_slice(prog, crit):
    plab, pi, _, V = crit

    def data_parents(n, names):
        out = set()
        for d in statements(prog):
            for x in DEF(prog, d) & names:
                seen = set()
                stack = list(_succ_stmts(prog, d))
                while stack:
                    m = stack.pop()
                    if m in seen:
                        continue
                    seen.add(m)
                    if m == n:
                        out.add(d)
                        break
                    if x not in DEF(prog, m):
                        stack.extend(_succ_stmts(prog, m))
        return out

    def control_parents(n):
        y = n[0]
        out = set()
        for x, b in prog.blocks.items():
            if b.term[0] != "br":
                continue
            strict = y != x and _postdominates(prog, y, x)
            if not strict and any(_postdominates(prog, y, s) for s in toyir.succs(prog, x)):
                out.add((x, len(b.instrs)))
        return out

    start = data_parents((plab, pi), set(V)) | control_parents((plab, pi))
    S = set(start)
    stack = list(start)
    while stack:
        n = stack.pop()
        for m in data_parents(n, REF(prog, n)) | control_parents(n):
            if m not in S:
                S.add(m)
                stack.append(m)
    return S


# ------------------------------------------------------- perturbed reruns


def _values_at(prog, args, crit, keep=None, rng=None):
    """Walk the blocks of the run on args, in the same order, and return the
    values of V at the criterion. If keep is given, every instruction outside
    keep writes a random value instead of its own, and every branch goes the
    way it went in the real run."""
    plab, pi, q, V = crit
    blocks, _, _ = _record(prog, args)
    env = dict(zip(prog.params, args))
    seen = 0
    for lab in blocks:
        b = prog.blocks[lab]
        for i in range(len(b.instrs) + 1):
            if (lab, i) == (plab, pi):
                seen += 1
                if seen == q:
                    return {x: env[x] for x in V if x in env}
            if i == len(b.instrs):
                break
            ins = b.instrs[i]
            if keep is not None and (lab, i) not in keep:
                env[ins[1]] = rng.randint(-50, 50)
                continue
            try:
                env[ins[1]] = _eval(ins, env)
            except toyir._Trap:
                # The real run did not trap here, so this instance read a
                # random value and is not one the criterion depends on.
                env[ins[1]] = rng.randint(-50, 50)
    return None


def _random_criterion(rng, prog):
    nodes = statements(prog)
    lab, i = rng.choice(nodes)
    names = sorted({v for n in nodes for v in DEF(prog, n)} | set(prog.params))
    q = rng.randint(1, 3)
    return (lab, i, q, set(rng.sample(names, rng.randint(1, min(2, len(names))))))


def _programs(seed, count):
    rng = random.Random(seed)
    for trial in range(count):
        prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(2, 8), trial % 2 == 0)
        yield rng, prog


# ----------------------------------------------------------------- tests


def test_page_example():
    prog = toyir.parse(LOOP)
    crit = ("B5", 0, 1, {"s"})
    static = {("B0", 0), ("B0", 1), ("B1", 0), ("B1", 1), ("B2", 0), ("B2", 1), ("B3", 0), ("B4", 1)}
    assert _static_slice(prog, crit) == static
    assert toyir.run(prog, [3, 5]) == ("ret", 0)
    assert dynamic_slice(prog, [3, 5], crit) == {("B0", 1)}
    assert toyir.run(prog, [3, 1]) == ("ret", 1)
    assert dynamic_slice(prog, [3, 1], crit) == static
    assert dynamic_slice(prog, [0, 0], crit) == {("B0", 1)}
    # The test of i == k in the second turn of the loop, for input (3, 1).
    assert dynamic_slice(prog, [3, 1], ("B2", 1, 2, {"d"})) =={("B0", 0), ("B1", 0), ("B1", 1), ("B2", 0), ("B4", 1)}
    # The run reaches B3 only once.
    assert dynamic_slice(prog, [3, 1], ("B3", 0, 2, {"s"})) is None


def test_ipdom_matches_definition():
    for rng, prog in _programs(1, 200):
        ip = ipdom(prog)
        for x in prog.blocks:
            strict = [y for y in prog.blocks if y != x and _postdominates(prog, y, x)]
            if not strict:
                assert ip[x] == EXIT
            else:
                assert ip[x] in strict
                assert all(_postdominates(prog, y, ip[x]) for y in strict)


def test_matches_instance_graph():
    found = 0
    for rng, prog in _programs(2, 300):
        for _ in range(4):
            crit = _random_criterion(rng, prog)
            args = [rng.randint(-5, 9), rng.randint(-5, 9)]
            got = dynamic_slice(prog, args, crit)
            want = _reference(prog, args, crit)
            if want is None:
                # The reference stops at the end of the run; a trap ends it too.
                assert got is None
            else:
                assert got == want
                found += 1
    assert found > 350


def test_slice_holds_for_its_input():
    checked = broken = 0
    for rng, prog in _programs(3, 300):
        for _ in range(3):
            crit = _random_criterion(rng, prog)
            args = [rng.randint(-5, 9), rng.randint(-5, 9)]
            S = dynamic_slice(prog, args, crit)
            if S is None:
                continue
            want = _values_at(prog, args, crit)
            for _ in range(5):
                assert _values_at(prog, args, crit, S, rng) == want
            checked += 1
            # The test can fail: without one assignment of the slice, the
            # values often change.
            assigns = sorted(n for n in S if DEF(prog, n))
            if assigns:
                fewer = S - {rng.choice(assigns)}
                broken += any(_values_at(prog, args, crit, fewer, rng) != want for _ in range(5))
    assert checked > 200
    assert broken > 100


def test_slice_is_inside_static_slice_and_often_smaller():
    smaller = 0
    for rng, prog in _programs(4, 250):
        crit = _random_criterion(rng, prog)
        static = _static_slice(prog, crit)
        for _ in range(4):
            args = [rng.randint(-5, 9), rng.randint(-5, 9)]
            S = dynamic_slice(prog, args, crit)
            if S is None:
                continue
            assert S <= static
            smaller += S < static
    assert smaller > 60


def test_slice_does_not_hold_for_another_input():
    prog = toyir.parse(LOOP)
    crit = ("B5", 0, 1, {"s"})
    S = dynamic_slice(prog, [3, 5], crit)
    rng = random.Random(6)
    want = _values_at(prog, [3, 1], crit)
    assert want == {"s": 1}
    got = [_values_at(prog, [3, 1], crit, S, rng) for _ in range(10)]
    assert any(g != want for g in got)

History

Weiser's slices (1979 to 1984) were static. Korel and Laski (1988) defined the dynamic slice in Information Processing Letters, for debugging, as a program that keeps the behavior of one run. Agrawal and Horgan (PLDI 1990) recast it as the statements reached in dependence graphs of the run, compared four ways to compute it, and introduced the reduced dynamic dependence graph. Korel and Yalamanchili (1994) computed slices forward during the run. Tip's survey (1995) compared the definitions. Zhang, Gupta and Zhang made forward slicing practical on large runs in 2004, with binary decision diagrams, and Xin and Zhang (2007) gave an online method for dynamic control dependence that also covers calls and irregular control flow.

References

  1. Bogdan Korel and Janusz Laski, Dynamic program slicing, Information Processing Letters 29(3), 1988, pages 155-163, the dynamic slicing criterion (input, statement occurrence, variables) and slices that must run along the projected path
  2. Hiralal Agrawal and Joseph R. Horgan, Dynamic program slicing, Proceedings of the ACM SIGPLAN 1990 Conference on Programming Language Design and Implementation, ACM SIGPLAN Notices 25(6), 1990, pages 246-256, four methods, from marking the static graph to the dynamic dependence graph and its reduced form
  3. Bogdan Korel and Satish Yalamanchili, Forward computation of dynamic program slices, Proceedings of the 1994 ACM SIGSOFT International Symposium on Software Testing and Analysis (ISSTA '94), 1994, pages 66-79, computing executable dynamic slices during the run, without keeping the trace
  4. Xiangyu Zhang, Rajiv Gupta and Youtao Zhang, Efficient forward computation of dynamic slices using reduced ordered binary decision diagrams, Proceedings of the 26th International Conference on Software Engineering (ICSE 2004), pages 502-511, one slice set per name kept during the run, stored as shared BDDs
  5. Bin Xin and Xiangyu Zhang, Efficient online detection of dynamic control dependence, Proceedings of the 2007 International Symposium on Software Testing and Analysis (ISSTA '07), pages 185-195, dynamic control dependence found online with a stack keyed by immediate post-dominators
  6. Frank Tip, A survey of program slicing techniques, Journal of Programming Languages 3(3), 1995, pages 121-189, the section on dynamic slicing, which compares the executable slices of Korel and Laski with the graph methods of Agrawal and Horgan

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/1V18D7/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