Algorithmadvanced
Subscript-wise dependence tests
Also called ZIV SIV MIV tests, delta test.
Classifies subscript pairs by the number of loop indices they use and applies an exact test to each class, joining results by the delta test.
- Solves
- Dependence testing
- Time
- O(m^2 k + m log C + 3^k m k) worstO(m k) best
- Space
- O(m k) extra
- Where
- C = the largest absolute value of a coefficient; k = the depth of the loop nest; m = the number of subscripts
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The practical dependence tests, as organized by Goff, Kennedy and Tseng, solve the dependence testing problem one subscript at a time, with the cheapest exact test that fits each subscript. A subscript pair is ZIV if it uses no loop index, SIV if it uses one, and MIV if it uses more. Most subscripts in real code are ZIV or SIV, and for these there are exact tests that cost a few arithmetic operations and also give the distance or the direction of the dependence. Subscripts that share a loop index are coupled; the delta test passes the facts found by the SIV tests (a distance, or a fixed value of an index) into the other subscripts of the group, which often turns them into SIV subscripts too. Only the MIV subscripts that remain go to a general test such as the GCD and Banerjee tests.
In plain words
An array access with several dimensions gives one condition per dimension. Look at each one. If it uses no loop variable, it is true always or never, and that settles it. If it uses one loop variable, a short formula tells exactly which pairs of iterations satisfy it, for instance "the second access is always one iteration later". If two conditions share a loop variable, the answer from one is used to simplify the other, and the process is repeated until nothing more can be learned. Only conditions that still mix several loop variables at the end go to the slower, approximate tests. When none are left, the answer is exact: the compiler knows the exact directions and often the exact distances of the dependence.
The problem
As in dependence testing: a rectangular nest of depth with loop over , two references with affine subscripts, one equation per dimension
for the source iteration and the sink iteration . Output: "independent", or the set of direction vectors that may occur, the distance at each level where it is fixed, and a flag that says whether the set is exact. The page uses Wolfe's notation: at level means . A direction vector whose first non- entry is belongs to the dependence from the sink reference to the source reference, as described on the direction vector page. The answer "independent" must never be given when a dependence exists.
The algorithm
The tests keep, for each level , the exact set of pairs allowed by the SIV equations seen so far. Each is the whole square, empty, one point, or the integer points of a segment .
PRACTICAL-TEST(subscript pairs, bounds):- 1
for each subscript pair that uses no loop index (ZIV) do - 2
if its two constants differ then return "independent" - 3
partition the other pairs into coupled groups: pairs that share a level go together - 4
for each group do (the delta test) - 5
S_l <- all pairs in [L_l, U_l]^2, for each level l - 6
repeat - 7
rewrite each pending pair with the facts of the S_l (a point, a fixed i_l, a fixed j_l, or a distance) - 8
if a pair uses no level now: if its constant is not 0 then return "independent"; drop it - 9
if a pair uses one level l now: S_l <- S_l ∩ {solutions} (strong, weak-zero, weak-crossing or exact SIV test); drop it - 10
if some S_l is empty then return "independent" - 11
until a pass changes nothing; the pending pairs are the MIV pairs - 12
D <- the direction vectors of the group allowed by the S_l and by the GCD and Banerjee tests on each MIV pair - 13
if D is empty then return "independent" - 14
return the product of the sets D, the distances fixed by the S_l, and exact = (no MIV pair is left)
The SIV tests. Write the SIV equation of level as , so the two subscripts are and with .
| test | when | solutions |
|---|---|---|
| strong SIV | ; a dependence exists if and only if is an integer and | |
| weak-zero SIV | or | one index is fixed: or , which must be an integer in the bounds |
| weak-crossing SIV | : the pairs cross at the middle | |
| exact SIV | other | the extended Euclidean algorithm gives the solutions , cut to the bounds |
All four are exact for one equation in the bounds. The strong SIV test gives the distance at once.
The delta step (line L7). A level state gives one of four facts, and each one simplifies the other equations of the group:
- one point : the terms of level become a constant;
- a fixed (, from weak-zero): the term becomes a constant;
- a fixed (): the term becomes a constant;
- a fixed distance (, from strong SIV): the terms become , which leaves only one index of that level.
An equation that loses all but one level becomes an SIV equation, and the loop goes on.
The MIV pairs (line L12). For each combination of level directions allowed by the states, each remaining equation must pass a GCD test and a Banerjee test, where the range of each level is taken from its exact state when it has one, and from the Banerjee formulas when the level is still free.
Example
for i = 1 to 6:
for j = 1 to 6:
A[i+1][i+j] = A[i][i+j] + 1
Let be the iteration of the write and that of the read. The subscript pairs are (SIV, level 1) and (MIV, levels 1 and 2). They share level 1, so they form one coupled group.
| step | action | result |
|---|---|---|
| L9 | strong SIV on : , | |
| L7 | rewrite with | , now SIV at level 2 |
| L9 | strong SIV: | |
| L11 | no pair left; a pass changes nothing | no MIV pair, so the result is exact |
| L12 | level 1 allows only , level 2 only |
So there is exactly one flow dependence, with distance , carried by the loop. The loop can run in parallel, and loop interchange is illegal, because it would turn into . A test that looks at each subscript on its own would only learn that the second subscript allows many directions.
Proving independence. For A[i][i] = A[i][i+1] the first pair gives the strong SIV distance , so . The delta step rewrites the second pair with into , and line L8 answers "independent". The GCD test says "maybe" for each subscript.
Exact SIV beats the general tests. For A[2*i] = A[3*i + 2] with , the GCD and Banerjee tests say "maybe". The exact SIV test finds the solutions of and cuts them to the bounds: needs , and needs . The set is empty: independent.
A pair that stays MIV. For X[i+j] = X[i+j-1] in a nest, the only equation uses both levels and no SIV fact exists, so it stays MIV. Line L12 tests all nine combinations with the GCD and Banerjee tests and keeps , , and . The result is marked as not exact, although here enumeration of all pairs gives the same four vectors. The first three are flow dependences from the write to the read; is an anti dependence from the read to the write, with direction .
Correctness
The full proof is in proofs/correctness.md. Its main steps:
- Strong SIV is exact. means , so every solution has ; this needs to be an integer, and because both indices lie in . Conversely, if both hold, the pairs with are solutions, and this range is not empty.
- The other SIV tests are exact. Each describes the integer solutions of one equation in two variables as a lattice line (Bezout for the exact test), and cutting a line to a box is exact with floor and ceiling divisions.
- The delta step keeps the solution set. Each rewrite replaces a term by an expression equal to it on every pair of the level state, so the solution set of the group never changes. A dropped equation is , and an answer "independent" comes from an equation with , or from an empty level state.
- Soundness. Every real solution lies in the level states, satisfies each remaining MIV equation, and so passes the GCD and Banerjee filters with its own direction vector.
- Exactness. If no MIV equation remains, the solution set is the product of the level states, so every combination of nonempty direction parts is realized.
Proof: The SIV tests are exact, the delta test keeps every solution, and the result is exact when no MIV subscript remainsfull
Setting
The nest has depth ; loop runs over the integers and . A pair of references gives one equation per dimension,
where the source subscript is and the sink subscript is . The solution set is the set of integer pairs in the box that solve all the equations. A level is used by an equation if or . An equation is ZIV, SIV or MIV if it uses zero, one, or more levels.
A level state is a set of integer pairs , kept in one of four forms: all pairs (free), no pair (empty), one pair (point), or the pairs for the integers with (line), with .
We write for the set of with for each that solve every equation of the list . At the start is the list of the subscript equations and every is free, so .
Lemma 1 (the line in the box)
line_in_box(x0, y0, p, q, L, U) returns the state whose pairs are exactly the points , , that lie in .
Proof. For , holds exactly for ; for the division by turns the inequalities around, which gives the bounds of axis_range; for the condition does not depend on , and it holds for all or for none. The same holds for and . The set of good is the intersection of the two ranges. It is empty, one value (a point), or an interval with at least two values (a line).
Theorem 1 (exactness of the strong SIV test)
Let . The equation has an integer solution if and only if divides and for . All its solutions then have the distance , and they are the pairs for .
Proof. The equation is . If is a solution, then divides and . Both and lie in , so . Conversely, let divide and . A pair solves the equation, and it lies in the box if and only if and , that is, . This interval is nonempty: if it is and ; if it is and . So a solution exists. Every solution has , so it is of the form .
In the code, the equation is written with , so , and the line is cut to the box by Lemma 1, which gives the interval above.
Theorem 2 (exactness of the other SIV tests)
For , siv_solve(a, b, c, L, U) returns exactly the set .
Proof. Theorem 1 covers .
- Weak-zero, . The equation is . It has a solution only if divides , and then and is any integer: the line . The case is the same with the roles of and exchanged, .
- Weak-crossing, . The equation is . It has a solution only if divides , and then the solutions are the pairs with : the line .
- Exact SIV. Here and are both nonzero. Let and from the extended Euclidean algorithm. If does not divide , there is no solution (Bezout). Otherwise is a solution. If is another, then ; dividing by , with , so divides . Writing and dividing by gives . Conversely every such point is a solution. So the solutions are the line with .
In each case Lemma 1 cuts the line to the box exactly.
Lemma 2 (meet)
meet(S, a, b, c, L, U) returns .
Proof. If , the equation is , true for all pairs or for none. For a free state this is Theorem 2. For an empty state the result is empty. For a point, the code checks the equation. For a line, substitute: is . If , either every or no solves it. Otherwise it has at most one solution , which must be an integer in .
Lemma 3 (the delta step keeps the solution set)
Let be the result of propagate on an equation with the states . For every with for all , the two equations have the same truth value.
Proof. propagate changes the terms of one level at a time, and each change replaces the term by an expression equal to it on every pair of :
- is the point : on the term is the constant , which moves to the right side.
- is a line with : every pair of has , so moves to the right side.
- is a line with : every pair has , and moves to the right side.
- is a line with : every pair has . Then , and moves to the right side.
Other states are left alone. The sum of the terms is unchanged on the pairs of the states, so the two equations agree there.
Theorem 3 (the delta test keeps every solution, and ends)
During delta_test, the value of , with the list of pending equations plus the equations that were moved into states, never changes. So it is always equal to . The loop ends.
Proof. Each step does one of four things to a pending equation.
- Rewrite it by Lemma 3. On the pairs of the states the new equation is equivalent to the old one, so does not change.
- Drop it when it uses no level and : the equation holds everywhere.
- Stop with "independent" when it uses no level and : the equation never holds, so is empty.
- Move it into when it uses only level : by Lemma 2 the new state is the set of pairs of that satisfy it, so keeping it in the state is the same as keeping it in the list. If the state becomes empty, is empty, and the test stops with "independent".
So every answer "independent" is correct, and when the loop ends, where is the list of the remaining equations, each with at least two levels.
The loop ends: a pass that changes nothing ends it, and each pass that changes something removes at least one equation from the pending list, which starts with equations. So there are at most passes.
The coupled groups do not change this: two equations of different groups use disjoint sets of levels, so running the delta test on each group alone gives the same states and the same remaining equations as running it on all equations together, and is the product of the solution sets of the groups, together with all pairs of the levels that no equation uses.
Theorem 4 (soundness)
If is not empty, dependence does not answer "independent", and the direction vector of each is in the returned set. Every distance it reports is the distance of every solution at that level.
Proof. A ZIV equation that the code rejects has and no index, so it has no solution. By Theorem 3, the delta test answers "independent" only when is empty. Take and a group. By Theorem 3, for each level of the group, and the pair has the direction , so it is in the part of with that direction. level_view returns exactly this part (for a line, the condition on is a linear condition on , solved with floor and ceiling), so the direction is among the options of the level. Each remaining MIV equation holds at . term_values gives, for each level, an interval and a lattice that contain every value of on that part (the Banerjee bounds for a free level, and the exact endpoints and step of the parametrization for a point or a line). So the value is in the sum of the intervals and in the sum of the lattices, and miv_allows accepts. The vector restricted to the group is therefore in the group set, and the product over the groups and the unused levels contains . Finally, a distance is reported only for a state in which all pairs have the same difference , and every solution lies in its state.
Theorem 5 (exactness without MIV equations)
If no MIV equation remains in any group, the returned answer is exact: "independent" if and only if is empty, and the set of direction vectors is exactly .
Proof. With no MIV equation left, Theorem 3 gives : a tuple of pairs, one from each state, with no further condition. For a vector in the returned set, each level option was kept because the part of with direction is not empty (Lemma 1 and the exactness of level_view). Choosing one pair from each part gives an element of with direction . With Theorem 4, the two sets are equal. If were empty, some would be empty, and the test would have answered "independent".
When MIV equations remain, the flag exact is false, and only Theorem 4 holds: the set can contain a direction vector without a solution. This is the one-sided promise of all conservative tests.
Cost
Let be the number of subscripts. The classification and the union-find take time. The delta test makes at most passes; each pass rewrites at most equations in time and calls meet, whose cost is a few divisions and one extended gcd, for coefficients up to . So the delta test costs . The MIV filter tests at most direction vectors against at most equations at each, ; it runs only when MIV equations remain.
Complexity
Classification and the union-find partition take time. The delta loop runs at most passes, because each pass that changes something removes an equation. A pass rewrites at most equations in each, and each SIV test costs a few divisions and at most one extended gcd, . So the delta test costs . The MIV filter tests at most combinations of directions with equations of terms, ; it runs only for groups that keep MIV equations, and the Banerjee hierarchy cuts most combinations early. When every subscript is ZIV or separable SIV, the whole test costs plus the size of the output.
Properties
- Conservative in one direction only. "Independent" is always right. When MIV pairs remain, the direction set can contain vectors without a dependence.
- Exact on ZIV and SIV. Without MIV pairs, the answer, the direction set and the distances are exact.
- Distances for free. The strong SIV test and the delta step give exact distances, which unimodular transformations and loop skewing need.
- Rectangular bounds. The tests above assume constant bounds; triangular bounds weaken the SIV tests to "maybe" on the bounds, or need a general test.
Variants and improvements
- RDIV subscripts. Goff, Kennedy and Tseng also treat subscripts such as
A[i]againstA[j]where and are indices of two different loops (restricted double index variable). They are handled like exact SIV with the two loops' bounds. - Symbolic constants. If is a symbolic expression such as or , the strong SIV test can still decide when the expression is known to be larger than the trip count, or give a symbolic distance.
- Other coupled-subscript tests. The lambda test of Li, Yew and Zhu and the power test of Wolfe and Tseng handle coupled MIV subscripts with linear combinations or with Fourier-Motzkin elimination over the integer solutions.
- Exact general test. The omega test replaces the GCD and Banerjee filter for the remaining MIV pairs and makes the whole result exact.
- Hierarchical directions. Instead of the product at line L12, refine the direction vector one level at a time and cut a branch at the first failed test, as in the Banerjee test.
When to use it
It is the default dependence analyzer of loop optimizers for Fortran-like code with affine subscripts and rectangular nests: the common cases are decided exactly and fast, with distances, and the costly general tests run only on the few MIV subscripts left. For triangular nests, symbolic bounds or value-based dependences, a polyhedral analysis (omega test, Feautrier's dataflow) is more precise.
Pitfalls
- Testing subscripts separately and intersecting the answers. For coupled subscripts, the direction sets of the subscripts can each be nonempty while the system has no solution, as in
A[i][i] = A[i][i+1]. Intersecting direction sets is sound, but weaker than the delta step. - Forgetting the bound in the strong SIV test. can be an integer and still be larger than the trip count; then there is no dependence.
- Sign of the distance. With the subscripts (source) and (sink), the distance is , not . A sign error turns a flow dependence into an anti dependence.
- Weak-zero at the ends of the loop. A weak-zero solution such as for
A[i] = A[1]hits only the first iteration; peeling that iteration removes the dependence, which is the classic use of the test. - Weak-crossing at the middle. For
A[i] = A[n - i + 1]all dependences cross the middle iteration; splitting the loop there removes them. - Calling the result exact when MIV pairs remain. Only the result without MIV pairs is exact.
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/practical-dependence-tests/. The authors are listed in prov/B1R5XX.jsonl.
"""Subscript-wise dependence testing: ZIV, SIV and MIV tests joined by the delta test.
A rectangular loop nest has depth k, and loop l runs over L_l..U_l, given as
bounds = [(L_1, U_1), ..., (L_k, U_k)]. A subscript is a tuple
(c0, c1, ..., ck) for c0 + c1*i1 + ... + ck*ik. The source reference uses
the indices i, the sink reference the indices j. A pair of references to an
array of m dimensions is given as two lists of m subscripts.
The direction of level l is "<" when i_l < j_l, "=" when i_l = j_l and ">"
when i_l > j_l (Wolfe's notation). The result lists raw direction vectors of
the solutions: a vector whose first non-"=" entry is ">" belongs to the
dependence from the sink reference to the source reference.
The solution set of one level is kept exactly, as one of
("free",) all pairs in the box
("empty",) no pair
("point", i, j) one pair
("line", i0, j0, p, q, tlo, thi) the pairs (i0 + p*t, j0 + q*t), tlo <= t <= thi
"""
from math import gcd
from itertools import product
FREE = ("free",)
EMPTY = ("empty",)
DIRS = "<=>"
def ceil_div(a: int, b: int) -> int:
return -((-a) // b)
def ext_gcd(a: int, b: int) -> tuple[int, int, int]:
"""Return (g, x, y) with a*x + b*y = g = gcd(a, b) and g >= 0."""
x0, y0, x1, y1 = 1, 0, 0, 1
while b != 0:
q, r = divmod(a, b)
a, b = b, r
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
if a < 0:
return -a, -x0, -y0
return a, x0, y0
def axis_range(x0: int, p: int, lo: int, hi: int):
"""The integers t with lo <= x0 + p*t <= hi, as (tmin, tmax), or None for all t."""
if p == 0:
return None if lo <= x0 <= hi else (1, 0)
if p > 0:
return ceil_div(lo - x0, p), (hi - x0) // p
return ceil_div(hi - x0, p), (lo - x0) // p
def line_in_box(i0: int, j0: int, p: int, q: int, lo: int, hi: int):
"""The points (i0 + p*t, j0 + q*t) inside [lo, hi]^2, as a level state."""
tlo, thi = None, None
for x0, s in ((i0, p), (j0, q)):
r = axis_range(x0, s, lo, hi)
if r is None:
continue
tlo = r[0] if tlo is None else max(tlo, r[0])
thi = r[1] if thi is None else min(thi, r[1])
if tlo > thi:
return EMPTY
if tlo == thi:
return ("point", i0 + p * tlo, j0 + q * tlo)
return ("line", i0, j0, p, q, tlo, thi)
def siv_kind(a: int, b: int) -> str:
"""The name of the SIV test for a*i - b*j = c, with (a, b) != (0, 0)."""
if a == b:
return "strong"
if a == 0 or b == 0:
return "weak-zero"
if a == -b:
return "weak-crossing"
return "exact"
def siv_solve(a: int, b: int, c: int, lo: int, hi: int):
"""All integer (i, j) in [lo, hi]^2 with a*i - b*j = c, as a level state."""
kind = siv_kind(a, b)
if kind == "strong":
# a*i + c1 = a*j + c2: the distance j - i is (c1 - c2) / a = -c / a.
if c % a != 0:
return EMPTY
d = -(c // a)
if abs(d) > hi - lo:
return EMPTY
return line_in_box(0, d, 1, 1, lo, hi)
if kind == "weak-zero":
if b == 0:
if c % a != 0:
return EMPTY
return line_in_box(c // a, 0, 0, 1, lo, hi)
if c % b != 0:
return EMPTY
return line_in_box(0, -(c // b), 1, 0, lo, hi)
if kind == "weak-crossing":
# a*i + a*j = c: the pairs with i + j = c / a, which cross at (c / a) / 2.
if c % a != 0:
return EMPTY
return line_in_box(0, c // a, 1, -1, lo, hi)
g, x, y = ext_gcd(a, -b)
if c % g != 0:
return EMPTY
p, q = b // g, a // g
if p < 0:
p, q = -p, -q
return line_in_box(x * (c // g), y * (c // g), p, q, lo, hi)
def meet(state, a: int, b: int, c: int, lo: int, hi: int):
"""The level state cut by the equation a*i - b*j = c."""
if a == 0 and b == 0:
return state if c == 0 else EMPTY
kind = state[0]
if kind == "empty":
return EMPTY
if kind == "free":
return siv_solve(a, b, c, lo, hi)
if kind == "point":
return state if a * state[1] - b * state[2] == c else EMPTY
_, i0, j0, p, q, tlo, thi = state
coef = a * p - b * q
rhs = c - a * i0 + b * j0
if coef == 0:
return state if rhs == 0 else EMPTY
if rhs % coef != 0:
return EMPTY
t = rhs // coef
if not tlo <= t <= thi:
return EMPTY
return ("point", i0 + p * t, j0 + q * t)
def propagate(A: list[int], B: list[int], c: int, states: list):
"""The delta step: rewrite sum(A[l] i_l - B[l] j_l) = c with the known level facts."""
A, B = list(A), list(B)
for l in range(len(A)):
if A[l] == 0 and B[l] == 0:
continue
st = states[l]
if st[0] == "point":
c -= A[l] * st[1] - B[l] * st[2]
A[l] = B[l] = 0
elif st[0] == "line":
_, i0, j0, p, q, _, _ = st
if p == 0: # i_l is the constant i0
c -= A[l] * i0
A[l] = 0
elif q == 0: # j_l is the constant j0
c += B[l] * j0
B[l] = 0
elif p == q: # j_l = i_l + d with the distance d = j0 - i0
c += B[l] * (j0 - i0)
A[l] -= B[l]
B[l] = 0
return A, B, c
def level_view(state, d: str, lo: int, hi: int):
"""The part of a level state with direction d, or None if it is empty."""
kind = state[0]
if kind == "empty":
return None
if kind == "free":
return None if d != "=" and hi - lo < 1 else ("free", d)
if kind == "point":
i, j = state[1], state[2]
return state if direction(i, j) == d else None
_, i0, j0, p, q, tlo, thi = state
e0, e1 = i0 - j0, p - q # i - j = e0 + e1*t
if d == "=":
if e1 == 0:
return state if e0 == 0 else None
if e0 % e1 != 0 or not tlo <= -(e0 // e1) <= thi:
return None
t = -(e0 // e1)
return ("point", i0 + p * t, j0 + q * t)
# "<" needs e0 + e1*t <= -1, and ">" needs e0 + e1*t >= 1.
t1, t2 = tlo, thi
if e1 == 0:
ok = e0 <= -1 if d == "<" else e0 >= 1
return state if ok else None
if d == "<":
bound = -1 - e0
if e1 > 0:
t2 = min(t2, bound // e1)
else:
t1 = max(t1, ceil_div(bound, e1))
else:
bound = 1 - e0
if e1 > 0:
t1 = max(t1, ceil_div(bound, e1))
else:
t2 = min(t2, bound // e1)
if t1 > t2:
return None
return ("line", i0, j0, p, q, t1, t2)
def direction(i: int, j: int) -> str:
return "<" if i < j else ("=" if i == j else ">")
def term_values(view, a: int, b: int, lo: int, hi: int):
"""(min, max, step, offset) for the values of a*i - b*j over a level view.
Every value lies in [min, max] and is offset plus a multiple of step.
"""
if view[0] == "free":
d = view[1]
pa, na, pb, nb = max(a, 0), max(-a, 0), max(b, 0), max(-b, 0)
n = hi - lo
if d == "=":
e = a - b
return max(e, 0) * lo - max(-e, 0) * hi, max(e, 0) * hi - max(-e, 0) * lo, e, 0
if d == "<":
v0 = (a - b) * lo - b
return v0 - max(na + b, 0) * (n - 1), v0 + max(pa - b, 0) * (n - 1), gcd(a, b), 0
v0 = (a - b) * lo + a
return v0 - max(pb - a, 0) * (n - 1), v0 + max(a + nb, 0) * (n - 1), gcd(a, b), 0
if view[0] == "point":
v = a * view[1] - b * view[2]
return v, v, 0, v
_, i0, j0, p, q, t1, t2 = view
k0, k1 = a * i0 - b * j0, a * p - b * q
v1, v2 = k0 + k1 * t1, k0 + k1 * t2
return min(v1, v2), max(v1, v2), k1, k0
def miv_allows(eq, psi_views: dict, bounds) -> bool:
"""GCD and Banerjee test of one MIV equation over the chosen level views."""
A, B, c = eq
lo_sum, hi_sum, g, off = 0, 0, 0, 0
for l, view in psi_views.items():
if A[l] == 0 and B[l] == 0:
continue
lo, hi, step, offset = term_values(view, A[l], B[l], *bounds[l])
lo_sum += lo
hi_sum += hi
g = gcd(g, step)
off += offset
if not lo_sum <= c <= hi_sum:
return False
return (c - off) % g == 0 if g != 0 else c == off
def coupled_groups(pairs, k: int) -> list:
"""Union-find on the levels: pairs that share a level end in one group."""
parent = list(range(k))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for f, g in pairs:
used = [l for l in range(k) if f[l + 1] or g[l + 1]]
for l in used[1:]:
parent[find(l)] = find(used[0])
groups: dict = {}
for f, g in pairs:
used = [l for l in range(k) if f[l + 1] or g[l + 1]]
groups.setdefault(find(used[0]), []).append((f, g))
return list(groups.values())
def delta_test(group, k: int, bounds):
"""Run the delta test on one coupled group.
Returns None if the group proves independence, else (states, miv) with
the exact solution set of each level under the SIV constraints, and the
equations that stay MIV.
"""
states = [FREE] * k # @line L5
pending = [([f[l + 1] for l in range(k)], [g[l + 1] for l in range(k)], g[0] - f[0]) for f, g in group]
changed = True
while changed: # @line L6
changed = False
rest = []
for A, B, c in pending:
A, B, c = propagate(A, B, c, states) # @line L7
used = [l for l in range(k) if A[l] or B[l]]
if not used:
if c != 0:
return None # @line L8
changed = True
elif len(used) == 1:
l = used[0]
states[l] = meet(states[l], A[l], B[l], c, *bounds[l]) # @line L9
if states[l] == EMPTY:
return None # @line L10
changed = True
else:
rest.append((A, B, c))
pending = rest # @line L11
return states, pending
def distance_of(state, lo: int, hi: int):
"""The distance j - i if it is the same for every pair of the state, else None."""
if state[0] == "free":
return 0 if lo == hi else None
if state[0] == "point":
return state[2] - state[1]
if state[0] == "line" and state[3] == state[4]:
return state[2] - state[1]
return None
def dependence(src, snk, bounds) -> dict:
"""Test two references; return the directions, distances and exactness.
The result has the keys "independent" (bool), "directions" (a set of
tuples over the k levels), "distances" (a list with an int or None for
each level) and "exact" (True when no MIV equation remained, so that the
directions are exactly those of the integer solutions).
"""
k = len(bounds)
pairs = []
for f, g in zip(src, snk):
if all(f[l + 1] == 0 and g[l + 1] == 0 for l in range(k)): # @line L1
if f[0] != g[0]:
return {"independent": True, "directions": set(), "distances": [None] * k, "exact": True} # @line L2
else:
pairs.append((f, g))
states = [FREE] * k
level_dirs = [None] * k
group_dirs = []
exact = True
for group in coupled_groups(pairs, k): # @line L3
levels = sorted({l for f, g in group for l in range(k) if f[l + 1] or g[l + 1]})
res = delta_test(group, k, bounds) # @line L4
if res is None:
return {"independent": True, "directions": set(), "distances": [None] * k, "exact": True}
st, miv = res
for l in levels:
states[l] = st[l]
options = [[d for d in DIRS if level_view(st[l], d, *bounds[l]) is not None] for l in levels]
found = set()
for combo in product(*options): # @line L12
views = {l: level_view(st[l], d, *bounds[l]) for l, d in zip(levels, combo)}
if all(miv_allows(eq, views, bounds) for eq in miv):
found.add(combo)
if not found:
return {"independent": True, "directions": set(), "distances": [None] * k, "exact": True} # @line L13
if miv:
exact = False
group_dirs.append((levels, found))
for l in levels:
level_dirs[l] = True
free_options = []
for l in range(k):
if level_dirs[l] is None:
free_options.append((l, [d for d in DIRS if level_view(FREE, d, *bounds[l]) is not None]))
directions = set()
group_choices = [sorted(found) for _, found in group_dirs]
for picks in product(*group_choices, *[opts for _, opts in free_options]):
vec = [None] * k
for (levels, _), combo in zip(group_dirs, picks[: len(group_dirs)]):
for l, d in zip(levels, combo):
vec[l] = d
for (l, _), d in zip(free_options, picks[len(group_dirs):]):
vec[l] = d
directions.add(tuple(vec))
distances = [distance_of(states[l], *bounds[l]) for l in range(k)]
return {"independent": False, "directions": directions, "distances": distances, "exact": exact} # @line L14
if __name__ == "__main__":
# for i = 1 to 8: for j = 1 to 8: A[i + 1][j] = A[i][j]
r = dependence([(1, 1, 0), (0, 0, 1)], [(0, 1, 0), (0, 0, 1)], [(1, 8), (1, 8)])
print(r) # directions {("<", "=")}, distances [1, 0], exact
# for i = 1 to 8: A[i][i] = A[i][i + 1]: the delta test proves independence
print(dependence([(0, 1), (0, 1)], [(0, 1), (1, 1)], [(1, 8)])["independent"])
practical_dependence_tests.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/practical-dependence-tests/. The authors are listed in prov/B1R5XX.jsonl.
"""Entry point named after the slug. The code is in subscript_dependence.py,
because the tools treat a file whose name ends in _tests as a test file."""
from subscript_dependence import (
EMPTY,
FREE,
coupled_groups,
delta_test,
dependence,
level_view,
meet,
siv_kind,
siv_solve,
)
__all__ = [
"EMPTY",
"FREE",
"coupled_groups",
"delta_test",
"dependence",
"level_view",
"meet",
"siv_kind",
"siv_solve",
]
test_practical_dependence_tests.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/practical-dependence-tests/. The authors are listed in prov/B1R5XX.jsonl.
import random
from itertools import product
from practical_dependence_tests import EMPTY, FREE, dependence, level_view, meet, siv_kind, siv_solve
def value(sub, x):
return sub[0] + sum(c * v for c, v in zip(sub[1:], x))
def sign(a, b):
return "<" if a < b else ("=" if a == b else ">")
def box(bounds):
return list(product(*[range(lo, hi + 1) for lo, hi in bounds]))
def brute_pairs(src, snk, bounds):
pts = box(bounds)
return [(i, j) for i in pts for j in pts if all(value(f, i) == value(g, j) for f, g in zip(src, snk))]
def points(state, lo, hi):
"""The set of pairs of a level state, by enumeration."""
if state[0] == "empty":
return set()
if state[0] == "free":
return {(x, y) for x in range(lo, hi + 1) for y in range(lo, hi + 1)}
if state[0] == "point":
return {(state[1], state[2])}
_, i0, j0, p, q, tlo, thi = state
return {(i0 + p * t, j0 + q * t) for t in range(tlo, thi + 1)}
def random_bounds(rng, k):
top = {1: 8, 2: 6, 3: 4}[k]
out = []
for _ in range(k):
lo = rng.randint(0, 2)
out.append((lo, rng.randint(lo, top)))
return out
def random_subscript(rng, k, used):
f = [rng.randint(-5, 5)] + [0] * k
g = [rng.randint(-5, 5)] + [0] * k
for l in used:
f[l + 1] = rng.choice([0, 1, 1, -1, 2, rng.randint(-4, 4)])
g[l + 1] = rng.choice([0, 1, 1, -1, 2, f[l + 1], -f[l + 1], rng.randint(-4, 4)])
return f, g
def random_case(rng):
k = rng.randint(1, 3)
bounds = random_bounds(rng, k)
m = rng.randint(1, 3)
src, snk = [], []
i = [rng.randint(lo, hi) for lo, hi in bounds]
j = [rng.randint(lo, hi) for lo, hi in bounds]
meet_here = rng.random() < 0.6
for _ in range(m):
size = rng.choice([0, 1, 1, 1, 2, 2, 3])
used = rng.sample(range(k), min(size, k))
f, g = random_subscript(rng, k, used)
if meet_here:
g[0] += value(f, i) - value(g, j)
src.append(tuple(f))
snk.append(tuple(g))
return src, snk, bounds
def check(src, snk, bounds):
res = dependence(src, snk, bounds)
pairs = brute_pairs(src, snk, bounds)
true_dirs = {tuple(sign(a, b) for a, b in zip(i, j)) for i, j in pairs}
if pairs:
assert not res["independent"], (src, snk, bounds, pairs[0])
if res["independent"]:
return res, pairs
assert true_dirs <= res["directions"], (src, snk, bounds, true_dirs, res)
if res["exact"]:
assert true_dirs == res["directions"], (src, snk, bounds, true_dirs, res)
assert pairs, (src, snk, bounds, res)
for l, d in enumerate(res["distances"]):
if d is not None:
assert all(j[l] - i[l] == d for i, j in pairs), (src, snk, bounds, l, d)
return res, pairs
def test_siv_tests_are_exact():
for a in range(-4, 5):
for b in range(-4, 5):
if a == 0 and b == 0:
continue
for c in range(-9, 10):
for lo, hi in [(1, 1), (1, 2), (0, 4), (1, 8), (2, 7)]:
st = siv_solve(a, b, c, lo, hi)
want = {(x, y) for x in range(lo, hi + 1) for y in range(lo, hi + 1) if a * x - b * y == c}
assert points(st, lo, hi) == want, (a, b, c, lo, hi, st)
if st[0] == "line":
assert st[5] < st[6]
def test_siv_kinds():
assert siv_kind(3, 3) == "strong"
assert siv_kind(0, 2) == "weak-zero"
assert siv_kind(2, 0) == "weak-zero"
assert siv_kind(2, -2) == "weak-crossing"
assert siv_kind(2, 3) == "exact"
def test_meet_is_exact():
rng = random.Random(21)
for _ in range(3000):
lo = rng.randint(0, 2)
hi = rng.randint(lo, 8)
st = FREE
want = points(FREE, lo, hi)
for _ in range(rng.randint(1, 3)):
a, b, c = rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(-8, 8)
st = meet(st, a, b, c, lo, hi)
want = {(x, y) for x, y in want if a * x - b * y == c}
assert points(st, lo, hi) == want, (st, want)
def test_level_view_is_exact():
rng = random.Random(22)
for _ in range(3000):
lo = rng.randint(0, 2)
hi = rng.randint(lo, 8)
a, b, c = rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(-8, 8)
st = meet(FREE, a, b, c, lo, hi) if rng.random() < 0.8 else FREE
for d in "<=>":
v = level_view(st, d, lo, hi)
want = {(x, y) for x, y in points(st, lo, hi) if sign(x, y) == d}
if v is None:
assert not want
elif v[0] == "free":
assert want == points(FREE, lo, hi) - {(x, y) for x, y in points(FREE, lo, hi) if sign(x, y) != d}
else:
assert points(v, lo, hi) == want
def test_never_independent_when_dependent_and_exact_when_claimed():
rng = random.Random(23)
dependent = exact = miv = 0
for _ in range(2500):
src, snk, bounds = random_case(rng)
res, pairs = check(src, snk, bounds)
dependent += bool(pairs)
exact += res["exact"]
miv += not res["exact"]
assert dependent > 500
assert exact > 1000
assert miv > 50
def test_page_examples():
# A[i + 1][j] = A[i][j] in an 8 by 8 nest: strong SIV twice, distance (1, 0).
res, _ = check([(1, 1, 0), (0, 0, 1)], [(0, 1, 0), (0, 0, 1)], [(1, 8), (1, 8)])
assert res["directions"] == {("<", "=")} and res["distances"] == [1, 0] and res["exact"]
# A[i][i] = A[i][i + 1]: the delta test proves independence.
res, _ = check([(0, 1), (0, 1)], [(0, 1), (1, 1)], [(1, 8)])
assert res["independent"]
# A[2*i] = A[3*i + 2] for i = 1..3: the exact SIV test proves independence.
assert dependence([(0, 2)], [(2, 3)], [(1, 3)])["independent"]
# A[5] = A[7]: ZIV.
assert dependence([(5, 0)], [(7, 0)], [(1, 8)])["independent"]
# Weak-zero: a write of A[i] and a read of A[1] in each iteration, i = 1..8.
# Only iteration 1 writes A[1], and iterations 1..8 read it.
res, _ = check([(0, 1)], [(1, 0)], [(1, 8)])
assert res["directions"] == {("<",), ("=",)} and res["distances"] == [None]
# Weak-crossing: A[i] = A[9 - i], i = 1..8: i + j = 9.
res, _ = check([(0, 1)], [(9, -1)], [(1, 8)])
assert res["directions"] == {("<",), (">",)}
# The coupled example of the page: A[i + 1][i + j] = A[i][i + j], 1..6 by 1..6.
src, snk, bounds = [(1, 1, 0), (0, 1, 1)], [(0, 1, 0), (0, 1, 1)], [(1, 6), (1, 6)]
res, _ = check(src, snk, bounds)
assert res["exact"] and res["directions"] == {("<", ">")} and res["distances"] == [1, -1]
# An MIV pair that stays MIV: A[i + j] = A[i + j - 1] in a 1..4 by 1..4 nest.
res, pairs = check([(0, 1, 1)], [(-1, 1, 1)], [(1, 4), (1, 4)])
assert not res["exact"]
assert {tuple(sign(a, b) for a, b in zip(i, j)) for i, j in pairs} == res["directions"]
# The state constants of the module.
assert EMPTY == ("empty",) and FREE == ("free",)
History
Goff, Kennedy and Tseng presented the subscript classification, the named SIV tests and the delta test in "Practical dependence testing" at PLDI 1991, from their work on the parallelizing compiler systems at Rice University. They measured, on scientific Fortran programs, that ZIV and SIV subscripts are by far the most common, and that most coupled subscripts become SIV after the delta step. The exact test for one equation in two variables is older; it is in Banerjee's work. Allen and Kennedy's book gives the whole suite as the standard dependence tester.
References
- Gina Goff, Ken Kennedy and Chau-Wen Tseng, Practical dependence testing, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI), 1991, the ZIV, SIV and MIV classes, separable and coupled subscripts, the strong, weak-zero, weak-crossing and exact SIV tests, the delta test and the measurements on scientific programs
- Randy Allen and Ken Kennedy, Optimizing Compilers for Modern Architectures, a Dependence-Based Approach, Morgan Kaufmann, 2002 (copyright 2001), Chapter 3, Dependence Testing (subscript partitioning, the single-subscript tests, the delta test and the order in which the tests are applied)
- Michael Wolfe, High Performance Compilers for Parallel Computing, Addison-Wesley, 1996, the chapter on dependence testing (single-index subscripts and the exact test for two variables)
- Utpal Banerjee, Dependence Analysis for Supercomputing, Kluwer Academic Publishers, 1988, the exact test for one linear equation in two variables with bounds
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 B1R5XX Edit this page History Report an error Markdown