Algorithm Search⌘K

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.

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
Properties
deterministiciterative

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 kk with loop ll over Ll≤il≤UlL_l \le i_l \le U_l, two references with affine subscripts, one equation per dimension

∑l=1k(arlil−brljl)=br0−ar0,r=1,…,m,\sum_{l=1}^{k} \bigl(a_{rl} i_l - b_{rl} j_l\bigr) = b_{r0} - a_{r0}, \qquad r = 1, \dots, m,

for the source iteration i⃗\vec{i} and the sink iteration j⃗\vec{j}. 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 ll means il<jli_l < j_l. 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 ll, the exact set SlS_l of pairs (il,jl)(i_l, j_l) allowed by the SIV equations seen so far. Each SlS_l is the whole square, empty, one point, or the integer points of a segment (x0+pt,y0+qt)(x_0 + p t, y_0 + q t).

  1. PRACTICAL-TEST(subscript pairs, bounds):
  2. 1for each subscript pair that uses no loop index (ZIV) do
  3. 2if its two constants differ then return "independent"
  4. 3partition the other pairs into coupled groups: pairs that share a level go together
  5. 4for each group do (the delta test)
  6. 5S_l <- all pairs in [L_l, U_l]^2, for each level l
  7. 6repeat
  8. 7rewrite each pending pair with the facts of the S_l (a point, a fixed i_l, a fixed j_l, or a distance)
  9. 8if a pair uses no level now: if its constant is not 0 then return "independent"; drop it
  10. 9if a pair uses one level l now: S_l <- S_l ∩ {solutions} (strong, weak-zero, weak-crossing or exact SIV test); drop it
  11. 10if some S_l is empty then return "independent"
  12. 11until a pass changes nothing; the pending pairs are the MIV pairs
  13. 12D <- the direction vectors of the group allowed by the S_l and by the GCD and Banerjee tests on each MIV pair
  14. 13if D is empty then return "independent"
  15. 14return 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 ll as ai−bj=ca i - b j = c, so the two subscripts are ai+c1a i + c_1 and bj+c2b j + c_2 with c=c2−c1c = c_2 - c_1.

test when solutions
strong SIV a=ba = b j−i=d=(c1−c2)/aj - i = d = (c_1 - c_2)/a; a dependence exists if and only if dd is an integer and ∣d∣≤U−L\lvert d \rvert \le U - L
weak-zero SIV a=0a = 0 or b=0b = 0 one index is fixed: i=c/ai = c/a or j=−c/bj = -c/b, which must be an integer in the bounds
weak-crossing SIV a=−ba = -b i+j=c/ai + j = c/a: the pairs cross at the middle c/(2a)c/(2a)
exact SIV other the extended Euclidean algorithm gives the solutions (x0+(b/g)t,y0+(a/g)t)(x_0 + (b/g) t, y_0 + (a/g) t), 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 (x∗,y∗)(x^*, y^*): the terms of level ll become a constant;
  • a fixed ili_l (p=0p = 0, from weak-zero): the term alila_l i_l becomes a constant;
  • a fixed jlj_l (q=0q = 0): the term bljlb_l j_l becomes a constant;
  • a fixed distance jl=il+dj_l = i_l + d (p=qp = q, from strong SIV): the terms become (al−bl)il−bld(a_l - b_l) i_l - b_l d, 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 (i,j)(i, j) be the iteration of the write and (i′,j′)(i', j') that of the read. The subscript pairs are i+1=i′i + 1 = i' (SIV, level 1) and i+j=i′+j′i + j = i' + j' (MIV, levels 1 and 2). They share level 1, so they form one coupled group.

step action result
L9 strong SIV on i−i′=−1i - i' = -1: d1=1d_1 = 1, ∣d1∣≤5\lvert d_1 \rvert \le 5 S1={(t,t+1):1≤t≤5}S_1 = \{(t, t+1) : 1 \le t \le 5\}
L7 rewrite i+j−i′−j′=0i + j - i' - j' = 0 with i′=i+1i' = i + 1 j−j′=1j - j' = 1, now SIV at level 2
L9 strong SIV: d2=−1d_2 = -1 S2={(t,t−1):2≤t≤6}S_2 = \{(t, t-1) : 2 \le t \le 6\}
L11 no pair left; a pass changes nothing no MIV pair, so the result is exact
L12 level 1 allows only <<, level 2 only >> D={(<,>)}D = \{(<, >)\}

So there is exactly one flow dependence, with distance (1,−1)(1, -1), carried by the ii loop. The jj loop can run in parallel, and loop interchange is illegal, because it would turn (1,−1)(1, -1) into (−1,1)(-1, 1). 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 00, so S1={(t,t)}S_1 = \{(t, t)\}. The delta step rewrites the second pair i−i′=1i - i' = 1 with i′=ii' = i into 0=10 = 1, 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 1≤i≤31 \le i \le 3, the GCD and Banerjee tests say "maybe". The exact SIV test finds the solutions (1+3t,2t)(1 + 3t, 2t) of 2i−3i′=22i - 3i' = 2 and cuts them to the bounds: j=2t≥1j = 2t \ge 1 needs t≥1t \ge 1, and i=1+3t≤3i = 1 + 3t \le 3 needs t≤0t \le 0. The set is empty: independent.

A pair that stays MIV. For X[i+j] = X[i+j-1] in a 4×44 \times 4 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:

  1. Strong SIV is exact. ai+c1=aj+c2a i + c_1 = a j + c_2 means a(j−i)=c1−c2a (j - i) = c_1 - c_2, so every solution has j−i=d=(c1−c2)/aj - i = d = (c_1 - c_2)/a; this needs dd to be an integer, and ∣d∣≤U−L\lvert d \rvert \le U - L because both indices lie in [L,U][L, U]. Conversely, if both hold, the pairs (t,t+d)(t, t + d) with max⁡(L,L−d)≤t≤min⁡(U,U−d)\max(L, L - d) \le t \le \min(U, U - d) are solutions, and this range is not empty.
  2. 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.
  3. 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 0=00 = 0, and an answer "independent" comes from an equation 0=c0 = c with c≠0c \ne 0, or from an empty level state.
  4. 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.
  5. 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 kk; loop ll runs over the integers Ll,…,UlL_l, \dots, U_l and Nl=Ul−LlN_l = U_l - L_l. A pair of references gives one equation per dimension,

∑l=1k(Alil−Bljl)=c,c=b0−a0,\sum_{l=1}^{k} (A_l i_l - B_l j_l) = c, \qquad c = b_0 - a_0,

where the source subscript is a0+∑lAlila_0 + \sum_l A_l i_l and the sink subscript is b0+∑lBljlb_0 + \sum_l B_l j_l. The solution set is the set Σ\Sigma of integer pairs (i⃗,j⃗)(\vec{i}, \vec{j}) in the box ∏l[Ll,Ul]2\prod_l [L_l, U_l]^2 that solve all the equations. A level ll is used by an equation if Al≠0A_l \ne 0 or Bl≠0B_l \ne 0. An equation is ZIV, SIV or MIV if it uses zero, one, or more levels.

A level state SlS_l is a set of integer pairs (x,y)∈[Ll,Ul]2(x, y) \in [L_l, U_l]^2, kept in one of four forms: all pairs (free), no pair (empty), one pair (point), or the pairs (x0+pt,y0+qt)(x_0 + p t, y_0 + q t) for the integers tt with tlo≤t≤thit_{lo} \le t \le t_{hi} (line), with (p,q)≠(0,0)(p, q) \ne (0, 0).

We write Σ(E,S⃗)\Sigma(E, \vec{S}) for the set of (i⃗,j⃗)(\vec{i}, \vec{j}) with (il,jl)∈Sl(i_l, j_l) \in S_l for each ll that solve every equation of the list EE. At the start EE is the list of the subscript equations and every SlS_l is free, so Σ(E,S⃗)=Σ\Sigma(E, \vec{S}) = \Sigma.

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 (x0+pt,y0+qt)(x_0 + pt, y_0 + qt), t∈Zt \in \mathbb{Z}, that lie in [L,U]2[L, U]^2.

Proof. For p>0p > 0, L≤x0+pt≤UL \le x_0 + p t \le U holds exactly for ⌈(L−x0)/p⌉≤t≤⌊(U−x0)/p⌋\lceil (L - x_0)/p \rceil \le t \le \lfloor (U - x_0)/p \rfloor; for p<0p < 0 the division by pp turns the inequalities around, which gives the bounds of axis_range; for p=0p = 0 the condition does not depend on tt, and it holds for all tt or for none. The same holds for yy and qq. The set of good tt is the intersection of the two ranges. It is empty, one value (a point), or an interval with at least two values (a line). □\square

Theorem 1 (exactness of the strong SIV test)

Let a≠0a \ne 0. The equation ai+c1=aj+c2a i + c_1 = a j + c_2 has an integer solution (i,j)∈[L,U]2(i, j) \in [L, U]^2 if and only if aa divides c1−c2c_1 - c_2 and ∣d∣≤U−L|d| \le U - L for d=(c1−c2)/ad = (c_1 - c_2)/a. All its solutions then have the distance j−i=dj - i = d, and they are the pairs (t,t+d)(t, t + d) for max⁡(L,L−d)≤t≤min⁡(U,U−d)\max(L, L - d) \le t \le \min(U, U - d).

Proof. The equation is a(j−i)=c1−c2a(j - i) = c_1 - c_2. If (i,j)(i, j) is a solution, then aa divides c1−c2c_1 - c_2 and j−i=dj - i = d. Both ii and jj lie in [L,U][L, U], so ∣d∣=∣j−i∣≤U−L|d| = |j - i| \le U - L. Conversely, let aa divide c1−c2c_1 - c_2 and ∣d∣≤U−L|d| \le U - L. A pair (t,t+d)(t, t + d) solves the equation, and it lies in the box if and only if L≤t≤UL \le t \le U and L−d≤t≤U−dL - d \le t \le U - d, that is, max⁡(L,L−d)≤t≤min⁡(U,U−d)\max(L, L - d) \le t \le \min(U, U - d). This interval is nonempty: if d≥0d \ge 0 it is [L,U−d][L, U - d] and U−d≥LU - d \ge L; if d<0d < 0 it is [L−d,U][L - d, U] and L−d≤UL - d \le U. So a solution exists. Every solution has j−i=dj - i = d, so it is of the form (t,t+d)(t, t + d). □\square

In the code, the equation is written ai−aj=ca i - a j = c with c=c2−c1c = c_2 - c_1, so d=−c/ad = -c/a, and the line (0+t,d+t)(0 + t, d + t) is cut to the box by Lemma 1, which gives the interval above.

Theorem 2 (exactness of the other SIV tests)

For (a,b)≠(0,0)(a, b) \ne (0, 0), siv_solve(a, b, c, L, U) returns exactly the set {(x,y)∈[L,U]2∩Z2:ax−by=c}\{(x, y) \in [L, U]^2 \cap \mathbb{Z}^2 : a x - b y = c\}.

Proof. Theorem 1 covers a=ba = b.

  • Weak-zero, b=0b = 0. The equation is ax=ca x = c. It has a solution only if aa divides cc, and then x=c/ax = c/a and yy is any integer: the line (c/a,0)+t(0,1)(c/a, 0) + t(0, 1). The case a=0a = 0 is the same with the roles of xx and yy exchanged, y=−c/by = -c/b.
  • Weak-crossing, b=−ab = -a. The equation is a(x+y)=ca(x + y) = c. It has a solution only if aa divides cc, and then the solutions are the pairs with x+y=c/ax + y = c/a: the line (0,c/a)+t(1,−1)(0, c/a) + t(1, -1).
  • Exact SIV. Here aa and bb are both nonzero. Let g=gcd⁡(a,−b)>0g = \gcd(a, -b) > 0 and ax1−by1=ga x_1 - b y_1 = g from the extended Euclidean algorithm. If gg does not divide cc, there is no solution (Bezout). Otherwise (x0,y0)=(c/g)(x1,y1)(x_0, y_0) = (c/g)(x_1, y_1) is a solution. If (x,y)(x, y) is another, then a(x−x0)=b(y−y0)a(x - x_0) = b(y - y_0); dividing by gg, (a/g)(x−x0)=(b/g)(y−y0)(a/g)(x - x_0) = (b/g)(y - y_0) with gcd⁡(a/g,b/g)=1\gcd(a/g, b/g) = 1, so b/gb/g divides x−x0x - x_0. Writing x−x0=(b/g)tx - x_0 = (b/g) t and dividing by b/g≠0b/g \ne 0 gives y−y0=(a/g)ty - y_0 = (a/g) t. Conversely every such point is a solution. So the solutions are the line (x0,y0)+t(p,q)(x_0, y_0) + t(p, q) with (p,q)=±(b/g,a/g)(p, q) = \pm(b/g, a/g).

In each case Lemma 1 cuts the line to the box exactly. □\square

Lemma 2 (meet)

meet(S, a, b, c, L, U) returns {(x,y)∈S:ax−by=c}\{(x, y) \in S : a x - b y = c\}.

Proof. If a=b=0a = b = 0, the equation is 0=c0 = c, 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: a(x0+pt)−b(y0+qt)=ca(x_0 + pt) - b(y_0 + qt) = c is (ap−bq)t=c−ax0+by0(ap - bq) t = c - a x_0 + b y_0. If ap−bq=0ap - bq = 0, either every tt or no tt solves it. Otherwise it has at most one solution tt, which must be an integer in [tlo,thi][t_{lo}, t_{hi}]. □\square

Lemma 3 (the delta step keeps the solution set)

Let (A′,B′,c′)(A', B', c') be the result of propagate on an equation (A,B,c)(A, B, c) with the states S⃗\vec{S}. For every (i⃗,j⃗)(\vec{i}, \vec{j}) with (il,jl)∈Sl(i_l, j_l) \in S_l for all ll, 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 Alil−BljlA_l i_l - B_l j_l by an expression equal to it on every pair of SlS_l:

  • SlS_l is the point (x∗,y∗)(x^*, y^*): on SlS_l the term is the constant Alx∗−Bly∗A_l x^* - B_l y^*, which moves to the right side.
  • SlS_l is a line with p=0p = 0: every pair of SlS_l has il=x0i_l = x_0, so Alil=Alx0A_l i_l = A_l x_0 moves to the right side.
  • SlS_l is a line with q=0q = 0: every pair has jl=y0j_l = y_0, and −Bljl=−Bly0-B_l j_l = -B_l y_0 moves to the right side.
  • SlS_l is a line with p=qp = q: every pair has jl−il=(y0−x0)+(q−p)t=y0−x0=:δj_l - i_l = (y_0 - x_0) + (q - p)t = y_0 - x_0 =: \delta. Then Alil−Bljl=(Al−Bl)il−BlδA_l i_l - B_l j_l = (A_l - B_l) i_l - B_l \delta, and BlδB_l \delta 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. □\square

Theorem 3 (the delta test keeps every solution, and ends)

During delta_test, the value of Σ(E,S⃗)\Sigma(E, \vec{S}), with EE the list of pending equations plus the equations that were moved into states, never changes. So it is always equal to Σ\Sigma. The loop ends.

Proof. Each step does one of four things to a pending equation.

  1. Rewrite it by Lemma 3. On the pairs of the states the new equation is equivalent to the old one, so Σ(E,S⃗)\Sigma(E, \vec{S}) does not change.
  2. Drop it when it uses no level and c=0c = 0: the equation 0=00 = 0 holds everywhere.
  3. Stop with "independent" when it uses no level and c≠0c \ne 0: the equation 0=c0 = c never holds, so Σ(E,S⃗)=Σ\Sigma(E, \vec{S}) = \Sigma is empty.
  4. Move it into SlS_l when it uses only level ll: by Lemma 2 the new state is the set of pairs of SlS_l that satisfy it, so keeping it in the state is the same as keeping it in the list. If the state becomes empty, Σ\Sigma is empty, and the test stops with "independent".

So every answer "independent" is correct, and when the loop ends, Σ=Σ(EMIV,S⃗)\Sigma = \Sigma(E_{MIV}, \vec{S}) where EMIVE_{MIV} 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 mm equations. So there are at most m+1m + 1 passes. □\square

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 Σ\Sigma 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 Σ\Sigma is not empty, dependence does not answer "independent", and the direction vector ψ(i⃗,j⃗)=(sign(il,jl))l\psi(\vec{i}, \vec{j}) = (\mathrm{sign}(i_l, j_l))_l of each (i⃗,j⃗)∈Σ(\vec{i}, \vec{j}) \in \Sigma 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 a0≠b0a_0 \ne b_0 and no index, so it has no solution. By Theorem 3, the delta test answers "independent" only when Σ\Sigma is empty. Take (i⃗,j⃗)∈Σ(\vec{i}, \vec{j}) \in \Sigma and a group. By Theorem 3, (il,jl)∈Sl(i_l, j_l) \in S_l for each level of the group, and the pair has the direction ψl\psi_l, so it is in the part of SlS_l with that direction. level_view returns exactly this part (for a line, the condition sign(x−y)\mathrm{sign}(x - y) on x−y=e0+e1tx - y = e_0 + e_1 t is a linear condition on tt, solved with floor and ceiling), so the direction ψl\psi_l is among the options of the level. Each remaining MIV equation holds at (i⃗,j⃗)(\vec{i}, \vec{j}). term_values gives, for each level, an interval and a lattice offset+step Z\text{offset} + \text{step}\,\mathbb{Z} that contain every value of Alil−BljlA_l i_l - B_l j_l 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 cc 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 ψ(i⃗,j⃗)\psi(\vec{i}, \vec{j}). Finally, a distance is reported only for a state in which all pairs have the same difference y−xy - x, and every solution lies in its state. □\square

Theorem 5 (exactness without MIV equations)

If no MIV equation remains in any group, the returned answer is exact: "independent" if and only if Σ\Sigma is empty, and the set of direction vectors is exactly {ψ(i⃗,j⃗):(i⃗,j⃗)∈Σ}\{\psi(\vec{i}, \vec{j}) : (\vec{i}, \vec{j}) \in \Sigma\}.

Proof. With no MIV equation left, Theorem 3 gives Σ=∏lSl\Sigma = \prod_l S_l: a tuple of pairs, one from each state, with no further condition. For a vector ψ⃗\vec{\psi} in the returned set, each level option was kept because the part of SlS_l with direction ψl\psi_l is not empty (Lemma 1 and the exactness of level_view). Choosing one pair from each part gives an element of Σ\Sigma with direction ψ⃗\vec{\psi}. With Theorem 4, the two sets are equal. If Σ\Sigma were empty, some SlS_l would be empty, and the test would have answered "independent". □\square

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 mm be the number of subscripts. The classification and the union-find take O(mk)O(mk) time. The delta test makes at most m+1m + 1 passes; each pass rewrites at most mm equations in O(k)O(k) time and calls meet, whose cost is a few divisions and one extended gcd, O(log⁡C)O(\log C) for coefficients up to CC. So the delta test costs O(m2k+mlog⁡C)O(m^2 k + m \log C). The MIV filter tests at most 3k3^k direction vectors against at most mm equations at O(k)O(k) each, O(3kmk)O(3^k m k); it runs only when MIV equations remain.

Complexity

Classification and the union-find partition take O(mk)O(mk) time. The delta loop runs at most m+1m + 1 passes, because each pass that changes something removes an equation. A pass rewrites at most mm equations in O(k)O(k) each, and each SIV test costs a few divisions and at most one extended gcd, O(log⁡C)O(\log C). So the delta test costs O(m2k+mlog⁡C)O(m^2 k + m \log C). The MIV filter tests at most 3k3^k combinations of directions with mm equations of kk terms, O(3kmk)O(3^k m k); 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 O(mk)O(mk) 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] against A[j] where ii and jj are indices of two different loops (restricted double index variable). They are handled like exact SIV with the two loops' bounds.
  • Symbolic constants. If c1−c2c_1 - c_2 is a symbolic expression such as nn or n−1n - 1, 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. dd can be an integer and still be larger than the trip count; then there is no dependence.
  • Sign of the distance. With the subscripts ai+c1a i + c_1 (source) and aj+c2a j + c_2 (sink), the distance is j−i=(c1−c2)/aj - i = (c_1 - c_2)/a, not (c2−c1)/a(c_2 - c_1)/a. 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 i=1i = 1 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.

subscript_dependence.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example