Algorithm Search⌘K

Algorithmadvanced

Minimum-area retiming

Also called minimum register retiming.

Retimes a circuit to the fewest registers under a clock period bound, as the dual of a minimum cost flow problem.

Time
O(E V M) worst
Space
O(V^2) extra
Where
E = the number of wires; M = the number of constraints, at most E + V^2; V = the number of gates with the host
Properties
deterministicexactofflineiterative
Origin
Charles E. Leiserson, James B. Saxe, 1991

Minimum-area retiming moves the registers of a synchronous circuit so that it has the fewest registers, either with no clock period bound or with a period of at most cc. The variables are the same as in retiming: one integer r(v)r(v) per gate. The register count of the retimed circuit is a linear function of rr, and the constraints are difference constraints, so the problem is a linear program. Leiserson and Saxe observed that its dual is a min-cost flow problem with no capacities, and that the node potentials of an optimal flow give an optimal integer retiming.

In plain words

A register costs area and power. Retiming can move registers to places where fewer of them do the same job, for example from the two inputs of a gate to its one output. Each gate gets a number, which says how many registers it pushes from its outputs back to its inputs. The total count of registers is a sum of these numbers with plus and minus signs. The rules are the same as for retiming: no wire gets a negative count, and no long stretch of logic stays without a register when a clock period is given. So the task is to minimize a sum under rules of the form "this number minus that number is at most a constant". This is the mirror image of a cheapest way to ship goods through a network, and a flow algorithm solves it exactly.

The problem

The circuit is G=(V,E)G = (V, E) with gate delays d(v)d(v), register counts w(e)w(e), and a host hh, as on the retiming page. A retiming rr with r(h)=0r(h) = 0 gives wr(e)=w(e)+r(v)−r(u)w_r(e) = w(e) + r(v) - r(u) for e=(u,v)e = (u, v), and it is legal when all wr(e)≥0w_r(e) \ge 0. The input also has an optional period bound cc. The output is a legal retiming with c(Gr)≤cc(G_r) \le c that minimizes the register count, and that count. Two counts are common.

  • Per edge. N(r)=∑ewr(e)N(r) = \sum_e w_r(e), one register for each register on each wire.
  • Shared. Ns(r)=∑umax⁡e out of uwr(e)N_s(r) = \sum_u \max_{e \text{ out of } u} w_r(e). The fanout edges of a gate can share one chain of registers, and the gate needs as many as its most delayed fanout.

Like retiming, this page moves registers and keeps a single clock time for all of them. Clock skew scheduling keeps the registers and moves the clock arrival times. All three are solved through difference constraints.

The algorithm

Since ∑e(r(v)−r(u))\sum_e (r(v) - r(u)) counts r(x)r(x) once for each edge into xx and minus once for each edge out of xx, the per-edge count is

N(r)=∑ew(e)+∑xa(x) r(x),a(x)=indeg(x)−outdeg(x).N(r) = \sum_e w(e) + \sum_x a(x)\, r(x), \qquad a(x) = \mathrm{indeg}(x) - \mathrm{outdeg}(x).

So the problem is the linear program: minimize ∑xa(x)r(x)\sum_x a(x) r(x) subject to r(u)−r(v)≤br(u) - r(v) \le b for each constraint (u,v,b)(u, v, b). Its dual has one variable f≥0f \ge 0 per constraint: minimize ∑bf\sum b f subject to "inflow minus outflow equals a(x)a(x)" at every vertex, where the constraint (u,v,b)(u, v, b) is an arc u→vu \to v of cost bb. That is a min-cost flow problem.

  1. MIN-AREA-RETIMING(G, w, d, h, c, shared)
  2. 1S ← { (u, v, w(e)) : e = (u, v) ∈ E } ▷ (u, v, b) means r(u) - r(v) ≤ b
  3. 2B ← every edge e of G with breadth β(e) = 1 ▷ the terms of the objective
  4. 3if shared then for each gate u with k ≥ 2 fanout edges e_i = (u, v_i) do
  5. 4add a mirror vertex m_u, and add (v_i, m_u, w_max(u) - w(e_i)) to S for each i
  6. 5in B, give e_i and the new edge (v_i, m_u) the breadth 1/k; scale all breadths to integers
  7. 6if c is given then compute W and D, and add (u, v, W(u, v) - 1) to S for each D(u, v) > c
  8. 7a(x) ← Σ β(e) over the edges of B into x - Σ β(e) over the edges of B out of x
  9. 8arcs ← { u → v with cost b, no capacity : (u, v, b) ∈ S }
  10. 9f ← a min-cost flow on arcs with inflow(x) - outflow(x) = a(x) at each x,
  11. by successive shortest paths with Bellman-Ford
  12. 10if the arcs have a negative cycle or no flow meets a, return "infeasible"
  13. 11π ← shortest distances in the residual graph of f, from a virtual source
  14. 12r ← π(h) - π on the vertices of G
  15. 13return r and the count of G_r

Here wmax⁡(u)w_{\max}(u) is the largest w(ei)w(e_i) over the fanout edges of uu. Lines L3 to L5 build the mirror vertices of Leiserson and Saxe. The path u→vi→muu \to v_i \to m_u has wmax⁡(u)w_{\max}(u) registers for every ii, so the kk paths, each with breadth 1/k1/k, add up to wmax⁡(u)+r(mu)−r(u)w_{\max}(u) + r(m_u) - r(u). The constraint on the edge (vi,mu)(v_i, m_u) forces this value to be at least wr(ei)w_r(e_i) for each ii, and the optimum makes it equal to the largest one. Line L6 adds the period constraints of the retiming page. Lines L11 and L12 read the retiming off the flow: the potentials π\pi make every reduced cost b+π(u)−π(v)b + \pi(u) - \pi(v) nonnegative and make it zero on every arc that carries flow, which is complementary slackness for the pair of programs.

Example

One gate. A gate 11 with delay 1 reads the host twice, through edges (0,1)(0,1) with one register each, and drives the host by (1,0)(1,0) with none. So N=2N = 2, and a(0)=1−2=−1a(0) = 1 - 2 = -1, a(1)=2−1=1a(1) = 2 - 1 = 1. The arcs are 0→10 \to 1 of cost 1, twice, and 1→01 \to 0 of cost 0. The flow sends one unit from 00 to 11 along an arc of cost 1, so the dual optimum is 1, and NN drops by 1. The potentials have π(1)−π(0)=1\pi(1) - \pi(0) = 1, which gives r(1)=π(0)−π(1)=−1r(1) = \pi(0) - \pi(1) = -1. The two input registers become one register on the output edge (1,0)(1, 0), and the count is 1.

The correlator. Take the correlator of the retiming page, with 4 registers and period 24.

period bound cc least per-edge count least shared count
none 4 4
24, 16 4 4
14, 13 5 4
12 infeasible infeasible

At c=13c = 13, every legal retiming that meets the bound puts at least 5 registers on the edges. One of them is the retiming of the retiming page, with registers on the edges (1,2)(1,2), (3,4)(3,4), (5,6)(5,6), (6,7)(6,7) and (1,7)(1,7). The edges (1,2)(1,2) and (1,7)(1,7) both leave gate 1 with one register, so with sharing they use one register, and the count is 4.

Correctness

The per-edge count is the linear function above, and by the theorem on the retiming page, the constraints of lines L1 and L6 describe exactly the legal retimings that meet the period bound. With the mirror vertices, the minimum of the modeled objective over r(mu)r(m_u) is the shared count, so the program is right for both counts. The constraint matrix is the transpose of a network matrix, so it is totally unimodular, and with integer bounds the program has an integer optimum. Bellman-Ford returns integer potentials, the potentials meet complementary slackness with the optimal flow, and so r=−πr = -\pi (shifted to r(h)=0r(h) = 0) is optimal for the primal. The full proof gives the details.

Proof: The flow dual gives a legal retiming with the fewest registersfull

We use the notation of the page. SS is the set of constraints (u,v,b)(u, v, b), each meaning r(u)−r(v)≤br(u) - r(v) \le b, built by lines L1, L4 and L6. The vertex set XX is VV plus the mirror vertices. BB is the set of objective edges with their breadths β(e)>0\beta(e) > 0 after the scaling of line L5, and a(x)a(x) is the coefficient of line L7. Write λ\lambda for the scale factor of line L5, with λ=1\lambda = 1 for the per-edge count.

Lemma 1 (the feasible set). A map r:V→Zr : V \to \mathbb{Z} with r(h)=0r(h) = 0 is a legal retiming with c(Gr)≤cc(G_r) \le c exactly when it extends to XX so that all constraints of SS hold. Without a period bound, drop "c(Gr)≤cc(G_r) \le c".

Proof. The constraints of lines L1 and L6 are those of Theorem 1 on the retiming correctness page, so on VV they hold exactly for the legal retimings with c(Gr)≤cc(G_r) \le c. A constraint of line L4 has the form r(vi)−r(mu)≤wmax⁡(u)−w(ei)r(v_i) - r(m_u) \le w_{\max}(u) - w(e_i), a lower bound on r(mu)r(m_u). Each mirror vertex appears only in these lower bounds, so a large enough integer r(mu)r(m_u) meets them, and they never exclude a value of rr on VV. □\square

Lemma 2 (the objective). For every rr on XX that meets SS, ∑e∈Bβ(e) wr(e)=λN(r)+(terms that are≥0)\sum_{e \in B} \beta(e)\, w_r(e) = \lambda N(r) + (\text{terms that are} \ge 0), with equality on the per-edge model, and on the shared model when each r(mu)r(m_u) is the least value that meets line L4. Here NN is the count of the chosen model.

Proof. For the per-edge count, B=EB = E with β=1\beta = 1, and the sum is N(r)N(r). For the shared count, let uu have k≥2k \ge 2 fanout edges ei=(u,vi)e_i = (u, v_i) and let gi=(vi,mu)g_i = (v_i, m_u) with w(gi)=wmax⁡(u)−w(ei)w(g_i) = w_{\max}(u) - w(e_i). By Lemma 1 of the retiming proof, the path eigie_i g_i has wr(ei)+wr(gi)=w(ei)+w(gi)+r(mu)−r(u)=wmax⁡(u)+r(mu)−r(u)w_r(e_i) + w_r(g_i) = w(e_i) + w(g_i) + r(m_u) - r(u) = w_{\max}(u) + r(m_u) - r(u), the same value TuT_u for every ii. With breadth λ/k\lambda / k on each of the 2k2k edges, these terms add up to λTu\lambda T_u. Since wr(gi)≥0w_r(g_i) \ge 0 by line L4, Tu≥wr(ei)T_u \ge w_r(e_i) for every ii, so Tu≥max⁡iwr(ei)T_u \ge \max_i w_r(e_i). The least r(mu)r(m_u) that meets line L4 makes some wr(gi)=0w_r(g_i) = 0, so it gives Tu=max⁡iwr(ei)T_u = \max_i w_r(e_i). A gate with one fanout edge ee keeps β(e)=λ\beta(e) = \lambda and contributes λwr(e)\lambda w_r(e). Summing over uu gives the claim, with λNs(r)\lambda N_s(r) as the main term. □\square

So by Lemmas 1 and 2, the problem is the linear program

(P)min⁡∑x∈Xa(x) r(x)subject tor(u)−r(v)≤b for (u,v,b)∈S, r∈ZX,(P)\quad \min \sum_{x \in X} a(x)\, r(x) \quad \text{subject to} \quad r(u) - r(v) \le b \text{ for } (u, v, b) \in S,\ r \in \mathbb{Z}^X,

since ∑e∈Bβ(e)wr(e)=∑e∈Bβ(e)w(e)+∑xa(x)r(x)\sum_{e \in B} \beta(e) w_r(e) = \sum_{e \in B} \beta(e) w(e) + \sum_x a(x) r(x) by the same telescoping as on the page, and a minimizer may take each r(mu)r(m_u) at its least value without loss.

Lemma 3 (bounded). If SS is feasible, (P)(P) and its relaxation over RX\mathbb{R}^X are bounded below.

Proof. On the feasible set, every wr(e)w_r(e) with e∈Be \in B is at least 0, by line L1 for the edges of GG and by line L4 for the mirror edges. So the objective is at least −∑e∈Bβ(e)w(e)-\sum_{e \in B} \beta(e) w(e). □\square

Lemma 4 (duality). The dual of the relaxation of (P)(P) is

(F)min⁡∑(u,v,b)∈Sb fuvbsubject toinf(x)−outf(x)=a(x) for all x, f≥0,(F)\quad \min \sum_{(u,v,b) \in S} b\, f_{uvb} \quad \text{subject to} \quad \mathrm{in}_f(x) - \mathrm{out}_f(x) = a(x) \text{ for all } x,\ f \ge 0,

the min-cost flow problem of lines L8 and L9, where the constraint (u,v,b)(u, v, b) is an arc u→vu \to v. A pair of feasible solutions rr and ff is optimal exactly when f>0f > 0 only on arcs with r(u)−r(v)=br(u) - r(v) = b.

Proof. Write the constraints as Ar≤bA r \le b, where the row of (u,v,b)(u, v, b) has +1+1 at uu and −1-1 at vv. The dual of min⁡aTr\min a^T r subject to Ar≤bA r \le b with rr free is max⁡bTy\max b^T y subject to ATy=aA^T y = a and y≤0y \le 0. Put f=−y≥0f = -y \ge 0. Then (ATf)x(A^T f)_x is the flow out of xx minus the flow into xx, so ATy=aA^T y = a reads inf(x)−outf(x)=a(x)\mathrm{in}_f(x) - \mathrm{out}_f(x) = a(x), and the objective is −min⁡bTf-\min b^T f. The last claim is complementary slackness, from the complementary slackness page. □\square

Lemma 5 (the cases of line L10). If the constraint graph has a negative cycle, (P)(P) is infeasible. Otherwise (F)(F) has an optimal solution.

Proof. A negative cycle of arcs u→vu \to v of cost bb gives a sum of constraints whose left sides cancel and whose right side is negative, so SS has no solution, by the theorem on the difference constraints page. If there is no negative cycle, SS is feasible by the same theorem, (P)(P) is bounded by Lemma 3, so the relaxation has an optimum, and by LP duality (F)(F) is feasible and has an optimum of the same value. □\square

So line L10 returns "infeasible" exactly when no legal retiming meets the bound: when there is no negative cycle, successive shortest paths finds a flow, by the next lemma, and it cannot report a missing flow.

Lemma 6 (successive shortest paths). If the arcs have no negative cycle and (F)(F) is feasible, line L9 returns an optimal flow ff, and the residual graph of ff has no negative cycle.

Proof. Add a super source joined to each xx with a(x)<0a(x) < 0 by an arc of capacity −a(x)-a(x) and cost 0, and a super sink reached from each xx with a(x)>0a(x) > 0 by an arc of capacity a(x)a(x). Give each real arc the capacity U+1U + 1, where U=∑xmax⁡(a(x),0)U = \sum_x \max(a(x), 0). A flow of value UU that meets the demands never puts more than UU on an arc in an optimal solution with no flow cycles, and (F)(F) has such an optimal solution because removing a cycle of flow does not raise the cost when there is no negative cycle. So the capacity does not change the optimum. By the theorem on the successive shortest path page, the method keeps a flow whose residual graph has no negative cycle, and after UU units it has a flow of value UU of least cost. Its restriction to the real arcs is optimal for (F)(F). □\square

Lemma 7 (potentials). Let π\pi be the shortest distances of line L11, in the residual graph of ff restricted to XX, from a virtual source with a 0 arc to every vertex. Then r=π(h)−πr = \pi(h) - \pi satisfies SS and is tight on every arc with f>0f > 0.

Proof. The residual graph has no negative cycle by Lemma 6, so the distances exist, and they are integers because all costs are integers. Every real arc u→vu \to v of cost bb stays in the residual graph, since its flow is at most UU and its capacity is U+1U + 1. So π(v)≤π(u)+b\pi(v) \le \pi(u) + b, that is r(u)−r(v)=π(v)−π(u)≤br(u) - r(v) = \pi(v) - \pi(u) \le b, and SS holds. If f>0f > 0 on the arc, the reverse arc v→uv \to u of cost −b-b is in the residual graph, so π(u)≤π(v)−b\pi(u) \le \pi(v) - b. Together, π(v)−π(u)=b\pi(v) - \pi(u) = b, and the constraint is tight. Adding the constant π(h)\pi(h) keeps all differences. □\square

Theorem. If some legal retiming meets the period bound, MIN-AREA-RETIMING returns an integer legal retiming rr with r(h)=0r(h) = 0 and c(Gr)≤cc(G_r) \le c whose register count is the least over all such retimings, in the chosen model. Otherwise it returns "infeasible".

Proof. The second claim is Lemma 5 with Lemma 1. For the first, ff is feasible for (F)(F) by Lemma 6, and rr is feasible for the relaxation of (P)(P) and tight wherever f>0f > 0 by Lemma 7. By Lemma 4, rr is optimal for the relaxation, and it is an integer vector, so it is optimal for (P)(P). The integrality also follows from the fact that AA is the transpose of a network matrix and so totally unimodular. Lowering each r(mu)r(m_u) to its least value keeps SS and does not raise the objective, since a(mu)=∑iβ(gi)>0a(m_u) = \sum_i \beta(g_i) > 0 counts only edges into mum_u, so rr already has these least values at an optimum or another optimum has them with the same values on VV. By Lemmas 1 and 2, the restriction of rr to VV is a legal retiming that meets the bound and minimizes λN\lambda N, hence NN. ■\blacksquare

Complexity

The system has M≤E+V2M \le E + V^2 constraints, or EE with no period bound. Lines L1 to L7 take O(V3)O(V^3) time with the period bound, for WW and DD, and O(E)O(E) without it. For the per-edge count, the total demand ∑xmax⁡(a(x),0)\sum_x \max(a(x), 0) is at most EE, and each shortest path pushes at least one unit, so successive shortest paths make at most EE rounds of Bellman-Ford, each in O(VM)O(VM) time. That is O(EVM)O(EVM) time and O(V2)O(V^2) space. For the shared count, the scale factor of line L5 multiplies the demands, so this bound grows with the least common multiple of the fanout sizes. A min-cost flow method whose time does not depend on the demands, such as cost scaling, removes this factor.

Properties

  • Exact. The count is the least over all legal retimings with the period bound, for the count model chosen.
  • Integral. The optimum is reached by an integer retiming, by total unimodularity.
  • Infeasibility is detected. If no retiming meets the period bound, the constraint graph has a negative cycle, and line L10 reports it.
  • The function is kept. As for any retiming, the gates are unchanged, and the output streams are the same after the start-up phase.

Variants and improvements

  • Weighted registers. Give each edge a cost per register, for example for wide buses. The breadths of line L2 become these costs, and nothing else changes.
  • Least period first. Run retiming for the least period c∗c^*, then minimum-area retiming with c=c∗c = c^*. This gives the fewest registers among the fastest retimings.
  • Fewer constraints. Most period constraints are implied by others. Shenoy and Rudell (1994) prune them, which makes the method practical for large netlists.
  • Other flow solvers. Any min-cost flow solver that returns optimal potentials works, for example network simplex, whose dual values are the potentials, or successive shortest paths with Dijkstra and reduced costs.

When to use it

Use it when the clock period is fixed by the design and the register count, area or power should go down, for example after a pipeline was added by hand. Use the shared count for real hardware, since a gate with many fanouts can share one register chain. When the registers must stay put, for example because of test or verification, use clock skew scheduling for timing instead.

Pitfalls

  • Per-edge counts overstate the area. Without the mirror vertices, the program pays for every fanout edge, and it may refuse a move that a shared register makes cheap. In the correlator at c=13c = 13, the per-edge count is 5, but the circuit needs only 4 registers.
  • Lost constraints in the flow. The arcs have no capacity. A flow code that gives them a finite capacity must make it large enough that no arc is saturated, or the saturated arc drops out of the residual graph and its constraint is lost from the potentials. Then rr can break the period bound.
  • The sign of the potentials. The constraint r(u)−r(v)≤br(u) - r(v) \le b is met by r=−πr = -\pi, not by r=πr = \pi, when the arc is u→vu \to v of cost bb.
  • Initial states. As for retiming, the moved registers need new initial values, and a backward move can make them impossible to find.

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.

minimum_area_retiming.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-area-retiming/. The authors are listed in prov/HEA0W3.jsonl.

"""Minimum-area retiming as the dual of a minimum cost flow problem.

A circuit is a graph with vertices 0 .. n-1, integer delays d[v] >= 0 and
edges (u, v, w), a wire from u to v through w >= 0 registers. Vertex 0 is
the host and keeps r(0) = 0. Every cycle must hold a register. A retiming r
gives w_r(e) = w(e) + r(v) - r(u), and it is legal when every w_r(e) >= 0.

Two register counts are supported:
- per edge: the sum of w_r(e) over all edges;
- shared: the registers on the fanout edges of one vertex form one chain,
  so the count is the sum over u of the largest w_r(e) of an edge out of u.
The shared count uses the mirror vertices of Leiserson and Saxe.
"""

from math import lcm
from typing import Optional

Edge = tuple[int, int, int]


def register_count(edges: list[Edge], r: list[int], shared: bool = False) -> int:
    er = [(u, v, w + r[v] - r[u]) for (u, v, w) in edges]
    if not shared:
        return sum(w for (_, _, w) in er)
    most: dict[int, int] = {}
    for (u, _, w) in er:
        most[u] = max(most.get(u, 0), w)
    return sum(most.values())


def clock_period(n: int, d: list[int], edges: list[Edge]) -> int:
    """The largest delay of a path with no register. Raises ValueError if a
    cycle has no register."""
    succ: list[list[int]] = [[] for _ in range(n)]
    indeg = [0] * n
    for (u, v, w) in edges:
        if w == 0:
            succ[u].append(v)
            indeg[v] += 1
    arrive = list(d)
    queue = [v for v in range(n) if indeg[v] == 0]
    seen = 0
    while queue:
        u = queue.pop()
        seen += 1
        for v in succ[u]:
            arrive[v] = max(arrive[v], arrive[u] + d[v])
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    if seen < n:
        raise ValueError("a cycle has no register")
    return max(arrive) if n else 0


def wd_matrices(n: int, d: list[int], edges: list[Edge]):
    """W[u][v]: the fewest registers on a path u to v; D[u][v]: the largest
    delay of such a path, with d[u] and d[v]. None when there is no path."""
    best: list[list[Optional[tuple[int, int]]]] = [[None] * n for _ in range(n)]
    for v in range(n):
        best[v][v] = (0, 0)
    for (u, v, w) in edges:
        cand = (w, -d[u])
        if u != v and (best[u][v] is None or cand < best[u][v]):
            best[u][v] = cand
    for k in range(n):
        for i in range(n):
            if best[i][k] is None:
                continue
            for j in range(n):
                if best[k][j] is None:
                    continue
                cand = (best[i][k][0] + best[k][j][0], best[i][k][1] + best[k][j][1])
                if best[i][j] is None or cand < best[i][j]:
                    best[i][j] = cand
    W = [[None if best[u][v] is None else best[u][v][0] for v in range(n)] for u in range(n)]
    D = [[None if best[u][v] is None else d[v] - best[u][v][1] for v in range(n)] for u in range(n)]
    return W, D


def _bellman_ford(n: int, arcs: list[tuple[int, int, int]], src: Optional[int]):
    """Shortest distances over arcs (a, b, cost). From src, or from a virtual
    source joined to every node when src is None. Returns (dist, parent) or
    None on a negative cycle. Unreachable nodes have dist None."""
    dist: list[Optional[int]] = [0] * n if src is None else [None] * n
    parent: list[Optional[int]] = [None] * n
    if src is not None:
        dist[src] = 0
    for _ in range(n + 1):
        changed = False
        for i, (a, b, cost) in enumerate(arcs):
            if dist[a] is not None and (dist[b] is None or dist[a] + cost < dist[b]):
                dist[b] = dist[a] + cost
                parent[b] = i
                changed = True
        if not changed:
            return dist, parent
    return None


def min_cost_flow_dual(n: int, arcs: list[tuple[int, int, int]], demand: list[int]) -> Optional[tuple[int, list[int]]]:
    """Solve min sum(b * f) over uncapacitated arcs (u, v, b) with
    inflow(x) - outflow(x) = demand[x], by successive shortest paths.

    Returns the least cost and potentials pi with b + pi[u] - pi[v] >= 0 on
    every arc and equality on every arc with flow, or None if no flow meets
    the demands or a negative cycle exists."""
    if _bellman_ford(n, arcs, None) is None:
        return None
    total = sum(x for x in demand if x > 0)
    s, t = n, n + 1
    # residual arcs: [tail, head, cost, capacity]; arc 2k + 1 is the reverse of arc 2k
    res: list[list[int]] = []

    def add(a: int, b: int, cost: int, cap: int) -> None:
        res.append([a, b, cost, cap])
        res.append([b, a, -cost, 0])

    for (u, v, b) in arcs:
        # Uncapacitated: the flow on one arc never exceeds the total demand, so the
        # capacity total + 1 is never reached and every arc stays in the residual graph.
        add(u, v, b, total + 1)
    for x in range(n):
        if demand[x] < 0:
            add(s, x, 0, -demand[x])
        elif demand[x] > 0:
            add(x, t, 0, demand[x])
    cost = 0
    sent = 0
    while sent < total:  # @line L9
        live = [(a, b, c) for (a, b, c, cap) in res if cap > 0]
        index = [i for i, arc in enumerate(res) if arc[3] > 0]
        out = _bellman_ford(n + 2, live, s)
        assert out is not None  # the residual graph of a min-cost flow has no negative cycle
        dist, parent = out
        if dist[t] is None:
            return None
        path, x = [], t
        while x != s:
            i = index[parent[x]]
            path.append(i)
            x = res[i][0]
        push = min(res[i][3] for i in path)
        for i in path:
            res[i][3] -= push
            res[i ^ 1][3] += push
        cost += push * dist[t]
        sent += push
    live = [(a, b, c) for (a, b, c, cap) in res if cap > 0 and a < n and b < n]  # @line L11
    out = _bellman_ford(n, live, None)
    assert out is not None
    return cost, out[0]


def min_area_retiming(n: int, d: list[int], edges: list[Edge], c: Optional[int] = None,
                      shared: bool = False) -> Optional[tuple[int, list[int]]]:
    """The fewest registers over legal retimings with period at most c (no
    bound when c is None), and a retiming that reaches it. None if no legal
    retiming has period at most c."""
    clock_period(n, d, edges)
    cons = [(u, v, w) for (u, v, w) in edges]  # @line L1: (u, v, b) means r(u) - r(v) <= b
    breadth: list[tuple[int, int, int]] = []  # (tail, head, weight of the edge in the objective)
    m = n
    if shared:  # @line L3
        fanout: dict[int, list[Edge]] = {}
        for e in edges:
            fanout.setdefault(e[0], []).append(e)
        scale = lcm(*[len(es) for es in fanout.values()]) if fanout else 1  # @line L5: integer breadths
        for u, es in fanout.items():
            if len(es) == 1:
                breadth.append((u, es[0][1], scale))
                continue
            wmax = max(w for (_, _, w) in es)
            mirror = m
            m += 1
            for (_, v, w) in es:
                breadth.append((u, v, scale // len(es)))
                breadth.append((v, mirror, scale // len(es)))
                cons.append((v, mirror, wmax - w))  # @line L4
    else:
        scale = 1
        breadth = [(u, v, 1) for (u, v, _) in edges]  # @line L2
    if c is not None:  # @line L6
        W, D = wd_matrices(n, d, edges)
        for u in range(n):
            for v in range(n):
                if D[u][v] is not None and D[u][v] > c:
                    cons.append((u, v, W[u][v] - 1))
    # objective: sum over objective edges of beta * (r(head) - r(tail)), plus a constant
    coef = [0] * m  # @line L7
    for (u, v, beta) in breadth:
        coef[v] += beta
        coef[u] -= beta
    # min coef . r subject to r(u) - r(v) <= b has the dual: min sum b f over arcs u -> v
    # with inflow - outflow = coef, and the optimum r is minus the potentials.
    out = min_cost_flow_dual(m, cons, coef)  # @line L8
    if out is None:
        return None  # @line L10
    _, pi = out
    r = [-p + pi[0] for p in pi]  # @line L12
    return register_count(edges, r[:n], shared), r[:n]  # @line L13
test_minimum_area_retiming.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-area-retiming/. The authors are listed in prov/HEA0W3.jsonl.

import itertools
import random

from minimum_area_retiming import clock_period, min_area_retiming, min_cost_flow_dual, register_count, wd_matrices

# The correlator of the page: host 0, comparators 1 to 4 (delay 3), adders 5 to 7 (delay 7).
N = 8
DELAY = [0, 3, 3, 3, 3, 7, 7, 7]
EDGES = [(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 4, 1), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 0, 0),
         (3, 5, 0), (2, 6, 0), (1, 7, 0)]


def retimed(edges, r):
    return [(u, v, w + r[v] - r[u]) for (u, v, w) in edges]


def legal(edges, r) -> bool:
    return all(w >= 0 for (_, _, w) in retimed(edges, r))


def random_circuit(rng: random.Random, n: int):
    while True:
        d = [0] + [rng.randint(1, 5) for _ in range(n - 1)]
        edges = [(i, (i + 1) % n, rng.choice([0, 1, 1])) for i in range(n)]
        for _ in range(rng.randint(1, n + 1)):
            u, v = rng.randrange(n), rng.randrange(n)
            if u != v:
                edges.append((u, v, rng.choice([0, 0, 1, 2])))
        try:
            clock_period(n, d, edges)
        except ValueError:
            continue
        if sum(w for (_, _, w) in edges) <= 8:
            return d, edges


def fewest_registers(n, edges, src):
    best = [None] * n
    best[src] = 0
    for _ in range(n):
        for (u, v, w) in edges:
            if best[u] is not None and (best[v] is None or best[u] + w < best[v]):
                best[v] = best[u] + w
    return best


def all_legal_retimings(n, edges):
    """Every legal retiming with r(0) = 0, from the box -W(0, v) <= r(v) <= W(v, 0)."""
    down = fewest_registers(n, edges, 0)
    up = [fewest_registers(n, edges, v)[0] for v in range(n)]
    for t in itertools.product(*[range(-down[v], up[v] + 1) for v in range(1, n)]):
        r = [0, *t]
        if legal(edges, r):
            yield r


def test_one_gate() -> None:
    # Host 0 feeds gate 1 on two wires, each with a register; gate 1 feeds the host.
    edges = [(0, 1, 1), (0, 1, 1), (1, 0, 0)]
    count, r = min_area_retiming(2, [0, 1], edges)
    assert (count, r) == (1, [0, -1])


def test_flow_dual_small() -> None:
    # min 3 f01 + 1 f12 + 1 f02 with one unit from 0 to 2: the path 0 -> 2 costs 1.
    cost, pi = min_cost_flow_dual(3, [(0, 1, 3), (1, 2, 1), (0, 2, 1)], [-1, 0, 1])
    assert cost == 1
    for (u, v, b) in [(0, 1, 3), (1, 2, 1), (0, 2, 1)]:
        assert b + pi[u] - pi[v] >= 0
    assert 1 + pi[0] - pi[2] == 0  # the arc with flow is tight


def test_correlator() -> None:
    assert min_area_retiming(N, DELAY, EDGES) == (4, [0] * 8)
    count, r = min_area_retiming(N, DELAY, EDGES, 13)
    assert count == 5 and legal(EDGES, r)
    assert clock_period(N, DELAY, retimed(EDGES, r)) <= 13
    count, r = min_area_retiming(N, DELAY, EDGES, 13, shared=True)
    assert count == 4 and register_count(EDGES, r, shared=True) == 4
    assert min_area_retiming(N, DELAY, EDGES, 12) is None
    assert min_area_retiming(N, DELAY, EDGES, 16)[0] == 4


def test_against_bruteforce() -> None:
    rng = random.Random(5201)
    saved = 0
    for _ in range(120):
        n = rng.randint(3, 6)
        d, edges = random_circuit(rng, n)
        table = []
        for r in all_legal_retimings(n, edges):
            table.append((clock_period(n, d, retimed(edges, r)),
                          register_count(edges, r), register_count(edges, r, shared=True)))
        _, D = wd_matrices(n, d, edges)
        bounds = [None] + sorted({x for row in D for x in row if x is not None})
        for c in bounds:
            ok = [t for t in table if c is None or t[0] <= c]
            for shared in (False, True):
                got = min_area_retiming(n, d, edges, c, shared)
                if not ok:
                    assert got is None
                    continue
                best = min(t[2 if shared else 1] for t in ok)
                assert got is not None and got[0] == best
                count, r = got
                assert r[0] == 0 and legal(edges, r)
                assert register_count(edges, r, shared) == count
                if c is not None:
                    assert clock_period(n, d, retimed(edges, r)) <= c
        saved += min(t[1] for t in table) < register_count(edges, [0] * n)
    assert saved >= 20  # many instances lose registers

History

Leiserson and Saxe (1991) stated the minimum register problem as a linear program over the retiming variables, observed that its dual is a min-cost flow problem, and gave the mirror vertex construction for shared fanout registers. Shenoy and Rudell (1994) reduced the number of period constraints so that the method runs on large netlists.

References

  1. Charles E. Leiserson and James B. Saxe, Retiming synchronous circuitry, Algorithmica 6(1-6), 5 to 35, 1991, the sections on minimizing the number of registers, the linear program and its min-cost flow dual, and the mirror vertices for fanout sharing
  2. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 9, Sequential Logic Optimization (retiming for area)
  3. Efficient implementation of retiming, the reduction of the period constraints that makes minimum-area retiming run on large circuits (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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