Algorithm Search⌘K

Algorithmcore

Static timing analysis

Also called STA, block-based timing analysis.

Computes arrival times by a forward pass and required times by a backward pass over the timing graph in topological order, in linear time with no input vectors.

Time
Θ(V + E) worst · average · best
Space
Θ(V) extra
Where
E = the number of edges (cell arcs and net arcs); V = the number of vertices (pins) of the timing graph
Properties
deterministicexactiterative
Origin
Robert B. Hitchcock, Gordon L. Smith, David D. Cheng, 1982

Static timing analysis (STA) checks that every path of a digital circuit is fast enough, and that no path is too fast, without simulating any input vectors. It works on the timing graph, a DAG with a vertex per pin and a delay per edge. One forward pass in topological order computes the latest arrival time at each pin, one backward pass computes the required time, and their difference is the slack, all in Θ(V+E)\Theta(V + E) time. The result is exact for the graph, but it ignores the logic of the gates, so it is pessimistic when the longest path can never be excited (a false path).

In plain words

Think of each pin as a place, and each wire or gate as a road that takes a known time. The inputs start at known times. Visit the pins so that each pin comes after all pins that feed it. At each pin, write down the latest time a signal can get there: the largest "time at the pin before it plus the time of the road". This is the arrival time.

Then go backward from the outputs, which have deadlines. At each pin, write down the latest time a signal may be there and still reach every output on time. This is the required time.

The required time minus the arrival time is the slack. A negative slack means a signal can be late. The pins with the least slack form the critical path, the one to fix first.

The problem

The input is a timing graph G=(V,E)G = (V, E) that is a directed acyclic graph, a delay d(e)d(e) for each edge, an arrival time AT0(s)AT_0(s) for each start point ss (a vertex with no in-edge) and a required time RT0(t)RT_0(t) for each endpoint tt (a vertex with no out-edge). The output is, for each vertex vv, the arrival time AT(v)AT(v), the required time RT(v)RT(v) and the slack RT(v)−AT(v)RT(v) - AT(v) as defined on arrival time and required time:

AT(v)=max⁡P:s⇝v(AT0(s)+d(P)),RT(v)=min⁡P:v⇝t(RT0(t)−d(P)).AT(v) = \max_{P : s \leadsto v} \big(AT_0(s) + d(P)\big), \qquad RT(v) = \min_{P : v \leadsto t} \big(RT_0(t) - d(P)\big).

This is the longest path problem on a DAG, with many sources and given offsets, solved forward from the start points and backward from the endpoints. Each pass is the DAG longest path algorithm. In the early mode, used for the hold check, max and min swap places and the delays are the minimum delays.

The algorithm

  1. STATIC-TIMING-ANALYSIS(G, d, AT0, RT0)
  2. 1order ← a topological order of G (stop with an error if G has a cycle)
  3. 2for each vertex v in order do
  4. 3if v has no in-edge then AT(v) ← AT0(v)
  5. 4else AT(v) ← max over edges (u, v) of AT(u) + d(u, v)
  6. 5for each vertex u in the reverse of order do
  7. 6if u has no out-edge then RT(u) ← RT0(u)
  8. 7else RT(u) ← min over edges (u, v) of RT(v) − d(u, v)
  9. 8for each vertex v do slack(v) ← RT(v) − AT(v)
  10. 9return AT, RT, slack

Line L1 can use Kahn's algorithm or a depth-first search. In line L4 every predecessor uu comes before vv in the order, so AT(u)AT(u) is already known, and in line L7 every successor vv comes after uu, so it has been visited first in the reverse order. The early mode takes the minimum in line L4, the maximum in line L7, and AT(v)−RT(v)AT(v) - RT(v) in line L8.

To report a critical path, start at an endpoint of least slack and walk back along an in-edge (u,v)(u, v) with AT(u)+d(u,v)=AT(v)AT(u) + d(u, v) = AT(v) until a start point is reached. Every vertex on this path has the least slack.

Example

Take the three-gate circuit of the timing graph page: inputs a,b,ca, b, c with AT0=0,1,0AT_0 = 0, 1, 0, gates G1(a,b)G1(a, b), G2(b,c)G2(b, c), G3(G1,G2)G3(G1, G2) and the output yy with RT0(y)=9RT_0(y) = 9. The net arcs have delay 1, except b→G2/Ab \to G2/A with delay 2, and the cell arcs have delays G1G1: A→YA \to Y 3, B→YB \to Y 1; G2G2: A→YA \to Y 2, B→YB \to Y 3; G3G3: A→YA \to Y 2, B→YB \to Y 3.

The forward pass, in the order a,b,c,G1/A,G1/B,G2/A,G2/B,G1/Y,G2/Y,G3/A,G3/B,G3/Y,ya, b, c, G1/A, G1/B, G2/A, G2/B, G1/Y, G2/Y, G3/A, G3/B, G3/Y, y:

vertex line computation ATAT
aa, bb, cc L3 given 0, 1, 0
G1/AG1/A, G1/BG1/B L4 0+10 + 1, 1+11 + 1 1, 2
G2/AG2/A, G2/BG2/B L4 1+21 + 2, 0+10 + 1 3, 1
G1/YG1/Y L4 max⁡(1+3,2+1)\max(1 + 3, 2 + 1) 4
G2/YG2/Y L4 max⁡(3+2,1+3)\max(3 + 2, 1 + 3) 5
G3/AG3/A, G3/BG3/B L4 4+14 + 1, 5+15 + 1 5, 6
G3/YG3/Y L4 max⁡(5+2,6+3)\max(5 + 2, 6 + 3) 9
yy L4 9+19 + 1 10

The backward pass gives RT(y)=9RT(y) = 9, RT(G3/Y)=8RT(G3/Y) = 8, RT(G3/A)=6RT(G3/A) = 6, RT(G3/B)=5RT(G3/B) = 5, RT(G1/Y)=5RT(G1/Y) = 5, RT(G2/Y)=4RT(G2/Y) = 4, RT(G1/A)=2RT(G1/A) = 2, RT(G1/B)=4RT(G1/B) = 4, RT(G2/A)=2RT(G2/A) = 2, RT(G2/B)=1RT(G2/B) = 1, RT(a)=1RT(a) = 1, RT(c)=0RT(c) = 0 and RT(b)=min⁡(4−1,2−2)=0RT(b) = \min(4 - 1, 2 - 2) = 0. The slacks are −1-1 on b,G2/A,G2/Y,G3/B,G3/Y,yb, G2/A, G2/Y, G3/B, G3/Y, y, 0 on cc and G2/BG2/B, 1 on a,G1/A,G1/Y,G3/Aa, G1/A, G1/Y, G3/A, and 2 on G1/BG1/B. The output is one unit late. The backtrace from yy follows G3/BG3/B (since 6+3=96 + 3 = 9), G2/YG2/Y, G2/AG2/A (since 3+2=53 + 2 = 5) and bb, which is the critical path b→G2/A→G2/Y→G3/B→G3/Y→yb \to G2/A \to G2/Y \to G3/B \to G3/Y \to y with delay 9 and path slack 9−1−9=−19 - 1 - 9 = -1.

In early mode with RT0e(y)=4RT_0^{e}(y) = 4, the forward pass with minima gives ATe(y)=7AT^{e}(y) = 7, by the path b→G1/B→G1/Y→G3/A→G3/Y→yb \to G1/B \to G1/Y \to G3/A \to G3/Y \to y, and the early slack 7−4=37 - 4 = 3.

Correctness

The proof shows the following, by induction along the topological order.

  • Arrival times. After line L4 for vv, AT(v)AT(v) is the largest value of AT0(s)+d(P)AT_0(s) + d(P) over all paths PP from a start point ss to vv.
  • Required times. After line L7 for uu, RT(u)RT(u) is the smallest value of RT0(t)−d(P)RT_0(t) - d(P) over all paths PP from uu to an endpoint tt.
  • Slack. slack(v)\mathrm{slack}(v) is the least path slack RT0(t)−AT0(s)−d(P)RT_0(t) - AT_0(s) - d(P) over all start-to-end paths through vv, so the least vertex slack is the least slack over all paths.
  • Critical path. The backtrace always finds an in-edge that sets the arrival time, and it returns a start-to-end path whose slack is the least slack.

The proof uses no sign condition on the delays. Negative delays, which appear in some models of cell arcs, are allowed.

Proof: Static timing analysis computes the longest-path arrival times, the shortest-slack required times and the least path slack of every vertex in linear timefull

Let G=(V,E)G = (V, E) be a finite directed graph with a delay d(e)d(e) in an ordered abelian group (integers, rationals or reals) on each edge. Parallel edges are allowed. A start point is a vertex with no in-edge and an endpoint is a vertex with no out-edge. Each start point ss has a value AT0(s)AT_0(s) and each endpoint tt a value RT0(t)RT_0(t). For a path PP, d(P)d(P) is the sum of the delays of its edges; a path with one vertex has d(P)=0d(P) = 0. Define

A(v)=max⁡{AT0(s)+d(P):P a path from a start point s to v},A(v) = \max \{ AT_0(s) + d(P) : P \text{ a path from a start point } s \text{ to } v \},
R(v)=min⁡{RT0(t)−d(P):P a path from v to an endpoint t}.R(v) = \min \{ RT_0(t) - d(P) : P \text{ a path from } v \text{ to an endpoint } t \}.

Lemma 1 (the sets are finite and not empty). If GG is acyclic, then every vertex is reached from some start point and reaches some endpoint, and there are finitely many paths. So A(v)A(v) and R(v)R(v) are well defined.

Proof. A path in an acyclic graph repeats no vertex, so it has at most ∣V∣|V| vertices, and there are finitely many paths. From vv, follow in-edges backward as long as possible. No vertex repeats, so the walk stops after fewer than ∣V∣|V| steps, at a vertex with no in-edge. Reversed, the walk is a path from a start point to vv. The same argument with out-edges gives a path from vv to an endpoint. □\square

Lemma 2 (line L1). Line L1 succeeds if and only if GG is acyclic. If it succeeds, every edge (u,v)(u, v) has uu before vv in the order.

Proof. This is the correctness of topological sorting: a topological order exists if and only if the graph has no directed cycle, and Kahn's algorithm outputs all vertices exactly when the graph is acyclic. □\square

From now on GG is acyclic and the order of line L1 is fixed.

Lemma 3 (forward pass). When lines L2 to L4 finish, AT(v)=A(v)AT(v) = A(v) for every vertex vv.

Proof. By induction along the order. Let vv be the next vertex, and assume AT(u)=A(u)AT(u) = A(u) for all vertices before vv.

If vv has no in-edge, the only path that ends at vv and starts at a start point is the path with the single vertex vv, since a longer path would enter vv by an edge. So A(v)=AT0(v)A(v) = AT_0(v), which line L3 assigns.

Otherwise, every path PP from a start point ss to vv has at least one edge, because vv is not a start point. Let (u,v)(u, v) be its last edge and P′P' the rest, a path from ss to uu. Then AT0(s)+d(P)=AT0(s)+d(P′)+d(u,v)≤A(u)+d(u,v)AT_0(s) + d(P) = AT_0(s) + d(P') + d(u, v) \le A(u) + d(u, v). Conversely, for each in-edge (u,v)(u, v) and each path P′P' from a start point to uu, the path P′P' followed by (u,v)(u, v) ends at vv, since GG is acyclic and vv is not on P′P' (otherwise vv would come before uu in the order). Hence

A(v)=max⁡(u,v)∈E(A(u)+d(u,v)).A(v) = \max_{(u, v) \in E} \big( A(u) + d(u, v) \big).

All such uu come before vv by Lemma 2, so AT(u)=A(u)AT(u) = A(u), and line L4 assigns exactly this value. □\square

Lemma 4 (backward pass). When lines L5 to L7 finish, RT(u)=R(u)RT(u) = R(u) for every vertex uu.

Proof. The same induction along the reverse order. An endpoint has only the one-vertex path to an endpoint, so R(t)=RT0(t)R(t) = RT_0(t) (line L6). For any other uu, splitting each path from uu at its first edge (u,v)(u, v) gives R(u)=min⁡(u,v)∈E(R(v)−d(u,v))R(u) = \min_{(u, v) \in E} (R(v) - d(u, v)), and every such vv comes after uu in the order, so it was handled before uu in the reverse order. Line L7 assigns this value. □\square

Theorem 1 (slack). For every vertex vv,

RT(v)−AT(v)=min⁡{RT0(t)−AT0(s)−d(P):P a path from a start point s to an endpoint t through v}.RT(v) - AT(v) = \min \{ RT_0(t) - AT_0(s) - d(P) : P \text{ a path from a start point } s \text{ to an endpoint } t \text{ through } v \}.

In particular min⁡vslack(v)\min_v \mathrm{slack}(v) is the least slack of a start-to-end path.

Proof. A start-to-end path PP through vv splits at vv into a path P1P_1 from ss to vv and a path P2P_2 from vv to tt, with d(P)=d(P1)+d(P2)d(P) = d(P_1) + d(P_2). Conversely, any such P1P_1 and P2P_2 join into a path, because GG is acyclic: a vertex on both would close a cycle through vv. So the set of start-to-end paths through vv is the set of pairs (P1,P2)(P_1, P_2), with no constraint between the two parts. Hence

min⁡P∋v(RT0(t)−d(P2)−(AT0(s)+d(P1)))=min⁡P2(RT0(t)−d(P2))−max⁡P1(AT0(s)+d(P1))=R(v)−A(v),\min_{P \ni v} \big( RT_0(t) - d(P_2) - (AT_0(s) + d(P_1)) \big) = \min_{P_2} \big( RT_0(t) - d(P_2) \big) - \max_{P_1} \big( AT_0(s) + d(P_1) \big) = R(v) - A(v),

which is RT(v)−AT(v)RT(v) - AT(v) by Lemmas 3 and 4. Every start-to-end path passes through some vertex, so the least vertex slack is the least path slack. □\square

Theorem 2 (critical path). Let tt be an endpoint of least slack. The backtrace from tt always finds an in-edge (u,v)(u, v) with AT(u)+d(u,v)=AT(v)AT(u) + d(u, v) = AT(v) while vv is not a start point, and it ends at a start point ss after at most ∣V∣−1|V| - 1 steps. The path PP it returns has slack(P)=min⁡wslack(w)\mathrm{slack}(P) = \min_w \mathrm{slack}(w), and every vertex of PP has this slack.

Proof. By Lemma 3 the maximum in line L4 is attained by some in-edge, so the step is always possible. Each step moves to a vertex earlier in the order, so the walk ends, at a vertex with no in-edge. Adding the equalities along the path gives AT(t)=AT0(s)+d(P)AT(t) = AT_0(s) + d(P), so slack(P)=RT0(t)−AT(t)=slack(t)\mathrm{slack}(P) = RT_0(t) - AT(t) = \mathrm{slack}(t), since RT(t)=RT0(t)RT(t) = RT_0(t). Let m=min⁡wslack(w)m = \min_w \mathrm{slack}(w). By Theorem 1, mm is the least path slack, and some path ends at an endpoint whose slack is mm, so slack(t)=m\mathrm{slack}(t) = m. For a vertex ww of PP, Theorem 1 gives slack(w)≤slack(P)=m\mathrm{slack}(w) \le \mathrm{slack}(P) = m, and slack(w)≥m\mathrm{slack}(w) \ge m by the choice of mm. □\square

Theorem 3 (early mode). If line L4 takes the minimum, line L7 the maximum and line L8 computes AT(v)−RT(v)AT(v) - RT(v), then AT(v)AT(v) is the least value of AT0(s)+d(P)AT_0(s) + d(P), RT(v)RT(v) is the largest value of RT0(t)−d(P)RT_0(t) - d(P), and AT(v)−RT(v)AT(v) - RT(v) is the least value of AT0(s)+d(P)−RT0(t)AT_0(s) + d(P) - RT_0(t) over start-to-end paths through vv.

Proof. Apply Lemmas 3 and 4 and Theorem 1 to the delays −d-d, the start values −AT0-AT_0 and the end values −RT0-RT_0. Negation swaps max and min, and the slack of the negated problem is (−RT(v))−(−AT(v))=AT(v)−RT(v)(-RT(v)) - (-AT(v)) = AT(v) - RT(v). No step of the proofs used a sign condition on the delays. □\square

Theorem 4 (running time). With in-lists and out-lists, the algorithm takes Θ(V+E)\Theta(V + E) time and Θ(V)\Theta(V) extra space, counting each addition and comparison of delays as one step.

Proof. Line L1 takes Θ(V+E)\Theta(V + E) time with Kahn's algorithm. Lines L2 to L4 do O(1)O(1) work per vertex plus O(1)O(1) work per in-edge, and each edge is the in-edge of one vertex, so Θ(V+E)\Theta(V + E). The same holds for lines L5 to L7 with out-edges, and line L8 is Θ(V)\Theta(V). The arrays ATAT, RTRT, slack, the order and the in-degree counters of Kahn's algorithm take Θ(V)\Theta(V) space. Every vertex and edge must be read, so no algorithm does better than Ω(V+E)\Omega(V + E) in the worst case. ■\blacksquare

Complexity

  • Time. Line L1 takes Θ(V+E)\Theta(V + E) time. Lines L2 to L4 look at each edge once as an in-edge, and lines L5 to L7 once as an out-edge, so they take Θ(V+E)\Theta(V + E) time with unit-cost additions and comparisons. Line L8 takes Θ(V)\Theta(V). In total Θ(V+E)\Theta(V + E) in every case, which is O(P)O(P) for a netlist with PP pins.
  • Space. Three numbers per vertex and the order, so Θ(V)\Theta(V) extra space when the graph is given as in-lists and out-lists.
  • Comparison with path enumeration. The number of start-to-end paths can grow exponentially with the depth of the circuit; a chain of kk reconvergent pairs of paths has 2k2^k paths. STA finds the worst slack of all of them in linear time, because the max and the min distribute over the concatenation of path prefixes and suffixes.

Properties

  • Exact for the graph, pessimistic for the circuit. The arrival time is the largest delay of any path in the graph. If the logic of the gates makes that path impossible to excite, the real circuit is faster. STA never reports a time that is too early, so it is safe, but it can report violations that cannot happen.
  • No input vectors. STA does not depend on the values of the signals. This is the difference from timing simulation, which needs vectors and covers only the paths they excite.
  • Block-based. Each vertex keeps one arrival time per mode and transition. The cost does not depend on the number of paths. A path-based analysis keeps paths explicitly and can apply rules per path, at a higher cost.
  • Monotone. If a delay grows, no arrival time falls and no required time rises, so no slack grows. This is what makes incremental timing after a small change possible.

Variants and improvements

  • Rise and fall, and unateness. Each pin keeps a rising and a falling arrival time. A negative unate arc maps the input rising time to the output falling time, and a non-unate arc maps each input transition to both.
  • Slew propagation. With the nonlinear delay model, the delay of an arc depends on the input slew. Tools propagate the worst slew together with the latest arrival time. The two can come from different in-edges, which adds pessimism; some tools propagate several candidates.
  • Early and late, and on-chip variation. The setup check uses late data times and early capture clock times, and the hold check the opposite. Derating factors scale the delays of each mode to model variation across the chip.
  • Common path pessimism removal. The launch and capture clock paths often share a part of the clock tree. Using a late delay on that part for one and an early delay for the other is impossible in reality, and CPPR adds the difference back to the slack.
  • Exceptions. Designers declare false paths and multicycle paths in the constraints file (for example the SDC commands set_false_path and set_multicycle_path). The tool then removes or relaxes those paths, which needs some path tracking.
  • Path enumeration. To report the kk worst paths, the tool runs a k shortest paths style search on the DAG with the slacks as guides.
  • Incremental timing. After a change, only the forward cone of the change needs new arrival times and only the backward cone new required times. Timing-driven optimizers call this many times.
  • Statistical timing. Statistical static timing analysis replaces the numbers by random variables and the max by an approximate statistical max.

When to use it

  • To sign off that a synchronous design meets its clock period and hold constraints, for every input. This is the standard method for digital chips.
  • Inside optimization loops such as gate sizing, buffer insertion and timing-driven placement, where slacks must be recomputed after each change.
  • When the circuit has no combinational loops and its timing is given by delays per arc. For a circuit with loops, latches with time borrowing, or analog behavior, other methods are needed.

Pitfalls

  • Late arrival for the hold check. The hold check must use the earliest arrival. Using the late times hides every hold violation; see setup and hold constraints.
  • Combinational loops. A cycle in the timing graph has no topological order. The tool must cut the loop at some arc, and the result depends on the cut.
  • Reading slack as path slack. The slack at a vertex is the least slack of all paths through it, not the slack of one particular path.
  • False violations. A negative slack on a false path is not a real violation. Declaring it a false path without proof is also a mistake, because then a real path may go unchecked.
  • Clock pessimism. Without CPPR, the shared part of the clock tree counts twice and the slack is too small.

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.

static_timing_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/static-timing-analysis/. The authors are listed in prov/84BFXG.jsonl.

from collections import deque
from typing import Mapping, Optional, Sequence


def topological_order(n: int, edges: Sequence[tuple[int, int, object]]) -> list[int]:
    """Kahn's algorithm. Raises ValueError if the graph has a cycle."""
    indeg = [0] * n
    out: list[list[int]] = [[] for _ in range(n)]
    for u, v, _ in edges:
        out[u].append(v)
        indeg[v] += 1
    queue = deque(v for v in range(n) if indeg[v] == 0)
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in out[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    if len(order) != n:
        raise ValueError("the timing graph has a cycle")
    return order


def static_timing_analysis(
    n: int,
    edges: Sequence[tuple[int, int, object]],
    at_start: Mapping[int, object],
    rt_end: Mapping[int, object],
    early: bool = False,
):
    """Block-based static timing analysis on a timing DAG.

    The vertices are 0 .. n-1. Each edge is (u, v, d) with delay d (int or
    Fraction). at_start gives the arrival time of every vertex with no in-edge
    (a start point), and rt_end the required time of every vertex with no
    out-edge (an endpoint).

    Late mode (early=False, the setup check):
        AT(v) = max over edges (u, v) of AT(u) + d,
        RT(u) = min over edges (u, v) of RT(v) - d,
        slack(v) = RT(v) - AT(v).
    Early mode (early=True, the hold check) swaps max and min, and
        slack(v) = AT(v) - RT(v).
    A negative slack is a violation in both modes.

    Returns (AT, RT, slack) as lists. Raises ValueError on a cycle or a
    missing start or end time. Time and extra space: O(V + E).
    """
    pick_at = min if early else max
    pick_rt = max if early else min
    ins: list[list[tuple[int, object]]] = [[] for _ in range(n)]
    outs: list[list[tuple[int, object]]] = [[] for _ in range(n)]
    for u, v, d in edges:
        ins[v].append((u, d))
        outs[u].append((v, d))
    order = topological_order(n, edges)  # @line L1
    at: list[Optional[object]] = [None] * n
    for v in order:  # @line L2
        if not ins[v]:  # @line L3
            if v not in at_start:
                raise ValueError(f"start point {v} has no arrival time")
            at[v] = at_start[v]
        else:
            at[v] = pick_at(at[u] + d for u, d in ins[v])  # @line L4
    rt: list[Optional[object]] = [None] * n
    for u in reversed(order):  # @line L5
        if not outs[u]:  # @line L6
            if u not in rt_end:
                raise ValueError(f"endpoint {u} has no required time")
            rt[u] = rt_end[u]
        else:
            rt[u] = pick_rt(rt[v] - d for v, d in outs[u])  # @line L7
    if early:  # @line L8
        slack = [at[v] - rt[v] for v in range(n)]
    else:
        slack = [rt[v] - at[v] for v in range(n)]
    return at, rt, slack  # @line L9


def critical_path(
    n: int,
    edges: Sequence[tuple[int, int, object]],
    at: Sequence[object],
    slack: Sequence[object],
    early: bool = False,
) -> list[int]:
    """A path of least slack, from a start point to an endpoint.

    Start at an endpoint of least slack and walk back along in-edges whose
    delay sets the arrival time (AT(u) + d == AT(v)).
    """
    ins: list[list[tuple[int, object]]] = [[] for _ in range(n)]
    outdeg = [0] * n
    for u, v, d in edges:
        ins[v].append((u, d))
        outdeg[u] += 1
    ends = [v for v in range(n) if outdeg[v] == 0]
    v = min(ends, key=lambda x: slack[x])
    path = [v]
    while ins[v]:
        v = next(u for u, d in ins[v] if at[u] + d == at[v])
        path.append(v)
    path.reverse()
    return path
test_static_timing_analysis.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/static-timing-analysis/. The authors are listed in prov/84BFXG.jsonl.

import random
from fractions import Fraction

import pytest

from static_timing_analysis import critical_path, static_timing_analysis

# The circuit of the page: three gates, a pin-level timing graph.
NAMES = ["a", "b", "c", "G1/A", "G1/B", "G1/Y", "G2/A", "G2/B", "G2/Y", "G3/A", "G3/B", "G3/Y", "y"]
IDX = {s: i for i, s in enumerate(NAMES)}
EXAMPLE_ARCS = [
    ("a", "G1/A", 1), ("b", "G1/B", 1), ("b", "G2/A", 2), ("c", "G2/B", 1),
    ("G1/A", "G1/Y", 3), ("G1/B", "G1/Y", 1), ("G2/A", "G2/Y", 2), ("G2/B", "G2/Y", 3),
    ("G1/Y", "G3/A", 1), ("G2/Y", "G3/B", 1), ("G3/A", "G3/Y", 2), ("G3/B", "G3/Y", 3),
    ("G3/Y", "y", 1),
]
EXAMPLE_EDGES = [(IDX[u], IDX[v], d) for u, v, d in EXAMPLE_ARCS]


def brute(n, edges, at_start, rt_end, early):
    """AT, RT and slack of every vertex from the list of all start-to-end paths."""
    pick_at = min if early else max
    pick_rt = max if early else min
    at, rt, slack = [None] * n, [None] * n, [None] * n
    for verts, edge_delays in paths_with_edges(n, edges):
        s, t = verts[0], verts[-1]
        prefix = [0]
        for d in edge_delays:
            prefix.append(prefix[-1] + d)
        total = prefix[-1]
        path_slack = (at_start[s] + total - rt_end[t]) if early else (rt_end[t] - at_start[s] - total)
        for i, v in enumerate(verts):
            a = at_start[s] + prefix[i]
            r = rt_end[t] - (total - prefix[i])
            at[v] = a if at[v] is None else pick_at(at[v], a)
            rt[v] = r if rt[v] is None else pick_rt(rt[v], r)
            slack[v] = path_slack if slack[v] is None else min(slack[v], path_slack)
    return at, rt, slack


def paths_with_edges(n, edges):
    """Every start-to-end path, as (vertices, delays of its edges); parallel edges give separate paths."""
    outs = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v, d in edges:
        outs[u].append((v, d))
        indeg[v] += 1
    result = []

    def walk(v, verts, ds):
        if not outs[v]:
            result.append((verts, ds))
            return
        for w, d in outs[v]:
            walk(w, verts + [w], ds + [d])

    for s in range(n):
        if indeg[s] == 0:
            walk(s, [s], [])
    return result


def random_dag(rng, n, p, frac):
    perm = list(range(n))
    rng.shuffle(perm)
    edges = []
    for i in range(n):
        for j in range(i + 1, n):
            if rng.random() < p:
                k = 2 if rng.random() < 0.1 else 1
                for _ in range(k):
                    if frac:
                        d = Fraction(rng.randint(-3, 12), rng.randint(1, 4))
                    else:
                        d = rng.randint(0, 9)
                    edges.append((perm[i], perm[j], d))
    rng.shuffle(edges)
    return edges


def times(rng, n, edges, frac):
    indeg = [0] * n
    outdeg = [0] * n
    for u, v, _ in edges:
        outdeg[u] += 1
        indeg[v] += 1
    val = (lambda: Fraction(rng.randint(-4, 8), rng.randint(1, 3))) if frac else (lambda: rng.randint(0, 5))
    at0 = {v: val() for v in range(n) if indeg[v] == 0}
    rt0 = {v: val() + 20 for v in range(n) if outdeg[v] == 0}
    return at0, rt0


def test_example_of_the_page():
    at, rt, slack = static_timing_analysis(13, EXAMPLE_EDGES, {IDX["a"]: 0, IDX["b"]: 1, IDX["c"]: 0}, {IDX["y"]: 9})
    assert [at[IDX[s]] for s in NAMES] == [0, 1, 0, 1, 2, 4, 3, 1, 5, 5, 6, 9, 10]
    assert [rt[IDX[s]] for s in NAMES] == [1, 0, 0, 2, 4, 5, 2, 1, 4, 6, 5, 8, 9]
    assert [slack[IDX[s]] for s in NAMES] == [1, -1, 0, 1, 2, 1, -1, 0, -1, 1, -1, -1, -1]
    path = critical_path(13, EXAMPLE_EDGES, at, slack)
    assert [NAMES[v] for v in path] == ["b", "G2/A", "G2/Y", "G3/B", "G3/Y", "y"]


def test_example_early_mode():
    # hold-style required time 4 at y: the shortest path must take at least 4
    at, rt, slack = static_timing_analysis(13, EXAMPLE_EDGES, {IDX["a"]: 0, IDX["b"]: 1, IDX["c"]: 0}, {IDX["y"]: 4}, early=True)
    assert at[IDX["y"]] == 7
    assert slack[IDX["y"]] == 3


@pytest.mark.parametrize("frac", [False, True])
@pytest.mark.parametrize("early", [False, True])
def test_against_path_enumeration(frac, early):
    rng = random.Random(2026 + 2 * frac + early)
    for _ in range(300):
        n = rng.randint(1, 8)
        edges = random_dag(rng, n, rng.choice([0.2, 0.4, 0.6]), frac)
        at0, rt0 = times(rng, n, edges, frac)
        at, rt, slack = static_timing_analysis(n, edges, at0, rt0, early)
        assert (at, rt, slack) == brute(n, edges, at0, rt0, early)
        path = critical_path(n, edges, at, slack, early)
        assert slack[path[-1]] == min(slack)
        assert all(slack[v] == min(slack) for v in path)


def test_worst_slack_is_worst_path_slack():
    rng = random.Random(7)
    for _ in range(200):
        n = rng.randint(2, 8)
        edges = random_dag(rng, n, 0.5, False)
        at0, rt0 = times(rng, n, edges, False)
        _, _, slack = static_timing_analysis(n, edges, at0, rt0)
        worst = min(rt0[p[-1]] - at0[p[0]] - sum(ds) for p, ds in paths_with_edges(n, edges))
        assert min(slack) == worst


def test_cycle_and_missing_times():
    with pytest.raises(ValueError):
        static_timing_analysis(2, [(0, 1, 1), (1, 0, 1)], {}, {})
    with pytest.raises(ValueError):
        static_timing_analysis(2, [(0, 1, 1)], {}, {1: 5})
    with pytest.raises(ValueError):
        static_timing_analysis(2, [(0, 1, 1)], {0: 0}, {})

History

Timing analysis by longest path began with the PERT method of project planning. Kirkpatrick and Clark (1966) at IBM applied PERT to logic design. Robert Hitchcock, Gordon Smith and David Cheng described the IBM Timing Analysis program in 1982, in the IBM Journal of Research and Development, and Hitchcock gave an account of it at the 19th Design Automation Conference the same year. TA analyzed the circuit block by block, computed arrival times, required times and slacks with no simulation, and found almost all timing problems of the IBM 3081 before hardware debugging. Since then block-based STA has been the sign-off method of digital design, extended with slews, on-chip variation, CPPR and statistical timing. Research on false paths in the late 1980s, such as the work of Du, Yen and Ghanta (1989) and of McGeer and Brayton (1989), addressed the pessimism of the purely structural analysis.

References

  1. Robert B. Hitchcock, Gordon L. Smith and David D. Cheng, Timing analysis of computer hardware, IBM Journal of Research and Development 26(1), 100 to 105, 1982, the block-oriented analysis, the arrival times, required times and slacks, and the use on the IBM 3081
  2. Robert B. Hitchcock, Timing verification and the timing analysis program, Proceedings of the 19th Design Automation Conference, 594 to 604, 1982, the TA program, the slack report and the comparison of block-oriented and path-oriented analysis
  3. T. I. Kirkpatrick and N. R. Clark, PERT as an aid to logic design, IBM Journal of Research and Development 10(2), 135 to 141, 1966, the use of PERT longest path computations on logic networks
  4. J. Bhasker and Rakesh Chadha, Static Timing Analysis for Nanometer Designs, A Practical Approach, Springer, 2009, Chapter 2, STA Concepts, Chapter 8, Timing Verification, and Chapter 10, Robust Verification (common path pessimism and on-chip variation)
  5. Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, Springer, 1st edition, 2011, Chapter 8, Timing Closure, Section 8.2.1, Static Timing Analysis

Where this leads

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.average
  • 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
  • a scene preset for the example