Algorithmcore
Cycle-based simulation
Also called cycle simulation.
Simulates a synchronous design one clock cycle at a time, evaluating the logic between registers once per cycle in levelized order, with no timing inside the cycle.
- Solves
- Logic simulation
- Time
- O(N + P + T (G + P)) worst · best
- Space
- O(N + P) extra
- Where
- G = the number of gates; N = the number of nets; P = the number of gate input pins; T = the number of clock cycles
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
Cycle-based simulation runs a synchronous design one clock cycle at a time. The registers cut every loop, so the logic between them has no loops and can be put in levelized order once. In each cycle the simulator evaluates every gate once, in that order, from the primary inputs of the cycle and the register values, and then all registers take the values at their data inputs together, as at a clock edge. This page is in the logic simulation half of logic and circuit simulation. The delay model is zero delay inside the cycle: the clock edge is the only time, and nothing is computed about when a signal settles. That is enough when static timing analysis has already shown that every path meets the setup constraint, and it lets the simulator drop the event queue and run the logic as compiled code.
In plain words
In a synchronous design all registers change at the clock edge. Between two edges the gates do their work, and if the design is timed right, every signal has its final value before the next edge.
So the simulator does not track time inside the cycle. For each cycle it sets the inputs, runs through the gates once in an order where each gate comes after the gates it reads, and copies the new values into the registers. One cycle costs one evaluation per gate, whatever the delays are.
What it cannot show is anything that happens between the edges: glitches, races, or a path that is too slow.
The problem
The input is a synchronous design with one clock: primary inputs, D flip-flops with an output , a data input and an initial value, gates, and a list of primary outputs. Every loop of gates must pass through a register. The design is a Mealy machine: the state is the vector of register values, and for an input vector the logic gives the next state , the values of the , and the outputs . Given and inputs , the output is for each cycle , where .
The algorithm
CYCLE-SIM(design, s0, x_1, ..., x_T)- 1
cut every register r: q_r becomes an input of the logic L and d_r an output of L - 2
levelize the gates of L by Kahn's algorithm; stop with "loop" if a loop of gates is not cut by a register - 3
s ← s0 - 4
for k = 1 to T do - 5
evaluate every gate of L once, in level order, on the inputs x_k and the register values s - 6
record the values of the primary outputs for cycle k - 7
s ← the values of d_r for all registers r, all at once - 8
return the recorded outputs and s
Line L7 must take all new register values from the values computed in L5 before it writes any of them. Writing the registers one by one, so that a later register reads the new value of an earlier one, is the classic bug of a shift register simulated in the wrong order.
Line L5 can be the bit-parallel program of compiled-code simulation. Then each lane of a word runs its own copy of the design, for example with a different random seed of the test bench.
Example
A serial adder adds two numbers given least significant bit first. It has inputs and , one register for the carry, initial value 0, and the gates , , , and , which is the data input of . Add and , so and in cycles 1 to 5.
| cycle | ||||||||
|---|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0 |
| 2 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 |
| 3 | 1 | 1 | 1 | 0 | 1 | 1 | 0 | 1 |
| 4 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
The sum bits are , which is . Each cycle evaluates five gates in the order (level 1), (level 2) and (level 3), so 25 gate evaluations for the whole run.
The tests also show what the method gives up. In a design where , the logic has depth 3. A unit-delay simulation with a clock period of 4 time units samples settled values and agrees with the cycle-based run. With a period of 2 it samples values that have not settled, and the two runs differ. The cycle-based run cannot see this setup violation.
Correctness
The proof in proofs/correctness.md shows two things. First, line L5 computes and exactly, by the argument of compiled-code simulation on the loop-free logic, so by induction on the run gives the outputs and states of the Mealy machine. Second, it relates the result to timed behavior: if every gate has delay 1 and the clock period is larger than the depth of the logic, a net of level has its final value from time units after the edge, so the values sampled just before the next edge are the values of the cycle-based run. The tests check the first claim against an explicit next-state table built by direct evaluation of every pair of state and input, and the second against a unit-delay step simulation with period , on random designs.
Proof: Cycle-based simulation computes the Mealy machine of the design, and agrees with unit-delay timing when the period exceeds the depthfull
Let the design have primary inputs, registers with outputs , data inputs and initial values, and gates. After the cut of line L1, the logic has inputs (the primary inputs) and (the register outputs), and every loop of gates of the design passes through a register, so has no loop. For values of the registers and of the inputs, every net of has a unique value , defined by induction on the level. Put and for the primary outputs . Lines L1 to L8 refer to the pseudocode of the page.
Theorem 1 (the Mealy machine). For inputs , let . In cycle , line L6 records , and after line L7 of cycle , .
Proof. Line L2 succeeds, since has no loop (Kahn's algorithm levelizes every loop-free netlist; see the proof of compiled-code simulation). By induction on : before cycle , (true for by L3). Line L5 evaluates the gates in an order where every gate follows the drivers of its inputs, so by induction along the order, every net gets the value . Line L6 records . Line L7 reads all values before it writes any register, so .
Timed model. Give every gate delay 1, and let the clock have period . In cycle the primary inputs hold and the registers hold during the time steps . A gate output at step is the gate function of the values at step ; before the first step the gate outputs have arbitrary values. At the end of cycle the registers take , the values of the at step , and the outputs are sampled at the same step. Let be the depth of , the largest level of a net.
Theorem 2 (agreement with timing). If , then for every , and the outputs sampled at step are .
Proof. Induction on , with . In cycle , the inputs and registers are and at all steps of the cycle. Claim: a net of level has the value at every step with . For the net is an input or a register output, constant over the cycle. For a gate output of level and a step , its value is the gate function of the values at step , where every input of the gate, of level at most , already has its final value by induction. So the gate output has the value . Since , step lies in the range for every net, so the sampled outputs are and .
The bound is tight for some designs. If , a net of level whose value changes in a cycle can be sampled before it settles; the tests show a design with where gives a different run. Real delays are not unit, and the condition becomes the setup constraint of static timing analysis, with the delay of each path in place of its length.
Complexity
Levelization costs once. Each cycle evaluates each gate once and reads each input pin once, so it costs , and cycles cost . The memory is the netlist and one value per net, . With bit-parallel words of bits, independent runs cost the same as one.
An event-driven simulator of the same design spends work only on the nets that change, but pays for the queue and for every glitch inside the cycle. In designs where a large part of the logic is active in every cycle, cycle-based simulation is faster, by a factor that depends on the activity and on the glitches it avoids; this page does not measure it.
Properties
- Exact at the clock edges for designs that meet their timing, and blind between them.
- Deterministic order. Races between registers cannot appear, since all registers update together at L7. A real circuit with clock skew or a hold violation can still have such a race.
- No initialization by time. The initial state is given. With unknown initial state the values must be X, which needs multi-valued logic and brings X pessimism.
Variants and improvements
- Multiple clocks. With several clocks of fixed ratio, the simulator steps through the clock edges in time order and at each edge evaluates the logic that feeds the registers of that clock.
- Event-driven cycles. Evaluate only the cones whose inputs changed since the last cycle. This saves work when most of the design is idle, at the cost of a little bookkeeping.
- Latches. Two-phase latch designs can be simulated by evaluating the logic once per phase.
- Hardware engines and emulators. Special machines such as the Yorktown Simulation Engine run the same once-per-cycle evaluation in parallel hardware.
- Unrolling for analysis. The same cut at the registers gives the time-frame expansion used in sequential test generation and bounded model checking.
When to use it
Use cycle-based simulation for long functional runs of synchronous designs: processor regressions, software running on a hardware model, and checks where only the values at the clock edges matter. Use event-driven simulation when the design has asynchronous parts, combinational loops, latches with transparency that matters, several unrelated clocks, or when glitches and delays are the point of the run. Use static timing analysis, not simulation, to check that the cycle-based assumption holds.
Pitfalls
- Updating registers one at a time. A shift register , then shifts the input two places in one cycle. Compute all new values, then write them.
- Loops not cut by a register. A cross-coupled latch made of gates has no levelized order. The implementation rejects it.
- Assuming the timing is fine. A cycle-based run passes even when a path is longer than the clock period. The match with real timing holds only after static timing analysis.
- Gated and derived clocks. A clock that goes through logic makes registers update at times the simple model does not know. Such designs need care in the order of edges, or event-driven simulation.
- Asynchronous resets. A reset that acts without a clock edge is outside the model and must be handled as a special case.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cycle-based-simulation/. The authors are listed in prov/BBKYW7.jsonl.
"""Cycle-based simulation of a synchronous design with one clock.
The registers cut every loop. The logic between them is levelized once and
then evaluated once per clock cycle with zero delay, and all registers take
their new values together at the clock edge. There is no time inside a cycle.
"""
from __future__ import annotations
from typing import Dict, List, Sequence, Tuple
from logicnet import Circuit, eval2
class CombinationalLoop(ValueError):
"""A loop of gates that no register cuts."""
class SyncDesign:
"""inputs: primary inputs. regs: (q, d, initial value) for each D flip-flop.
gates: (out, op, ins) of the logic. outputs: nets observed each cycle.
"""
def __init__(self, inputs: Sequence[str], regs: Sequence[Tuple[str, str, int]],
gates: Sequence[Tuple[str, str, Sequence[str]]], outputs: Sequence[str]):
self.inputs = list(inputs)
self.regs = [(q, d, v) for q, d, v in regs]
# The register outputs become inputs of the logic and the D nets its outputs.
self.logic = Circuit(self.inputs + [q for q, _, _ in self.regs], gates, list(outputs) + [d for _, d, _ in self.regs]) # @line L1
self.outputs = list(outputs)
def levelize(c: Circuit) -> List[int]:
"""Kahn's algorithm on the gate graph of the logic."""
waiting = [len({n for n in ins if n in c.driver}) for _, _, ins in c.gates]
order = [i for i in range(len(c.gates)) if waiting[i] == 0]
head = 0
while head < len(order):
out = c.gates[order[head]][0]
head += 1
for h in c.fanout[out]:
waiting[h] -= 1
if waiting[h] == 0:
order.append(h)
if len(order) != len(c.gates):
raise CombinationalLoop("a loop of gates is not cut by a register")
return order
def simulate(design: SyncDesign, stimulus: Sequence[Dict[str, int]]) -> Tuple[List[Dict[str, int]], Dict[str, int]]:
"""Run one cycle per entry of stimulus. Returns the outputs of each cycle and the final state."""
c = design.logic
order = levelize(c) # @line L2
state = {q: v for q, _, v in design.regs} # @line L3
trace: List[Dict[str, int]] = []
for x in stimulus: # @line L4
val = dict(x)
val.update(state)
for g in order: # @line L5
out, op, ins = c.gates[g]
val[out] = eval2(op, [val[n] for n in ins])
trace.append({o: val[o] for o in design.outputs}) # @line L6
state = {q: val[d] for q, d, _ in design.regs} # @line L7
return trace, state # @line L8
logicnet.py 173 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate netlists and gate functions for the logic simulation pages.
A value is 0, 1 or X = 2, where X means "unknown, it can be 0 or 1".
A circuit has named primary inputs, gates (out, op, ins) and named primary
outputs. Every net is a primary input or the output of exactly one gate.
The gates may form loops, but direct_eval needs a circuit without loops.
This module holds no simulation algorithm. It gives the gate functions, the
netlist, a direct recursive evaluation that serves as the reference, random
circuits for tests and the binary completions of a three-valued vector.
"""
from __future__ import annotations
import itertools
import random
from typing import Dict, Iterator, List, Optional, Sequence, Tuple
X = 2
OPS = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF")
ONE_INPUT = ("NOT", "BUF")
def eval2(op: str, vals: Sequence[int]) -> int:
"""The gate function on values in {0, 1}."""
if op == "AND":
return int(all(vals))
if op == "OR":
return int(any(vals))
if op == "NAND":
return 1 - int(all(vals))
if op == "NOR":
return 1 - int(any(vals))
if op == "XOR":
return sum(vals) & 1
if op == "XNOR":
return 1 - (sum(vals) & 1)
if op == "NOT":
return 1 - vals[0]
if op == "BUF":
return vals[0]
raise ValueError(f"unknown gate {op}")
def not3(v: int) -> int:
return X if v == X else 1 - v
def eval3(op: str, vals: Sequence[int]) -> int:
"""Kleene's strong three-valued gate function on values in {0, 1, X}."""
if op in ("AND", "NAND"):
r = 0 if 0 in vals else (X if X in vals else 1)
return r if op == "AND" else not3(r)
if op in ("OR", "NOR"):
r = 1 if 1 in vals else (X if X in vals else 0)
return r if op == "OR" else not3(r)
if op in ("XOR", "XNOR"):
r = X if X in vals else sum(vals) & 1
return r if op == "XOR" else not3(r)
if op == "NOT":
return not3(vals[0])
if op == "BUF":
return vals[0]
raise ValueError(f"unknown gate {op}")
class Circuit:
"""A gate netlist. gates is a list of (output net, op, list of input nets)."""
def __init__(self, inputs: Sequence[str], gates: Sequence[Tuple[str, str, Sequence[str]]], outputs: Sequence[str]):
self.inputs: List[str] = list(inputs)
self.gates: List[Tuple[str, str, List[str]]] = [(out, op, list(ins)) for out, op, ins in gates]
self.outputs: List[str] = list(outputs)
self.driver: Dict[str, int] = {}
for i, (out, op, ins) in enumerate(self.gates):
if op not in OPS:
raise ValueError(f"unknown gate {op}")
if not ins or (op in ONE_INPUT and len(ins) != 1):
raise ValueError(f"gate {out} has a wrong number of inputs")
if out in self.driver or out in self.inputs:
raise ValueError(f"net {out} has two drivers")
self.driver[out] = i
self.nets: List[str] = self.inputs + [g[0] for g in self.gates]
self.fanout: Dict[str, List[int]] = {n: [] for n in self.nets}
for i, (out, op, ins) in enumerate(self.gates):
for n in ins:
if n not in self.fanout:
raise ValueError(f"net {n} has no driver")
if i not in self.fanout[n]:
self.fanout[n].append(i)
for n in self.outputs:
if n not in self.fanout:
raise ValueError(f"output {n} has no driver")
def is_acyclic(self) -> bool:
"""True when no gate depends on its own output (three-colour depth-first search)."""
colour = [0] * len(self.gates)
for root in range(len(self.gates)):
if colour[root]:
continue
colour[root] = 1
stack = [(root, iter(self.gates[root][2]))]
while stack:
g, it = stack[-1]
nxt = None
for n in it:
if n in self.driver:
nxt = self.driver[n]
break
if nxt is None:
colour[g] = 2
stack.pop()
elif colour[nxt] == 1:
return False
elif colour[nxt] == 0:
colour[nxt] = 1
stack.append((nxt, iter(self.gates[nxt][2])))
return True
def direct_eval(self, vec: Dict[str, int], three: bool = False) -> Dict[str, int]:
"""Value of every net, each computed from its definition with memoization."""
f = eval3 if three else eval2
val: Dict[str, int] = {n: vec[n] for n in self.inputs}
busy = set()
def get(n: str) -> int:
if n in val:
return val[n]
if n in busy:
raise ValueError("the circuit has a loop")
busy.add(n)
out, op, ins = self.gates[self.driver[n]]
val[n] = f(op, [get(m) for m in ins])
return val[n]
for n in self.nets:
get(n)
return val
def random_circuit(rng: random.Random, n_inputs: int, n_gates: int, n_outputs: Optional[int] = None,
loops: bool = False, ops: Sequence[str] = OPS) -> Circuit:
"""A random circuit. Without loops, gate k reads only inputs and gates 0..k-1."""
inputs = [f"i{k}" for k in range(n_inputs)]
names = [f"g{k}" for k in range(n_gates)]
gates = []
for k in range(n_gates):
op = rng.choice(ops)
pool = inputs + (names if loops else names[:k])
arity = 1 if op in ONE_INPUT else rng.randint(2, 3)
ins = rng.sample(pool, min(arity, len(pool)))
if op not in ONE_INPUT and len(ins) < 2:
op = "BUF"
gates.append((names[k], op, ins))
if n_outputs is None:
n_outputs = min(3, n_gates)
return Circuit(inputs, gates, names[n_gates - n_outputs:])
def all_vectors(names: Sequence[str]) -> Iterator[Dict[str, int]]:
"""Every assignment of 0 and 1 to the names."""
for bits in itertools.product((0, 1), repeat=len(names)):
yield dict(zip(names, bits))
def completions(vec: Dict[str, int]) -> Iterator[Dict[str, int]]:
"""Every binary vector that agrees with vec wherever vec is not X."""
free = [n for n, v in vec.items() if v == X]
for bits in itertools.product((0, 1), repeat=len(free)):
out = dict(vec)
out.update(zip(free, bits))
yield out
test_cycle_based_simulation.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cycle-based-simulation/. The authors are listed in prov/BBKYW7.jsonl.
import itertools
import random
import pytest
from cycle_based_simulation import CombinationalLoop, SyncDesign, simulate
from logicnet import eval2, random_circuit
# The page example: a serial adder with one carry register.
ADDER = SyncDesign(
["a", "b"],
[("c", "cn", 0)],
[("x1", "XOR", ["a", "b"]), ("s", "XOR", ["x1", "c"]), ("g1", "AND", ["a", "b"]),
("g2", "AND", ["x1", "c"]), ("cn", "OR", ["g1", "g2"])],
["s"],
)
def random_design(rng):
n_in, n_reg = rng.randint(1, 3), rng.randint(1, 4)
c = random_circuit(rng, n_in + n_reg, rng.randint(2, 20), n_outputs=2)
qs = c.inputs[n_in:]
regs = [(q, rng.choice([g[0] for g in c.gates] + qs), rng.randint(0, 1)) for q in qs]
return SyncDesign(c.inputs[:n_in], regs, c.gates, c.outputs)
def fsm_table(design):
"""The explicit next-state and output table, from direct evaluation of every (state, input) pair."""
qs = [q for q, _, _ in design.regs]
table = {}
for s in itertools.product((0, 1), repeat=len(qs)):
for x in itertools.product((0, 1), repeat=len(design.inputs)):
full = design.logic.direct_eval(dict(zip(qs + design.inputs, s + x)))
table[s, x] = (tuple(full[d] for _, d, _ in design.regs), {o: full[o] for o in design.outputs})
return table
def depth(c):
memo = {n: 0 for n in c.inputs}
def lev(n):
if n not in memo:
memo[n] = 1 + max(lev(m) for m in c.gates[c.driver[n]][2])
return memo[n]
return max([lev(n) for n in c.nets] + [0])
def clocked_step_reference(design, stimulus, period):
"""Unit delay per gate. Inputs change at the clock edge; registers sample the D nets just before the next edge."""
c = design.logic
state = {q: v for q, _, v in design.regs}
prev = {n: 0 for n in c.nets}
prev.update(state)
trace = []
for x in stimulus:
for _ in range(period):
cur = dict(x)
cur.update(state)
for out, op, ins in c.gates:
cur[out] = eval2(op, [prev[n] for n in ins])
prev = cur
trace.append({o: prev[o] for o in design.outputs})
state = {q: prev[d] for q, d, _ in design.regs}
return trace, state
def test_serial_adder():
a, b = [0, 1, 1, 0, 0], [1, 1, 1, 0, 0] # 6 and 7, least significant bit first
trace, state = simulate(ADDER, [{"a": p, "b": q} for p, q in zip(a, b)])
assert [t["s"] for t in trace] == [1, 0, 1, 1, 0] # 13
assert state == {"c": 0}
@pytest.mark.parametrize("seed", range(15))
def test_matches_explicit_fsm_table(seed):
rng = random.Random(seed)
d = random_design(rng)
table = fsm_table(d)
stim = [{n: rng.randint(0, 1) for n in d.inputs} for _ in range(60)]
trace, state = simulate(d, stim)
s = tuple(v for _, _, v in d.regs)
for x, out in zip(stim, trace):
s, want = table[s, tuple(x[n] for n in d.inputs)]
assert out == want
assert tuple(state[q] for q, _, _ in d.regs) == s
@pytest.mark.parametrize("seed", range(15))
def test_matches_unit_delay_reference_when_the_period_exceeds_the_depth(seed):
rng = random.Random(100 + seed)
d = random_design(rng)
stim = [{n: rng.randint(0, 1) for n in d.inputs} for _ in range(30)]
period = depth(d.logic) + 1
assert clocked_step_reference(d, stim, period) == simulate(d, stim)
def test_short_period_breaks_the_match():
# q' = NOT(NOT(NOT(q))) has depth 3, so a period of 2 samples a value that has not settled.
d = SyncDesign([], [("q", "n3", 0)], [("n1", "NOT", ["q"]), ("n2", "NOT", ["n1"]), ("n3", "NOT", ["n2"])], ["q"])
stim = [{}] * 8
assert clocked_step_reference(d, stim, 4) == simulate(d, stim)
assert clocked_step_reference(d, stim, 2) != simulate(d, stim)
def test_loop_not_cut_by_a_register_is_rejected():
d = SyncDesign(["s", "r"], [], [("q", "NOR", ["r", "qn"]), ("qn", "NOR", ["s", "q"])], ["q"])
with pytest.raises(CombinationalLoop):
simulate(d, [{"s": 0, "r": 0}])
History
Cycle simulation grew with design styles that make every loop pass through a register. IBM's level-sensitive scan design rules (scan design) are one such style, and IBM built engines on this assumption: the Yorktown Simulation Engine (Pfister, 1982) evaluated the whole logic once per machine cycle in special hardware, and HSS (Barzilai, Carter, Rosen and Rutledge, 1987) ran the loop-free logic between latches as compiled code on 16 or 32 patterns at a time. Cycle-based software simulators and hardware emulators then became the usual tools for long functional runs of large synchronous designs, next to event-driven simulators of VHDL and Verilog.
References
- Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter Logic Simulation (compiled simulation of synchronous circuits, levelization, and the comparison with event-driven simulation)
- Zeev Barzilai, J. Lawrence Carter, Barry K. Rosen and Joseph D. Rutledge, HSS, a high-speed simulator, IEEE Transactions on Computer-Aided Design 6(4), 601 to 617, 1987, the simulation of the cycle-free logic between latches as compiled code, once per clock
- G. F. Pfister, The Yorktown Simulation Engine, introduction, Proceedings of the 19th Design Automation Conference, 51 to 54, 1982, a hardware engine that evaluates the whole logic of a synchronous design once per machine cycle from a fixed program
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BBKYW7 Edit this page History Report an error Markdown