Algorithm Search⌘K

Algorithmcore

Allen-Kennedy vectorization algorithm

Also called Allen-Kennedy codegen.

Distributes a loop nest by the strongly connected components of its dependence graph, level by level, and turns each statement that is on no cycle into a vector statement.

Time
O(n (r + e)) worst
Space
O(r + e) extra
Where
e = the number of edges of the dependence graph; n = the depth of the loop nest; r = the number of statements
Properties
deterministicrecursive

The Allen-Kennedy algorithm, called codegen by its authors, turns a loop nest into vector statements and sequential loops. At level kk it builds the dependence graph of the statements with the dependences that are carried at level kk or deeper or are loop independent, splits it into strongly connected components, and emits the components in topological order. A component with a cycle keeps a sequential loop at level kk and is handled again at level k+1k + 1. A statement that is on no cycle becomes a vector statement over all its loops from level kk inward. Allen and Kennedy built it for the PFC translator from Fortran to vector Fortran at Rice University, and published it in 1987.

In plain words

A compiler wants to turn a loop into array operations, such as "add these two whole arrays", that a vector machine runs fast. A statement can become an array operation only if no iteration of it needs a result of another iteration of the same loop. The algorithm draws an arrow between two statements when one must run before the other. Statements that wait for each other in a circle must stay in an ordinary loop, because the order of their iterations matters. Every other statement can run as one array operation, at the right place in the order of the arrows. Inside each circle, the algorithm looks one loop deeper, where some arrows disappear, and tries again.

The problem

Input. A loop nest that forms one chain of loops: loop 1 holds loop 2, which holds loop 3, up to depth nn. Statement SS is inside the loops 1 to dSd_S. The statements and their text order are given. The dependence graph DD has an edge S→TS \to T labelled with level ll for each dependence from an instance of SS to an instance of TT that is carried at level ll, and with level n+1n + 1 for a loop-independent one.

Output. An equivalent program built only from the original loops (run sequentially) and vector statements. A vector statement over the loops kk to dSd_S runs, for fixed outer indices i1,…,ik−1i_1, \dots, i_{k-1}, all instances of SS at once: it reads all its operands, then it writes all its results, as an array assignment in Fortran 90 does. It is legal only if no dependence joins two of its instances.

The dependence graph comes from dependence testing. The algorithm uses only the level of each edge, not its distance.

The algorithm

  1. CODEGEN(R, k) ▷ R: a set of statements; k: the current loop level
  2. 1E <- the edges of D between statements of R with level >= k
  3. 2pi_1, ..., pi_m <- the strongly connected components of (R, E), in topological order
  4. 3for c <- 1 to m do
  5. 4if pi_c has two or more statements, or a statement with an edge to itself in E then
  6. 5emit "for i_k = L_k to U_k:" ▷ a sequential loop
  7. 6CODEGEN(pi_c, k + 1)
  8. 7else
  9. 8S <- the only statement of pi_c
  10. 9emit S as a vector statement over the loops k to d_S ▷ a scalar statement if d_S = k - 1

The call CODEGEN(all statements, 1) produces the program. Line L1 drops the dependences carried at levels 11 to k−1k - 1, because the enclosing sequential loops already keep them, and keeps the loop-independent ones (level n+1n + 1) at every level. Line L2 uses Tarjan's algorithm and a topological sort of the component graph; ties go to the text order. A component with a cycle needs the loop at level kk to stay sequential, since some of its dependences go from one iteration of that loop to a later one in both directions around the cycle. At level k+1k + 1 the edges carried at level kk are gone, so the cycle may break.

Example

This is a small copy of the example in Allen and Kennedy's book, with all loops from 1 to 4 and N=2N = 2:

for i = 1 to 4:
  S1: X[i] = Y[i] + 10
  for j = 1 to 4:
    S2: B[j] = A[j][N]
    for k = 1 to 4:
      S3: A[j+1][k] = B[j] + C[j][k]
    S4: Y[i+j] = A[j+1][N]

The dependence graph has these edges, found by checking all pairs of instances (LI means loop independent, level 4):

edge levels reason
S2 to S2 1 output on B[j]B[j], written in every ii
S2 to S3 1, LI flow on B[j]B[j]
S3 to S2 1, 2 flow on A[j+1][N]A[j+1][N], read as A[j][N]A[j][N] at j+1j + 1 or at a later ii
S3 to S3 1 output on A[j+1][k]A[j+1][k], written in every ii
S3 to S4 1, LI flow on A[j+1][N]A[j+1][N]
S4 to S3 1 anti on A[j+1][N]A[j+1][N]
S4 to S4 1 output on Y[i+j]Y[i+j]
S4 to S1 1 flow on YY

Level 1. All edges count. The components are {S2,S3,S4}\{S2, S3, S4\}, with the cycle S3→S4→S3S3 \to S4 \to S3, and {S1}\{S1\}. The edge S4→S1S4 \to S1 puts the big component first. So the ii loop stays sequential around the first one, and S1 becomes a vector statement over ii after it.

Level 2, inside the ii loop. The edges of level 2 or more among S2, S3, S4 are S2→S3S2 \to S3 (LI), S3→S2S3 \to S2 (level 2) and S3→S4S3 \to S4 (LI). The components are {S2,S3}\{S2, S3\}, with a cycle, and then {S4}\{S4\}. So the jj loop stays sequential around S2 and S3, and S4 becomes a vector statement over jj.

Level 3, inside the jj loop. Only S2→S3S2 \to S3 (LI) is left. There is no cycle. S2 has depth 2, so it is a scalar statement, and S3 becomes a vector statement over kk.

for i = 1 to 4:
  for j = 1 to 4:
    S2: B[j] = A[j][2]
    S3: A[j+1][1:4] = B[j] + C[j][1:4]
  S4: Y[i+1:i+4] = A[2:5][2]
S1: X[1:4] = Y[1:4] + 10

S1 moved to the end, after all of the ii loop. This is legal, because no dependence goes from S1 to the other statements, and it is needed, because S1 reads values of YY that S4 writes in earlier iterations.

Correctness

The full proof is in proofs/correctness.md. It has three parts.

Every dependence is kept. Take a dependence from S(i⃗)S(\vec{i}) to T(j⃗)T(\vec{j}) with level ll. Follow the recursion to the deepest call CODEGEN(R,k)(R, k) that has both SS and TT in RR. If l<kl < k, this call sits inside the sequential loop at level ll, which runs iteration ili_l before jlj_l. If l≥kl \ge k, the edge is in line L1. The two statements cannot be in one component, since that component would be cyclic and line L6 would make a deeper call with both. So the topological order emits all of the component of SS before all of that of TT, for the same outer indices. An acyclic component is one statement with no edge to itself of level kk or more, so no dependence joins two instances of one vector statement, and the read-then-write semantics is exact.

Each statement is vectorized at the first level where it is on no cycle. Let GmG_m be the graph of the edges with level mm or more. These graphs shrink as mm grows. The region RR that contains SS at level kk is the component of SS in Gk−1G_{k-1}, and it contains the component of SS in GkG_k. So SS becomes a vector statement at the smallest mm for which SS is on no cycle of GmG_m.

No program of the same kind does better. Suppose some program built from the original loops, loop distribution, statement order and vector statements runs SS as a vector statement over the loops mm to dSd_S, and SS is on a cycle of GmG_m. All the statements of the cycle are pieces in one sequence for each fixed i1,…,im−1i_1, \dots, i_{m-1}, and the order of the pieces is the same for all outer indices. Every edge of the cycle has its source and sink in the same outer iteration, so it forces its source piece to be no later than its sink piece, and strictly earlier when one of them is the piece of SS. Around the cycle this gives the piece of SS before itself, which is impossible. Darte and Vivien proved more in 1997: with dependence levels as the only information, no transformation at all finds more parallel loops.

Proof: Allen-Kennedy codegen keeps every dependence and vectorizes each statement as early as possiblefull

We use the notation of the page. The loops form one chain of depth nn, so for each kk the statements of depth kk or more are one contiguous run of the text, inside loop kk. Statement SS is inside the loops 11 to dSd_S. An instance is S(i⃗)S(\vec{i}) with i⃗=(i1,…,idS)\vec{i} = (i_1, \dots, i_{d_S}). A dependence pair goes from an instance S(i⃗)S(\vec{i}) that runs first in the sequential program to an instance T(j⃗)T(\vec{j}). Its level ll is the first common loop where i⃗\vec{i} and j⃗\vec{j} differ, and then il<jli_l < j_l. If they agree on all common loops, the level is n+1n + 1 (loop independent). For 1≤m≤n+11 \le m \le n + 1, the graph GmG_m has the statements as nodes and an edge S→TS \to T when some pair from SS to TT has level mm or more.

A generated program is a tree. A loop node at level kk runs its children in order for each value of iki_k, in increasing order. A vector node (S,k)(S, k) runs, for the current values of i1,…,ik−1i_1, \dots, i_{k-1}, all instances of SS with those outer indices as one step: it reads all its operands, then writes all its results. Each statement is in exactly one vector node, and the loops above it run all values of i1,…,ik−1i_1, \dots, i_{k-1}, so each instance runs in exactly one step.

By the reordering theorem on the legality page, the generated program computes the same memory as the original one if two conditions hold: every dependence pair runs in order (the step of the source strictly before the step of the sink), and no dependence pair has both instances in one step. The second condition makes the read-then-write rule of a step exact: no instance of the step reads or overwrites a cell that another instance of the same step writes.

Lemma 1 (backward edges and cycles). (a) A loop-independent pair goes from a statement to a statement strictly later in the text. (b) Every statement on a cycle of GkG_k, with k≤nk \le n, has depth at least kk. (c) Gn+1G_{n+1} has no cycle.

Proof. (a) If the instances agree on all common loops, the sequential program runs them in text order, and two different instances of one statement cannot agree on all its loops. (c) follows from (a), because the text positions only grow along a path of Gn+1G_{n+1}. For (b), an edge of GkG_k that does not go strictly forward in the text comes, by (a), from a pair of level ll with k≤l≤nk \le l \le n, so both of its statements share loop ll and have depth at least l≥kl \ge k. Take a cycle of GkG_k. Let YY be its statement that comes first in the text, and ZZ the one that comes last. The edge of the cycle into YY and the edge out of ZZ do not go strictly forward, so YY and ZZ have depth at least kk. All statements of the cycle lie between YY and ZZ in the text, and the statements of depth kk or more are contiguous, so all of them have depth at least kk. □\square

Lemma 2 (regions). For k≥2k \ge 2, the region RR of a call CODEGEN(R,k)(R, k) is a strongly connected component of Gk−1G_{k-1} restricted to the region of the parent call, with a cycle, and all its statements have depth at least k−1k - 1. The call runs inside sequential loop nodes at the levels 11 to k−1k - 1.

Proof. Line L6 makes the call at level kk for a component of the edges of level k−1k - 1 or more that has two statements or a self edge, so it has a cycle. Lemma 1(b) gives the depths. Line L5 emits the loop node at level k−1k - 1 around the call, and by induction the parent call is inside the loops at levels 11 to k−2k - 2. □\square

Theorem 1 (every dependence is kept). For every dependence pair from S(i⃗)S(\vec{i}) to T(j⃗)T(\vec{j}), with level ll, the step of S(i⃗)S(\vec{i}) comes strictly before the step of T(j⃗)T(\vec{j}), and the two instances are not in one step.

Proof. The root call has both SS and TT in its region. Let CODEGEN(R,k)(R, k) be the deepest call whose region contains both. There are two cases.

Case A: l<kl < k. By Lemma 2, the call runs inside a sequential loop node at level ll, and both steps are below it. The instances agree on i1,…,il−1i_1, \dots, i_{l-1}, so they are in the same run of that loop node, and il<jli_l < j_l, so the step of S(i⃗)S(\vec{i}) runs in an earlier iteration of it. The pair is in order, and not in one step.

Case B: l≥kl \ge k. Then S→TS \to T is an edge in the set EE of line L1. If SS and TT were in the same component, that component would have a cycle (two statements, or the self edge S→SS \to S when S=TS = T), and line L6 would call CODEGEN at level k+1k + 1 on a region that holds both, against the choice of RR. So they are in different components, and the edge goes from the component of SS to that of TT. Line L2 puts the component of SS first. The instances agree on i1,…,ik−1i_1, \dots, i_{k-1}, so they are in the same run of the code of this call, in which all the code of the component of SS runs before all the code of the component of TT. The pair is in order, and not in one step. □\square

Theorem 2 (the vector level). Statement SS becomes a vector node (S,m)(S, m) where mm is the least integer m≥1m \ge 1 such that SS is on no cycle of GmG_m. Also m≤dS+1m \le d_S + 1.

Proof. The graphs shrink as mm grows: G1⊇G2⊇⋯⊇Gn+1G_1 \supseteq G_2 \supseteq \dots \supseteq G_{n+1}. By Lemma 1(b), SS is on no cycle of GdS+1G_{d_S + 1} when dS<nd_S < n, and by Lemma 1(c) when dS=nd_S = n. So the least mm is at most dS+1d_S + 1.

Let Ck(S)C_k(S) be the set of statements that are on a common cycle with SS in GkG_k, together with SS; this is the strongly connected component of SS in GkG_k. We show by induction on kk: if the call at level kk whose region contains SS exists, its region contains Ck(S)C_k(S), and the component of SS that its line L2 finds is exactly Ck(S)C_k(S). For k=1k = 1 the region is all statements and EE is all edges of G1G_1. For the step, the call at level k+1k + 1 exists only if line L4 found Ck(S)C_k(S) cyclic, and its region is Ck(S)C_k(S). A cycle of Gk+1G_{k+1} through SS is a cycle of GkG_k, so Ck+1(S)⊆Ck(S)C_{k+1}(S) \subseteq C_k(S), and line L1 at level k+1k + 1 keeps every edge of Gk+1G_{k+1} inside Ck(S)C_k(S). So the component of SS there is Ck+1(S)C_{k+1}(S).

Line L4 at level kk finds the component of SS cyclic exactly when SS is on a cycle of GkG_k. So the calls go down while SS is on a cycle, and SS becomes a vector node at the first level mm where it is not. □\square

Theorem 3 (maximality in the distribution model). Take any program built from the original loops, in their original nesting and direction, by loop distribution and by reordering the pieces at each level, in which each statement SS is in one vector node (S,k)(S, k) that replaces its loops kk to dSd_S. If the program keeps every dependence pair in order and has no pair inside one step, then k≥mSk \ge m_S for each statement, where mSm_S is the level of Theorem 2.

Proof. Assume that the program runs SS as (S,k)(S, k) with k<mSk < m_S. Then SS is on a cycle S=S0→S1→⋯→Sp=SS = S_0 \to S_1 \to \dots \to S_p = S of GkG_k, which we take simple. If p=1p = 1, a pair of instances of SS has level kk or more, so it shares i1,…,ik−1i_1, \dots, i_{k-1} and lies in one step, which is not allowed. So p≥2p \ge 2, and SS appears only at the two ends of the cycle.

By Lemma 1(b), every statement of the cycle has depth at least kk, so it is inside the loops 11 to k−1k - 1 of the original program. In the new program these loops were distributed, and the pieces were ordered. At the level of the vector node (S,k)(S, k), inside the loops 11 to k−1k - 1 that hold it, consider the sequence of pieces that holds (S,k)(S, k). Each statement of the cycle with the same i1,…,ik−1i_1, \dots, i_{k-1} as SS either runs in a piece of this sequence or runs entirely before or after the whole sequence; we give it the position −∞-\infty or +∞+\infty in those two cases and the index of its piece otherwise. The order of the pieces does not depend on i1,…,ik−1i_1, \dots, i_{k-1}. Write P(X)P(X) for the position of statement XX.

Each edge Sa→Sa+1S_a \to S_{a+1} comes from a pair of level kk or more, so its two instances share i1,…,ik−1i_1, \dots, i_{k-1}. The program keeps the pair in order, so P(Sa)≤P(Sa+1)P(S_a) \le P(S_{a+1}), because a later position runs later for the same outer indices. When one of SaS_a and Sa+1S_{a+1} is SS, the inequality is strict: the piece of SS is the single step (S,k)(S, k), and the other statement is not SS, so it is in another piece or outside the sequence. Around the cycle this gives P(S)<P(S)P(S) < P(S), which is impossible. □\square

Theorem 3 is limited to programs of this kind. Darte and Vivien (1997) proved a stronger result: if the only information about the dependences is their level, no transformation finds more parallel loops than Allen and Kennedy's algorithm.

Termination and cost. Each call at level kk calls itself only at level k+1k + 1, and by Lemma 1(c) no call at level n+2n + 2 is made, so the depth of the recursion is at most n+1n + 1. The regions of the calls at one level are disjoint. If each call passes the edges inside each child region down to that child, the work at one level is O(r+e)O(r + e) for line L1, Tarjan's algorithm and the topological sort. The total is O(n(r+e))O(n(r + e)) time.

Complexity

Each call runs Tarjan's algorithm and a topological sort on the edges inside its region, in O(rR+eR)O(r_R + e_R) time. The regions of the calls at one level are disjoint, so one level costs O(r+e)O(r + e) in total, and there are at most n+1n + 1 levels. The worst case is O(n(r+e))O(n(r + e)) time and O(r+e)O(r + e) extra space for the graph, the component lists and the recursion. In a real compiler the dependence tests that build the graph cost far more than codegen. The implementation on this page builds the graph by brute force over all pairs of instances on small loop bounds, which is quadratic in the number of instances and is only for testing.

Properties

  • Distribution only. The algorithm never interchanges loops and never changes the order of iterations of a loop it keeps. It only distributes loops and reorders statements.
  • Level information only. It uses the level of each edge and nothing else. The direction vectors and distances are not needed.
  • Sequential loops are kept whole. A loop that stays sequential at level kk is a plain loop. Its inner part may still have vector statements and DOALL loops.
  • Parallel loops as well as vectors. The same recursion, with "run as a parallel loop" instead of "emit as a vector statement", finds DOALL loops; that is the version that Darte and Vivien study.

Variants and improvements

  • Breaking cycles first. Scalar expansion, renaming, node splitting and loop skewing remove some dependences or change their level before codegen runs. Allen and Kennedy describe them in the chapter on fine-grained parallelism of their book.
  • Loop interchange. In a cyclic component, a loop that carries no dependence of the component can move inward, so that the vector statement runs along it; see loop interchange.
  • Self anti-dependences. A statement such as A[i] = A[i+1] + 1 has a self edge that is an anti-dependence. The read-then-write semantics of a vector statement keeps it, so a compiler can ignore such edges in line L4. The plain algorithm does not.
  • Fixed-length vectors. A machine with vectors of VLVL elements runs a vector statement in strips of VLVL; see strip mining and vectorization.
  • Richer dependence information. With distance vectors or dependence polyhedra, more parallelism is possible, for example by skewing; the hyperplane method and Feautrier's scheduling use it.

When to use it

Use it in a vectorizing or parallelizing compiler for loop nests whose dependences are known only up to their level, or whose distances are not uniform. It is simple, fast and optimal for that information. For innermost-loop SIMD code on modern processors it is the core of loop vectorization, together with strip mining and alignment. For short straight-line code, SLP vectorization packs statements of one block instead.

Pitfalls

  • Text order instead of topological order. With S1: C[i] = A[i-1] and S2: A[i] = B[i], the only edge goes from S2 to S1, carried at level 1. The vector statements must run S2 first. Emitting them in text order reads AA before it is written.
  • Dropping loop-independent edges at deep levels. Line L1 must keep the edges of level n+1n + 1 at every level. Without them, two statements of one iteration can come out in the wrong order.
  • Edges of level exactly kk. Line L1 takes level kk or more, not only level kk. Edges carried deeper still order the statements.
  • Missing self edges. A single statement with a carried edge to itself, such as A[i+1] = A[i] + 1, is a cycle. Treating every one-statement component as acyclic gives a wrong vector statement.
  • Element-by-element semantics. The proof uses the rule that a vector statement reads all operands before it writes. That holds for the statements that the algorithm emits, but not for a hand-written loop that a reader takes for a vector statement.
  • A scalar on every iteration. A scalar temporary written in each iteration makes a cycle at every level. Expand it into an array first.

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.

allen_kennedy_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/allen-kennedy-algorithm/. The authors are listed in prov/WZS56G.jsonl.
"""Allen-Kennedy vector code generation (codegen) on a chain of loops.

A program is one chain of loops: loop 1 holds loop 2, which holds loop 3,
and so on up to depth n. Loop l runs its index from bounds[l-1][0] to
bounds[l-1][1], both included. The statements are listed in text order.
Statement S sits at depth d (it is inside loops 1 to d) and has the form

    W[f(i)] = c0 + c1 * R1[g1(i)] + ... + e . i     (mod MOD)

where every subscript is affine in the d indices of S. The statements with
a depth of l + 1 or more must be contiguous in the text for every l, so that
the loops form one chain.

The dependence graph has an edge (S, T, level) for each pair of instances
S(i) before T(j) that touch the same cell, at least one of them a write.
The level is the first loop where i and j differ, or LI = n + 1 for a
loop-independent dependence. codegen(R, k) follows the page: it takes the
strongly connected components of the edges of level k or more inside R, in
topological order; a cyclic component becomes a sequential loop at level k
with a recursive call at level k + 1, and an acyclic one (a single
statement) becomes a vector statement over the loops k to depth(S).
"""

from itertools import product

MOD = (1 << 61) - 1


class Stmt:
    """A statement W[f(i)] = c0 + sum(c_r * R_r[g_r(i)]) + e . i."""

    def __init__(self, name, depth, write, reads, coefs, const=1, idx_coefs=None):
        self.name = name
        self.depth = depth
        self.write = write          # (array, [(coeffs, const), ...])
        self.reads = reads          # list of (array, [(coeffs, const), ...])
        self.coefs = coefs          # one integer per read
        self.const = const
        self.idx_coefs = idx_coefs or [0] * depth

    def cell(self, acc, it):
        arr, subs = acc
        return (arr,) + tuple(sum(a * x for a, x in zip(co, it)) + c for co, c in subs)

    def value(self, mem, it, init):
        v = self.const + sum(e * x for e, x in zip(self.idx_coefs, it))
        for co, acc in zip(self.coefs, self.reads):
            v += co * read(mem, self.cell(acc, it), init)
        return v % MOD


class Program:
    def __init__(self, bounds, stmts):
        self.bounds = bounds        # list of (lo, hi) per loop level
        self.stmts = stmts
        self.n = len(bounds)
        check_chain(self)


def check_chain(prog):
    """The statements of depth > l form one contiguous run, for each l."""
    for l in range(prog.n):
        pos = [p for p, s in enumerate(prog.stmts) if s.depth > l]
        if pos and pos[-1] - pos[0] + 1 != len(pos):
            raise ValueError("the loops do not form one chain")


def read(mem, cell, init):
    if cell not in mem:
        mem[cell] = init(cell)
    return mem[cell]


def instances(prog):
    """All statement instances (s, it) in the order of the sequential program."""
    out = []

    def body(level, prefix, ids):
        p = 0
        while p < len(ids):
            s = ids[p]
            if prog.stmts[s].depth == level:
                out.append((s, prefix))
                p += 1
            else:
                q = p
                while q < len(ids) and prog.stmts[ids[q]].depth > level:
                    q += 1
                lo, hi = prog.bounds[level]
                for v in range(lo, hi + 1):
                    body(level + 1, prefix + (v,), ids[p:q])
                p = q

    body(0, (), list(range(len(prog.stmts))))
    return out


def accesses(prog, inst):
    s, it = inst
    st = prog.stmts[s]
    for acc in st.reads:
        yield st.cell(acc, it), False
    yield st.cell(st.write, it), True


def dependence_pairs(prog):
    """Brute force: every dependent pair of instances (src, snk), src first."""
    seq = instances(prog)
    by_cell = {}
    for pos, inst in enumerate(seq):
        for cell, w in accesses(prog, inst):
            by_cell.setdefault(cell, []).append((pos, inst, w))
    pairs = set()
    for lst in by_cell.values():
        for a in range(len(lst)):
            for b in range(a + 1, len(lst)):
                pa, ia, wa = lst[a]
                pb, ib, wb = lst[b]
                if (wa or wb) and pa != pb:
                    pairs.add((ia, ib) if pa < pb else (ib, ia))
    return pairs


def level_of(prog, src, snk):
    """First loop level where the common indices differ, or n + 1 (loop independent)."""
    (s, i), (t, j) = src, snk
    c = min(prog.stmts[s].depth, prog.stmts[t].depth)
    for l in range(c):
        if i[l] != j[l]:
            return l + 1
    return prog.n + 1


def dependence_graph(prog, pairs=None):
    """Edges (s, t, level) of the statement-level dependence graph."""
    if pairs is None:
        pairs = dependence_pairs(prog)
    return {(a[0], b[0], level_of(prog, a, b)) for a, b in pairs}


def tarjan_scc(nodes, succ):
    """Strongly connected components (Tarjan); returns a list of lists."""
    index, low, on, stack, comps = {}, {}, set(), [], []
    counter = [0]

    def visit(v):
        index[v] = low[v] = counter[0]
        counter[0] += 1
        stack.append(v)
        on.add(v)
        for w in succ.get(v, ()):
            if w not in index:
                visit(w)
                low[v] = min(low[v], low[w])
            elif w in on:
                low[v] = min(low[v], index[w])
        if low[v] == index[v]:
            comp = []
            while True:
                w = stack.pop()
                on.discard(w)
                comp.append(w)
                if w == v:
                    break
            comps.append(sorted(comp))

    for v in nodes:
        if v not in index:
            visit(v)
    return comps


def topo_components(nodes, edges):
    """SCCs in a topological order of the condensation, ties by text order."""
    succ = {}
    for a, b in edges:
        succ.setdefault(a, []).append(b)
    comps = tarjan_scc(sorted(nodes), succ)
    where = {v: c for c, comp in enumerate(comps) for v in comp}
    indeg = [0] * len(comps)
    out = [set() for _ in comps]
    for a, b in edges:
        ca, cb = where[a], where[b]
        if ca != cb and cb not in out[ca]:
            out[ca].add(cb)
            indeg[cb] += 1
    ready = sorted((comps[c][0], c) for c in range(len(comps)) if indeg[c] == 0)
    order = []
    while ready:
        _, c = ready.pop(0)
        order.append(comps[c])
        for d in out[c]:
            indeg[d] -= 1
            if indeg[d] == 0:
                ready.append((comps[d][0], d))
                ready.sort()
    return order


def codegen(prog, graph, region=None, k=1):
    """Allen-Kennedy codegen(R, k). Returns a list of nodes:
    ("loop", k, children) is a sequential loop at level k, and
    ("vec", s, k) runs statement s as a vector statement over loops k to depth(s)."""
    if region is None:
        region = list(range(len(prog.stmts)))
    rs = set(region)
    edges = [(a, b) for a, b, lev in graph if a in rs and b in rs and lev >= k]  # @line L1
    comps = topo_components(region, edges)  # @line L2
    code = []
    for comp in comps:  # @line L3
        if len(comp) > 1 or (comp[0], comp[0]) in edges:  # @line L4
            assert all(prog.stmts[s].depth >= k for s in comp)
            inner = codegen(prog, graph, comp, k + 1)  # @line L6
            code.append(("loop", k, inner))  # @line L5
        else:  # @line L7
            s = comp[0]  # @line L8
            code.append(("vec", s, k))  # @line L9
    return code


def vector_levels(code, out=None):
    """For each statement, the level k at which it is vectorized."""
    if out is None:
        out = {}
    for node in code:
        if node[0] == "loop":
            vector_levels(node[2], out)
        else:
            out[node[1]] = node[2]
    return out


def run_sequential(prog, init):
    mem = {}
    for s, it in instances(prog):
        st = prog.stmts[s]
        v = st.value(mem, it, init)
        mem[st.cell(st.write, it)] = v
    return mem


def run_code(prog, code, init, steps=None):
    """Run generated code. A vector statement reads all its operands, then
    writes all its results. If steps is a dict, it records for each instance
    the number of the step (vector statement execution) that ran it."""
    mem = {}
    counter = [0]

    def run(nodes, prefix):
        for node in nodes:
            if node[0] == "loop":
                lo, hi = prog.bounds[node[1] - 1]
                for v in range(lo, hi + 1):
                    run(node[2], prefix + (v,))
            else:
                s, k = node[1], node[2]
                st = prog.stmts[s]
                ranges = [range(lo, hi + 1) for lo, hi in prog.bounds[k - 1:st.depth]]
                its = [prefix[:k - 1] + rest for rest in product(*ranges)]
                vals = [st.value(mem, it, init) for it in its]
                for it, v in zip(its, vals):
                    mem[st.cell(st.write, it)] = v
                if steps is not None:
                    for it in its:
                        steps[(s, it)] = counter[0]
                counter[0] += 1

    run(code, ())
    return mem


NAMES = "ijklmn"


def show_sub(co, c, vec_from):
    terms = []
    for l, a in enumerate(co):
        if a:
            v = NAMES[l]
            terms.append((v if a == 1 else "-" + v if a == -1 else f"{a}*{v}"))
    s = "+".join(terms).replace("+-", "-")
    if c or not s:
        s = (s + ("+" if c > 0 and s else "") + str(c)) if s else str(c)
    return s


def show(prog, code, indent=0):
    """Print generated code; a vector statement lists its vector indices."""
    lines = []
    pad = "  " * indent
    for node in code:
        if node[0] == "loop":
            l = node[1]
            lo, hi = prog.bounds[l - 1]
            lines.append(f"{pad}for {NAMES[l - 1]} = {lo} to {hi}:")
            lines.extend(show(prog, node[2], indent + 1))
        else:
            s, k = node[1], node[2]
            st = prog.stmts[s]

            def acc(a):
                arr, subs = a
                return arr + "".join("[" + show_sub(co, c, k) + "]" for co, c in subs)

            parts = [acc(r) for r in st.reads] + ([str(st.const)] if st.const else [])
            rhs = " + ".join(parts) or "0"
            vec = ",".join(NAMES[l] for l in range(k - 1, st.depth))
            head = f"vector ({vec}): " if vec else ""
            lines.append(f"{pad}{head}{st.name}: {acc(st.write)} = {rhs}")
    return lines


def sub(coeffs, const):
    return (tuple(coeffs), const)


def book_example(N=2, size=4):
    """The imperfect nest of the page (a small copy of Allen and Kennedy's example):

    for i: S1: X[i] = Y[i] + 10
           for j: S2: B[j] = A[j][N]
                  for k: S3: A[j+1][k] = B[j] + C[j][k]
                  S4: Y[i+j] = A[j+1][N]
    """
    b = [(1, size)] * 3
    s1 = Stmt("S1", 1, ("X", [sub([1], 0)]), [("Y", [sub([1], 0)])], [1], 10)
    s2 = Stmt("S2", 2, ("B", [sub([0, 1], 0)]), [("A", [sub([0, 1], 0), sub([0, 0], N)])], [1], 0)
    s3 = Stmt("S3", 3, ("A", [sub([0, 1, 0], 1), sub([0, 0, 1], 0)]),
              [("B", [sub([0, 1, 0], 0)]), ("C", [sub([0, 1, 0], 0), sub([0, 0, 1], 0)])], [1, 1], 0)
    s4 = Stmt("S4", 2, ("Y", [sub([1, 1], 0)]), [("A", [sub([0, 1], 1), sub([0, 0], N)])], [1], 0)
    return Program(b, [s1, s2, s3, s4])


if __name__ == "__main__":
    prog = book_example()
    g = dependence_graph(prog)
    for e in sorted(g):
        print(prog.stmts[e[0]].name, "->", prog.stmts[e[1]].name, "level", e[2])
    print("\n".join(show(prog, codegen(prog, g))))
test_allen_kennedy_algorithm.py 208 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/allen-kennedy-algorithm/. The authors are listed in prov/WZS56G.jsonl.

import random

from allen_kennedy_algorithm import (
    MOD,
    Program,
    Stmt,
    book_example,
    codegen,
    dependence_graph,
    dependence_pairs,
    run_code,
    run_sequential,
    show,
    vector_levels,
)


def init_value(cell):
    v = 7
    for x in cell:
        v = (v * 1000003 + (ord(x) if isinstance(x, str) else x + 50)) % MOD
    return v


def random_program(rng):
    n = rng.randint(1, 3)
    bounds = [(rng.randint(0, 1), rng.randint(2, 3)) for _ in range(n)]
    while True:
        r = rng.randint(1, 4)
        depths = [rng.randint(1, n) for _ in range(r)]
        ok = True
        for l in range(n):
            pos = [p for p, d in enumerate(depths) if d > l]
            if pos and pos[-1] - pos[0] + 1 != len(pos):
                ok = False
        if ok:
            break
    arrays = {"A": rng.randint(1, 2), "B": rng.randint(1, 2), "C": 1}

    def access(d):
        arr = rng.choice("ABC")
        subs = []
        for _ in range(arrays[arr]):
            co = [0] * d
            if rng.random() < 0.85:
                co[rng.randrange(d)] = rng.choice([1, 1, 1, -1, 2])
            subs.append((tuple(co), rng.randint(-1, 1)))
        return (arr, subs)

    stmts = []
    for s, d in enumerate(depths):
        reads = [access(d) for _ in range(rng.randint(0, 2))]
        coefs = [rng.randrange(1, MOD) for _ in reads]
        idx = [rng.randrange(MOD) for _ in range(d)]
        stmts.append(Stmt(f"S{s + 1}", d, access(d), reads, coefs, rng.randrange(MOD), idx))
    return Program(bounds, stmts)


def on_cycle(graph, s, m):
    """Brute force: is s reachable from itself through edges of level >= m?"""
    succ = {}
    for a, b, lev in graph:
        if lev >= m:
            succ.setdefault(a, set()).add(b)
    seen, todo = set(), list(succ.get(s, ()))
    while todo:
        v = todo.pop()
        if v == s:
            return True
        if v not in seen:
            seen.add(v)
            todo.extend(succ.get(v, ()))
    return False


def ordered_partitions(items):
    if not items:
        yield []
        return
    first, rest = items[0], items[1:]
    for part in ordered_partitions(rest):
        for i in range(len(part)):
            yield part[:i] + [[first] + part[i]] + part[i + 1:]
        for i in range(len(part) + 1):
            yield part[:i] + [[first]] + part[i:]


def all_codes(prog, region, k):
    """Every code of the model: loop distribution and statement order at each
    level, each piece a sequential loop at level k or a one-statement vector."""
    out = []
    for part in ordered_partitions(region):
        choices = []
        for block in part:
            opts = []
            if len(block) == 1:
                opts.append(("vec", block[0], k))
            if all(prog.stmts[s].depth >= k for s in block):
                for inner in all_codes(prog, sorted(block), k + 1):
                    opts.append(("loop", k, inner))
            choices.append(opts)
        combos = [[]]
        for opts in choices:
            combos = [c + [o] for c in combos for o in opts]
        out.extend(combos)
    return out


def keeps_all(prog, code, pairs):
    steps = {}
    run_code(prog, code, init_value, steps)
    return all(steps[a] < steps[b] for a, b in pairs)


def test_book_example():
    prog = book_example()
    code = codegen(prog, dependence_graph(prog))
    assert show(prog, code) == [
        "for i = 1 to 4:",
        "  for j = 1 to 4:",
        "    S2: B[j] = A[j][2]",
        "    vector (k): S3: A[j+1][k] = B[j] + C[j][k]",
        "  vector (j): S4: Y[i+j] = A[j+1][2]",
        "vector (i): S1: X[i] = Y[i] + 10",
    ]
    assert run_code(prog, code, init_value) == run_sequential(prog, init_value)


def test_simple_cases():
    s = lambda co, c: (tuple(co), c)
    # A[i+1] = A[i] + B[i]: a flow cycle at level 1, so a sequential loop.
    rec = Program([(1, 5)], [Stmt("S1", 1, ("A", [s([1], 1)]), [("A", [s([1], 0)]), ("B", [s([1], 0)])], [1, 1], 0)])
    assert codegen(rec, dependence_graph(rec)) == [("loop", 1, [("vec", 0, 2)])]
    # S1: A[i] = B[i]; S2: C[i] = A[i-1]: no cycle, both vector, S1 first.
    two = Program([(1, 5)], [
        Stmt("S1", 1, ("A", [s([1], 0)]), [("B", [s([1], 0)])], [1], 0),
        Stmt("S2", 1, ("C", [s([1], 0)]), [("A", [s([1], -1)])], [1], 0)])
    assert codegen(two, dependence_graph(two)) == [("vec", 0, 1), ("vec", 1, 1)]
    # Backward carried dependence: S1 reads A[i+1], S2 writes A[i]. The
    # vector code must put S1 first; its read of A[i+1] precedes S2's write.
    back = Program([(1, 5)], [
        Stmt("S1", 1, ("B", [s([1], 0)]), [("A", [s([1], 1)])], [1], 0),
        Stmt("S2", 1, ("A", [s([1], 0)]), [("C", [s([1], 0)])], [1], 0)])
    code = codegen(back, dependence_graph(back))
    assert code == [("vec", 0, 1), ("vec", 1, 1)]
    assert run_code(back, code, init_value) == run_sequential(back, init_value)
    # S1: C[i] = A[i-1]; S2: A[i] = B[i]. The only edge goes from S2 to S1
    # (carried flow), so the topological order puts S2 first. Text order
    # would read A before it is written.
    rev = Program([(1, 5)], [
        Stmt("S1", 1, ("C", [s([1], 0)]), [("A", [s([1], -1)])], [1], 0),
        Stmt("S2", 1, ("A", [s([1], 0)]), [("B", [s([1], 0)])], [1], 0)])
    code = codegen(rev, dependence_graph(rev))
    assert code == [("vec", 1, 1), ("vec", 0, 1)]
    assert run_code(rev, code, init_value) == run_sequential(rev, init_value)
    wrong = [("vec", 0, 1), ("vec", 1, 1)]
    assert run_code(rev, wrong, init_value) != run_sequential(rev, init_value)


def test_random_programs_keep_every_dependence():
    rng = random.Random(1987)
    for _ in range(300):
        prog = random_program(rng)
        pairs = dependence_pairs(prog)
        graph = dependence_graph(prog, pairs)
        code = codegen(prog, graph)
        steps = {}
        mem = run_code(prog, code, init_value, steps)
        for a, b in pairs:
            assert steps[a] < steps[b], (a, b)
        assert mem == run_sequential(prog, init_value)


def test_vector_level_is_first_acyclic_level():
    rng = random.Random(9)
    for _ in range(300):
        prog = random_program(rng)
        graph = dependence_graph(prog)
        lv = vector_levels(codegen(prog, graph))
        for s, st in enumerate(prog.stmts):
            m = 1
            while m <= prog.n and on_cycle(graph, s, m):
                m += 1
            assert lv[s] == m
            assert m <= st.depth + 1


def test_maximal_among_all_distributions():
    rng = random.Random(2001)
    tried = 0
    while tried < 60:
        prog = random_program(rng)
        if len(prog.stmts) > 3 or prog.n > 2:
            continue
        tried += 1
        pairs = dependence_pairs(prog)
        best = vector_levels(codegen(prog, dependence_graph(prog, pairs)))
        found_legal = False
        for code in all_codes(prog, list(range(len(prog.stmts))), 1):
            if keeps_all(prog, code, pairs):
                found_legal = True
                lv = vector_levels(code)
                for s in lv:
                    assert lv[s] >= best[s]
        assert found_legal

History

Randy Allen and Ken Kennedy developed the algorithm for PFC, the Parallel Fortran Converter, at Rice University, and published it in the ACM Transactions on Programming Languages and Systems in 1987. The ideas of dependence graphs and their strongly connected components came from the work of Kuck and his group at Illinois on the Parafrase system. Allen and Kennedy's 2001 book gives the algorithm under the name codegen, with the example above. In 1997 Darte and Vivien proved that it finds the most parallel loops possible when the only information is the level of each dependence.

References

  1. Randy Allen and Ken Kennedy, Automatic translation of FORTRAN programs to vector form, ACM Transactions on Programming Languages and Systems 9(4), 1987, 491-542, the vector code generation procedure (codegen on the strongly connected components of the dependence graph, level by level) and the PFC translator
  2. Randy Allen and Ken Kennedy, Optimizing Compilers for Modern Architectures, a Dependence-Based Approach, Morgan Kaufmann, 2002 (copyright 2001), Chapter 2 (the section on parallelization and vectorization, with the advanced vectorization algorithm codegen and its worked example) and Chapter 5 (transformations that break dependence cycles before vectorization)
  3. Alain Darte and Frédéric Vivien, On the optimality of Allen and Kennedy's algorithm for parallelism extraction in nested loops, Parallel Algorithms and Applications 12(1-3), 1997, 83-112, the main theorem (with dependence levels as the only information, no algorithm finds more parallel loops than Allen and Kennedy's)
  4. Michael Wolfe, High Performance Compilers for Parallel Computing, Addison-Wesley, 1996, the chapter on vector code generation (loop distribution by strongly connected components and vector statements)

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.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
  • History with a source
  • a scene preset for the example