The Complete Guide to HDL Simulation With Icarus, Verilator and GTKWave
Simulate Verilog and VHDL with Icarus Verilog, Verilator, GHDL and cocotb, view waveforms in GTKWave, write self-checking tests and choose the right tool.

Simulation is how hardware designers find out what their code does before it costs anything to be wrong. You describe a circuit in a hardware description language, a program called a simulator reads that description and pretends to be the circuit, you feed it inputs over simulated time, and you look at what comes out. The difference from software testing is that the code under test is not a program that runs; it is a description of wires and registers that a simulator must interpret or compile. This guide covers the free tools that make that practical: Icarus Verilog 12.0 and Verilator 5.032 for Verilog and SystemVerilog, GHDL 5.0 for VHDL, cocotb 1.9 for writing tests in Python, and GTKWave 3.3 for looking at the waveforms they produce. It starts from an empty directory and ends with formal proofs and firmware running on a simulated CPU, and it assumes only that you can use a terminal and have read a few lines of Verilog. Each section links to a focused post when you want the long version.
Here is the short version. Use Icarus Verilog for small designs and quick checks, because it compiles in an instant and models unknown values as real hardware languages define them. Use Verilator when a design is large, a run is long or you want a C++ or Python testbench, because it translates the design to native code. Use GHDL for VHDL. Dump waveforms to a VCD or FST file and open them in GTKWave. Make every testbench decide for itself whether the design passed, so a script can run it. Everything else in this guide is detail on those five sentences.
What a simulator actually does
Hardware is parallel. Every flip-flop in a chip looks at its inputs at the same instant, and every gate reacts continuously. A program is sequential, so a simulator has to fake that parallelism, and it does so with a model of time. Simulated time is a number the simulator owns. It advances only when nothing else can happen at the current instant.
An event-driven simulator keeps a queue of changes. When a signal changes, every piece of logic that reads it is put on the queue. The simulator runs those, which may change more signals, which schedule more logic, until the queue is empty, and only then moves time to the next scheduled change. That is how Icarus Verilog and GHDL work, and it gives faithful behaviour for delays, unknown values and ordering rules.
A cycle-based simulator makes a stronger assumption: the design is synchronous, so what matters is the state after each clock edge. It works out the order of all the logic once, when it compiles, and then evaluates the whole design in one pass per clock. That is how Verilator works, and it is why it is fast. The cost is that it models signals as plain bits, with no unknown or high-impedance values.
Three words appear in every simulation and are worth fixing now. The design under test, often written DUT, is the module you are checking. The testbench is code that wraps it: it creates the clock, applies reset, drives inputs and checks outputs, and it never becomes hardware. The waveform is the recorded history of signal values against time, which is what you open in a viewer when something goes wrong.
Choose your tools
Five tools cover almost every need on a laptop, and they fit together.
| Tool | What it is | Use it for |
|---|---|---|
Icarus Verilog (iverilog, vvp) | event-driven Verilog and partial SystemVerilog simulator | small designs, learning, netlists, x checking |
| Verilator | translates Verilog and SystemVerilog to C++ | big designs, long runs, lint, C++ and Python testbenches |
| GHDL | VHDL compiler and simulator | any VHDL design |
| cocotb | Python framework that drives a simulator | tests with data structures, random stimulus, reuse of Python code |
| GTKWave | waveform viewer | reading VCD, FST and GHW files |
You will probably end with two simulators, because they answer different questions. A good default for a beginner is Icarus Verilog for the first weeks and Verilator once a design is big enough that waiting for it becomes annoying. Install them from your platform's package manager: the Linux distributions package all five, and on macOS Homebrew has them. Check the versions with iverilog -V, verilator --version, ghdl --version and gtkwave --version, and write the versions in your project's README, because a flag that exists in one release may behave differently in another.
Your first simulation
Make a directory and put a design in it. This is a four-bit counter with a synchronous reset: on every rising clock edge it adds one, unless reset is high, in which case it goes back to zero.
module counter (
input wire clk,
input wire rst,
output reg [3:0] count
);
always @(posedge clk) begin
if (rst)
count <= 4'd0;
else
count <= count + 4'd1;
end
endmoduleThe testbench has no ports. It makes a clock, holds reset for a moment, lets the counter run and writes the waveform file:
`timescale 1ns/1ps
module counter_tb;
reg clk = 1'b0;
reg rst = 1'b1;
wire [3:0] count;
counter dut (.clk(clk), .rst(rst), .count(count));
always #5 clk = ~clk;
initial begin
$dumpfile("counter.vcd");
$dumpvars(0, counter_tb);
#22 rst = 1'b0;
#200 $finish;
end
endmoduleThe pieces to notice are always #5 clk = ~clk;, which flips the clock every five nanoseconds so the period is ten, the initial block that runs once from time zero, and the two $dump calls that tell the simulator to record signals. Compile and run:
iverilog -g2012 -o counter_sim counter.v counter_tb.v
vvp counter_sim
gtkwave counter.vcdVCD info: dumpfile counter.vcd opened for output.iverilog compiles to an intermediate file and vvp executes it. GTKWave opens with a tree of modules on the left; expand counter_tb, select clk, rst and count, and add them to the waveform pane. You should see count hold zero until reset is released at 22 ns, then step 1, 2, 3 on each rising edge starting at 25 ns, reach 15 at 165 ns and wrap to 0 at 175 ns. If your waveform matches that, your toolchain works. The long version of this walkthrough, with the Makefile and the reason the first edge after reset is the one at 25 ns, is the post on simulating a Verilog module with Icarus Verilog and viewing it in GTKWave.
Writing a testbench that talks back
Waveforms are for debugging. For everything else, the testbench should speak up. A testbench in plain Verilog can print what it sees with $display, trace changes with $monitor and check results with if. The first rule is to let the design settle before you look at it, which means waiting a short delay after changing inputs:
`timescale 1ns/1ps
module adder_tb;
reg [3:0] a;
reg [3:0] b;
wire [4:0] sum;
integer errors;
adder dut (.a(a), .b(b), .sum(sum));
task check(input [3:0] ta, input [3:0] tb, input [4:0] expected);
begin
a = ta;
b = tb;
#1;
if (sum !== expected) begin
$display("FAIL: %0d + %0d = %0d, expected %0d", ta, tb, sum, expected);
errors = errors + 1;
end
end
endtask
initial begin
errors = 0;
check(4'd0, 4'd0, 5'd0);
check(4'd3, 4'd4, 5'd7);
check(4'd15, 4'd15, 5'd30);
if (errors == 0) $display("PASS");
else $display("FAIL: %0d errors", errors);
$finish;
end
endmodulePASSThree habits are visible there and matter for everything that follows. The comparison uses !==, the case-inequality operator, so an unknown x in sum counts as a mismatch instead of silently passing. The checking is in a task, so each test is one line. And the testbench ends by printing a single PASS or FAIL line, which is what a script can look for. The post on writing a Verilog testbench with initial blocks and $display covers the format specifiers, $monitor, and a loop that tests all 256 input combinations of this adder.
Recording waveforms on purpose
$dumpfile names the output and $dumpvars starts recording. Their arguments are worth understanding, because dumping everything on a big design makes a file nobody can open. $dumpvars(0, top) records every level of hierarchy under top. $dumpvars(1, top) records only the signals declared directly in top. A hierarchical name selects one signal: $dumpvars(0, top.dut.count). Four companion tasks, $dumpoff, $dumpon, $dumpall and $dumpflush, let you record only the interesting window of a long run and protect the buffer when a run might crash.
A Value Change Dump is a text file. It starts with a header naming each signal, assigning it a short code and recording the width, and continues with time stamps followed by value changes. Only changes are written, so a quiet signal costs nothing. For big designs, Icarus can write the compressed FST format instead if you run vvp counter_sim -fst, and GTKWave opens either one. The post on dumping waveforms with $dumpfile and $dumpvars shows what a VCD looks like byte by byte and how to diagnose a dump that opens but shows no changes.
Getting the most out of GTKWave
GTKWave is a viewer with a few features worth learning in the first hour. Right-click a signal to change how it is shown: binary, decimal, hexadecimal or signed. Drag signals into the order you want and use blank dividers to group them. Place a marker by middle-clicking, and read the time difference to the cursor in the toolbar, which is how you measure a latency in cycles. Use Zoom Fit to see the whole run and the zoom to selection to examine a single edge. Save your arrangement with File, Write Save File, and reopen it with gtkwave counter.vcd counter.gtkw so you do not rebuild the signal list every session. Red lines in a waveform are unknown values, and they are the first thing to look for: an x after reset means a register nothing initialises.
Testbenches that check themselves
A testbench that prints values for you to read does not survive past a few dozen vectors. The standard upgrade is a reference model: an independent description of what the design should do, written as a function, against which every output is compared. The model must be independent of the design, written from the specification and in a different style, or a misunderstanding appears in both and the bug passes.
function [8:0] ref_alu(input [1:0] op, input [7:0] a, input [7:0] b);
integer r;
begin
case (op)
2'd0: r = a + b;
2'd1: r = a - b;
2'd2: r = a & b;
default: r = a ^ b;
endcase
ref_alu = r[8:0];
end
endfunctionThat function checks an eight-bit ALU that produces a nine-bit result with a carry or borrow in the top bit. The model computes in 32-bit integers, so overflow is not something it can get wrong, and the borrow behaviour falls out of the arithmetic. Pair it with two kinds of stimulus: a list of directed corner cases, zero, one, the sign boundary and all ones, because bugs live at boundaries, and a loop of seeded random vectors, which cover the middle and repeat exactly because the seed is fixed. End with one verdict line and a watchdog so a hung design fails instead of waiting forever. Finally, break the design on purpose once and confirm the testbench goes red; a check that has never failed has never been proven to work. The post on self-checking testbenches with reference models builds this whole ALU testbench and shows the failure output.
Verilator, the compiled simulator
Verilator takes your Verilog and writes C++ for it. The compiler turns that into an executable, and your testbench is a C++ program that creates the model, toggles its clock and reads its outputs. For a four-bit counter that sounds like a lot of ceremony, and it is, but the payoff comes with a design that simulates for millions of cycles.
verilator --cc --exe --build --trace -Wall \
--top-module counter counter.v tb_counter.cpp
./obj_dir/VcounterThe generated class is named V plus the top module's name, ports are member variables, and the one method that matters is eval(), which computes the design's response to the current inputs. The mistake everyone makes once is to change clk and forget to call eval(), after which nothing reacts and the waveform is flat. The structure of a complete C++ testbench, including the Verilator 5 VerilatedContext and the trace object, is in the post on building a C++ testbench for a Verilog module with Verilator.
Verilator also ships a linter. verilator --lint-only -Wall design.v parses and checks without compiling anything, in about a second, and reports width mismatches, unused signals, incomplete case statements, inferred latches and undriven outputs. Make it the first command in your test target. It finds the class of bugs that otherwise show up as a mysterious x an hour into debugging. The post on linting Verilog with verilator --lint-only shows each common warning, how to waive one in a .vlt file with a reason, and how to keep the count at zero.
Two things to know about Verilator that surprise newcomers. It models only two values, so uninitialised registers start at zero instead of x, and a missing reset can pass quietly where Icarus would show it. Run with +verilator+rand+reset+2 to start registers at random values and expose designs that depend on a lucky zero. And it can run an ordinary Verilog testbench, with delays and $display, if you use --binary --timing, which is a good way to move an existing Icarus testbench over without writing C++.
Testing in Python with cocotb
When test logic gets complicated, Verilog is a hard language to write it in. cocotb leaves the design in Verilog or VHDL and moves the testbench into Python. Tests are async functions. Each await hands control to the simulator until a condition is true, for example await RisingEdge(dut.clk), so simulated time passes only where you wait.
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import ReadOnly, RisingEdge
@cocotb.test()
async def counts_up_and_wraps(dut):
cocotb.start_soon(Clock(dut.clk, 10, units="ns").start())
dut.rst.value = 1
for _ in range(2):
await RisingEdge(dut.clk)
dut.rst.value = 0
for expected in range(1, 20):
await RisingEdge(dut.clk)
await ReadOnly()
assert int(dut.count.value) == expected % 16ReadOnly() waits until the time step has settled so you read the new value, not the one from before the edge. A Makefile that sets TOPLEVEL, MODULE, VERILOG_SOURCES and includes Makefile.sim runs it on Icarus by default or on Verilator with SIM=verilator. Python gives you random, files, classes and every library on PyPI, so a reference model can be NumPy or a protocol parser. The cost is speed, since every signal access crosses between Python and the simulator. The full tutorial, with timeouts and a scoreboard, is the post on testing HDL designs in Python with cocotb.
VHDL with GHDL
VHDL has its own free simulator, and it is stricter about workflow than the Verilog tools because the language defines the workflow: analyse each file into a library, elaborate a top-level unit into an executable, then run it. GHDL exposes the three steps as three commands. Files must be analysed in dependency order, so the design comes before the testbench that instantiates it.
ghdl -a --std=08 counter.vhd counter_tb.vhd
ghdl -e --std=08 counter_tb
ghdl -r --std=08 counter_tb --stop-time=200ns --vcd=counter.vcdcounter_tb.vhd:26:5:@106ns:(report note): PASS: count is 9 at 106 ns
simulation stopped by --stop-time @200nsThe options after the entity name belong to the simulation run. --stop-time is needed when the clock is a concurrent assignment that never ends, --vcd or --wave writes the waveform, and --assert-level=error makes a failing assertion return a non-zero exit code, which scripts need. The post on simulating VHDL from the command line with GHDL has the counter and testbench in VHDL-2008, the ghdl -i and ghdl -m shortcut for large projects and the errors you will see: a unit not found because the analysis order was wrong, metavalue warnings from the numeric packages at time zero, and a process with no wait that loops forever in zero time.
Simulating after synthesis
Everything so far simulates the source you wrote. A synthesis tool turns that source into a different design, a netlist of gates and flip-flops, and the two should behave identically. Occasionally they do not: a combinational case with a missing branch becomes a latch, a register without a reset starts as something unexpected, a race that the simulator resolved one way is resolved differently by the tool. Gate-level simulation runs the netlist through the same testbench to find out. With Yosys, the open-source synthesis tool, and Icarus, the flow is two commands and a comparison testbench:
yosys -q -p "read_verilog counter.v; synth -top counter; rename counter counter_gl; write_verilog -noattr counter_gl.v"
iverilog -g2012 -o gl_sim counter.v counter_gl.v compare_tb.v
vvp gl_simPASS: gate level matches RTL for 32 cyclesThe rename gives the netlist's top module a different name so both versions can live in one simulation, and the testbench drives them with the same inputs and compares their outputs on every clock with !==. For a netlist mapped to a specific FPGA family you add that family's simulation models, such as cells_sim.v for iCE40. This is a functional check only: it has no delays, so timing belongs to place and route. The post on running gate-level simulation of a Yosys netlist shows how to inject a fault into the netlist to prove the comparison can fail, and what each kind of mismatch usually means.
Time inside a time step
Two events can happen at the same simulated time and still be ordered, and that order is behind most of the bugs that only appear on one simulator. Verilog divides each time step into regions that run in a fixed sequence. Ordinary assignments and process bodies run in the Active region. Nonblocking assignments evaluate their right-hand sides there but apply their updates later, in the NBA region, after every active process of the time step has run. $strobe and $monitor report at the very end, in the Postponed region. VHDL has the same idea under another name: signal assignments take effect after all ready processes have run, and each round of that is a delta cycle that consumes no simulated time.
The practical rules are short. Use nonblocking assignments for registers and blocking assignments for combinational logic inside a process, which is what makes parallel flip-flops see old values. Never build a clock out of an assignment: a copy of a clock made with <= arrives a region late, and registers on the copy capture new values where registers on the original capture old ones. Do not change testbench inputs on the exact clock edge, because whether the design sees the old or the new value depends on which active process the simulator happens to run first. Drive on the falling edge instead.
always @(negedge clk) begin
a <= next_a;
b <= next_b;
endBecause stimulus changes half a cycle before the next rising edge, the design sees stable inputs at every active edge, whatever order the simulator chose. The post on delta cycles and scheduling regions has a program that prints a value in the Active, Inactive and Postponed regions of one time step, with the output, and walks through the derived-clock race.
Testing a design at more than one size
Real designs are parameterised: a counter has a width, a FIFO has a depth. A testbench that checks only the default width proves nothing about the others, and the bugs that live in parameters, such as a wrap computed with the wrong constant, only appear at a different size. Verilog lets the testbench override a parameter on the instance, so one file can test several configurations:
module counter_n #(
parameter WIDTH = 4
) (
input wire clk,
input wire rst,
output reg [WIDTH-1:0] count
);
always @(posedge clk) begin
if (rst)
count <= {WIDTH{1'b0}};
else
count <= count + 1'b1;
end
endmoduleA testbench module can itself take a parameter and be instantiated several times from a top-level wrapper, or you can compile it repeatedly with a command-line override. Icarus accepts a define or a parameter override at compile time:
iverilog -g2012 -P counter_n_tb.WIDTH=3 -o sim3 counter_n.v counter_n_tb.v
iverilog -g2012 -P counter_n_tb.WIDTH=8 -o sim8 counter_n.v counter_n_tb.v
vvp sim3
vvp sim8PASS: width 3 wrapped at 8
PASS: width 8 wrapped at 256The -P option sets a top-level parameter of the named module, so the testbench passes WIDTH down to the instance and computes the expected wrap value as 1 << WIDTH. Verilator has the same control as -GWIDTH=8. Test the smallest legal width and a width that is not a power of two as well as the default, because off-by-one mistakes in width arithmetic cluster at the extremes. A generate loop in the testbench can instantiate the design at many widths in one run when the compile time matters more than the separation.
The same discipline applies to anything with a depth, a count or a timeout. If the design has a parameter, the test suite should run it at least at its minimum, its default and a value with no special factors, and the log should say which it ran.
Which simulator for which job
The choice is not a matter of taste, so decide with a table:
| You need | Reach for |
|---|---|
| a quick check of a small module | Icarus Verilog |
| to see unknown values on missing resets | Icarus Verilog |
| delays inside the design or on a netlist | Icarus Verilog or GHDL |
| a long run, a CPU core, a big design | Verilator |
| a C++ reference model or a C++ driver | Verilator |
| strong lint in one second | verilator --lint-only |
| VHDL | GHDL |
| Python tests | cocotb on Icarus or Verilator |
| a formal proof | SymbiYosys |
The common professional pattern uses several. Quick tests run on Icarus or Verilator's binary mode, long system runs on Verilator, a short gate-level pass runs before release, and the lint runs on every commit. The post comparing Icarus Verilog and Verilator goes further, with one program that prints xxxx on one and 0000 on the other, and explains what that difference means for a missing reset. The single most useful trick is to run your own tests on both: a design that passes on one and fails on the other has a race, an uninitialised register or a missing reset, and finding it now is cheaper than finding it on a board.
Making a long run fast
A simulation that takes ten minutes gets run once a day; one that takes ten seconds gets run after every change. Verilator gives you levers, and the rule is to measure before you pull any. Run the same executable with tracing off and on, and time both. If the traced run is far slower, the waveform is your cost. Switch to the FST format with --trace-fst, which is binary and compressed, lower the trace depth, and dump only the window of cycles you care about:
const bool in_window = ctx->time() >= 2000000 && ctx->time() < 2002000;
if (trace && in_window) tfp.dump(ctx->time());If the traced and untraced runs are close, the model is the cost. Raise the optimisation with -O3, --x-assign fast and -CFLAGS "-O2", and try --threads N only when the design is large enough to give each thread real work, since the synchronisation between threads makes small designs slower. verilator_gantt shows where threads wait. The post on speeding up Verilator with multithreading and FST traces uses a design of sixty-four registers to show every step with a decision table, and gives no timings because they depend on your machine.
Proving instead of testing
A simulation covers the inputs you thought of. A formal tool covers all of them, up to a bound or for all time. SymbiYosys takes assertions written in the RTL and either proves them or returns the shortest trace that breaks one. A lock register that must never change after its lock bit is set is a good first property:
always_ff @(posedge clk) begin
if (f_past_valid && !$past(rst) && $past(locked)) begin
assert (locked);
assert (secret == $past(secret));
end
endA .sby file with bmc, prove and cover tasks runs bounded model checking, k-induction and reachability checks. A passing proof ends with DONE (PASS, rc=0), and a failing one writes a waveform of the counterexample that you open in GTKWave and read as the exact steps of the bug. Two cautions apply. A proof is only as good as its properties, and an over-constrained assume makes a proof vacuous, so pair every assertion with a cover that shows the interesting state is reachable. And formal fits crisp properties on blocks of modest size: locks, handshakes, FIFO full and empty rules. It does not replace simulation of whole systems. The post on proving design properties in SymbiYosys builds the lock register, shows a back-door bug found by the solver and explains each task.
Running firmware on simulated hardware
When the design is a processor, the most valuable test is the real program. Co-simulation runs a firmware binary on the CPU's RTL, with memory and a UART modelled in the C++ harness. A small core such as PicoRV32 needs a harness of about eighty lines: clock the core, watch its memory handshake, serve reads and writes from an array, treat a write to one address as a character to print and a write to another as the end of the run.
Hello from RV32I
sum 1..10 = 55
firmware exited with code 0The compiler flags must match the core, so build with -march=rv32i -mabi=ilp32 for a core that implements only the base integer instructions, and link -lgcc if the program needs division. When the program fails, the trap output and the address of the last instruction fetch point at the faulting instruction in the disassembly. That is the same loop you would use with a debugger on a board, available months before the board exists. The post on co-simulating firmware and RTL walks through every file. The larger version of the idea, a Linux kernel on a soft RISC-V core generated by LiteX and running on an FPGA, is covered in the post on running Linux on a VexRiscv SoC.
A debugging session from symptom to cause
Take a bug that every beginner writes. A module counts pulses on an input and is meant to report the total. The author forgets that a register needs a starting value:
module pulse_count (
input wire clk,
input wire pulse,
output reg [3:0] total
);
always @(posedge clk) begin
if (pulse)
total <= total + 4'd1;
end
endmoduleThe testbench sends three pulses and prints the total:
`timescale 1ns/1ps
module pulse_count_tb;
reg clk = 1'b0;
reg pulse = 1'b0;
wire [3:0] total;
pulse_count dut (.clk(clk), .pulse(pulse), .total(total));
always #5 clk = ~clk;
initial begin
$dumpfile("pulse.vcd");
$dumpvars(0, pulse_count_tb);
repeat (3) begin
@(negedge clk) pulse = 1'b1;
@(negedge clk) pulse = 1'b0;
end
#10 $display("total = %0d", total);
$finish;
end
endmoduleVCD info: dumpfile pulse.vcd opened for output.
total = xThe answer is x, not 3. A guess would be that the pulses are not reaching the module, but the waveform answers the question in seconds. Open pulse.vcd in GTKWave and look at total: it is red from the first clock edge through the end of the run, and it never takes a real value. A register that never leaves x was never assigned a known value, and because x + 1 is still x, adding pulses to it changes nothing. The pulse input is toggling correctly, which rules out the testbench. The module has no reset and no initial value, so there is no way for total to ever become known.
The fix is a reset, which is also the right design, since real flip-flops do not start at zero:
module pulse_count (
input wire clk,
input wire rst,
input wire pulse,
output reg [3:0] total
);
always @(posedge clk) begin
if (rst)
total <= 4'd0;
else if (pulse)
total <= total + 4'd1;
end
endmoduleAdd a rst input to the testbench, hold it high for the first two edges and the answer becomes total = 3. Notice what the exercise teaches about tools. Verilator would have printed total = 3 for the broken design as well, because its two-state model starts registers at zero, so the missing reset would have passed there and failed on Icarus. Running both is how you find it. Lint would not help here, because the register is assigned on one path and a linter does not know you meant it to start at a particular value; only a simulator with unknown values, or a formal tool, notices that nothing ever initialises it. The order of attack for any wrong output is the same: find the first signal that is wrong in the waveform, work backwards through what drives it, and stop at the first signal whose inputs are all correct.
Measuring what your tests exercised
A passing test says nothing about the behaviour it never reached. Coverage tells you which lines and branches the tests touched. Verilator can instrument a model with --coverage, which writes a data file at the end of the run, and its verilator_coverage tool turns that into annotated source:
verilator --cc --exe --build --coverage --top-module alu alu.v tb_alu.cpp
./obj_dir/Valu
verilator_coverage --annotate logs/annotate coverage.datTotal coverage (7/9) 77.78%The annotated copy of alu.v in logs/annotate marks each line with the number of times it ran, and lines never hit carry a leading percent sign and zeros:
000300 2'd0: y <= {1'b0, a} + {1'b0, b};
000300 2'd1: y <= {1'b0, a} - {1'b0, b};
%000000 2'd2: y <= {1'b0, a & b};
000300 default: y <= {1'b0, a ^ b};The numbers are an illustrative example. What matters is the line with the percent sign: no test ever selected operation 2, so a bug in the AND case could not have been found. Treat uncovered lines as a to-do list for the next directed test, not as a number to push to 100. Some lines are unreachable by design, and chasing them wastes effort. Coverage tells you where the tests are blind; it cannot tell you the checks are right, which is why the reference model and the deliberate-failure test come first.
A project layout that scales
The commands above are simple to run once and hard to remember. Give them a home. A layout that holds up for hundreds of files:
project/
rtl/ design sources, one module per file, file named after the module
tb/ testbenches, one per unit under test
sim/ Makefile and run scripts; build output goes in build/
lint.vlt Verilator waivers, each with a comment saying why
build/ generated files, ignored by version controlA Makefile is enough to start:
RTL = ../rtl/counter.v
TB = ../tb/counter_tb.v
all: lint test
lint:
verilator --lint-only -Wall ../lint.vlt --top-module counter $(RTL)
test: build/counter_sim
cd build && vvp counter_sim | tee counter.log
grep -q '^PASS' build/counter.log
build/counter_sim: $(RTL) $(TB)
mkdir -p build
iverilog -g2012 -o build/counter_sim $(RTL) $(TB)
clean:
rm -rf buildmake first lints, then builds and runs the simulation, then greps for the PASS line. The grep matters: vvp exits with status 0 after $finish no matter what the testbench found, so the exit code alone cannot tell a script that the test failed. A simulator that crashes before printing anything also leaves no PASS, and the grep catches that. When the design has many tests, write a small runner that loops over the testbench files, runs each, and prints a one-line summary, and make the whole thing the only thing CI runs.
for tb in ../tb/*_tb.v; do
name=$(basename "$tb" .v)
iverilog -g2012 -o "build/$name" ../rtl/*.v "$tb" && vvp "build/$name" | grep -q '^PASS' \
&& echo "ok $name" || echo "FAIL $name"
doneok alu_tb
ok counter_tb
FAIL uart_tbThree disciplines keep a project healthy as it grows. Name the seed of every random test in the log, so a failure repeats. Keep lint at zero warnings, recording any waiver in the .vlt file with a reason. And run each testbench on at least two simulators once the design stabilises.
A field manual of failures
Most simulation problems come from a short list. Match the symptom, then check the cause.
| Symptom | Likely cause | Check |
|---|---|---|
| waveform is empty or has no signals | $dumpvars missing, called too late, or naming a scope that does not exist | read the VCD body after $enddefinitions |
every output is x | no reset applied, or reset asserted for too short a time | find the first edge where reset is high |
x appears only after a clock edge | register read before it was ever written | look for the signal's first assignment |
| simulation never ends | a free-running clock with no $finish | add $finish or a watchdog |
| output is one cycle behind what you expect | sampled before the design settled | read after a delay or on the falling edge |
| test passes on Icarus, fails on Verilator | race, or reliance on x | run with random reset values |
| test passes on Verilator, fails on Icarus | missing reset hidden by zero initial values | look for a register with no reset |
Unknown module type | a source file is missing from the command line | list every file explicitly |
| a flat waveform in a Verilator run | eval() not called after changing an input | call it after every input change |
| width warnings everywhere | untyped constants and mixed widths | give constants sizes: 4'd1 |
The most useful habit is to read the waveform for the reset behaviour before anything else, because most mysteries begin there. The second is to predict before you look: write down what the signals should do, then open the viewer, and treat every difference as information.
Who this guide does not fit
The tools here are the right start and the right default for open hardware, FPGA hobby work, teaching, CPU cores and a great deal of professional block-level verification. They are the wrong tool, or only part of one, in four situations.
Teams using UVM. The Universal Verification Methodology needs a simulator with full SystemVerilog class and constrained-random support, which Icarus does not provide and Verilator supports only in part. If your employer or your IP vendor ships a UVM environment, you will run it on a commercial simulator, though the habits in this guide still apply.
Designs with licensed vendor IP. A transceiver, a memory controller or a DSP primitive may come as an encrypted model that runs only on the vendor's simulator. Use that simulator for those blocks and the open tools for everything around them.
Analog and mixed-signal work. These tools simulate digital logic. Circuits with analog behaviour need a SPICE-class simulator, and the digital part is verified separately.
Sign-off for silicon. Tape-out flows require timing simulation with annotated delays and equivalence checking in tools that foundries qualify. Open tools help you find bugs earlier but do not replace those steps.
If none of these describes you, you can go a long way, as far as a verified RISC-V core running Linux, on what this guide covers.
A learning path
Learn in this order. First, one design, one testbench, one waveform: the counter and Icarus Verilog until the commands are automatic. Second, self-checking tests with a reference model and an exhaustive loop, because a test that decides for itself is the foundation of everything else. Third, lint, then Verilator and a C++ testbench, because that is where speed and strictness arrive. Fourth, cocotb, when the checking logic needs data structures. Fifth, the gate-level and race topics, once you have been bitten by an x you cannot explain. Sixth, formal on one small, crisp property. Seventh, a CPU running firmware, which ties the hardware and software halves of your own work together.
At each stage, break something on purpose and watch the checker catch it. A test you have seen fail is a test you can trust.


