Algorithm Search⌘K

Algorithmcore

Tree covering technology mapping

Also called DAGON, Keutzer tree covering.

Keutzer's mapper that splits the subject graph into trees and covers each tree optimally by dynamic programming over pattern matches of library gates.

Time
O(N L s 2^s) worst
Space
O(N) extra
Where
L = the number of library patterns; N = the number of nodes of the subject graph; s = the largest number of nodes in a pattern
Properties
deterministicnot exactofflineiterative
Origin
Kurt Keutzer, 1987

Tree covering technology mapping maps a circuit into the gates of a cell library. The circuit is first written as a subject graph of base gates, for example 2-input NAND gates and inverters, and each library gate is written as one or more pattern trees over the same base gates. The subject graph is cut into trees at every node with more than one fanout. In each tree, a dynamic program from the leaves to the root finds, for every node, the cheapest way to cover the subtree below it with pattern matches, and the cover of the tree root gives the cover of the tree. Keutzer described this method in 1987 in his mapper DAGON, using the tree matching and dynamic programming of code generators. The cover of each tree is optimal for the given subject graph and library. The cover of the whole circuit is optimal only among the covers that respect the cut into trees, and a cover that duplicates logic across a cut can be cheaper.

In plain words

A cell library offers gates such as NAND, NOR, AND-OR-INVERT and inverters, each with a size. The job is to rebuild a circuit from these gates with the smallest total size.

Write the circuit and every library gate in the same small parts, say 2-input NANDs and inverters. A library gate then looks like a small tree of parts. Covering the circuit means placing these trees over it so that every part is covered once.

Where a wire splits to several places, cut the circuit, so it falls into trees. In a tree, work from the inputs up. At each part, try every library gate that fits there, add the best known cost of whatever is under its inputs, and keep the cheapest. The answer at the top of a tree is its best cover.

The problem

The input is a subject graph and a library. The subject graph is a directed acyclic graph of primary inputs, inverters and 2-input NAND gates, with a set of outputs. A library gate has an area and a pattern, a tree whose inner nodes are NAND and INV and whose leaves are the inputs of the gate. A pattern matches at node vv if the subject graph below vv has the same shape, with the two inputs of a NAND taken in either order. The match covers the nodes that the inner nodes of the pattern land on, and its inputs are the nodes that the leaves land on.

A cover is a set of matches such that every output gate is the root of a match and every input of a match is a primary input or the root of a match. The goal of this page is the least total area. This is one form of technology mapping. The cut into trees adds a rule. Let RR be the set of gates that drive an output or have more than one fanout, counted only among the gates that reach an output. The tree of r∈Rr \in R is rr with the gates that reach rr through gates outside RR. A tree cover is a cover whose matches cover only nodes of one tree, so that no match covers a node of RR except at its root.

The algorithm

  1. TREE-COVER(G, library)
  2. 1R ← the gates of G with more than one fanout, and the output gates, among the gates that reach an output
  3. 2for each gate v of G in topological order do
  4. 3cost(v) ← ∞
  5. 4for each library gate g and each match of g at v whose covered nodes other than v are gates outside R do
  6. 5c ← area(g) + the sum of leafcost(u) over the inputs u of the match
  7. 6if c < cost(v) then cost(v) ← c; choice(v) ← (g, the inputs of the match)
  8. 7leafcost(u) is 0 if u is a primary input or in R, and cost(u) otherwise
  9. 8cover ← ∅; todo ← the output gates
  10. 9while todo is not empty do
  11. 10take v from todo; if v is not in cover then add (v, choice(v)) to cover and add the gates among the inputs of choice(v) to todo
  12. 11return cover and the sum of the areas of its gates

Line L4 is tree pattern matching: the pattern is walked down from vv, and at each NAND both orders of the inputs are tried. Lines L5 and L6 are the dynamic program on a tree: the cost of a node is the area of its best match plus the costs of the subtrees under the inputs of that match. At an input that is a primary input or the root of another tree, the cost is 0 here, because that tree is paid for once at its own root. Lines L8 to L10 read the cover back from the outputs. The total equals the sum of cost(r)\mathrm{cost}(r) over r∈Rr \in R.

Example

The toy library of this page has these gates and areas, made up for the examples: INV 2, NAND2 3, NOR2 3, AND2 4, OR2 4, NAND3 4, AOI21 4, OAI21 4, NAND4 5 and AOI22 5. AND2 is the pattern INV(NAND(xx, xx)), AOI21 is INV(NAND(NAND(xx, xx), INV(xx))) and AOI22 is INV(NAND(NAND(xx, xx), NAND(xx, xx))).

Take o=ab+cd‾o = \overline{ab + cd}, written as n4=NAND(a,b)n_4 = \mathrm{NAND}(a, b), n5=NAND(c,d)n_5 = \mathrm{NAND}(c, d), n6=NAND(n4,n5)n_6 = \mathrm{NAND}(n_4, n_5) and o=INV(n6)o = \mathrm{INV}(n_6). No node has more than one fanout, so the whole graph is one tree with root oo.

node matches tried best cost
n4n_4 NAND2 over a,ba, b: 3 3
n5n_5 NAND2 over c,dc, d: 3 3
n6n_6 NAND2 over n4,n5n_4, n_5: 3+3+3=93 + 3 + 3 = 9 9
oo AOI22 over a,b,c,da, b, c, d: 5; AND2 over n4,n5n_4, n_5: 4+3+3=104 + 3 + 3 = 10; INV over n6n_6: 2+9=112 + 9 = 11 5

The cover is one AOI22 of area 5. Without AOI22 and NAND4 in the library, the best cover is AND2 over two NAND2 gates, with area 10.

Now take n=NAND(a,b)n = \mathrm{NAND}(a, b) with two fanouts, o1=INV(n)=abo_1 = \mathrm{INV}(n) = ab and o2=INV(NAND(n,INV(c)))=ab+c‾o_2 = \mathrm{INV}(\mathrm{NAND}(n, \mathrm{INV}(c))) = \overline{ab + c}. The node nn is in RR, so there are three trees, with roots nn, o1o_1 and o2o_2. The tree of nn costs 3 for a NAND2. The tree of o1o_1 costs 2 for an INV over nn. In the tree of o2o_2, AOI21 does not fit, because it would cover nn, so the best is AND2 over nn and INV(c)\mathrm{INV}(c), with 4+2=64 + 2 = 6. The tree cover has area 3+2+6=113 + 2 + 6 = 11. A cover that duplicates nn, with AND2 over a,ba, b for o1o_1 and AOI21 over a,b,ca, b, c for o2o_2, has area 8, so the tree cover is not optimal for the whole graph.

Correctness

The full proof shows that the trees split the gates that reach an output, that each tree is a rooted tree with fanout 1 inside, and that cost(v)\mathrm{cost}(v) is the least area of a cover of the subtree below vv, by induction over the tree, since the subtrees under the inputs of a match are disjoint. The cost of a tree cover is the sum of independent tree costs, so the result is a least area tree cover. Every match computes its node from its inputs, so the cover computes the outputs.

Proof: Tree covering gives a valid cover of least area among tree coversfull

Let GG be a subject graph: a directed acyclic graph of primary inputs (PIs), inverters and 2-input NAND gates, with a set of output gates. Let V∗V^* be the set of gates from which an output can be reached, and for u∈V∗u \in V^* let fo(u)\mathrm{fo}(u) be the number of fanin slots of gates of V∗V^* that hold uu. Let RR be the set of gates u∈V∗u \in V^* with fo(u)>1\mathrm{fo}(u) > 1 or uu an output, as at line L1. A match of library gate gg at vv is a map of the pattern of gg into GG that sends the pattern root to vv, each inner node to a gate of the same kind, and the children of an inner node to the fanins of its image, in some order. Its covered set is the image of the inner nodes, and its inputs are the images of the pattern leaves. An admissible match at vv is one whose covered nodes other than vv are gates outside RR, as at line L4.

Lemma 1 (the trees). Every gate w∈V∗∖Rw \in V^* \setminus R has exactly one fanout gate in V∗V^*, and that fanout reads ww in one slot. Following these fanouts from ww reaches a unique first node r(w)∈Rr(w) \in R. With r(r)=rr(r) = r for r∈Rr \in R, the sets T(r)={w∈V∗:r(w)=r}T(r) = \{w \in V^* : r(w) = r\} split the gates of V∗V^*, and in each T(r)T(r) the fanout edges form a tree rooted at rr.

Proof. A gate w∈V∗w \in V^* reaches an output, and it is not an output since w∉Rw \notin R, so it has a fanout in V∗V^*, and fo(w)=1\mathrm{fo}(w) = 1 gives exactly one, in one slot. The fanout is also in V∗V^*. The walk moves forward in a finite acyclic graph and can stop only at a node of RR, since every node outside RR has a next node; it must stop because it reaches an output after finitely many steps and outputs are in RR. The walk is unique, so r(w)r(w) is well defined, the sets T(r)T(r) are disjoint, and they cover V∗V^*. The parent of w≠rw \ne r in T(r)T(r) is its unique fanout, so the edges form a tree. □\square

For v∈T(r)v \in T(r), let TvT_v be the set of nodes of T(r)T(r) below vv, that is vv and the gates of T(r)T(r) whose walk passes vv. A cover of TvT_v is a set MM of admissible matches with roots in TvT_v such that vv is a root, every input of a match of MM that is a gate outside RR is a root of a match of MM, and the roots are distinct. Its area is the sum of the areas of its gates.

Lemma 2 (shape of an admissible match). Let mm be an admissible match at v∈V∗v \in V^*. Then its covered nodes are in TvT_v, its inputs are distinct when they are gates outside RR, and for distinct inputs u,u′u, u' of mm that are gates outside RR, the sets TuT_u and Tu′T_{u'} are disjoint and do not meet the covered set.

Proof. A covered node other than vv is a gate outside RR, so it has one fanout, which is its parent in the image of the pattern. By induction from the root, each covered node is in TvT_v. An input uu that is a gate outside RR has one fanout slot, so only one pattern leaf can land on it. Its fanout is a covered node, so u∈Tvu \in T_v, and TuT_u lies below that covered node. If TuT_u and Tu′T_{u'} met, or if TuT_u held a covered node, one node would have two paths up to vv through the tree, which Lemma 1 rules out: a node of TuT_u goes up through uu, and a covered node or a node of Tu′T_{u'} does not go through uu. □\square

Lemma 3 (the dynamic program). For every gate v∈V∗v \in V^*, line L6 sets cost(v)\mathrm{cost}(v) to the least area of a cover of TvT_v, and choice(v)\mathrm{choice}(v) is the root match of such a cover.

Proof. Induction on the topological order, which visits the inputs of a match before its root. Let MM be a cover of TvT_v and mm its match at vv. Let UU be the inputs of mm that are gates outside RR. For u∈Uu \in U, the matches of MM with roots in TuT_u form a cover of TuT_u: uu is a root, and an input of such a match that is a gate outside RR lies in TuT_u, by Lemma 2 applied to that match. By Lemma 2 these sets of matches are disjoint for different uu and do not contain mm. So the area of MM is at least area(m)+∑u∈Ucost(u)\mathrm{area}(m) + \sum_{u \in U} \mathrm{cost}(u), by induction, which is the value of line L5 for mm, since leafcost is 0 for PIs and nodes of RR. Conversely, for each admissible match mm at vv, the union of mm with least covers of TuT_u for u∈Uu \in U is a cover of TvT_v with exactly that area. Line L4 tries every admissible match, so the least value of line L5 is the least area of a cover. □\square

Theorem. Lines L8 to L11 return a cover of GG that computes the outputs of GG, and its area is the least area of a tree cover, a cover whose matches are all admissible. The area equals ∑r∈Rcost(r)\sum_{r \in R} \mathrm{cost}(r).

Proof. Validity. Each gate in the cover has the match choice(v)\mathrm{choice}(v), and line L10 adds every gate input of that match to the work list, so every input of a chosen match is a PI or a gate of the cover. A match computes the function of its root from its inputs, because the library gate computes the function of its pattern, and the pattern has the same shape as the subject graph below the root. By induction in topological order, every gate of the cover computes the same function as in GG, and so do the outputs.

Which matches are read back. Starting from the outputs, which are in RR, line L10 adds choice(r)\mathrm{choice}(r) for a root r∈Rr \in R, then the roots of the least cover of TrT_r by Lemma 3, and at each input in RR it starts again at that root. Every r∈Rr \in R is reached: rr is in V∗V^*, so a path leads from rr to an output, and the tree that contains the next node of the path on the way out has rr as an input of its cover, since every node of a tree is covered and every edge into a covered node from outside the covered set is an input. So the returned cover is the union over r∈Rr \in R of least covers of TrT_r, and its area is ∑rcost(r)\sum_{r} \mathrm{cost}(r).

Optimality among tree covers. Let MM be any tree cover. Every output gate is a root of MM. Every gate r∈Rr \in R is a root of MM as well: some gate reads rr, and the match that covers that gate is admissible, so rr is not one of its covered nodes but one of its inputs, which must be a root. For each r∈Rr \in R, the matches of MM with roots in TrT_r form a cover of TrT_r, by the same argument as in Lemma 3, and these sets are disjoint because the TrT_r are disjoint. So the area of MM is at least ∑r∈Rcost(r)\sum_{r \in R} \mathrm{cost}(r). ■\blacksquare

Remark. A cover in which a match covers a node of RR other than its root duplicates the logic of that node, and it is not a tree cover. Such covers can have less area, as the second example of the page shows, so the theorem does not say that the result is a least area cover of GG.

Termination. Each gate is handled once at lines L2 to L6, each node has finitely many matches, and line L10 adds a gate to the cover at most once.

Complexity

At each of the NN nodes, line L4 tries the LL patterns. A pattern with ss nodes has at most s/2s/2 NAND nodes, so at most 2s/22^{s/2} orders of inputs, and each order is checked in O(s)O(s), which gives O(NLs2s)O(N L s 2^s) in all, a loose bound. For a fixed library this is linear in the size of the subject graph. The tables cost and choice take O(N)O(N) space. Lines L8 to L11 take O(N)O(N) time. Real mappers prepare the library patterns once, often as an automaton for tree matching, so that matching at a node costs less.

Properties

What is proved. The result is a valid cover: every output and every input of a match is driven, and the mapped circuit computes the same outputs. Its area is the least among all tree covers of the given subject graph with the given patterns. Each tree is covered without duplicating logic, since inside a tree every gate has one fanout.

What is not proved. The result is not the least area cover of the subject graph, as the second example shows. Finding that cover for a general DAG is stated to be NP-hard in the mapping literature, and this page does not prove it. The result also depends on the subject graph: another decomposition of the same function into NAND and INV can lead to a smaller cover, and the algorithm does not search over decompositions. Area is the only cost here, and the optimality says nothing about delay.

What is measured. Nothing beyond the examples. The tests of this page compare the dynamic program with an exhaustive search over tree covers on 300 random subject graphs (seed 21), and check that an exhaustive search over all covers of the graph, with duplication, never costs more than the tree cover and costs less on some graphs (seed 22).

Variants and improvements

  • Delay. With a delay for each gate that does not depend on its load, the same dynamic program can minimize the arrival time at each node, keeping the best match for each node by arrival time. The mapper of MIS has such a delay mode.
  • Inverter pairs. Adding a pair of inverters on every wire of the subject graph lets patterns match with either polarity, and the dynamic program removes the pairs it does not need.
  • Several patterns per gate. A gate such as NAND4 has several decompositions into 2-input NANDs. Listing each as a pattern lets the gate match more subject graphs.
  • Covering across cuts. Mappers can let a match cover a node with more than one fanout and pay for a copy of its logic, which can find the cheaper cover of the second example at the cost of losing the exact tree result.
  • Boolean matching. Instead of matching the shape of a pattern, match the function of a cut with Boolean matching. This finds matches that structural matching misses, and it is the basis of cut-based cell mappers.

When to use it

Use tree covering for standard cell mapping when a fast mapper with a clear optimality guarantee per tree is enough, and when the subject graph is already well structured, for example after AIG optimization. When duplication across fanout points or matches that do not depend on the structure matter, use a cut-based mapper with Boolean matching. For FPGAs, use LUT mapping instead.

Pitfalls

  • Dead logic in the tree roots. Count fanouts only among the gates that reach an output. A dead gate that reads a node can make it a tree root for no reason and change the cover.
  • One order of NAND inputs. Matching only the order of the pattern misses matches. Try both orders at each NAND of the pattern.
  • A library that cannot cover a node. The library must at least contain INV and NAND2 with their plain patterns, or some node can have no match.
  • Leaf costs of tree roots. A tree root costs 0 as the input of another tree. If its cost is added in each tree that reads it, its area is paid many times.
  • Reading optimality too widely. The result is optimal per tree for this subject graph, not for the circuit.

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.

tree_covering_technology_mapping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tree-covering-technology-mapping/. The authors are listed in prov/QGBZ88.jsonl.

"""Tree covering technology mapping in the style of DAGON (Keutzer, 1987).

The subject graph is a network of two-input NAND gates and inverters,
given as `kinds` and `fanins` in topological order: kinds[v] is "in",
"inv" or "nand", and every fanin of v is smaller than v. `outputs` lists
the nodes that drive primary outputs.

Each library gate has an area and a pattern, a tree over the same base
gates. A pattern is "x" (an input of the gate), ("inv", p) or
("nand", p, q). A pattern matches at a node when the subject graph has
the same shape below the node, with the two inputs of a NAND in either
order.

The subject graph is cut into trees at every node with more than one
fanout and at every output. Inside one tree, dynamic programming from
the leaves to the root gives the least area cover of every node:
cost(v) is the least area(g) + sum of cost(l) over a match of gate g at
v with inputs l, where cost(l) = 0 for a primary input or the root of
another tree. The total area is the sum of the costs of the tree roots.
"""

from typing import Sequence

# A toy library. The areas are made up for the examples of the page.
LIBRARY = [
    ("INV", 2, ("inv", "x")),
    ("NAND2", 3, ("nand", "x", "x")),
    ("AND2", 4, ("inv", ("nand", "x", "x"))),
    ("NOR2", 3, ("inv", ("nand", ("inv", "x"), ("inv", "x")))),
    ("OR2", 4, ("nand", ("inv", "x"), ("inv", "x"))),
    ("NAND3", 4, ("nand", "x", ("inv", ("nand", "x", "x")))),
    ("AOI21", 4, ("inv", ("nand", ("nand", "x", "x"), ("inv", "x")))),
    ("OAI21", 4, ("nand", ("nand", ("inv", "x"), ("inv", "x")), "x")),
    ("NAND4", 5, ("nand", ("inv", ("nand", "x", "x")), ("inv", ("nand", "x", "x")))),
    ("AOI22", 5, ("inv", ("nand", ("nand", "x", "x"), ("nand", "x", "x")))),
]


def live_nodes(fanins, outputs) -> set:
    """The nodes from which an output can be reached; other nodes are dead logic."""
    seen, stack = set(), list(outputs)
    while stack:
        w = stack.pop()
        if w not in seen:
            seen.add(w)
            stack.extend(fanins[w])
    return seen


def tree_roots(kinds, fanins, outputs) -> set:
    """Live gates where the subject graph is cut: more than one fanout, or an output."""
    live = live_nodes(fanins, outputs)
    cnt = [0] * len(fanins)
    for v in live:
        for u in fanins[v]:
            cnt[u] += 1
    outs = set(outputs)
    return {v for v in live if kinds[v] != "in" and (cnt[v] > 1 or v in outs)}


def matches(kinds, fanins, pat, v, inner_ok) -> list:
    """Every list of subject nodes that the inputs of pattern pat bind to at v.

    The root of the pattern is v. A node that an inner node of the
    pattern (not its root, not an input) covers must pass inner_ok.
    """
    if pat == "x":
        return [[v]]
    if kinds[v] != pat[0]:
        return []

    def sub(p, u):
        if p == "x":
            return [[u]]
        if not inner_ok(u):
            return []
        return matches(kinds, fanins, p, u, inner_ok)

    if pat[0] == "inv":
        return sub(pat[1], fanins[v][0])
    a, b = fanins[v]
    out = []
    for x, y in ((a, b), (b, a)):
        for la in sub(pat[1], x):
            for lb in sub(pat[2], y):
                out.append(la + lb)
    return out


def tree_cover(kinds: Sequence[str], fanins: Sequence[Sequence[int]], outputs: Sequence[int],
               library=LIBRARY):
    """Return (total area, cover). The cover maps a gate root to (gate name, inputs)."""
    for v, fi in enumerate(fanins):
        need = {"in": 0, "inv": 1, "nand": 2}[kinds[v]]
        if len(fi) != need or any(u >= v for u in fi):
            raise ValueError("bad subject graph at node %d" % v)
    roots = tree_roots(kinds, fanins, outputs)  # @line L1

    def inner_ok(u):  # inside the current tree: a gate that is not a tree root
        return kinds[u] != "in" and u not in roots

    def leaf_cost(u):  # @line L7
        return 0 if kinds[u] == "in" or u in roots else cost[u]

    cost: list = [0] * len(kinds)
    choice: list = [None] * len(kinds)
    for v in range(len(kinds)):  # @line L2
        if kinds[v] == "in":
            continue
        best = None  # @line L3: no match yet, cost infinite
        for name, area, pat in library:  # @line L4
            for leaves in matches(kinds, fanins, pat, v, inner_ok):
                c = area + sum(leaf_cost(u) for u in leaves)  # @line L5
                if best is None or c < best[0]:  # @line L6
                    best = (c, name, leaves)
        if best is None:
            raise ValueError("the library cannot cover node %d" % v)
        cost[v], choice[v] = best[0], (best[1], best[2])

    cover: dict = {}
    todo = [v for v in outputs if kinds[v] != "in"]  # @line L8
    while todo:  # @line L9
        v = todo.pop()  # @line L10
        if v in cover:
            continue
        cover[v] = choice[v]
        todo.extend(u for u in choice[v][1] if kinds[u] != "in")
    total = sum(area for name, area, _ in library for v in cover if cover[v][0] == name)
    return total, cover  # @line L11


def evaluate_pattern(pat, values) -> int:
    """Value of a pattern; values is an iterator over its inputs, left to right."""
    if pat == "x":
        return next(values)
    if pat[0] == "inv":
        return 1 - evaluate_pattern(pat[1], values)
    a = evaluate_pattern(pat[1], values)
    b = evaluate_pattern(pat[2], values)
    return 1 - (a & b)
test_tree_covering_technology_mapping.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tree-covering-technology-mapping/. The authors are listed in prov/QGBZ88.jsonl.

import random
from itertools import combinations

from tree_covering_technology_mapping import (LIBRARY, evaluate_pattern, matches, tree_cover,
                                              tree_roots)

AREA = {name: area for name, area, _ in LIBRARY}
PAT = {name: pat for name, _, pat in LIBRARY}

# The example of the page: o = NOT(a b + c d), as NAND2 and INV.
#   0 a, 1 b, 2 c, 3 d, 4 = nand(a, b), 5 = nand(c, d), 6 = nand(4, 5), 7 = inv(6)
EX_KINDS = ["in", "in", "in", "in", "nand", "nand", "nand", "inv"]
EX_FANINS = [[], [], [], [], [0, 1], [2, 3], [4, 5], [6]]

# Sharing: n = nand(a, b) feeds o1 = inv(n) = a b and o2 = inv(nand(n, inv(c))) = NOT(a b + c).
#   0 a, 1 b, 2 c, 3 = n, 4 = o1, 5 = inv(c), 6 = nand(n, 5), 7 = o2
SH_KINDS = ["in", "in", "in", "nand", "inv", "inv", "nand", "inv"]
SH_FANINS = [[], [], [], [0, 1], [3], [2], [3, 5], [6]]


def canon_pattern(p) -> str:
    if p == "x":
        return "x"
    if p[0] == "inv":
        return "i(" + canon_pattern(p[1]) + ")"
    return "n(" + ",".join(sorted([canon_pattern(p[1]), canon_pattern(p[2])])) + ")"


CANON = {}
for _name, _area, _pat in LIBRARY:
    c = canon_pattern(_pat)
    CANON[c] = min(CANON.get(c, _area), _area)


def canon_region(kinds, fanins, v, stop) -> str:
    """Shape of the region below v, cut at the nodes of stop and at the inputs."""
    if kinds[v] == "in" or v in stop:
        return "x"
    if kinds[v] == "inv":
        return "i(" + canon_region(kinds, fanins, fanins[v][0], stop) + ")"
    a, b = fanins[v]
    return "n(" + ",".join(sorted([canon_region(kinds, fanins, a, stop),
                                   canon_region(kinds, fanins, b, stop)])) + ")"


def trees(kinds, fanins, outputs) -> dict:
    """Map each tree root to the nodes of its tree."""
    roots = tree_roots(kinds, fanins, outputs)
    out = {}
    for r in roots:
        nodes, stack = [], [r]
        while stack:
            w = stack.pop()
            nodes.append(w)
            stack.extend(u for u in fanins[w] if kinds[u] != "in" and u not in roots)
        out[r] = nodes
    return out


def brute_tree_area(kinds, fanins, outputs) -> int:
    """Try every set of gate roots inside every tree; each region must be a whole gate."""
    roots = tree_roots(kinds, fanins, outputs)
    total = 0
    for r, nodes in trees(kinds, fanins, outputs).items():
        inner = [w for w in nodes if w != r]
        best = None
        for size in range(len(inner) + 1):
            for pick in combinations(inner, size):
                s = set(pick) | {r}
                stop = s | roots
                cost = 0
                for g in s:
                    shape = canon_region(kinds, fanins, g, stop - {g})
                    if shape not in CANON:
                        break
                    cost += CANON[shape]
                else:
                    best = cost if best is None else min(best, cost)
        total += best
    return total


def brute_dag_area(kinds, fanins, outputs) -> int:
    """Least area over every DAG cover: gates may span multiple fanout points."""
    gates = [v for v in range(len(kinds)) if kinds[v] != "in"]
    every = lambda u: kinds[u] != "in"  # noqa: E731
    opts = {v: [(area, set(lv)) for name, area, pat in LIBRARY
                for lv in matches(kinds, fanins, pat, v, every)] for v in gates}
    must = {o for o in outputs if kinds[o] != "in"}
    rest = [v for v in gates if v not in must]
    best = None
    for size in range(len(rest) + 1):
        for pick in combinations(rest, size):
            s = must | set(pick)
            cost = 0
            for v in s:
                ok = [a for a, lv in opts[v] if all(kinds[u] == "in" or u in s for u in lv)]
                if not ok:
                    break
                cost += min(ok)
            else:
                best = cost if best is None else min(best, cost)
    return best


def simulate(kinds, fanins, m, n_in) -> list:
    val = []
    for v, k in enumerate(kinds):
        if k == "in":
            val.append((m >> (n_in - 1 - v)) & 1)
        elif k == "inv":
            val.append(1 - val[fanins[v][0]])
        else:
            val.append(1 - (val[fanins[v][0]] & val[fanins[v][1]]))
    return val


def check_cover(kinds, fanins, outputs, cover) -> None:
    n_in = kinds.count("in")
    for m in range(1 << n_in):
        val = simulate(kinds, fanins, m, n_in)
        got = {v: val[v] for v in range(len(kinds)) if kinds[v] == "in"}

        def get(v):
            if v not in got:
                name, leaves = cover[v]
                got[v] = evaluate_pattern(PAT[name], iter([get(u) for u in leaves]))
            return got[v]

        for o in outputs:
            assert get(o) == val[o]


def random_subject(rng, n_in, n_gates, window):
    kinds, fanins = ["in"] * n_in, [[] for _ in range(n_in)]
    for v in range(n_in, n_in + n_gates):
        lo = max(0, v - window)
        if rng.random() < 0.35:
            kinds.append("inv")
            fanins.append([rng.randrange(lo, v)])
        else:
            kinds.append("nand")
            fanins.append(sorted(rng.sample(range(lo, v), 2)) if v - lo >= 2 else [0, 0])
    outs = sorted(set([len(kinds) - 1, rng.randrange(n_in, len(kinds))]))
    return kinds, fanins, outs


def test_example() -> None:
    area, cover = tree_cover(EX_KINDS, EX_FANINS, [7])
    assert area == 5 and cover == {7: ("AOI22", [0, 1, 2, 3])}
    # without AOI22 and NAND4 the best cover is AOI21 over a NAND2
    small = [g for g in LIBRARY if g[0] not in ("AOI22", "NAND4")]
    area, cover = tree_cover(EX_KINDS, EX_FANINS, [7], small)
    assert area == 10 and cover[7] == ("AND2", [4, 5])
    assert brute_tree_area(EX_KINDS, EX_FANINS, [7]) == 5


def test_sharing_loses_against_dag_cover() -> None:
    outs = [4, 7]
    area, cover = tree_cover(SH_KINDS, SH_FANINS, outs)
    # NAND2 for n, INV for o1, INV for c and AND2 for o2: 3 + 2 + 2 + 4
    assert area == 11 and set(cover) == {3, 4, 5, 7}
    assert brute_tree_area(SH_KINDS, SH_FANINS, outs) == 11
    # AND2(a, b) and AOI21(a, b, c), with nand(a, b) built twice: 4 + 4
    assert brute_dag_area(SH_KINDS, SH_FANINS, outs) == 8
    check_cover(SH_KINDS, SH_FANINS, outs, cover)


def test_against_exhaustive_tree_covers() -> None:
    rng = random.Random(21)
    done = 0
    while done < 300:
        kinds, fanins, outs = random_subject(rng, rng.randint(1, 5), rng.randint(1, 18), 6)
        if max(len(t) for t in trees(kinds, fanins, outs).values()) > 14:
            continue
        area, cover = tree_cover(kinds, fanins, outs)
        assert area == brute_tree_area(kinds, fanins, outs)
        check_cover(kinds, fanins, outs, cover)
        done += 1


def test_tree_cover_is_a_dag_cover() -> None:
    rng = random.Random(22)
    strict = 0
    for _ in range(150):
        kinds, fanins, outs = random_subject(rng, rng.randint(2, 4), rng.randint(2, 11), 4)
        area, _ = tree_cover(kinds, fanins, outs)
        dag = brute_dag_area(kinds, fanins, outs)
        assert dag <= area
        strict += dag < area
    assert strict > 0


def test_rejects_bad_graph() -> None:
    try:
        tree_cover(["in", "nand"], [[], [0]], [1])
    except ValueError:
        return
    raise AssertionError("a NAND with one fanin must be rejected")

History

Code generators of the 1970s and 1980s already selected machine instructions for expression trees by tree pattern matching and dynamic programming, after Aho and Johnson (1976). In 1987 Keutzer presented DAGON at the Design Automation Conference. It wrote the circuit and the library in the same base gates, cut the circuit into trees, and covered each tree with the methods of code generation, so that the cover of each tree is optimal. In the same year, Detjens, Gannot, Rudell, Sangiovanni-Vincentelli and Wang described the mapper of MIS, which used the same idea with inverter pairs and later with delay costs. Tree covering stayed the standard way to map into cell libraries for many years, and the cut-based mappers that came later still use its dynamic program.

References

  1. DAGON: technology binding and local optimization by DAG matching, Proceedings of the 24th ACM/IEEE Design Automation Conference (1987), pages 341 to 347; the partition into trees, the tree matching and the dynamic programming
  2. Synthesis and Optimization of Digital Circuits, chapter 10, library binding, tree covering (general locator, not checked)

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
  • at least three sources
  • a scene preset for the example