Algorithm Search⌘K

Algorithmadvanced

Control flow structuring

Also called decompiler structuring, structural analysis for decompilation.

Turns the control flow graph of a binary function into structured if, while and switch statements, with as few gotos as possible.

Time
O(n^2) worst · average · best
Space
O(n + m) extra
Where
m = the number of edges between them; n = the number of reachable basic blocks
Properties
deterministicnot duplicates codenot goto optimalsemantics preserving
Origin
Cristina Cifuentes, 1994

Control flow structuring is the step of a decompiler that turns a control flow graph back into the statements of a structured language: sequences, if and if-else statements, and loops. The input usually comes from a disassembler that has found the basic blocks of a function and the jumps between them. The output is an abstract syntax tree with the same executions as the graph. When part of the graph matches no structured statement, a goto is used for it. This page shows the classic method, schema reduction. It finds a small piece of the graph that matches a known form, such as an if-then, replaces it with one node that holds the statement, and repeats. When no form matches, one edge becomes a goto and the reduction goes on.

In plain words

A compiled function is a set of boxes with arrows between them. Each box holds some plain statements. An arrow says where the program goes next, and a box with two arrows chooses one by a condition. People read code better as "if this, do that, then go on", not as arrows.

The method looks for shapes that it knows. Two boxes in a row with one arrow between them become one box. A box with an arrow back to itself becomes a loop. A box that splits into two paths that meet again becomes an if-else. Each time it finds a shape, it draws a new box around it. In the end, one box holds the whole function as nested statements.

Some arrow patterns match no shape. For these, the method writes an explicit "go to that box" statement, deletes the arrow, and continues.

The problem

The input is a directed graph GG with an entry block. Each block has zero successors (it returns), one successor, or two successors chosen by the condition that the block computes, tt when it is true and ff when it is false. The output is an AST built from these statements:

statement meaning
Block(v)(v) run the statements of block vv
Seq(A1,…,Ak)(A_1, \dots, A_k) run the parts in order
If(c,s,A)(c, s, A) if the condition of block cc is ss, run AA
IfElse(c,s,A,B)(c, s, A, B) the same with an else part BB
Loop(P,c,s,Q)(P, c, s, Q) loop: run PP; if the condition of cc is not ss, leave; run QQ
Forever(B)(B) loop: run BB
Goto(v)(v), Return jump to the start of block vv; leave the function

The output must have the same executions as GG: for every choice of condition outcomes, it runs the same blocks in the same order. Each block must appear once, so no code is copied. The aim is to use few gotos. Every graph can be written without gotos if new variables are allowed, by the theorem of Böhm and Jacopini (1966). Without new variables and without copying code, some graphs need gotos.

The algorithm

A region is a part of the graph that is already structured. It has one entry block, an AST, and out-edges of the same three kinds as a block. At the start, each block is a region. A schema matches at a head region xx when its arms have xx as their only predecessor and are not the entry. The schemas are tried in this order:

  • sequence: x→yx \to y becomes Seq(Ax,Ay)(A_x, A_y) with the out-edges of yy.
  • forever: x→xx \to x becomes Forever(Ax)(A_x).
  • do-while: xx branches to itself and to oo. This becomes Loop(Ax,c,s,empty)(A_x, c, s, \text{empty}), which goes to oo.
  • while: xx branches to bb and to oo, and b→xb \to x. This becomes Loop(Ax,c,s,Ab)(A_x, c, s, A_b), which goes to oo.
  • if-then: xx branches to aa and to oo, and a→oa \to o or aa returns. This becomes Seq(Ax,If(c,s,Aa))(A_x, \text{If}(c, s, A_a)), which goes to oo.
  • if-else: xx branches to aa and to bb, and both go to the same jj or both return. This becomes Seq(Ax,IfElse(c,s,Aa,Ab))(A_x, \text{IfElse}(c, s, A_a, A_b)), which goes to jj.
  1. STRUCTURE(G, entry)
  2. 1make one region per block reachable from entry, with Block(v) as its AST (and Return after it if v has no successors)
  3. 2repeat: order ← the regions in depth-first postorder from entry
  4. 3for each x in order: if a schema matches with head x then
  5. 4replace x and the regions it absorbs by one region x with the schema's AST and out-edges; go to L2
  6. 5if no region has an out-edge then leave the loop
  7. 6pick the first edge x → y in order where y is the entry or has at least 2 predecessors, or else the first edge
  8. 7remove the edge and put Goto(y) at the end of the AST of x, under an If when x branches
  9. 8return Seq(the AST of the entry region, the ASTs of the other regions)

Line L3 visits the regions in depth-first postorder, so the inner parts of a nested statement are reduced before the outer parts. Line L4 always keeps the id of the head, so an edge to xx still means an edge to the start of the new region. Line L6 is the fallback. An edge into a join point is the best choice, because removing it can make a schema match there. Line L8 also outputs the regions that only gotos reach. These regions never fall through to the next one, because each of them ends in a Return, a Goto or a loop without an exit.

Example

A function with a while loop that has an if-then inside it, followed by an if-else:

block successors
B0 B1
B1 B2 if c1 is true, else B5
B2 B3 if c2 is true, else B4
B3, B4 B4, B1
B5 B6 if c5 is true, else B7
B6, B7 B8, B8
B8 returns

The first postorder is B4, B3, B2, B8, B6, B7, B5, B1, B0. The steps are:

step head schema absorbed the new AST of the head
1 B2 if-then B3 B2; if c2: B3 (goes to B4)
2 B2 sequence B4 B2; if c2: B3; B4 (goes to B1)
3 B5 if-else B6, B7 B5; if c5: B6 else B7 (goes to B8)
4 B5 sequence B8 B5; if c5: B6 else B7; B8; return
5 B1 while B2 loop {B1; if not c1: leave; B2; if c2: B3; B4} (goes to B5)
6 B1 sequence B5 the loop, then B5 ... return
7 B0 sequence B1 the whole function

In step 2, B4 can join B2 only after step 1, because before it B4 had two predecessors, B2 and B3. In step 5, the region B2 has B1 as its only predecessor and goes back to B1, so it is a loop body. The result has no goto:

B0
loop { B1; if not c1: leave; B2; if c2: { B3 }; B4 }
B5
if c5: { B6 } else { B7 }
B8
return

A short-circuit condition is different. For if (c0 and c1) B2 else B3; B4, the compiler makes B0 branch to B1 or B3, and B1 branch to B2 or B3. No schema matches, because B3 has two predecessors and B2 and B3 do not meet in one step. Line L6 turns the edge B2 → B4 into a goto. After that, everything reduces:

B0
if c0: { B1; if c1: { B2; goto B4 } }
B3
B4
return

Correctness

Each step rewrites the program in a way that keeps its executions. To see this, put the code of each region next to its out-edges, written as jumps. This gives a flat program with jumps, the linked program. At the start, it is the graph itself. The regions never fall through into each other, so they can be placed in any order. Each schema then does one of two things. It moves the code of an arm next to the head and deletes a jump to the next instruction. Or it writes the branch at the end of the head as an If, IfElse or loop test that makes the same choice on the same condition. The goto step moves a jump from the edge into the code of the region. So the linked program stays equivalent to the graph. At the end there are no edges, and the linked program is the output AST. Each merge joins two disjoint sets of blocks, so no block is lost or copied. Termination follows because each step lowers the number of regions plus the number of edges by at least one. The full proof is in the proofs folder.

Proof: Schema reduction with goto fallback keeps every execution and stopsfull

We prove three things about STRUCTURE on a control flow graph GG with entry block 00, nn reachable blocks and mm edges between them: the output AST has the same executions as GG, it contains each reachable block exactly once, and the main loop stops after at most n+mn + m steps.

Executions. Fix an outcome table τ\tau, where τ(v,k)\tau(v, k) is the value of the condition of block vv the kk-th time it is tested. A run of GG under τ\tau starts at block 00, records each block it executes, and after the kk-th execution of a block vv with two successors (t,f)(t, f) goes to tt if τ(v,k)\tau(v, k) is true and to ff otherwise. A block with no successors ends the run. For an AST, we lower it to flat code by the usual rules: Block(v)(v) becomes "exec vv" with the label vv on it; If(c,s,A)(c, s, A) becomes "unless c=sc = s jump to LL; code of AA; LL:"; IfElse is the same with a jump over the else part; Loop(P,c,s,Q)(P, c, s, Q) becomes "TT: code of PP; unless c=sc = s jump to EE; code of QQ; jump TT; EE:"; Forever(B)(B) becomes "TT: code of BB; jump TT"; Goto(v)(v) becomes "jump to label vv"; Return becomes "halt". A test of cc reads τ(c,k)\tau(c, k), where kk is the number of executions of cc so far. The events of a run are the executions and the tests with their outcomes, in order. Two programs are equivalent if they give the same event sequence under every τ\tau.

States and the linked program. A state of the algorithm is a set of regions. Each region xx has an AST AxA_x and out-edges: none, one target ss, or two targets (t,f)(t, f) chosen by the condition of a block cxc_x. The linked program PP of a state is the concatenation, over the regions, of a chunk per region: the code of AxA_x, followed by the link code "jump ss" for one target, "if cxc_x is true jump tt, else jump ff" for two targets, or nothing for none. A jump to a region yy is a jump to the label yy. PP starts at the label of the entry.

Invariants. For every state reached by the algorithm:

  1. The sets of blocks in the ASTs of the regions are disjoint and their union is the set of reachable blocks. Each block appears once in its region.
  2. Region xx has the id of a block, and the code of AxA_x begins with "exec xx". Every out-edge of every region names a region that exists.
  3. If region xx has no out-edges, a run that enters the code of AxA_x never reaches its end.
  4. The linked program is equivalent to GG.

Initial state (line L1). Each reachable block vv is a region with $A_v = $ Block(v)(v) and the out-edges of vv, or $A_v = $ Seq(Block(v)(v), Return) when vv has no successors. A block whose two successors are equal is given one successor; its test has no effect on the path, and the event sequence of GG is read without that test. Invariants 1 to 3 are clear. The linked program executes vv, then follows the edge of GG that τ\tau picks, so it is GG itself in flat form, which gives 4.

Chunks can be moved. By invariant 3 and the form of the link code, no chunk can fall through to the next chunk: it ends with a jump, with a halt, or with code whose end is never reached. Jumps go to labels, not to positions. So placing the chunks in any order gives an equivalent program, and a "jump LL" with LL the next instruction can be removed. We use these two facts in each case below. Let XX be the chunk of the head xx, and write OO for the target that the schema keeps.

  • Sequence. XX = code(Ax)(A_x); jump yy, and yy has xx as its only predecessor. Place the chunk of yy after XX and delete the jump, which now goes to the next instruction by invariant 2. The result is the chunk of the new region, with the out-edges of yy. No other region names yy, so invariant 2 holds after yy is deleted.
  • If-then. XX = code(Ax)(A_x); if cxc_x = ss jump aa else jump OO. The chunk of aa is code(Aa)(A_a) followed by "jump OO" or by nothing. The new chunk is code(Ax)(A_x); unless cx=sc_x = s jump LL; code(Aa)(A_a); LL: jump OO. If the test gives ss, both programs run code(Aa)(A_a) next and then jump to OO, or never leave AaA_a. Otherwise both jump to OO. The test is the same test of the same block, so the events agree.
  • If-else. The same argument, with the two arms and their common target, or with no target, in which case the new region has no out-edges and invariant 3 holds because neither arm reaches its end.
  • While. XX = code(Ax)(A_x); if cx=sc_x = s jump bb else jump OO, and the chunk of bb is code(Ab)(A_b); jump xx. The new chunk is TT: code(Ax)(A_x); unless cx=sc_x = s jump EE; code(Ab)(A_b); jump TT; EE: jump OO. The label xx is at TT by invariant 2, so the two programs make the same moves.
  • Do-while and forever. The self-edge "jump xx" is the jump to TT of the loop, so the code is the same up to the names of the labels. A forever region has no out-edges and never reaches the end of its code, which keeps invariant 3.
  • Goto (lines L6 and L7). For one target, the link "jump yy" becomes the statement Goto(y)(y) at the end of AxA_x, which is the same instruction; the region now has no out-edges and never reaches its end. For two targets, "if cxc_x is true jump tt, else jump ff" becomes "unless cx=sc_x = s jump LL; jump yy; LL: jump OO" with ss the sense that leads to yy, which makes the same choice.

In each case the block sets of the merged regions are joined and nothing is copied, which keeps invariant 1, and the new region keeps the id of xx, whose code still begins with "exec xx", which keeps invariant 2. Each case keeps invariant 4, because it replaces a linked program by an equivalent one.

Theorem 1 (correctness). The returned AST is equivalent to GG, and it contains each block reachable from the entry exactly once.

Proof. The loop ends at line L5 when no region has out-edges. Then every chunk is just the code of its AST, and by invariant 3 none of them reaches its end. Line L8 returns the AST of the entry followed by the other regions. Its code is the linked program with the entry chunk first, which starts at the label of the entry by invariant 2. By invariant 4 it is equivalent to GG. Invariant 1 gives the second claim. ■\blacksquare

Theorem 2 (termination and cost). The loop of lines L2 to L7 makes at most n+mn + m steps, and the algorithm takes O(n2)O(n^2) time when every block has at most two successors.

Proof. Let Φ\Phi be the number of regions plus the number of out-edges. At the start, Φ=n+m\Phi = n + m. A sequence step removes one region and the edge x→yx \to y. A forever or do-while step removes the self-edge. A while step removes the region bb and the edges x→bx \to b and b→xb \to x. An if-then step removes the arm and at least the edge to it. An if-else step removes two regions. A goto step removes one edge. So each step lowers Φ\Phi by at least 1, and Φ≥1\Phi \ge 1 while a region exists, so there are at most n+mn + m steps. One step computes a depth-first postorder and the predecessor lists in O(n+m)O(n + m) time, tests the schemas in O(1)O(1) time per region, and builds the new AST in O(n)O(n) time. With m≤2nm \le 2n, the total is O((n+m)2)=O(n2)O((n + m)^2) = O(n^2). □\square

What is not proved. The theorems do not say that the number of gotos is the smallest possible. The goto step picks the first edge into a join point or into the entry, which is a heuristic. The tests check, on 500 random programs built from sequence, if, if-else, while and do-while, that the result has no goto, but the page does not prove this.

Complexity

The number of regions plus the number of edges starts at n+mn + m and falls by at least one at each step, so there are at most n+mn + m steps. Each step computes a postorder and the predecessor lists in O(n+m)O(n + m) time. It tests each schema in O(1)O(1) time per region and builds the new AST in O(n)O(n) time. Each block has at most two successors, so m≤2nm \le 2n, and the total time is O(n2)O(n^2). A straight run of nn blocks already needs n−1n - 1 steps on shrinking graphs, so this simple version takes quadratic time on every input. The regions and the AST take O(n+m)O(n + m) space. The model is the word RAM.

Properties

  • Keeps the semantics. For every choice of condition outcomes, the output runs the same blocks in the same order as the graph.
  • No code is copied. Each block appears in the output exactly once.
  • Gotos are not minimal. The goto rule is a heuristic. The test file measures two cases. On 500 random graphs with at most 8 blocks, 443 needed no goto and the others needed 1 to 5. On 500 random programs built from sequence, if, if-else, while and do-while, none needed a goto. These are measurements, not proved bounds.
  • Deterministic. The output depends only on the graph and the order of the successors.

Variants and improvements

  • Compound conditions. Cifuentes merged chains of branches like the short-circuit example into one condition c0 and c1 before structuring. This removes the most common source of gotos in compiled code.
  • Switch statements. A block with many successors, from a jump table that the disassembler resolved, becomes a switch when its cases meet at one point.
  • Loops by dominators and intervals. Find the loops first, by natural loops, dominators or a loop nesting forest. Then structure each loop body, and turn the exits from a loop into break statements.
  • Semantics-preserving structural analysis. Schwartz, Lee, Woo and Brumley (Phoenix, 2013) made each schema check that it keeps the semantics. They also refine the graph step by step, which lowers the number of gotos.
  • No gotos at all. Yakdan and coauthors (DREAM, 2015) compute, for each block, the condition under which control reaches it from the region head, and build the AST from these conditions without fixed patterns. Regions with more than one entry or exit are first transformed into equivalent single-entry forms.
  • Node splitting. Copying a block that has many predecessors can make an irreducible graph reducible, at the cost of a larger output.
  • A state variable. The Böhm and Jacopini form uses one loop, a variable that holds the next block, and a switch over it. It never needs a goto, but it is hard to read. It is the same form that control flow flattening produces on purpose.

When to use it

Use control flow structuring when a person must read a binary function, as in malware analysis, vulnerability research or the review of code with no source. It is the last stage of a decompiler, after disassembly, the recovery of the control flow graph and the recovery of expressions and types. The simple schema version is a good base. It is easy to verify, and it gives clean output for code from standard compilers. Add compound conditions and switch recovery before you add more complex methods. Use a goto-free method, such as reaching conditions, when the output goes to a tool that does not accept gotos, or when a lower number of gotos matters more than a shorter output.

Pitfalls

  • Merging a block that has other predecessors. If line L3 merges x→yx \to y when yy also has other predecessors, the edges from those predecessors point to a region that no longer exists. Require that yy has xx as its only predecessor and is not the entry, as the schemas of line L3 do.
  • No Return after an exit block. If line L1 gives an exit block only Block(v)(v), an if-then whose arm returns falls through into the code after the If, and the output runs blocks that the graph never runs. Put Return after every block with no successors, as line L1 does.
  • Trying the conditionals before the loops. At the head of a while loop whose exit arm returns, the if-then schema also matches. It gives a correct but less readable "loop forever, with an exit inside". Try the loop schemas before the if-then schema in line L3.
  • A goto to a block with one predecessor. If line L6 picks any edge, it can cut off a region that the next schema would absorb. That region is then reached only by the goto. Prefer edges into join points and into the entry, as line L6 does.
  • Testing a condition in the wrong place. The condition of block cc must be tested right after cc runs, because a later block can change the values it reads. The schemas put each If or loop test right after the head AST, which ends with cc.

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.

control_flow_structuring.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/control-flow-structuring/. The authors are listed in prov/Y2RJX0.jsonl.

"""Control flow structuring by iterative schema reduction, with goto as the fallback.

The input is a control flow graph given as a list succ, where succ[v] is the
tuple of successors of block v: () for a block that returns, (s,) for a block
that goes on to s, and (t, f) for a block that ends with a branch on its own
condition, going to t when the condition is true and to f when it is false.
Block 0 is the entry. The output is an abstract syntax tree (AST) in which each
reachable block appears exactly once.

AST semantics:
    Block(v)                      run the statements of block v
    Seq(items)                    run the items in order
    If(c, sense, then)            if the condition of block c equals sense, run then
    IfElse(c, sense, then, else)  the same with an else part
    Loop(pre, c, sense, post)     loop { pre; if the condition of c differs from sense: break; post }
    Forever(body)                 loop { body }
    Goto(v)                       continue at the start of Block(v)
    Return()                      leave the function
A condition always belongs to the block that ran just before it is tested.
"""

from dataclasses import dataclass
from typing import NamedTuple, Optional, Union


@dataclass(frozen=True)
class Block:
    v: int


@dataclass(frozen=True)
class Seq:
    items: tuple["Node", ...]


@dataclass(frozen=True)
class If:
    cond: int
    sense: bool
    then: "Node"


@dataclass(frozen=True)
class IfElse:
    cond: int
    sense: bool
    then: "Node"
    orelse: "Node"


@dataclass(frozen=True)
class Loop:
    pre: "Node"
    cond: int
    sense: bool
    post: "Node"


@dataclass(frozen=True)
class Forever:
    body: "Node"


@dataclass(frozen=True)
class Goto:
    target: int


@dataclass(frozen=True)
class Return:
    pass


Node = Union[Block, Seq, If, IfElse, Loop, Forever, Goto, Return]

EMPTY = Seq(())


@dataclass
class Region:
    """A single-entry part of the graph that is already structured."""

    ast: Node
    targets: tuple[int, ...]  # the out-edges, in the same form as succ
    cond: Optional[int] = None  # the block whose condition picks between two targets


class Result(NamedTuple):
    ast: Node
    steps: list[tuple[str, int, tuple[int, ...]]]  # (schema or "goto", head region, absorbed regions or goto target)
    gotos: int


def seq(*parts: Node) -> Node:
    """Concatenate statements, flattening nested sequences."""
    items: list[Node] = []
    for part in parts:
        items.extend(part.items if isinstance(part, Seq) else (part,))
    return items[0] if len(items) == 1 else Seq(tuple(items))


def reachable(succ: list[tuple[int, ...]], entry: int) -> list[int]:
    seen, stack = {entry}, [entry]
    while stack:
        for y in succ[stack.pop()]:
            if y not in seen:
                seen.add(y)
                stack.append(y)
    return sorted(seen)


def postorder(regions: dict[int, Region], entry: int) -> list[int]:
    """Depth-first postorder from the entry, then from regions that only gotos reach."""
    seen: set[int] = set()
    order: list[int] = []
    for root in [entry] + sorted(regions):
        if root in seen:
            continue
        seen.add(root)
        stack = [(root, 0)]
        while stack:
            x, i = stack[-1]
            targets = regions[x].targets
            if i < len(targets):
                stack[-1] = (x, i + 1)
                if targets[i] not in seen:
                    seen.add(targets[i])
                    stack.append((targets[i], 0))
            else:
                stack.pop()
                order.append(x)
    return order


def match(regions: dict[int, Region], preds: dict[int, list[int]], entry: int, x: int) -> Optional[tuple[str, Region, list[int]]]:
    """The first schema whose head is x: (name, new region, absorbed regions), or None."""

    def only_from_x(y: int) -> bool:
        return y != x and y != entry and preds[y] == [x]

    r = regions[x]
    if len(r.targets) == 1:
        (y,) = r.targets
        if y == x:
            return "forever", Region(Forever(r.ast), ()), []
        if only_from_x(y):
            ry = regions[y]
            return "sequence", Region(seq(r.ast, ry.ast), ry.targets, ry.cond), [y]
        return None
    if len(r.targets) != 2:
        return None
    t, f = r.targets
    c = r.cond
    assert c is not None
    arms = ((True, t, f), (False, f, t))  # (sense, the arm, the other target)
    for sense, arm, other in arms:
        if arm == x:
            return "do-while", Region(Loop(r.ast, c, sense, EMPTY), (other,)), []
    for sense, arm, other in arms:
        if only_from_x(arm) and regions[arm].targets == (x,):
            return "while", Region(Loop(r.ast, c, sense, regions[arm].ast), (other,)), [arm]
    for sense, arm, other in arms:
        if only_from_x(arm) and regions[arm].targets in ((other,), ()):
            return "if-then", Region(seq(r.ast, If(c, sense, regions[arm].ast)), (other,)), [arm]
    if only_from_x(t) and only_from_x(f):
        rt, rf = regions[t], regions[f]
        if rt.targets == rf.targets and len(rt.targets) <= 1:
            return "if-else", Region(seq(r.ast, IfElse(c, True, rt.ast, rf.ast)), rt.targets), [t, f]
    return None


def structure(succ: list[tuple[int, ...]], entry: int = 0) -> Result:
    """Turn the control flow graph into an AST with the same executions.

    Precondition: every successor is a valid block index. Postcondition: for
    every choice of condition outcomes, the AST runs the same sequence of
    blocks as the graph, and each block reachable from the entry appears
    exactly once. Cost: O(n (n + m)) time for n blocks and m edges.
    """
    regions: dict[int, Region] = {}
    for v in reachable(succ, entry):  # @line L1
        s = succ[v]
        if len(s) == 2 and s[0] == s[1]:
            s = (s[0],)
        if not s:
            regions[v] = Region(seq(Block(v), Return()), ())
        elif len(s) == 1:
            regions[v] = Region(Block(v), s)
        else:
            regions[v] = Region(Block(v), s, v)
    steps: list[tuple[str, int, tuple[int, ...]]] = []
    gotos = 0
    while True:
        order = postorder(regions, entry)  # @line L2
        preds: dict[int, list[int]] = {x: [] for x in regions}
        for x in order:
            for y in regions[x].targets:
                preds[y].append(x)
        found = None
        for x in order:  # @line L3
            found = match(regions, preds, entry, x)
            if found is not None:
                break
        if found is not None:
            name, new, absorbed = found
            for y in absorbed:  # @line L4
                del regions[y]
            regions[x] = new
            steps.append((name, x, tuple(absorbed)))
            continue
        edges = [(x, y) for x in order for y in regions[x].targets]
        if not edges:  # @line L5
            break
        joins = [(x, y) for x, y in edges if y == entry or len(preds[y]) >= 2]
        x, y = (joins or edges)[0]  # @line L6
        r = regions[x]
        if len(r.targets) == 1:  # @line L7
            regions[x] = Region(seq(r.ast, Goto(y)), ())
        else:
            assert r.cond is not None
            t, f = r.targets
            sense = y == t
            regions[x] = Region(seq(r.ast, If(r.cond, sense, Goto(y))), (f if sense else t,))
        steps.append(("goto", x, (y,)))
        gotos += 1
    rest = [regions[x].ast for x in sorted(regions) if x != entry]
    return Result(seq(regions[entry].ast, *rest), steps, gotos)  # @line L8
test_control_flow_structuring.py 273 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/control-flow-structuring/. The authors are listed in prov/Y2RJX0.jsonl.

import random
from collections import Counter

from control_flow_structuring import Block, Forever, Goto, If, IfElse, Loop, Node, Return, Seq, reachable, structure

LIMIT = 60

PAGE_EXAMPLE = [(1,), (2, 5), (3, 4), (4,), (1,), (6, 7), (8,), (8,), ()]
SHORT_CIRCUIT = [(1, 3), (2, 3), (4,), (4,), ()]  # if (c0 and c1) {B2} else {B3}; B4


def compile_ast(ast: Node) -> list[tuple]:
    """Lower the AST to flat code with jumps, by the usual compilation rules."""
    prog: list[list] = []
    label: dict[int, int] = {}

    def emit(node: Node) -> None:
        if isinstance(node, Block):
            label[node.v] = len(prog)
            prog.append(["exec", node.v])
        elif isinstance(node, Seq):
            for item in node.items:
                emit(item)
        elif isinstance(node, If):
            skip = ["unless", node.cond, node.sense, None]
            prog.append(skip)
            emit(node.then)
            skip[3] = len(prog)
        elif isinstance(node, IfElse):
            to_else = ["unless", node.cond, node.sense, None]
            prog.append(to_else)
            emit(node.then)
            to_end = ["jump", None]
            prog.append(to_end)
            to_else[3] = len(prog)
            emit(node.orelse)
            to_end[1] = len(prog)
        elif isinstance(node, Loop):
            top = len(prog)
            emit(node.pre)
            leave = ["unless", node.cond, node.sense, None]
            prog.append(leave)
            emit(node.post)
            prog.append(["jump", top])
            leave[3] = len(prog)
        elif isinstance(node, Forever):
            top = len(prog)
            emit(node.body)
            prog.append(["jump", top])
        elif isinstance(node, Goto):
            prog.append(["goto", node.target])
        elif isinstance(node, Return):
            prog.append(["halt"])
        else:
            raise TypeError(node)

    emit(ast)
    prog.append(["fell off the end"])
    out = []
    for ins in prog:
        if ins[0] == "goto":
            out.append(("jump", label[ins[1]]))
        else:
            out.append(tuple(ins))
    return out


def run_code(prog: list[tuple], table: list[list[bool]]) -> list[int]:
    trace: list[int] = []
    visits: Counter = Counter()
    pc = 0
    for _ in range(100 * LIMIT):
        if len(trace) == LIMIT:
            break
        ins = prog[pc]
        if ins[0] == "exec":
            trace.append(ins[1])
            visits[ins[1]] += 1
            pc += 1
        elif ins[0] == "halt":
            break
        elif ins[0] == "jump":
            pc = ins[1]
        elif ins[0] == "unless":
            _, c, sense, target = ins
            pc = pc + 1 if table[c][visits[c] - 1] == sense else target
        else:
            trace.append(-1)
            break
    return trace


def run_cfg(succ: list[tuple[int, ...]], table: list[list[bool]]) -> list[int]:
    trace: list[int] = []
    visits: Counter = Counter()
    v = 0
    while len(trace) < LIMIT:
        trace.append(v)
        visits[v] += 1
        s = succ[v]
        if not s:
            break
        v = s[0] if len(s) == 1 or table[v][visits[v] - 1] else s[1]
    return trace


def blocks_in(ast: Node) -> list[int]:
    out, stack = [], [ast]
    while stack:
        node = stack.pop()
        if isinstance(node, Block):
            out.append(node.v)
        elif isinstance(node, Seq):
            stack.extend(node.items)
        elif isinstance(node, If):
            stack.append(node.then)
        elif isinstance(node, IfElse):
            stack.extend([node.then, node.orelse])
        elif isinstance(node, Loop):
            stack.extend([node.pre, node.post])
        elif isinstance(node, Forever):
            stack.append(node.body)
    return out


def count_gotos(ast: Node) -> int:
    stack, n = [ast], 0
    while stack:
        node = stack.pop()
        n += isinstance(node, Goto)
        if isinstance(node, Seq):
            stack.extend(node.items)
        elif isinstance(node, If):
            stack.append(node.then)
        elif isinstance(node, IfElse):
            stack.extend([node.then, node.orelse])
        elif isinstance(node, Loop):
            stack.extend([node.pre, node.post])
        elif isinstance(node, Forever):
            stack.append(node.body)
    return n


def check_same_runs(succ: list[tuple[int, ...]], rng: random.Random, tables: int = 3) -> int:
    res = structure(succ)
    assert sorted(blocks_in(res.ast)) == reachable(succ, 0)
    assert count_gotos(res.ast) == res.gotos
    edges = sum(len(s) for s in succ)
    assert len(res.steps) <= len(succ) + edges
    prog = compile_ast(res.ast)
    for _ in range(tables):
        table = [[rng.random() < 0.5 for _ in range(LIMIT + 1)] for _ in succ]
        assert run_code(prog, table) == run_cfg(succ, table)
    return res.gotos


def random_cfg(rng: random.Random) -> list[tuple[int, ...]]:
    n = rng.randrange(1, 9)
    succ = []
    for _ in range(n):
        k = rng.choices([0, 1, 2], [1, 3, 4])[0]
        succ.append(tuple(rng.randrange(n) for _ in range(k)))
    return succ


def structured_cfg(rng: random.Random) -> list[tuple[int, ...]]:
    """A CFG built from sequence, if, if-else, while and do-while, so it has a goto-free form."""
    succ: list[list] = []

    def new(k: int) -> int:
        succ.append([None] * k)
        return len(succ) - 1

    def build(depth: int) -> tuple[int, list[tuple[int, int]]]:
        kind = rng.choice(["block"] * 2 + (["seq", "if", "ifelse", "while", "dowhile"] if depth > 0 else []))
        if kind == "block":
            v = new(1)
            return v, [(v, 0)]
        if kind == "seq":
            a, out_a = build(depth - 1)
            b, out_b = build(depth - 1)
            for node, slot in out_a:
                succ[node][slot] = b
            return a, out_b
        if kind in ("if", "ifelse"):
            c = new(2)
            arm = rng.randrange(2)
            a, out_a = build(depth - 1)
            succ[c][arm] = a
            if kind == "if":
                return c, out_a + [(c, 1 - arm)]
            b, out_b = build(depth - 1)
            succ[c][1 - arm] = b
            return c, out_a + out_b
        if kind == "while":
            h = new(2)
            arm = rng.randrange(2)
            a, out_a = build(depth - 1)
            succ[h][arm] = a
            for node, slot in out_a:
                succ[node][slot] = h
            return h, [(h, 1 - arm)]
        a, out_a = build(depth - 1)
        c = new(2)
        arm = rng.randrange(2)
        for node, slot in out_a:
            succ[node][slot] = c
        succ[c][arm] = a
        return a, [(c, 1 - arm)]

    entry, out = build(3)
    end = new(0)
    for node, slot in out:
        succ[node][slot] = end
    # Renumber so that the entry is block 0.
    order = [entry] + [v for v in range(len(succ)) if v != entry]
    index = {v: i for i, v in enumerate(order)}
    return [tuple(index[w] for w in succ[v]) for v in order]


def test_page_example() -> None:
    res = structure(PAGE_EXAMPLE)
    assert [(name, x, absorbed) for name, x, absorbed in res.steps] == [
        ("if-then", 2, (3,)),
        ("sequence", 2, (4,)),
        ("if-else", 5, (6, 7)),
        ("sequence", 5, (8,)),
        ("while", 1, (2,)),
        ("sequence", 1, (5,)),
        ("sequence", 0, (1,)),
    ]
    assert res.gotos == 0
    assert res.ast == Seq(
        (
            Block(0),
            Loop(Block(1), 1, True, Seq((Block(2), If(2, True, Block(3)), Block(4)))),
            Block(5),
            IfElse(5, True, Block(6), Block(7)),
            Block(8),
            Return(),
        )
    )
    check_same_runs(PAGE_EXAMPLE, random.Random(40), tables=20)


def test_short_circuit_needs_one_goto() -> None:
    res = structure(SHORT_CIRCUIT)
    assert res.gotos == 1
    assert res.steps[0] == ("goto", 2, (4,))
    assert res.ast == Seq((Block(0), If(0, True, Seq((Block(1), If(1, True, Seq((Block(2), Goto(4))))))), Block(3), Block(4), Return()))
    check_same_runs(SHORT_CIRCUIT, random.Random(41), tables=20)


def test_random_graphs_keep_every_run() -> None:
    rng = random.Random(42)
    for _ in range(500):
        check_same_runs(random_cfg(rng), rng)


def test_structured_programs_need_no_gotos() -> None:
    rng = random.Random(43)
    for _ in range(500):
        assert check_same_runs(structured_cfg(rng), rng, tables=2) == 0


def test_single_block_and_self_loop() -> None:
    assert structure([()]).ast == Seq((Block(0), Return()))
    assert structure([(0,)]).ast == Forever(Block(0))
    res = structure([(0, 1), ()])
    assert res.ast == Seq((Loop(Block(0), 0, True, Seq(())), Block(1), Return()))

History

Böhm and Jacopini (1966) showed that every flow chart can be written with sequence, selection and iteration alone, if new variables are allowed. Baker (1977) gave an algorithm that turns a flow graph into structured statements and keeps gotos where needed. It was used to translate Fortran into a structured dialect. Sharir (1980) introduced structural analysis, which finds regions that match control structures and reduces the graph, for data flow analysis in compilers. Cifuentes (1994) applied these ideas to decompilation of binaries. Her method structured loops, conditionals, switch statements and compound conditions in the graphs of decompiled functions. Schwartz, Lee, Woo and Brumley (USENIX Security 2013) made structural analysis keep the semantics and measured the correctness of decompiled code. Yakdan, Eschweiler, Gerhards-Padilla and Smith (NDSS 2015) gave a method that produces no gotos on their test set.

References

  1. Micha Sharir, Structural analysis: a new approach to flow analysis in optimizing compilers, Computer Languages 5, 1980, the reduction of a flow graph by repeated replacement of regions that match control structures
  2. Cristina Cifuentes, Reverse compilation techniques, PhD thesis, Queensland University of Technology, 1994, the chapter on control flow analysis, which structures loops, two-way and n-way conditionals and compound conditions in the graph of a decompiled function
  3. Edward J. Schwartz, JongHyup Lee, Maverick Woo and David Brumley, Native x86 decompilation using semantics-preserving structural analysis and iterative control-flow structuring, USENIX Security Symposium 2013, the semantics-preserving structural analysis of the Phoenix decompiler and its measured correctness
  4. Khaled Yakdan, Sebastian Eschweiler, Elmar Gerhards-Padilla and Matthew Smith, No more gotos: decompilation using pattern-independent control-flow structuring and semantics-preserving transformations, Network and Distributed System Security Symposium (NDSS) 2015, structuring by reaching conditions without patterns, and the transformations that remove the remaining gotos

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 proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
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