Algorithmadvanced
Superword-level parallelism vectorization
Also called SLP vectorization.
Packs isomorphic independent statements of a basic block into SIMD instructions, starting from adjacent memory accesses.
- Time
- O(n^3) worst
- Space
- O(n^2) extra
- Where
- n = the number of statements in the basic block
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
SLP vectorization finds SIMD work inside one basic block. It packs statements that do the same operation on different data, and that do not depend on each other, into one SIMD instruction. Larsen and Amarasinghe named this superword level parallelism in 2000. Loop vectorization needs a loop whose iterations can run side by side. SLP needs only a straight block of code, for example the body of a loop after loop unrolling, or hand-unrolled code for colours, coordinates or complex numbers. The algorithm starts from loads and stores to adjacent memory cells, follows the data flow from there, and schedules the packs in an order that keeps every dependence.
In plain words
Look at a list of small steps that a program does one after the other. Often the same kind of step appears several times on neighbouring pieces of data: load the first number, load the second number, and so on, then multiply each of them. A processor can do four or eight such steps in one go, if they are of the same kind and none of them needs the result of another. The method first finds groups of loads or stores of neighbouring memory cells. It then follows where those values go and where the stored values came from, and groups the matching steps there too. In the end it writes the groups out in an order in which every value is ready before it is used.
The problem
Input. A basic block of three-address statements, and a number of lanes . A statement is a load x = A[c], a store A[c] = y, or an operation x = y op z, where x, y, z are scalar names (y and z may be constants) and c is a constant index or an address known up to a common base.
Output. A sequence of items. Each item is either one statement or a group of 2 to statements in a lane order. A group runs as one SIMD instruction: it reads the operands of all lanes, then writes all results. The output must compute the same final values of all names and all memory cells as , for every initial state.
Definitions. Two statements are isomorphic if they do the same operation: both loads from the same array, both stores to the same array, or both operations with the same operator. They are independent if there is no path of dependences from one to the other inside . A group of loads or stores is contiguous if lane accesses the cell right after the cell of lane , so that one vector load or store does the work.
The goal is to cover many statements with few groups. The best packing is an optimization problem with very many choices. The algorithm below is a greedy heuristic, and it is always correct whatever it packs.
The algorithm
SLP(B, VL)- 1
P <- the pairs (s, t) of loads or stores with t on the next cell after s, for which CANPACK(P, s, t) - 2
W <- the pairs of P ▷ a work list - 3
while W is not empty: take a pair (s, t) from W - 4
for each operand position j: let s', t' define operand j of s and t; if CANPACK(P, s', t') then add (s', t') to P and W - 5
for each pair of uses u of s and v of t at the same operand position: if CANPACK(P, u, v) then add (u, v) to P and W - 6
G <- the chains of P, joined by (s, t), (t, u) -> (s, t, u), cut where a member depends on an earlier one or the length passes VL - 7
while some statement of B is not emitted do - 8
x <- the first statement, in text order, whose item (its group, or x alone) has all its predecessors emitted - 9
if x exists then emit the item of x - 10
else split the group of the first statement not yet emitted into single statements CANPACK(P, s, t): s and t are isomorphic and independent, t is on the next cell after s if they access memory,s is the left element of no pair in P, and t is the right element of no pair in P
Lines L1 to L5 build a set of pairs. The seeds of line L1 are the cheapest packs, since a contiguous vector load or store replaces several scalar ones with no shuffle. Line L4 follows the use-def chains: if and are packed, the statements that computed their operands are good candidates, because their results then land in one vector register in the right lane order. Line L5 follows the def-use chains in the same way. The rule that each statement is the left element of at most one pair and the right element of at most one pair makes a set of disjoint chains. Line L6 joins the chains, and cuts them into groups of at most statements that are pairwise independent. Lines L7 to L10 are a list scheduler: each group waits until every statement that one of its members depends on is done. When packs wait for each other in a cycle, line L10 breaks a group up.
Example
Unroll A[i] = B[i] * C[i] + D[i] four times and write it in three-address form, with names b0, c0, m0, d0, s0 for lane 0 and so on:
b0 = B[0]; c0 = C[0]; m0 = b0 * c0; d0 = D[0]; s0 = m0 + d0; A[0] = s0
b1 = B[1]; c1 = C[1]; m1 = b1 * c1; d1 = D[1]; s1 = m1 + d1; A[1] = s1
... the same for lanes 2 and 3
These are 24 statements. Line L1 finds the seed pairs of adjacent loads , the same for and , and the adjacent stores to . Line L5 follows the uses of and (the first operand of the multiplications) and adds , and so on; it then adds the additions from the uses of the products. Line L4 would find the same pairs from the stores. Line L6 joins the pairs into six chains of four. All lanes are independent, so line L8 emits them in this order:
<b0, b1, b2, b3> = B[0:4]
<c0, c1, c2, c3> = C[0:4]
<m0, m1, m2, m3> = <b0, b1, b2, b3> * <c0, c1, c2, c3>
<d0, d1, d2, d3> = D[0:4]
<s0, s1, s2, s3> = <m0, m1, m2, m3> + <d0, d1, d2, d3>
A[0:4] = <s0, s1, s2, s3>
Six SIMD instructions replace 24 scalar ones, and every operand vector is the result of one earlier group in the same lane order, so no shuffle is needed. With the same pairs give twelve groups of two.
A blocked case. In a = A[0]; b = a + 1; A[1] = b; c = A[1]; d = c + 1; A[2] = d, the loads of A[0] and A[1] are adjacent, but the second load reads the value that the first lane stored, so a path of dependences joins them. CANPACK refuses the pair, and nothing is packed.
A cycle between packs. Suppose two groups are and , with dependences and . The first group needs done, and the second needs done. No item is ready, so line L10 splits the first group, and the scheduler emits , then the group , then .
Correctness
The full proof is in proofs/correctness.md. The output computes the same final state as , whatever pairs the heuristic picks.
- Every group is a legal SIMD instruction. Each pair passes CANPACK, so its members are isomorphic, independent and, for memory, contiguous in lane order. Isomorphism and contiguity carry along a chain. Line L6 checks independence against every earlier member of the group, not only the neighbour, because a chain does not by itself make and independent.
- The schedule keeps every dependence. The first statement not yet emitted has all its predecessors emitted, because they come earlier in the text. So if it is alone, it is ready, and if nothing is ready it is in a group, which line L10 splits. Each split removes a group, so the loop ends. An item is emitted only after every predecessor of each member, and no predecessor is inside the item, by independence.
- Same values. If every dependence keeps its order, each read sees the same last writer as in , by the reordering argument for straight-line code. Inside a group no lane reads or writes a location that another lane writes, so reading all lanes before writing them is the same as running them one by one.
Proof: SLP vectorization emits legal SIMD groups in an order that computes the same valuesfull
A location is a scalar name or a memory cell. A statement reads some locations and writes one. Statements and with have a dependence if they touch a common location and at least one of them writes it. We write if there is a path of dependences from to . Two statements are independent if neither nor . A group runs by reading all operands of all its lanes from the current state, and then writing all results.
Lemma 1 (pairs). Every pair in has and isomorphic and independent, and if they access memory, accesses the cell right after the cell of . Every statement is the left element of at most one pair and the right element of at most one pair.
Proof. Lines L1, L4 and L5 add a pair only after CANPACK accepts it, and CANPACK checks exactly these facts against the current . A pair is never removed.
By the second statement of Lemma 1, the pairs form disjoint simple paths and cycles in the graph whose edges are the pairs. Line L6 walks each path from its start, and each cycle from some member, and cuts it into pieces.
Lemma 2 (groups). Each group produced by line L6 has , all members are pairwise isomorphic and pairwise independent, and if they access memory, accesses the cell after for each .
Proof. Consecutive members form a pair of , so by Lemma 1 they are isomorphic and, for memory, adjacent. Isomorphism is an equivalence relation (same kind and same array or operator), so all members are isomorphic. Line L6 adds a member to the current group only if it is independent of every member already in it and the group has fewer than members; otherwise it starts a new group. So all members are pairwise independent and . Groups of one member are dropped and run as scalar statements.
Lemma 3 (schedule). The loop of lines L7 to L10 ends. It emits every statement exactly once. For every dependence , the item of is emitted strictly before the item of .
Proof. Let be the first statement, in text order, that is not yet emitted. Every predecessor of has , so it is emitted. If is not in a group, its item is ready, and line L8 finds an item. So when no item is ready, is in a group, and line L10 removes that group. Every round either emits at least one statement or removes a group, so after at most emissions and removals the loop ends with all statements emitted. An emitted item is marked done as a whole, so no statement is emitted twice.
Take a dependence . If and were in one item, that item would be a group with , against Lemma 2 (a split only makes smaller items). So they are in different items. Line L8 emits the item of only when every predecessor of every member is emitted, so is emitted earlier.
Lemma 4 (one group is a sequence). Running a group as one instruction gives the same state as running its members one by one in lane order.
Proof. The members are pairwise independent, so in particular no two of them have a dependence: no member reads a location that another member writes, and no two members write the same location. In the sequential run, each member reads only locations that no other member writes, so it reads the values of the state before the group, as the SIMD run does. The members write different locations, so the order of the writes does not matter.
Theorem. For every initial state, the emitted code computes the same final values of all locations as the block .
Proof. By Lemma 4, the emitted code is the same as the sequential run of a permutation of the statements of (the items in order, the lanes of each group in lane order). By Lemma 3, keeps the order of every dependent pair. We show by induction along that each statement reads the same values in as in , and so writes the same value.
Take a location that reads. If no statement before in writes , then no such statement exists before in either: a writer of after in has the dependence , so it stays after . So reads the initial value in both. Otherwise let be the last writer of before in . The dependence keeps before in . Any other writer of before in comes before in and has the dependence , so it stays before . Any writer after in stays after . So the last writer of before in is . By the induction hypothesis writes the same value in both runs, so reads the same value.
For the final state, the last writer of each location in stays after all other writers of that location, by the output dependences, and it writes the same value. Locations that no statement writes keep their initial values.
The proof uses none of the heuristic choices: which seeds line L1 tries first, which candidate lines L4 and L5 accept, or where line L6 starts a cycle. Those choices change only how many statements end up in groups.
Complexity
Let be the number of statements. Computing the dependences of a block of constant-index accesses costs , and the reachability sets for the independence test cost with edges, and space. The seeds take tests. Each statement is the left element of at most one pair, so at most pairs enter the work list. A pair costs for its definitions and for pairs of uses, so the extension is . Line L6 is . Each emission of the scheduler scans statements and edges, and there are at most emissions and splits, so it is too. The total is time. Production compilers limit the size of the block or the search, and use cost models; the cubic bound is for the plain algorithm.
Properties
- Always correct. The heuristic choices (which seeds, which candidate when several fit) change only the speed of the result.
- Not optimal. A greedy choice can block a better packing. The best packing is an optimization problem; goSLP solves it pairwise optimally with integer linear programming.
- Lane order matters for cost, not for correctness. If an operand vector is not one earlier group in the same order, the compiler needs shuffles or inserts, which cost instructions. The use-def and def-use extension keeps the lanes aligned along the data flow.
- Works without loops. It finds parallelism in straight code, so it also helps loops that loop vectorization rejects, after unrolling.
Variants and improvements
- Cost-driven choice. Larsen and Amarasinghe estimate the savings of each candidate pair, counting packing and unpacking costs, and pick the best one when several fit. The implementation here takes the first candidate that fits.
- Bottom-up from stores. Some compilers, LLVM among them, start mainly from groups of adjacent stores, build a tree of packs toward the loads, and keep the tree if a cost model says it pays.
- Global packing. goSLP (Mendis and Amarasinghe, 2018) chooses the packs of a whole function by integer linear programming over pairs, and picks the lane permutations by dynamic programming.
- Loop-aware SLP. Unroll a loop by and run SLP on the body. This covers loops whose statements are isomorphic only after unrolling, and loops with a few lanes of different shape.
- Reductions and alternating operations. Extensions pack trees of additions that end in one sum, and pairs such as
+and-in alternate lanes, when the machine has an add-subtract instruction.
When to use it
Use SLP for code that is already unrolled, for structures of a few fields that are processed in the same way, and as a second pass after loop vectorization. Use loop vectorization when a loop has many iterations with the same body; it does not need unrolling and covers long trip counts with one vector loop. For a whole loop nest with carried dependences, the Allen-Kennedy algorithm is the tool.
Pitfalls
- Checking independence only between neighbours. Two pairs and can each be independent while depends on through a third statement. Packing , and into one group then reads a value before it is written.
- Direct dependence instead of a path. Two statements with no direct dependence may still be joined by a path through others. Packing them makes the group wait for a statement that waits for the group.
- Unknown addresses. With pointers, two stores may hit the same cell. Without an alias analysis that proves otherwise, the compiler must add a dependence, which blocks the pack.
- Packs that do not pay. A group whose operands come from scattered scalars needs one insert per lane, and a group whose results are used one by one needs one extract per lane. The cost model must count these, or the vector code is slower.
- Ignoring cycles between groups. A scheduler that just emits groups in text order can run a group before a statement that one of its members needs.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slp-vectorization/. The authors are listed in prov/VMGC16.jsonl.
"""Superword-level parallelism (SLP) vectorization of one basic block.
A basic block is a list of statements in three-address form:
("load", x, (A, c)) x = A[c]
("store", (A, c), y) A[c] = y
("op", x, (o, y, z)) x = y o z, with o in "+", "-", "*"
Here x, y, z are scalar names (y and z may also be int constants), A is an
array name and c is a constant index. The algorithm follows Larsen and
Amarasinghe (PLDI 2000): seed pairs from adjacent memory accesses, extend
the pairs along use-def and def-use chains, combine the pairs into groups of
at most VL statements, and schedule the groups in dependence order. A group
runs as one SIMD instruction: it reads the operands of all its lanes, then
writes all its results.
"""
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b}
def reads(st):
"""Locations read by a statement: ("v", name) or ("m", array, index)."""
kind, tgt, arg = st
if kind == "load":
return [("m",) + arg]
if kind == "store":
return [("v", arg)] if isinstance(arg, str) else []
return [("v", a) for a in arg[1:] if isinstance(a, str)]
def writes(st):
kind, tgt, arg = st
return ("m",) + tgt if kind == "store" else ("v", tgt)
def dependences(block):
"""All pairs (s, t), s < t, where s and t touch one location and one writes it."""
deps = set()
for t in range(len(block)):
rt, wt = set(reads(block[t])), writes(block[t])
for s in range(t):
rs, ws = set(reads(block[s])), writes(block[s])
if ws == wt or ws in rt or wt in rs:
deps.add((s, t))
return deps
def reach(n, deps):
"""reach[s] is the set of statements t with a dependence path from s to t."""
succ = [[] for _ in range(n)]
for s, t in deps:
succ[s].append(t)
out = [set() for _ in range(n)]
for s in range(n - 1, -1, -1):
for t in succ[s]:
out[s].add(t)
out[s] |= out[t]
return out
def isomorphic(a, b):
if a[0] != b[0]:
return False
if a[0] == "load":
return a[2][0] == b[2][0]
if a[0] == "store":
return a[1][0] == b[1][0]
return a[2][0] == b[2][0]
def adjacent(a, b):
"""For memory statements: b accesses the cell right after the cell of a."""
if a[0] == "load":
(x, i), (y, j) = a[2], b[2]
elif a[0] == "store":
(x, i), (y, j) = a[1], b[1]
else:
return True
return x == y and j == i + 1
class SLP:
def __init__(self, block, vl=4):
self.block = block
self.vl = vl
self.deps = dependences(block)
self.reach = reach(len(block), self.deps)
self.left, self.right = {}, {}
def independent(self, s, t):
return t not in self.reach[s] and s not in self.reach[t]
def can_pack(self, s, t):
b = self.block
return (s != t and isomorphic(b[s], b[t]) and adjacent(b[s], b[t])
and self.independent(s, t)
and s not in self.left and t not in self.right)
def add(self, s, t):
self.left[s] = t
self.right[t] = s
def def_of(self, s, name):
"""The last statement before s that writes the scalar name, or None."""
for p in range(s - 1, -1, -1):
if writes(self.block[p]) == ("v", name):
return p
return None
def uses_of(self, s):
"""(position, user) for each read of the scalar written by s, up to its next write."""
st = self.block[s]
if st[0] == "store":
return []
name, out = st[1], []
for u in range(s + 1, len(self.block)):
us = self.block[u]
ops = [us[2]] if us[0] == "store" else list(us[2][1:]) if us[0] == "op" else []
for pos, a in enumerate(ops):
if a == name:
out.append((pos, u))
if writes(us) == ("v", name):
break
return out
def operands(self, s):
st = self.block[s]
if st[0] == "store":
return [st[2]]
if st[0] == "op":
return list(st[2][1:])
return []
def seed(self):
b = self.block
mem = [s for s in range(len(b)) if b[s][0] in ("load", "store")]
for s in mem:
for t in mem:
if self.can_pack(s, t): # @line L1
self.add(s, t)
def extend(self):
work = sorted(self.left.items()) # @line L2
while work: # @line L3
s, t = work.pop(0)
for x, y in zip(self.operands(s), self.operands(t)):
if isinstance(x, str) and isinstance(y, str):
ds, dt = self.def_of(s, x), self.def_of(t, y)
if ds is not None and dt is not None and self.can_pack(ds, dt): # @line L4
self.add(ds, dt)
work.append((ds, dt))
us, ut = self.uses_of(s), self.uses_of(t)
for ps, u in us:
for pt, v in ut:
if ps == pt and self.can_pack(u, v): # @line L5
self.add(u, v)
work.append((u, v))
def combine(self):
"""Join pairs (s, t), (t, u) into chains; cut a chain where a member
depends on an earlier member or the length would pass VL."""
groups, seen = [], set()
starts = [s for s in sorted(self.left) if s not in self.right]
cyc = [s for s in sorted(self.left) if s in self.right]
for s in starts + cyc:
if s in seen:
continue
chain = [s]
seen.add(s)
while chain[-1] in self.left and self.left[chain[-1]] not in seen:
chain.append(self.left[chain[-1]])
seen.add(chain[-1])
cur = []
for x in chain:
if len(cur) == self.vl or not all(self.independent(x, y) for y in cur):
groups.append(cur)
cur = []
cur.append(x)
groups.append(cur)
return [g for g in groups if len(g) > 1]
def schedule(self, groups):
"""Emit the items in dependence order. Returns a list of lists of
statement numbers; a list of length 1 is a scalar statement."""
return schedule(self.block, self.deps, groups)
def run(self):
self.seed()
self.extend()
groups = self.combine() # @line L6
return self.schedule(groups)
def schedule(block, deps, groups):
group_of = {}
for g in groups:
for s in g:
group_of[s] = list(g)
preds = {t: set() for t in range(len(block))}
for s, t in deps:
preds[t].add(s)
done, out = set(), []
while len(done) < len(block): # @line L7
pick = None
for s in range(len(block)): # @line L8
if s in done:
continue
item = group_of.get(s, [s])
if all(p in done or p in item for x in item for p in preds[x]):
pick = item
break
if pick is None: # @line L10
first = min(s for s in range(len(block)) if s not in done)
for x in group_of.pop(first):
group_of.pop(x, None)
continue
out.append(pick) # @line L9
done.update(pick)
return out
def slp_vectorize(block, vl=4):
return SLP(block, vl).run()
def value(arg, env):
return arg if isinstance(arg, int) else env[arg]
def run_scalar(block, env, mem):
env, mem = dict(env), dict(mem)
for st in block:
exec_items([st], env, mem)
return env, mem
def exec_items(stmts, env, mem):
"""Run statements as one SIMD instruction: read every lane, then write."""
vals = []
for kind, tgt, arg in stmts:
if kind == "load":
vals.append(mem[arg])
elif kind == "store":
vals.append(value(arg, env))
else:
vals.append(OPS[arg[0]](value(arg[1], env), value(arg[2], env)))
for (kind, tgt, arg), v in zip(stmts, vals):
if kind == "store":
mem[tgt] = v
else:
env[tgt] = v
def run_vector(block, code, env, mem):
env, mem = dict(env), dict(mem)
for item in code:
exec_items([block[s] for s in item], env, mem)
return env, mem
def unrolled_example(n=4):
"""A[i] = B[i] * C[i] + D[i] for i = 0 .. n-1, unrolled into three-address code."""
block = []
for i in range(n):
block += [("load", f"b{i}", ("B", i)), ("load", f"c{i}", ("C", i)),
("op", f"m{i}", ("*", f"b{i}", f"c{i}")), ("load", f"d{i}", ("D", i)),
("op", f"s{i}", ("+", f"m{i}", f"d{i}")), ("store", ("A", i), f"s{i}")]
return block
def show(block, code):
lines = []
for item in code:
sts = [block[s] for s in item]
kind = sts[0][0]
if len(item) == 1:
k, t, a = sts[0]
if k == "load":
lines.append(f"{t} = {a[0]}[{a[1]}]")
elif k == "store":
lines.append(f"{t[0]}[{t[1]}] = {a}")
else:
lines.append(f"{t} = {a[1]} {a[0]} {a[2]}")
elif kind == "load":
a = sts[0][2]
lines.append(f"<{', '.join(s[1] for s in sts)}> = {a[0]}[{a[1]}:{a[1] + len(sts)}]")
elif kind == "store":
t = sts[0][1]
lines.append(f"{t[0]}[{t[1]}:{t[1] + len(sts)}] = <{', '.join(str(s[2]) for s in sts)}>")
else:
o = sts[0][2][0]
lhs = ", ".join(s[1] for s in sts)
ys = ", ".join(str(s[2][1]) for s in sts)
zs = ", ".join(str(s[2][2]) for s in sts)
lines.append(f"<{lhs}> = <{ys}> {o} <{zs}>")
return lines
if __name__ == "__main__":
b = unrolled_example()
print("\n".join(show(b, slp_vectorize(b))))
test_slp_vectorization.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slp-vectorization/. The authors are listed in prov/VMGC16.jsonl.
import random
from slp_vectorization import (
run_scalar,
run_vector,
schedule,
show,
slp_vectorize,
unrolled_example,
)
def touched(st):
"""Brute force, written apart from the module: (reads, write) as sets."""
kind, tgt, arg = st
if kind == "load":
return {("mem",) + tuple(arg)}, ("var", tgt)
if kind == "store":
r = {("var", arg)} if isinstance(arg, str) else set()
return r, ("mem",) + tuple(tgt)
return {("var", a) for a in arg[1:] if isinstance(a, str)}, ("var", tgt)
def brute_deps(block):
deps = set()
for s in range(len(block)):
rs, ws = touched(block[s])
for t in range(s + 1, len(block)):
rt, wt = touched(block[t])
if ws == wt or ws in rt or wt in rs:
deps.add((s, t))
return deps
def brute_paths(n, deps):
succ = {}
for s, t in deps:
succ.setdefault(s, []).append(t)
paths = set()
for s in range(n):
todo, seen = list(succ.get(s, [])), set()
while todo:
t = todo.pop()
if t not in seen:
seen.add(t)
paths.add((s, t))
todo.extend(succ.get(t, []))
return paths
def names_and_cells(block):
names, cells = set(), set()
for st in block:
rs, w = touched(st)
for loc in rs | {w}:
(names if loc[0] == "var" else cells).add(loc[1:] if loc[0] == "mem" else loc[1])
return names, cells
def random_state(block, rng):
names, cells = names_and_cells(block)
env = {x: rng.randint(-9, 9) for x in names}
mem = {c: rng.randint(-9, 9) for c in cells}
return env, mem
def check(block, code, vl):
flat = sorted(s for item in code for s in item)
assert flat == list(range(len(block)))
deps = brute_deps(block)
paths = brute_paths(len(block), deps)
where = {s: k for k, item in enumerate(code) for s in item}
for s, t in deps:
assert where[s] < where[t], (s, t)
packs = 0
for item in code:
assert 1 <= len(item) <= vl
if len(item) == 1:
continue
packs += 1
sts = [block[s] for s in item]
k = sts[0][0]
for st in sts:
assert st[0] == k
if k == "load":
assert st[2][0] == sts[0][2][0]
elif k == "store":
assert st[1][0] == sts[0][1][0]
else:
assert st[2][0] == sts[0][2][0]
for a in item:
for b in item:
assert (a, b) not in paths
for x, y in zip(sts, sts[1:]):
if k == "load":
assert y[2] == (x[2][0], x[2][1] + 1)
if k == "store":
assert y[1] == (x[1][0], x[1][1] + 1)
return packs
def random_block(rng):
lanes = rng.randint(2, 5)
template, tvars = [], []
for j in range(rng.randint(2, 6)):
r = rng.random()
if r < 0.4 or len(tvars) < 1:
template.append(("load", f"t{j}", (rng.choice("ABC"), rng.randint(0, 4))))
tvars.append(f"t{j}")
elif r < 0.8:
a = rng.choice(tvars)
b = rng.choice(tvars + [rng.randint(1, 3)])
template.append(("op", f"t{j}", (rng.choice("+-*"), a, b)))
tvars.append(f"t{j}")
else:
template.append(("store", (rng.choice("ABC"), rng.randint(0, 4)), rng.choice(tvars)))
def inst(st, k):
kind, tgt, arg = st
if kind == "load":
return ("load", f"{tgt}_{k}", (arg[0], arg[1] + k))
if kind == "store":
return ("store", (tgt[0], tgt[1] + k), f"{arg}_{k}")
o, a, b = arg
nm = lambda x: f"{x}_{k}" if isinstance(x, str) else x
return ("op", f"{tgt}_{k}", (o, nm(a), nm(b)))
lane_code = [[inst(st, k) for st in template] for k in range(lanes)]
block = []
if rng.random() < 0.5:
for code in lane_code:
block += code
else:
pos = [0] * lanes
while any(pos[k] < len(lane_code[k]) for k in range(lanes)):
k = rng.choice([k for k in range(lanes) if pos[k] < len(lane_code[k])])
block.append(lane_code[k][pos[k]])
pos[k] += 1
for _ in range(rng.randint(0, 2)):
p = rng.randrange(len(block))
kind, tgt, arg = block[p]
if kind == "op":
block[p] = (kind, rng.choice([tgt, "t0_0"]), (rng.choice("+-*"),) + arg[1:])
elif kind == "load":
block[p] = (kind, tgt, (arg[0], rng.randint(0, 6)))
else:
block[p] = (kind, (rng.choice("ABC"), rng.randint(0, 6)), arg)
return block
def test_unrolled_loop():
b = unrolled_example()
code = slp_vectorize(b)
assert show(b, code) == [
"<b0, b1, b2, b3> = B[0:4]",
"<c0, c1, c2, c3> = C[0:4]",
"<m0, m1, m2, m3> = <b0, b1, b2, b3> * <c0, c1, c2, c3>",
"<d0, d1, d2, d3> = D[0:4]",
"<s0, s1, s2, s3> = <m0, m1, m2, m3> + <d0, d1, d2, d3>",
"A[0:4] = <s0, s1, s2, s3>",
]
assert check(b, code, 4) == 6
rng = random.Random(4)
env, mem = random_state(b, rng)
assert run_vector(b, code, env, mem) == run_scalar(b, env, mem)
# With two lanes the same block gives two groups per operation.
code2 = slp_vectorize(b, vl=2)
assert len(code2) == 12 and check(b, code2, 2) == 12
assert run_vector(b, code2, env, mem) == run_scalar(b, env, mem)
def test_dependent_chain_is_not_packed():
# a = A[0]; b = a + 1; A[1] = b; c = A[1]; d = c + 1; A[2] = d
b = [("load", "a", ("A", 0)), ("op", "b", ("+", "a", 1)), ("store", ("A", 1), "b"),
("load", "c", ("A", 1)), ("op", "d", ("+", "c", 1)), ("store", ("A", 2), "d")]
code = slp_vectorize(b)
assert code == [[0], [1], [2], [3], [4], [5]]
def test_cycle_between_groups_is_split():
# Groups {0, 3} and {1, 2} wait for each other: 0 -> 2 and 1 -> 3.
b = [("store", ("A", 0), "p"), ("store", ("B", 0), "r"),
("load", "x", ("A", 0)), ("load", "y", ("B", 0))]
deps = brute_deps(b)
code = schedule(b, deps, [[0, 3], [1, 2]])
assert code == [[0], [1, 2], [3]]
env, mem = {"p": 5, "r": 7}, {("A", 0): 1, ("B", 0): 2}
assert run_vector(b, code, env, mem) == run_scalar(b, env, mem)
def test_random_blocks():
rng = random.Random(2000)
total_packs = 0
for trial in range(400):
block = random_block(rng)
for vl in (2, 4):
code = slp_vectorize(block, vl)
total_packs += check(block, code, vl)
for _ in range(3):
env, mem = random_state(block, rng)
assert run_vector(block, code, env, mem) == run_scalar(block, env, mem)
assert total_packs > 500
def test_wrong_grouping_is_caught():
# Packing two dependent statements into one instruction changes the result,
# which is why the algorithm needs independence.
b = [("op", "x", ("+", "a", 1)), ("op", "y", ("+", "x", 1))]
env = {"a": 3, "x": 0}
assert run_vector(b, [[0, 1]], env, {}) != run_scalar(b, env, {})
assert slp_vectorize(b) == [[0], [1]]
History
Samuel Larsen and Saman Amarasinghe introduced superword level parallelism at MIT and presented the algorithm at PLDI 2000, aiming at the short SIMD units of multimedia instruction sets. They showed that unrolled loop bodies and straight-line kernels have much SIMD work that loop vectorization does not see. GCC and LLVM later added SLP vectorizers, and research went on to optimal packing, as in goSLP in 2018.
References
- Samuel Larsen and Saman Amarasinghe, Exploiting superword level parallelism with multimedia instruction sets, PLDI 2000, 145-156, Section 3 (the SLP algorithm, with alignment analysis, packset seeding from adjacent memory references, extension along use-def and def-use chains, combination of pairs and scheduling) and the definitions of isomorphic and independent statements
- Charith Mendis and Saman Amarasinghe, goSLP, globally optimized superword level parallelism framework, Proceedings of the ACM on Programming Languages 2(OOPSLA), 2018, article 110, the statement packing problem solved pairwise optimally with integer linear programming, and the choice of vector permutations by dynamic programming
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VMGC16 Edit this page History Report an error Markdown