The idea: code that tests a circuit

Before a design goes to an FPGA or a chip, you run it in a simulator (Icarus Verilog, Verilator, ModelSim, Vivado's xsim). The design does nothing by itself: something must make a clock, set the inputs and look at the outputs. That something is a testbench, a second Verilog module with no ports. It holds the design under test (DUT) as an instance and drives its wires.

A testbench is never synthesized. It can use things no hardware has: delays like #12, initial blocks, printing, and a $finish that stops time. The page runs one small testbench for a 4-bit counter, one event at a time. Each step lights up the lines that run, moves the time cursor, grows the waveform and prints what the simulator would print.

The testbench module counter_tb contains a clock generator (always #5 clk = ~clk), a stimulus initial block, the DUT counter, a golden model and a checker. clk goes to the DUT, the golden model and the checker; reset and en go to the DUT and the golden model; count from the DUT and expected from the golden model go into the checker, which prints PASS or FAIL to the console
The testbench wraps the DUT: it makes the clock and the inputs, and a golden model plus a checker decide PASS or FAIL.

The parts of this testbench

  • The DUT: counter dut(.clk, .reset, .en, .count); creates one counter. .clk is short for .clk(clk). The counter itself is the one from From Verilog to Hardware: always_ff with a synchronous reset and an enable.
  • The clock: always #5 clk = ~clk; waits 5 ns, flips clk, and repeats forever. With clk = 0 at the start, the rising edges are at 5, 15, 25 … ns and the period is 10 ns.
  • The stimulus: the initial block runs once from time 0. #12 means "wait 12 ns from now", so its lines run at 0, 12, 42, 62 and 132 ns.
  • The golden model: one line that computes what count should be, expected <= reset ? 0 : expected + en. It is written differently from the DUT on purpose, so a mistake in one is unlikely to be in the other.
  • The checker: at every falling edge, check(expected) compares count with expected, counts the checks and the errors, and prints a FAIL line when they differ.

Simulation time is a list of events

The simulator does not tick through every nanosecond. It keeps a list of events: things scheduled for a time. It jumps to the earliest one, runs everything that wakes up at that time, and jumps again. Here the times are 0, 5, 10, 12, 15, 20, 25 … 130, 132. Next Event on the page does exactly one such jump. `timescale 1ns/1ns says that #1 is 1 ns and times are printed in whole nanoseconds.

Inside one time step there is an order. Blocks woken by the event run first; a nonblocking <= only schedules its new value, which lands after all of them have read the old values; $monitor prints last, at the end of the step. (Demo: time 0 to 15 ns, one event at a time.) At 0 ns count is x, unknown. The reset is synchronous, so it only acts at the rising edge at 5 ns, and only then does count become 0.

Drive and check away from the clock edge

The DUT changes at rising edges. If the testbench changed en at exactly 15 ns, the result would depend on which block the simulator happened to run first: a race. So this testbench changes its inputs at 12, 42 and 62 ns, between edges, and it checks at the falling edges, half a period after the DUT updated. Each value it drives is steady at the next rising edge, and each value it reads has settled.

One clock cycle from 10 to 30 ns: en is set to 1 at 12 ns between edges, the DUT and the golden model update at the rising edge at 15 ns (count 0 to 1, expected 0 to 1), the checker compares at the falling edge at 20 ns and passes, the next rising edge is at 25 ns
Inputs change between edges, the DUT moves at the rising edge, the check runs at the falling edge: nothing happens at the same instant.

With en = 0 from 42 to 62 ns, the edges at 45 and 55 ns leave count at 3, and the golden model agrees, because expected + en adds 0. The edge at 65 ns makes it 4. (Demo: en = 0 holds the count.)

$display, $monitor, $time, $finish

System taskWhat it doesHere
$displayprints once, when the line runsthe FAIL line in check, the summary at 132 ns
$monitorstarted once; prints a line at the end of every time step in which one of its signals changed15 lines, from 0 reset=1 en=0 count=x to 125 … count=10
$timethe current simulation time, in `timescale unitsthe first number on every line
$finishstops the simulatorat 132 ns

$monitor prints per time step, not per change. At 12 ns both reset and en change, and there is one line, 12 reset=0 en=1 count=0. It also does not print when only clk changes, because clk is not in its list, and it stays quiet from 42 to 62 ns while count holds.

$finish matters more than it looks. always #5 schedules a new clock event every 5 ns, so the event list never empties. Without $finish the run would never end. (Demo: $finish ends the run: after 132 ns, Next Event finds nothing more to do.)

A self-checking testbench

You could read 15 printed lines, or the waveform, and decide whether they look right. That does not scale to thousands of cycles, and people miss things. A self-checking testbench decides for you: it knows the expected value at each check and says PASS or FAIL. The correct counter passes all 13 checks (falling edges 10, 20 … 130) and the last lines are 132 PASS: 0 errors and $finish called at 132 (1ns). (Demo: correct counter, run to $finish.)

The check uses !==, not !=. With !=, comparing an x gives x, an if treats x as false, and a DUT stuck at x would pass every check. !== compares the four values 0, 1, x and z exactly, so x counts as wrong.

Catching the planted bug

Pick "bug: wraps at 9". Line 5 of the DUT now reads count <= (count==9) ? 0 : count+1, a decimal counter by mistake. Until 115 ns everything matches. At the rising edge at 125 ns the DUT goes 9 → 0 while the golden model goes 9 → 10. $monitor prints 125 reset=0 en=1 count=0, which looks harmless. Then the check at the falling edge at 130 ns prints 130 FAIL count=0 expected=10, and the summary says 132 FAIL: 1 errors. (Demo: planted bug, count wraps at 9; Demo: bug close-up at 125 and 130 ns.)

Waveform from 100 to 132 ns: count goes 7, 8, 9, then 0 at 125 ns, shown in red; expected goes 7, 8, 9, 10. The checks at 110 and 120 ns pass, the check at 130 ns fails and prints 130 FAIL count=0 expected=10
The wrong value appears at the edge at 125 ns; the next check, at 130 ns, catches it and prints FAIL.

This is why the stimulus must reach the corner cases. If the testbench had stopped before the count reached 10, both counters would have passed. A good test plan lists what must be exercised: reset, enable low, every value, the wrap from 15 to 0.

Running it for real

With Icarus Verilog the same two files run like this:

iverilog -g2012 -o sim counter.sv counter_tb.sv
vvp sim

Add $dumpfile("counter.vcd"); $dumpvars(0, counter_tb); at the top of the initial block to save every signal change in a VCD file, and open it in GTKWave to get the waveform the page draws.

See also From Verilog to Hardware for what synthesis builds from always_ff, enable and reset, Sequential Logic for how the counter's flip-flops work inside and why setup and hold times matter at the edge, and Finite State Machines for the next kind of design you would test this way.

See also The ASIC Design Flow, where a testbench catches a missing enable before synthesis, the cheapest place to find it.

See also An FSM in SystemVerilog for a state machine written as an enum, an always_ff register and an always_comb case, the kind of design a testbench like this one checks.

What the page leaves out

The page runs one fixed testbench with a hand-written event model of it; it does not parse Verilog. Icarus Verilog was not available while the page was built, so the console lines come from a separate small simulation that follows the standard's scheduling rules and Icarus's print formats. Left out: the full scheduling regions (inactive, #0, observed, reactive), $strobe, file I/O, random stimulus ($urandom), SystemVerilog classes, clocking blocks, assertions and coverage, UVM, gate-level simulation with delays, and writing FSMs in Verilog.

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OLogic gatesLogic gatestruth table row picks the outputAdders, muxes, ALUAdders, muxes, ALUcritical path sets the delayMux, decoder, encoderMux, decoder, encoderSelect bits pick one input; decoder one lineBubble pushingBubble pushingDe Morgan: AND-OR becomes NAND-NANDAlgebraic factoringAlgebraic factoringShare kernels: 17 → 9 literalsTechnology mappingTechnology mappingCheapest pattern per node, reused upwardFast arithmeticFast arithmeticlookahead carry beats ripple carryBCD and Gray CodesBCD and Gray CodesBCD adder: sum > 9 or carry → add 6Multiply/divide hardwareMultiply/divide hardwareadd or subtract, then shift, once per bitVerilog to hardwareVerilog to hardwareassign gives gates, always_ff gives flopsVerilog testbenchGolden model + check task say PASS/FAILASIC design flowASIC design flowRTL→netlist→DEF→GDSII; slack shrinksPlace and RoutePlace and RouteAnneal by HPWL, then Lee wave routesOpen the Computer Architecture mind mapComputer Architectureoutput depends only on inputsCombinational logicLogic gatesLogic gatestruth table row picks the outputAdders, muxes, ALUAdders, muxes, ALUcritical path sets the delayMux, decoder, encoderMux, decoder, encoderSelect bits pick one input; decoder one lineBubble pushingBubble pushingDe Morgan: AND-OR becomes NAND-NANDAlgebraic factoringAlgebraic factoringShare kernels: 17 → 9 literalsTechnology mappingTechnology mappingCheapest pattern per node, reused upwardFast arithmeticFast arithmeticlookahead carry beats ripple carryBCD and Gray CodesBCD and Gray CodesBCD adder: sum > 9 or carry → add 6Multiply/divide hardwareMultiply/divide hardwareadd or subtract, then shift, once per bitVerilog to hardwareVerilog to hardwareassign gives gates, always_ff gives flopsVerilog testbenchGolden model + check task say PASS/FAILASIC design flowASIC design flowRTL→netlist→DEF→GDSII; slack shrinksPlace and RoutePlace and RouteAnneal by HPWL, then Lee wave routes
This page on the Computer Architecture mind map · 76 pages in 7 branches · open it to see the whole map and test yourself in recall mode.