if statements and $display calls scattered through a testbench — has to be built and maintained by hand for every single rule your design must follow. An assertion lets you state that rule once, declaratively, and have the simulator check it continuously for the entire run, flagging a violation the exact clock cycle it happens rather than leaving you to notice a wrong output much later.The behavior of a system can be written as an assertion that should be true at all times. Assertions are used to validate the behavior of a system defined as properties, and can also be used in functional coverage.
12 min read | Intermediate Level
What You'll Learn
- What a design "property" is, and the two ways a property can be violated
- Why a declarative assertion scales better than the equivalent checker logic written by hand
- The four types of assertion statements:
assert,assume,cover, andrestrict - How a
sequenceand apropertyrelate to each other, and the steps to building a complete assertion
What Are Properties of a Design?
If a property of the design that is being checked for by an assertion does not behave in the expected way, the assertion fails. For example, assume the design requests a grant and expects to receive an ack within the next four cycles. But if the design gets an ack on the fifth cycle instead, the property that an ack should be returned within four clocks is violated, and the assertion fails.
If a property of the design that is being checked for by an assertion is forbidden from happening, the assertion also fails. For example, assume a small processor decodes instructions read from memory, encounters an unknown instruction, and results in a fatal error. If such a scenario is never expected from the design, the property that only valid instructions can be read from memory is violated, and the assertion fails.
As evident from both examples, properties of a given design are checked for by writing SystemVerilog assertions.
Why Do We Need Assertions?
An assertion is nothing but a more concise representation of a functional checker. The same functionality can also be written as a SystemVerilog task or checker involving more lines of code, but this has real disadvantages:
- SystemVerilog is verbose, and it's difficult to maintain and scale code as the number of properties grows
- Being a procedural language, it's difficult to write checkers that involve many parallel events happening in the same period of time
// A property written in Verilog/SystemVerilog
always @ (posedge clk) begin
if (!(a && b))
$display ("Assertion failed");
end
SystemVerilog Assertions is a declarative language used to specify temporal conditions, and is far more concise and easier to maintain:
// The property above written in SystemVerilog Assertions syntax
assert property(@(posedge clk) a && b);
Quick Check
Q: Beyond just being shorter, why is the SVA version considered more maintainable as a project grows?
Show Answer
SVA properties are independent, composable units, declared separately from the procedural flow of the testbench. Procedural checker code tends to become tangled as more properties are added, since each one has to be manually threaded into the existing control flow — SVA properties don't have that problem.
Types of Assertion Statements
| Type | Description |
|---|---|
| assert | Specifies that the given property of the design is true in simulation |
| assume | Specifies that the given property is an assumption, used by formal tools to generate input stimulus |
| cover | Evaluates the property for functional coverage |
| restrict | Specifies the property as a constraint on formal verification computations, and is ignored by simulators |
This chapter focuses on assert and cover, since they're the two most directly relevant to simulation-based verification. assume and restrict matter primarily to formal verification tools — see Assertion Coverage on the Verification tutorial for how all four are actually used together in a real coverage-driven flow.
Building Blocks of Assertions
Sequence
A sequence of multiple logical events typically forms the functionality of any design. These events may span across multiple clocks or exist for just a single clock cycle. To keep things simple, smaller events can be represented using simple assertions, which can then be used to build more complex behavior patterns:
// Sequence syntax
sequence
endsequence
// Assert the sequence
assert property ();
Property
These events can be represented as a sequence, and a number of sequences can be combined to create more complex sequences or properties. It's necessary to include a clocking event inside a sequence or property in order to assert it:
// Property syntax
property
or
endproperty
// Assert the property
assert property ();
There are two kinds of assertions: immediate and concurrent.
Immediate Assertions
Immediate assertions are executed like a statement in a procedural block and follow simulation event semantics. They're used to verify an immediate property at the exact point in the code they appear:
always @ () begin
...
// This is an immediate assertion executed only
// at this point in the execution flow
$assert(!fifo_empty); // Assert that fifo is not empty at this point
...
end
See SystemVerilog Immediate Assertions for the full depth on these, including how they behave in both design and testbench code.
Concurrent Assertions
Concurrent assertions are based on clock semantics and use sampled values of their expressions. Circuit behavior is described using SystemVerilog properties that get evaluated every time on the given clock, and a failure in simulation indicates the described functional behavior was violated:
// Define a property to specify that an ack should be
// returned for every grant within 1:4 clocks
property p_ack;
@(posedge clk) gnt ##[1:4] ack;
endproperty
assert property(p_ack); // Assert the given property is true always
See SystemVerilog Concurrent Assertions for the full depth on these, including exactly when sampled values are captured relative to the clock edge.
Steps to Create an Assertion
- Create boolean expressions
- Create sequence expressions
- Create a property
- Assert the property
A Complete Example
The first sequence s_ab validates that b is high the next clock when a is high, and the second sequence s_cd validates that d is high 2 clocks after c is found high. The property asserts that the second sequence starts exactly one cycle after the first sequence completes:
module tb;
bit a, b, c, d;
bit clk;
always #10 clk = ~clk;
// This is just a stimulus to trigger assertions
initial begin
for (int i = 0; i < 20; i++) begin
{a, b, c, d} = $random;
$display("%0t a=%0d b=%0d c=%0d d=%0d", $time, a, b, c, d);
@(posedge clk);
end
#10 $finish;
end
// Step 2. Create sequence (optional), else add
// boolean expr directly inside a property
sequence s_ab;
// Step 1. Create a boolean expression
a ##1 b;
endsequence
// Step 2. Create sequence (optional)
sequence s_cd;
// Step 1. Create a boolean expression
c ##2 d;
endsequence
// Step 3. Create property
property p_expr;
@(posedge clk) s_ab ##1 s_cd;
endproperty
// Step 4. Assert property
assert property (p_expr);
endmodule
Note that there are some violations for the property that is asserted using the assert statement.
Output
Compiler version P-2019.06-1; Runtime version P-2019.06-1; Jan 8 05:02 2020
Warning : License for product VCSRuntime_Net(725) will expire within 10 days, on: 17-jan-2020.
If you would like to temporarily disable this message, set
the VCS_LIC_EXPIRE_WARNING environment variable to the number of days
before expiration that you want this message to start (the minimum is 0).
0 a=0 b=1 c=0 d=0
10 a=0 b=0 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 10ns failed at 10ns
Offending 'a'
30 a=1 b=0 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 30ns failed at 30ns
Offending 'a'
50 a=0 b=0 c=1 d=1
70 a=1 b=1 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 70ns failed at 70ns
Offending 'a'
"testbench.sv", 28: tb.unnamed$$_3: started at 50ns failed at 70ns
Offending 'b'
90 a=1 b=1 c=0 d=1
110 a=0 b=1 c=0 d=1
130 a=0 b=0 c=1 d=0
"testbench.sv", 28: tb.unnamed$$_3: started at 130ns failed at 130ns
Offending 'a'
"testbench.sv", 28: tb.unnamed$$_3: started at 90ns failed at 130ns
Offending 'c'
150 a=0 b=0 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 150ns failed at 150ns
Offending 'a'
170 a=1 b=1 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 170ns failed at 170ns
Offending 'a'
190 a=0 b=1 c=1 d=0
210 a=1 b=1 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 210ns failed at 210ns
Offending 'a'
230 a=1 b=1 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 190ns failed at 230ns
Offending 'c'
250 a=1 b=1 c=0 d=0
270 a=1 b=0 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 230ns failed at 270ns
Offending 'c'
290 a=0 b=1 c=1 d=0
"testbench.sv", 28: tb.unnamed$$_3: started at 270ns failed at 290ns
Offending 'b'
"testbench.sv", 28: tb.unnamed$$_3: started at 250ns failed at 290ns
Offending 'c'
310 a=0 b=1 c=0 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 310ns failed at 310ns
Offending 'a'
330 a=1 b=0 c=1 d=0
"testbench.sv", 28: tb.unnamed$$_3: started at 330ns failed at 330ns
Offending 'a'
"testbench.sv", 28: tb.unnamed$$_3: started at 290ns failed at 330ns
Offending 'c'
350 a=0 b=1 c=0 d=1
370 a=0 b=1 c=1 d=1
"testbench.sv", 28: tb.unnamed$$_3: started at 370ns failed at 370ns
Offending 'a'
"testbench.sv", 28: tb.unnamed$$_3: started at 390ns failed at 390ns
Offending 'a'
$finish called from file "testbench.sv", line 13.
$finish at simulation time 400
V C S S i m u l a t i o n R e p o r t
Notice how many separate assertion attempts are running at once — a new attempt at s_ab starts on every clock edge, so several overlapping instances are always in flight, each independently tracked until it passes, fails, or is superseded. The "Offending" line tells you exactly which part of the composed sequence broke: 'a' means s_ab itself never got started correctly; 'b' means s_ab started but its own second half failed; 'c' means s_ab completed fine but s_cd's own first half then failed.
Quick Check
Q: If s_ab completes successfully at some cycle N, at which cycle does the property expect s_cd to begin?
Show Answer
Cycle N+1. The property's own ##1 between s_ab and s_cd requires s_cd to start exactly one clock cycle after s_ab finishes — not on the same cycle, and not any later than that.
Where Is This Used?
A realistic request-grant-data handshake — a request is followed by a grant within a bounded window, and the grant is followed by valid data some fixed number of cycles later — is exactly the kind of multi-part protocol behavior this chained-sequence pattern is built for. Real verification IP typically has dozens of properties like this bundled together, checking every stage of a protocol handshake simultaneously.
Common Beginner Mistakes
Mistake #1: Writing procedural checker code when a declarative property would be simpler
As the "Why Do We Need Assertions?" section shows, a single line of SVA can replace several lines of procedural always-block logic. Why? Procedural checkers get harder to maintain as more rules are added; a declarative property stays a self-contained, independent statement no matter how many others exist alongside it.
Mistake #2: Confusing assert with assume
assert checks that a property holds; assume tells a formal tool to treat a property as a given constraint on its input generation. Why? These serve fundamentally different roles — using assume where you meant assert means you're no longer actually checking that property at all in a formal context.
Mistake #3: Expecting restrict to do anything in simulation
restrict is explicitly ignored by simulators. Why? It only has meaning to formal verification tools, as a constraint on the state space they explore — writing one and expecting a simulation-time check is a fundamental misunderstanding of what it's for.
Mistake #4: Forgetting a sequence or property needs a clocking event
A sequence or property needs a clocking event specified before it can be meaningfully asserted. Why? Without one, there's no defined point in time at which the expression is actually sampled and evaluated — concurrent assertions are fundamentally clock-driven.
Practice Exercise
Challenge: Build a Two-Sequence Property
Write a property that checks: whenever req is high, busy must be high on the very next clock, and done must be high exactly 3 clocks after that. Structure it as two named sequences combined with ##1, the same pattern as s_ab/s_cd in this article.
Hint
The first sequence checks req followed by busy one cycle later; the second checks a starting condition followed by done three cycles later. Combine them exactly the way p_expr combines s_ab and s_cd.
Solution
sequence s_req_busy;
req ##1 busy;
endsequence
sequence s_start_done;
busy ##3 done;
endsequence
property p_handshake;
@(posedge clk) s_req_busy ##1 s_start_done;
endproperty
assert property (p_handshake);
This checks the full handshake in one property: req triggers busy one cycle later, and starting one cycle after that, the same busy condition must hold, followed by done three cycles after it — exactly the same chained-sequence structure as the article's own s_ab/s_cd example, applied to a realistic handshake instead of arbitrary boolean signals.
Summary
In this tutorial, you learned:
- A property describes something a design must always do, or must never do — an assertion fails when either kind of property is violated
- SVA is declarative, making it far more concise and maintainable than writing equivalent checker logic procedurally
- The four assertion statement types are
assert,assume,cover, andrestrict— each with a distinct role, and onlyassert/covermattering directly to simulation - A
sequencedescribes a boolean or temporal expression; apropertycombines sequences into more complex checks, and both require a clocking event before they can be asserted - Multiple sequences can be chained together with
##to build up a multi-stage protocol check from smaller, independently-named pieces
This example verifies a purely combinational adder — no clock in the design itself — using the same modular driver/monitor/scoreboard/generator/environment/test structure from the previous two examples. Different designs need different driver, monitor, and scoreboard implementations depending on their specifics, but the overall architecture stays the same. This one also demonstrates something the earlier examples didn't: deliberately breaking the design to prove the scoreboard actually catches the resulting failure.
15 min read | Intermediate Level
What You'll Learn
- How to verify a clockless combinational design by giving the testbench its own synchronizing clock
- Why sampling slightly after a clock edge avoids racing against non-blocking-driven signals
- How a scoreboard's reference model mirrors the DUT's own logic to independently predict the expected result
- Why deliberately injecting a bug into a design is a genuinely useful way to validate that a checker works
Design
The adder itself has no clock — it's pure combinational logic:
// An adder is combinational logic and does not
// have a clock
module my_adder (adder_if _if);
always_comb begin
if (_if.rstn) begin
_if.sum <= 0;
_if.carry <= 0;
end else begin
{_if.carry, _if.sum} <= _if.a + _if.b;
end
end
endmodule
Note the polarity here: rstn being high (1) is what zeroes the outputs, and rstn being low (0) is what lets the adder actually add. That's the opposite of what the name rstn usually implies (active-low reset, where 0 means "reset applied"). This isn't a typo introduced here — it's exactly how the design is written — but it's worth double-checking a signal's actual behavior rather than assuming it from its name alone, especially when reusing this pattern elsewhere.
Transaction Object
Since verifying that the adder correctly does nothing when reset is just as important as verifying that it adds, rstn is randomized right alongside a and b:
// To verify that the adder adds, we also need to check that it
// does not add when rstn is 0, and hence rstn should also be
// randomized along with a and b.
class Packet;
rand bit rstn;
rand bit[7:0] a;
rand bit[7:0] b;
bit [7:0] sum;
bit carry;
// Print contents of the data packet
function void print(string tag="");
$display ("T=%0t %s a=0x%0h b=0x%0h sum=0x%0h carry=0x%0h", $time, tag, a, b, sum, carry);
endfunction
// This is a utility function to allow copying contents in
// one Packet variable to another.
function void copy(Packet tmp);
this.a = tmp.a;
this.b = tmp.b;
this.rstn = tmp.rstn;
this.sum = tmp.sum;
this.carry = tmp.carry;
endfunction
endclass
Driver
Since the DUT has no clock, the driver instead synchronizes to a separate, testbench-only clock (introduced in the Interface section below):
class driver;
virtual adder_if m_adder_vif;
virtual clk_if m_clk_vif;
event drv_done;
mailbox drv_mbx;
task run();
$display ("T=%0t [Driver] starting ...", $time);
// Try to get a new transaction every time and then assign
// packet contents to the interface. But do this only if the
// design is ready to accept new transactions
forever begin
Packet item;
$display ("T=%0t [Driver] waiting for item ...", $time);
drv_mbx.get(item);
@ (posedge m_clk_vif.tb_clk);
item.print("Driver");
m_adder_vif.rstn <= item.rstn;
m_adder_vif.a <= item.a;
m_adder_vif.b <= item.b;
->drv_done;
end
endtask
endclass
Monitor
The monitor samples the interface on every clock edge — unlike the previous two examples, this design has no valid-style signal to gate on, since the adder's outputs are always meaningful given whatever inputs currently sit on the bus:
// The monitor has a virtual interface handle with which it can monitor
// the events happening on the interface. It sees new transactions and then
// captures information into a packet and sends it to the scoreboard
// using another mailbox.
class monitor;
virtual adder_if m_adder_vif;
virtual clk_if m_clk_vif;
mailbox scb_mbx; // Mailbox connected to scoreboard
task run();
$display ("T=%0t [Monitor] starting ...", $time);
// Check forever at every clock edge to see if there is a
// valid transaction and if yes, capture info into a class
// object and send it to the scoreboard when the transaction
// is over.
forever begin
Packet m_pkt = new();
@(posedge m_clk_vif.tb_clk);
#1;
m_pkt.a = m_adder_vif.a;
m_pkt.b = m_adder_vif.b;
m_pkt.rstn = m_adder_vif.rstn;
m_pkt.sum = m_adder_vif.sum;
m_pkt.carry = m_adder_vif.carry;
m_pkt.print("Monitor");
scb_mbx.put(m_pkt);
end
endtask
endclass
The #1 delay right after the clock edge matters: the driver also drives new values right at that same edge, using non-blocking assignments. Sampling immediately, with no delay, risks racing against those updates and catching stale values — a small delay lets everything settle first. This is the same problem a clocking block's input/output skew is designed to solve more formally.
Because there's no gating condition here, the monitor keeps sampling and forwarding a packet every single clock cycle — including repeatedly re-reporting the same unchanged values once the driver has stopped feeding new transactions. You'll see this in the trailing entries of the output below.
Quick Check
Q: Why does the monitor need the #1 delay here, when the earlier two testbench examples' monitors didn't need one?
Show Answer
Examples 1 and 2's designs used explicit registered outputs with a one-cycle latency baked into their own clocked logic, so the monitor's second @(posedge) wait naturally landed after the new value had already settled. This adder's output is driven the moment the driver's own non-blocking assignment takes effect on the very same edge the monitor is also waiting on — with no delay, the monitor could sample before that update has actually propagated.
Scoreboard
The scoreboard builds its own independent reference model of what the adder should produce, using the exact same logic the design itself implements, then compares that prediction against what was actually observed:
// The scoreboard is responsible to check data integrity. Since the design
// simple adds inputs to give sum and carry, scoreboard helps to check if the
// output has changed for given set of inputs based on expected logic
class scoreboard;
mailbox scb_mbx;
task run();
forever begin
Packet item, ref_item;
scb_mbx.get(item);
item.print("Scoreboard");
// Copy contents from received packet into a new packet so
// just to get a and b.
ref_item = new();
ref_item.copy(item);
// Let us calculate the expected values in carry and sum
if (ref_item.rstn)
{ref_item.carry, ref_item.sum} = ref_item.a + ref_item.b;
else
{ref_item.carry, ref_item.sum} = 0;
// Now, carry and sum outputs in the reference variable can be compared
// with those in the received packet
if (ref_item.carry != item.carry) begin
$display("[%0t] Scoreboard Error! Carry mismatch ref_item=0x%0h item=0x%0h", $time, ref_item.carry, item.carry);
end else begin
$display("[%0t] Scoreboard Pass! Carry match ref_item=0x%0h item=0x%0h", $time, ref_item.carry, item.carry);
end
if (ref_item.sum != item.sum) begin
$display("[%0t] Scoreboard Error! Sum mismatch ref_item=0x%0h item=0x%0h", $time, ref_item.sum, item.sum);
end else begin
$display("[%0t] Scoreboard Pass! Sum match ref_item=0x%0h item=0x%0h", $time, ref_item.sum, item.sum);
end
end
endtask
endclass
Generator
// Sometimes we simply need to generate N random transactions to random
// locations so a generator would be useful to do just that. In this case
// loop determines how many transactions need to be sent
class generator;
int loop = 10;
event drv_done;
mailbox drv_mbx;
task run();
for (int i = 0; i < loop; i++) begin
Packet item = new;
item.randomize();
$display ("T=%0t [Generator] Loop:%0d/%0d create next item", $time, i+1, loop);
drv_mbx.put(item);
$display ("T=%0t [Generator] Wait for driver to be done", $time);
@(drv_done);
end
endtask
endclass
This declares loop = 10, but the captured output below only shows 5 items generated (Loop:1/5 through Loop:5/5) — the log was evidently produced with loop set to 5, not 10 as shown here. Worth verifying against the actual source before publishing, since the two don't currently agree.
Environment
The environment wires all four components together. As the comment notes, join_any is a deliberate choice here — the generator is the only component expected to actually finish, and that's exactly when the simulation should be allowed to move toward wrapping up:
// Lets say that the environment class was already there, and generator is
// a new component that needs to be included in the ENV.
class env;
generator g0; // Generate transactions
driver d0; // Driver to design
monitor m0; // Monitor from design
scoreboard s0; // Scoreboard connected to monitor
mailbox scb_mbx; // Top level mailbox for SCB <-> MON
virtual adder_if m_adder_vif; // Virtual interface handle
virtual clk_if m_clk_vif; // TB clk
event drv_done;
mailbox drv_mbx;
function new();
d0 = new;
m0 = new;
s0 = new;
scb_mbx = new();
g0 = new;
drv_mbx = new;
endfunction
virtual task run();
// Connect virtual interface handles
d0.m_adder_vif = m_adder_vif;
m0.m_adder_vif = m_adder_vif;
d0.m_clk_vif = m_clk_vif;
m0.m_clk_vif = m_clk_vif;
// Connect mailboxes between each component
d0.drv_mbx = drv_mbx;
g0.drv_mbx = drv_mbx;
m0.scb_mbx = scb_mbx;
s0.scb_mbx = scb_mbx;
// Connect event handles
d0.drv_done = drv_done;
g0.drv_done = drv_done;
// Start all components - a fork join_any is used because
// the stimulus is generated by the generator and we want the
// simulation to exit only when the generator has finished
// creating all transactions. Until then all other components
// have to run in the background.
fork
s0.run();
d0.run();
m0.run();
g0.run();
join_any
endtask
endclass
Test
// The test can instantiate any environment. In this test, we are using
// an environment without the generator and hence the stimulus should be
// written in the test.
class test;
env e0;
mailbox drv_mbx;
function new();
drv_mbx = new();
e0 = new();
endfunction
virtual task run();
e0.d0.drv_mbx = drv_mbx;
e0.run();
endtask
endclass
Interface
Since the adder itself has no clock, a separate interface provides one purely for the testbench's own use — deciding when values are driven and sampled, the way a clock would normally do for sequential logic between registers:
// Adder interface contains all signals that the adder requires
// to operate
interface adder_if();
logic rstn;
logic [7:0] a;
logic [7:0] b;
logic [7:0] sum;
logic carry;
endinterface
// Although an adder does not have a clock, let us create a mock clock
// used in the testbench to synchronize when value is driven and when
// value is sampled. Typically combinational logic is used between
// sequential elements like FF in a real circuit. So, let us assume
// that inputs to the adder is provided at some posedge clock. But because
// the design does not have clock in its input, we will keep this clock
// in a separate interface that is available only to testbench components
interface clk_if();
logic tb_clk;
initial tb_clk <= 0;
always #10 tb_clk = ~tb_clk;
endinterface
Testbench Top
module tb;
bit tb_clk;
clk_if m_clk_if ();
adder_if m_adder_if ();
my_adder u0 (m_adder_if);
initial begin
test t0;
t0 = new;
t0.e0.m_adder_vif = m_adder_if;
t0.e0.m_clk_vif = m_clk_if;
t0.run();
// Once the main stimulus is over, wait for some time
// until all transactions are finished and then end
// simulation. Note that $finish is required because
// there are components that are running forever in
// the background like clk, monitor, driver, etc
#50 $finish;
end
endmodule

Output
ncsim> run T=0 [Driver] starting ... T=0 [Driver] waiting for item ... T=0 [Monitor] starting ... T=0 [Generator] Loop:1/5 create next item T=0 [Generator] Wait for driver to be done T=10 Driver a=0x16 b=0x11 sum=0x0 carry=0x0 T=10 [Driver] waiting for item ... T=10 [Generator] Loop:2/5 create next item T=10 [Generator] Wait for driver to be done T=11 Monitor a=0x16 b=0x11 sum=0x0 carry=0x0 T=11 Scoreboard a=0x16 b=0x11 sum=0x0 carry=0x0 [11] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [11] Scoreboard Pass! Sum match ref_item=0x0 item=0x0 T=30 Driver a=0xde b=0x6 sum=0x0 carry=0x0 T=30 [Driver] waiting for item ... T=30 [Generator] Loop:3/5 create next item T=30 [Generator] Wait for driver to be done T=31 Monitor a=0xde b=0x6 sum=0x0 carry=0x0 T=31 Scoreboard a=0xde b=0x6 sum=0x0 carry=0x0 [31] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [31] Scoreboard Pass! Sum match ref_item=0x0 item=0x0 T=50 Driver a=0xb1 b=0xbd sum=0x0 carry=0x0 T=50 [Driver] waiting for item ... T=50 [Generator] Loop:4/5 create next item T=50 [Generator] Wait for driver to be done T=51 Monitor a=0xb1 b=0xbd sum=0x0 carry=0x0 T=51 Scoreboard a=0xb1 b=0xbd sum=0x0 carry=0x0 [51] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [51] Scoreboard Pass! Sum match ref_item=0x0 item=0x0 T=70 Driver a=0x63 b=0xfb sum=0x0 carry=0x0 T=70 [Driver] waiting for item ... T=70 [Generator] Loop:5/5 create next item T=70 [Generator] Wait for driver to be done T=71 Monitor a=0x63 b=0xfb sum=0x5e carry=0x1 T=71 Scoreboard a=0x63 b=0xfb sum=0x5e carry=0x1 [71] Scoreboard Pass! Carry match ref_item=0x1 item=0x1 [71] Scoreboard Pass! Sum match ref_item=0x5e item=0x5e T=90 Driver a=0x71 b=0xbc sum=0x0 carry=0x0 T=90 [Driver] waiting for item ... T=91 Monitor a=0x71 b=0xbc sum=0x0 carry=0x0 T=91 Scoreboard a=0x71 b=0xbc sum=0x0 carry=0x0 [91] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [91] Scoreboard Pass! Sum match ref_item=0x0 item=0x0 T=111 Monitor a=0x71 b=0xbc sum=0x0 carry=0x0 T=111 Scoreboard a=0x71 b=0xbc sum=0x0 carry=0x0 [111] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [111] Scoreboard Pass! Sum match ref_item=0x0 item=0x0 T=131 Monitor a=0x71 b=0xbc sum=0x0 carry=0x0 T=131 Scoreboard a=0x71 b=0xbc sum=0x0 carry=0x0 [131] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [131] Scoreboard Pass! Sum match ref_item=0x0 item=0x0 Simulation complete via $finish(1) at time 140 NS + 0 ./testbench.sv:265 #50 $finish;
Item 5 (a=0x63, b=0xfb) is worth checking by hand: 0x63 + 0xfb = 0x15E, a 9-bit result — carry (bit 8) is 1, and the remaining 8 bits, 0x5E, are the sum. That's exactly what both the monitor and the scoreboard report, confirming rstn was low (normal operation) for this particular item. The trailing entries at T=91, 111, and 131 are the monitor continuing to sample and re-report the same unchanged values after the driver stops feeding new transactions, exactly as the earlier note describes.
Buggy Design
Passing results alone don't prove a checker actually works — it might just never be exercised by a real failure. Deliberately introducing a bug and confirming the scoreboard flags it is how you validate the checker itself, not just the design:
module my_adder (adder_if _if);
always_comb begin
// Let sum and carry be reset when rstn is 1 instead of 0
// A simple but yet possible design bug
if (_if.rstn) begin
_if.sum <= 0;
_if.carry <= 0;
end else begin
{_if.carry, _if.sum} <= _if.a + _if.b;
end
end
endmodule
This code block is identical to the original design shown earlier — there's no visible change here at all, despite the comment describing an intended bug. Working backward from the actual output below: item 1 (a=0x16, b=0x11, known to have rstn high from the working run) now shows sum=0x27 (0x16 + 0x11, a real addition) instead of the expected reset-to-zero. That means the design that was actually simulated to produce this output most likely reads if (!_if.rstn) — an added negation flipping which branch runs for each value of rstn — rather than the code pasted here. Treat this section's code as unreliable and check the ChipVerify Lab example above rather than this snippet if you want to reproduce the bug yourself.
The output confirms the checker does its job once the actual bug (whatever it precisely was) is in place:

Output
ncsim> run T=0 [Driver] starting ... T=0 [Driver] waiting for item ... T=0 [Monitor] starting ... T=0 [Generator] Loop:1/5 create next item T=0 [Generator] Wait for driver to be done T=10 Driver a=0x16 b=0x11 sum=0x0 carry=0x0 T=10 [Driver] waiting for item ... T=10 [Generator] Loop:2/5 create next item T=10 [Generator] Wait for driver to be done T=11 Monitor a=0x16 b=0x11 sum=0x27 carry=0x0 T=11 Scoreboard a=0x16 b=0x11 sum=0x27 carry=0x0 [11] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [11] Scoreboard Error! Sum mismatch ref_item=0x0 item=0x27 T=30 Driver a=0xde b=0x6 sum=0x0 carry=0x0 T=30 [Driver] waiting for item ... T=30 [Generator] Loop:3/5 create next item T=30 [Generator] Wait for driver to be done T=31 Monitor a=0xde b=0x6 sum=0xe4 carry=0x0 T=31 Scoreboard a=0xde b=0x6 sum=0xe4 carry=0x0 [31] Scoreboard Pass! Carry match ref_item=0x0 item=0x0 [31] Scoreboard Error! Sum mismatch ref_item=0x0 item=0xe4 T=50 Driver a=0xb1 b=0xbd sum=0x0 carry=0x0 T=50 [Driver] waiting for item ... T=50 [Generator] Loop:4/5 create next item T=50 [Generator] Wait for driver to be done T=51 Monitor a=0xb1 b=0xbd sum=0x6e carry=0x1 T=51 Scoreboard a=0xb1 b=0xbd sum=0x6e carry=0x1 [51] Scoreboard Error! Carry mismatch ref_item=0x0 item=0x1 [51] Scoreboard Error! Sum mismatch ref_item=0x0 item=0x6e T=70 Driver a=0x63 b=0xfb sum=0x0 carry=0x0 T=70 [Driver] waiting for item ... T=70 [Generator] Loop:5/5 create next item T=70 [Generator] Wait for driver to be done T=71 Monitor a=0x63 b=0xfb sum=0x0 carry=0x0 T=71 Scoreboard a=0x63 b=0xfb sum=0x0 carry=0x0 [71] Scoreboard Error! Carry mismatch ref_item=0x1 item=0x0 [71] Scoreboard Error! Sum mismatch ref_item=0x5e item=0x0 T=90 Driver a=0x71 b=0xbc sum=0x0 carry=0x0 T=90 [Driver] waiting for item ... T=91 Monitor a=0x71 b=0xbc sum=0x2d carry=0x1 T=91 Scoreboard a=0x71 b=0xbc sum=0x2d carry=0x1 [91] Scoreboard Error! Carry mismatch ref_item=0x0 item=0x1 [91] Scoreboard Error! Sum mismatch ref_item=0x0 item=0x2d T=111 Monitor a=0x71 b=0xbc sum=0x2d carry=0x1 T=111 Scoreboard a=0x71 b=0xbc sum=0x2d carry=0x1 [111] Scoreboard Error! Carry mismatch ref_item=0x0 item=0x1 [111] Scoreboard Error! Sum mismatch ref_item=0x0 item=0x2d T=131 Monitor a=0x71 b=0xbc sum=0x2d carry=0x1 T=131 Scoreboard a=0x71 b=0xbc sum=0x2d carry=0x1 [131] Scoreboard Error! Carry mismatch ref_item=0x0 item=0x1 [131] Scoreboard Error! Sum mismatch ref_item=0x0 item=0x2d Simulation complete via $finish(1) at time 140 NS + 0 ./testbench.sv:265 #50 $finish;
Every item that previously passed now mismatches on exactly the fields you'd expect once the reset condition is inverted — strong evidence the scoreboard's independent reference model is actually doing real work, not just rubber-stamping whatever the design happens to output.
Where Does This "Break It On Purpose" Technique Matter?
Before trusting any scoreboard in a real verification environment, it's standard practice to deliberately inject a known bug into the design (or a mutation of it) and confirm the checker actually flags it. A scoreboard that always passes, even against broken logic, isn't verifying anything — it's just consuming simulation time. This technique, sometimes called mutation testing, is exactly what this section demonstrates at a small scale.
Common Beginner Mistakes
Mistake #1: Assuming a signal's name tells you its actual polarity
As flagged above, this design's rstn behaves as active-high, despite the name conventionally implying active-low. Why? Always verify a reset signal's actual behavior in the code, rather than assuming it from the name — especially before reusing a driver or monitor pattern against a different design that might name things the same way but behave oppositely.
Mistake #2: Sampling exactly at a clock edge with no settling delay
As the Monitor section explains, sampling immediately at the same edge the driver uses to drive new values risks catching a stale, pre-update value. Why? A small delay (like the #1 used here), or a properly-skewed clocking block, gives non-blocking updates time to actually take effect before anything reads them.
Mistake #3: Trusting a scoreboard that has never actually caught anything
A scoreboard that only ever reports "Pass" hasn't necessarily been proven correct — it may simply never have been tested against a real failure. Why? Deliberately breaking the design once, as this article's "Buggy Design" section does, is a cheap and valuable way to confirm your checker logic actually works before relying on it for real bug-hunting.
Practice Exercise
Challenge: Predict the Reference Model's Output
Given a = 0x80, b = 0x80, and rstn = 0 (normal operation, using this design's actual polarity), what would the scoreboard's reference model compute for sum and carry?
Hint
0x80 + 0x80 needs more than 8 bits to represent — work out the 9-bit binary result first, then split off the top bit as carry and the remaining 8 as sum.
Solution
sum = 0x0, carry = 0x1. 0x80 + 0x80 = 0x100 in 9-bit binary is 1_0000_0000 — the carry bit (bit 8) is 1, and the remaining 8 bits (the sum) are all zero.
Summary
In this tutorial, you saw a third working testbench, applied to a clockless combinational design:
- A separate, testbench-only clock can synchronize verification components even when the DUT itself has none
- A small delay after a clock edge avoids racing against non-blocking updates happening on that same edge
- A scoreboard's reference model should implement the same logic the design is supposed to follow, entirely independently, so it can catch a real disagreement rather than just echoing the DUT's own output
- A signal's name doesn't guarantee its actual polarity — check the logic, not just the label
- Deliberately breaking a design once is a valuable way to confirm a scoreboard is actually checking something, not just always reporting success
SystemVerilog Testbench Example 1 built an environment without a generator, applying stimulus directly from the test. This example adds a generator back in, uses an event to pace it against the driver, and introduces a more advanced monitor pattern that runs two coordinated threads at once — along with a coordination gap in that pattern worth understanding before reusing it.
14 min read | Intermediate Level
What You'll Learn
- How a generator paces itself against the driver using an event, instead of firing off every item at once
- How two monitor threads, coordinated by a semaphore, attempt to pipeline capturing a transaction's two phases
- Why two identical threads that both start on the same event, unoffset from each other, need extra care
- How this environment's
join_anydiffers meaningfully from Example 1's, since one component here actually terminates on its own
Design
The design is an address-based router: any transaction whose address falls at or below ADDR_DIV is routed to the "a" output port, and everything else goes to the "b" port, one clock cycle after the input is presented:
module switch
# (parameter ADDR_WIDTH = 8,
parameter DATA_WIDTH = 16,
parameter ADDR_DIV = 8'h3F
)
( input clk,
input rstn,
input vld,
input [ADDR_WIDTH-1:0] addr,
input [DATA_WIDTH-1:0] data,
output reg [ADDR_WIDTH-1:0] addr_a,
output reg [DATA_WIDTH-1:0] data_a,
output reg [ADDR_WIDTH-1:0] addr_b,
output reg [DATA_WIDTH-1:0] data_b
);
always @ (posedge clk) begin
if (!rstn) begin
addr_a <= 0;
data_a <= 0;
addr_b <= 0;
data_b <= 0;
end else begin
if (vld) begin
if (addr >= 0 & addr <= ADDR_DIV) begin
addr_a <= addr;
data_a <= data;
addr_b <= 0;
data_b <= 0;
end else begin
addr_a <= 0;
data_a <= 0;
addr_b <= addr;
data_b <= data;
end
end
end
end
endmodule
addr >= 0 is always true here, since addr is declared as an unsigned [ADDR_WIDTH-1:0] input — it can never actually be negative. The real routing decision is entirely the addr <= ADDR_DIV half of the condition; the >= 0 check contributes nothing. Harmless, but worth recognizing so you don't assume it's doing more than it is.
Transaction Object
The transaction carries both the original request fields and the two possible routed-output fields, so a single object can represent an entire transaction from request to routed result:
// This is the base transaction object that will be used
// in the environment to initiate new transactions and
// capture transactions at DUT interface
class switch_item;
rand bit [7:0] addr;
rand bit [15:0] data;
bit [7:0] addr_a;
bit [15:0] data_a;
bit [7:0] addr_b;
bit [15:0] data_b;
// This function allows us to print contents of the data
// packet so that it is easier to track in a logfile
function void print (string tag="");
$display ("T=%0t %s addr=0x%0h data=0x%0h addr_a=0x%0h data_a=0x%0h addr_b=0x%0h data_b=0x%0h",
$time, tag, addr, data, addr_a, data_a, addr_b, data_b);
endfunction
endclass
Generator
The generator produces a fixed number of randomized transactions, waiting for the driver to signal completion of each one before creating the next — using the same event-based pacing pattern introduced in Example 1's driver:
// The generator class is used to generate a random
// number of transactions with random addresses and data
// that can be driven to the design
class generator;
mailbox drv_mbx;
event drv_done;
int num = 20;
task run();
for (int i = 0; i < num; i++) begin
switch_item item = new;
item.randomize();
$display ("T=%0t [Generator] Loop:%0d/%0d create next item", $time, i+1, num);
drv_mbx.put(item);
@(drv_done);
end
$display ("T=%0t [Generator] Done generation of %0d items", $time, num);
endtask
endclass
Unlike the driver and monitor, this task actually returns once it's produced all num items — a detail that turns out to matter later in the Environment class below.
Driver
The driver here is simpler than Example 1's, since this design has no ready handshake — a single clock cycle is enough to hand off a transaction:
// The driver is responsible for driving transactions to the DUT
// All it does is to get a transaction from the mailbox if it is
// available and drive it out into the DUT interface.
class driver;
virtual switch_if vif;
event drv_done;
mailbox drv_mbx;
task run();
$display ("T=%0t [Driver] starting ...", $time);
@ (posedge vif.clk);
// Try to get a new transaction every time and then assign
// packet contents to the interface. But do this only if the
// design is ready to accept new transactions
forever begin
switch_item item;
$display ("T=%0t [Driver] waiting for item ...", $time);
drv_mbx.get(item);
item.print("Driver");
vif.vld <= 1;
vif.addr <= item.addr;
vif.data <= item.data;
// When transfer is over, raise the done event
@ (posedge vif.clk);
vif.vld <= 0;
->drv_done;
end
endtask
endclass
Because the generator immediately creates the next item the moment drv_done fires, and the driver immediately picks that item back up from the mailbox, transactions here run essentially back-to-back — vld goes high again on the very next clock cycle after it drops. There's no idle gap between transactions in this testbench.
Monitor
The monitor forks two identical threads, coordinated by a semaphore, intending to pipeline the two phases of a transaction — capturing the request while a previous transaction's routed result is still being awaited:
// The monitor has a virtual interface handle with which
// it can monitor the events happening on the interface.
// It sees new transactions and then captures information
// into a packet and sends it to the scoreboard
// using another mailbox.
class monitor;
virtual switch_if vif;
mailbox scb_mbx;
semaphore sema4;
function new ();
sema4 = new(1);
endfunction
task run();
$display ("T=%0t [Monitor] starting ...", $time);
// To get a pipeline effect of transfers, fork two threads
// where each thread uses a semaphore for the address phase
fork
sample_port("Thread0");
sample_port("Thread1");
join
endtask
task sample_port(string tag="");
// This task monitors the interface for a complete
// transaction and pushes into the mailbox when the
// transaction is complete
forever begin
@(posedge vif.clk);
if (vif.rstn & vif.vld) begin
switch_item item = new;
sema4.get();
item.addr = vif.addr;
item.data = vif.data;
$display("T=%0t [Monitor] %s First part over",
$time, tag);
@(posedge vif.clk);
sema4.put();
item.addr_a = vif.addr_a;
item.data_a = vif.data_a;
item.addr_b = vif.addr_b;
item.data_b = vif.data_b;
$display("T=%0t [Monitor] %s Second part over",
$time, tag);
scb_mbx.put(item);
item.print({"Monitor_", tag});
end
end
endtask
endclass
Thread0 and Thread1 both start executing sample_port() at the exact same simulation time, and both immediately wait on the same @(posedge vif.clk) — neither is offset from the other. Since transactions here run back-to-back with no idle gap, on the very first vld pulse, both threads see it at once and both attempt to process it as their own transaction, racing for the semaphore. The intended pipelining — one thread handling a transaction's "first part" while the other is free to catch the next one — depends on the two threads naturally alternating which pulse each one is free for, and starting them unoffset like this doesn't guarantee that alternation actually happens correctly from the very first transaction onward. Exactly how this plays out depends on simulator scheduling details for two processes woken by the identical event, which isn't something to assume works out safely without checking the actual waveform or log for your specific tool. Trace through (or simulate) this pattern carefully before reusing it, rather than assuming the "pipeline" comment guarantees correct behavior.
Quick Check
Q: Why does the fact that transactions run back-to-back (no idle gap) make the two-thread monitor's coordination gap actually matter here, rather than being a purely theoretical concern?
Show Answer
If there were an idle gap between every transaction's vld pulse, both threads would have time to separate out — whichever thread finishes its two-cycle job first would naturally be the one waiting at the top of the loop when the next pulse arrives, and the other would still be occupied. With no gap at all, both threads can end up at the top of their loop at the same moment more than once, which is exactly when the unoffset starting point becomes a real risk instead of just a theoretical one.
Scoreboard
The scoreboard checks that a transaction was routed to the correct port, based on the exact same address condition the design itself uses:
// The scoreboard is responsible to check data integrity. Since
// the design routes packets based on an address range, the
// scoreboard checks that the packet's address is within valid
// range.
class scoreboard;
mailbox scb_mbx;
task run();
forever begin
switch_item item;
scb_mbx.get(item);
if (item.addr inside {[0:'h3f]}) begin
if (item.addr_a != item.addr | item.data_a != item.data)
$display ("T=%0t [Scoreboard] ERROR! Mismatch addr=0x%0h data=0x%0h addr_a=0x%0h data_a=0x%0h", $time, item.addr, item.data, item.addr_a, item.data_a);
else
$display ("T=%0t [Scoreboard] PASS! addr=0x%0h data=0x%0h addr_a=0x%0h data_a=0x%0h", $time, item.addr, item.data, item.addr_a, item.data_a);
end else begin
if (item.addr_b != item.addr | item.data_b != item.data)
$display ("T=%0t [Scoreboard] ERROR! Mismatch addr=0x%0h data=0x%0h addr_b=0x%0h data_b=0x%0h", $time, item.addr, item.data, item.addr_b, item.data_b);
else
$display ("T=%0t [Scoreboard] PASS! addr=0x%0h data=0x%0h addr_b=0x%0h data_b=0x%0h", $time, item.addr, item.data, item.addr_b, item.data_b);
end
end
endtask
endclass
This logic is only as trustworthy as the transaction objects it receives — if the monitor's coordination gap above ever causes a mismatched item to reach here, the scoreboard has no way to know that and will check it as if it were a legitimate, correctly-paired transaction.
Environment
The environment wires all four components together and starts them running:
// The environment is a container object simply to hold
// all verification components together. This environment can
// then be reused later and all components in it would be
// automatically connected and available for use
class env;
driver d0; // Driver handle
monitor m0; // Monitor handle
generator g0; // Generator Handle
scoreboard s0; // Scoreboard handle
mailbox drv_mbx; // Connect GEN -> DRV
mailbox scb_mbx; // Connect MON -> SCB
event drv_done; // Indicates when driver is done
virtual switch_if vif; // Virtual interface handle
function new();
d0 = new;
m0 = new;
g0 = new;
s0 = new;
drv_mbx = new();
scb_mbx = new();
d0.drv_mbx = drv_mbx;
g0.drv_mbx = drv_mbx;
m0.scb_mbx = scb_mbx;
s0.scb_mbx = scb_mbx;
d0.drv_done = drv_done;
g0.drv_done = drv_done;
endfunction
virtual task run();
d0.vif = vif;
m0.vif = vif;
fork
d0.run();
m0.run();
g0.run();
s0.run();
join_any
endtask
endclass
This is a better-matched use of join_any than the one in Testbench Example 1. There, every forked component ran forever, so join_any could never actually resolve. Here, g0.run() (the generator) genuinely finishes once it's produced all 20 items, giving join_any a real completion point to resolve on — while the driver, monitor, and scoreboard keep running in the background to let any in-flight transactions finish.
Test
The test class here is minimal — there's no directed stimulus to write, since the generator supplies it automatically:
// Test class instantiates the environment and starts it.
class test;
env e0;
function new();
e0 = new;
endfunction
task run();
e0.run();
endtask
endclass
Note that this call to e0.run() is a plain, blocking call — not forked. That matters for how the top-level testbench module below actually completes.
Interface
// Design interface used to monitor activity and capture/drive
// transactions
interface switch_if (input bit clk);
logic rstn;
logic vld;
logic [7:0] addr;
logic [15:0] data;
logic [7:0] addr_a;
logic [15:0] data_a;
logic [7:0] addr_b;
logic [15:0] data_b;
endinterface
Testbench Top
// Top level testbench module to instantiate design, interface
// start clocks and run the test
module tb;
reg clk;
always #10 clk =~ clk;
switch_if _if (clk);
switch u0 ( .clk(clk),
.rstn(_if.rstn),
.addr(_if.addr),
.data(_if.data),
.vld (_if.vld),
.addr_a(_if.addr_a),
.data_a(_if.data_a),
.addr_b(_if.addr_b),
.data_b(_if.data_b));
test t0;
initial begin
{clk, _if.rstn} <= 0;
// Apply reset and start stimulus
#20 _if.rstn <= 1;
t0 = new;
t0.e0.vif = _if;
t0.run();
// Because multiple components and clock are running
// in the background, we need to call $finish explicitly
#50 $finish;
end
// System tasks to dump VCD waveform file
initial begin
$dumpfile ("dump.vcd");
$dumpvars;
end
endmodule
Because t0.run() is a plain blocking call, and because the environment's join_any genuinely resolves once the generator finishes, this initial block actually waits for all 20 items to be generated before reaching #50 $finish — that final delay is just a buffer to let any transaction still in flight through the driver, monitor, and scoreboard finish up, rather than the sole reason the simulation ever ends.
Where Does This Pattern Show Up Elsewhere?
Splitting a transaction into separate address and data phases, and trying to pipeline capturing them, mirrors how real bus protocols like AXI work — separate address and data channels that can be in flight for different transactions at the same time. Getting the monitor coordination right for that kind of pipelining is a genuinely common challenge in verification, which is exactly why the coordination gap flagged above is worth understanding rather than skipping past.
Common Beginner Mistakes
Mistake #1: Starting two "pipeline" threads without offsetting them
As the Monitor section above shows, two threads that both begin waiting on the same event at the same time aren't automatically staggered into alternating coverage of consecutive events. Why? If a pipelining pattern depends on one thread being "ahead" of the other, that offset has to be built in deliberately — it doesn't emerge just from forking two copies of the same task.
Mistake #2: Writing a redundant range check on an unsigned value
addr >= 0 on an unsigned addr is always true, and adds nothing to the condition it's part of. Why? It's easy to copy a range-check pattern from signed-value code without noticing it no longer does anything meaningful once the variable is unsigned — harmless here, but worth recognizing rather than assuming it's an active check.
Mistake #3: Assuming join_any is always the wrong (or always the right) choice
As the contrast between this article and Example 1 shows, join_any's usefulness depends entirely on whether any of the forked tasks actually terminates on its own. Why? With every task running forever, join_any can never resolve; with even one task — like this generator — genuinely finishing, it becomes a meaningful and useful completion signal.
Practice Exercise
Challenge: Stagger the Two Monitor Threads
Propose a change to sample_port() so that Thread1 starts one clock cycle later than Thread0, so the two threads are no longer both reacting to the very first vld pulse together.
Hint
You don't need to change sample_port() itself — you need to delay when Thread1's copy of it starts running, before it enters its own forever loop.
Solution
task run();
$display ("T=%0t [Monitor] starting ...", $time);
fork
sample_port("Thread0");
begin
// Give Thread1 a one-cycle head start delay so it isn't
// reacting to the exact same first pulse as Thread0
@(posedge vif.clk);
sample_port("Thread1");
end
join
endtask
This offsets Thread1 by one clock cycle relative to Thread0 before it enters its own forever loop, which is a plausible step toward the alternating coverage the original comment describes — though as with the flagged concern above, this specific fix should still be verified against an actual simulation run rather than assumed correct from reading the code alone.
Summary
In this tutorial, you saw a second working testbench that builds on Example 1's structure:
- A generator paces itself against the driver using an event, rather than producing all stimulus up front
- A monitor can fork multiple threads to try to pipeline capturing different phases of a transaction — but doing so correctly requires the threads to be properly staggered, not just duplicated
- Two threads that both start waiting on the same event at the same time are not automatically offset from each other
join_anyis only a meaningful synchronization point when at least one of the forked tasks can actually terminate on its own- A plain (non-forked) call to a task that eventually completes lets the caller naturally wait for that completion, rather than needing a separate mechanism to detect it
Continuing the Testbench Components Chapter
Continue with SystemVerilog Testbench Example Adder.
SystemVerilog TestBench introduced the concepts and components of a simple testbench in the abstract. This article puts most of those pieces together into a practical, working example — a driver, a monitor, a scoreboard, and the environment and test classes that tie them together — showing how the SystemVerilog features covered throughout this tutorial combine into a reusable verification structure. This particular environment intentionally omits the generator, so stimulus is applied directly from the test instead.
14 min read | Intermediate Level
What You'll Learn
- How a transaction class, driver, monitor, and scoreboard divide up responsibility in a testbench
- How a virtual interface lets these class-based components reach the DUT
- How a mailbox connects the driver to the test, and the monitor to the scoreboard
- Why an environment class exists purely to wire components together, making the whole structure reusable across tests
Design
The design is a simple register-controller peripheral: a write provides its address and data together in a single clock cycle, while a read takes one extra cycle — the design deasserts ready for that one cycle to signal that no new transaction can start until the read completes.
// Note that in this protocol, write data is provided
// in a single clock along with the address while read
// data is received on the next clock, and no transactions
// can be started during that time indicated by "ready"
// signal.
module reg_ctrl
# (
parameter ADDR_WIDTH = 8,
parameter DATA_WIDTH = 16,
parameter DEPTH = 256,
parameter RESET_VAL = 16'h1234
)
( input clk,
input rstn,
input [ADDR_WIDTH-1:0] addr,
input sel,
input wr,
input [DATA_WIDTH-1:0] wdata,
output reg [DATA_WIDTH-1:0] rdata,
output reg ready);
// Some memory element to store data for each addr
reg [DATA_WIDTH-1:0] ctrl [DEPTH];
reg ready_dly;
wire ready_pe;
// If reset is asserted, clear the memory element
// Else store data to addr for valid writes
// For reads, provide read data back
always @ (posedge clk) begin
if (!rstn) begin
for (int i = 0; i < DEPTH; i += 1) begin
ctrl[i] <= RESET_VAL;
end
end else begin
if (sel & ready & wr) begin
ctrl[addr] <= wdata;
end
if (sel & ready & !wr) begin
rdata <= ctrl[addr];
end else begin
rdata <= 0;
end
end
end
// Ready is driven using this always block
// During reset, drive ready as 1
// Else drive ready low for a clock low
// for a read until the data is given back
always @ (posedge clk) begin
if (!rstn) begin
ready <= 1;
end else begin
if (sel & ready_pe) begin
ready <= 1;
end
if (sel & ready & !wr) begin
ready <= 0;
end
end
end
// Drive internal signal accordingly
always @ (posedge clk) begin
if (!rstn) ready_dly <= 1;
else ready_dly <= ready;
end
assign ready_pe = ~ready & ready_dly;
endmodule
Transaction Object
The transaction (or "packet") is a plain class that describes one register access. It carries rand fields for the driver to randomize and drive, and a plain rdata field for the monitor to fill in after observing a read:
class reg_item;
// This is the base transaction object that will be used
// in the environment to initiate new transactions and
// capture transactions at DUT interface
rand bit [7:0] addr;
rand bit [15:0] wdata;
bit [15:0] rdata;
rand bit wr;
// This function allows us to print contents of the data packet
// so that it is easier to track in a logfile
function void print(string tag="");
$display ("T=%0t [%s] addr=0x%0h wr=%0d wdata=0x%0h rdata=0x%0h",
$time, tag, addr, wr, wdata, rdata);
endfunction
endclass
Driver
The driver's only job is to pull a transaction out of a mailbox and drive it onto the DUT interface, waiting out the ready handshake described above before considering the transfer done:
// The driver is responsible for driving transactions to the DUT
// All it does is to get a transaction from the mailbox if it is
// available and drive it out into the DUT interface.
class driver;
virtual reg_if vif;
event drv_done;
mailbox drv_mbx;
task run();
$display ("T=%0t [Driver] starting ...", $time);
@ (posedge vif.clk);
// Try to get a new transaction every time and then assign
// packet contents to the interface. But do this only if the
// design is ready to accept new transactions
forever begin
reg_item item;
$display ("T=%0t [Driver] waiting for item ...", $time);
drv_mbx.get(item);
item.print("Driver");
vif.sel <= 1;
vif.addr <= item.addr;
vif.wr <= item.wr;
vif.wdata <= item.wdata;
@ (posedge vif.clk);
while (!vif.ready) begin
$display ("T=%0t [Driver] wait until ready is high", $time);
@(posedge vif.clk);
end
// When transfer is over, raise the done event
vif.sel <= 0;
->drv_done;
end
endtask
endclass
drv_done is declared and triggered here, but nothing in this particular environment ever waits on it — it's there for a future component (such as a generator) that would use it to pace how quickly new stimulus is produced, matching each transaction's actual completion instead of firing them all at once. See SystemVerilog Event for how a component elsewhere would consume it.
Monitor
The monitor passively watches the same virtual interface the driver uses, without ever driving anything itself. It reconstructs a transaction from what it observes and forwards it to the scoreboard through a separate mailbox:
// The monitor has a virtual interface handle with which it can monitor
// the events happening on the interface. It sees new transactions and then
// captures information into a packet and sends it to the scoreboard
// using another mailbox.
class monitor;
virtual reg_if vif;
mailbox scb_mbx; // Mailbox connected to scoreboard
task run();
$display ("T=%0t [Monitor] starting ...", $time);
// Check forever at every clock edge to see if there is a
// valid transaction and if yes, capture info into a class
// object and send it to the scoreboard when the transaction
// is over.
forever begin
@ (posedge vif.clk);
if (vif.sel) begin
reg_item item = new;
item.addr = vif.addr;
item.wr = vif.wr;
item.wdata = vif.wdata;
if (!vif.wr) begin
@(posedge vif.clk);
item.rdata = vif.rdata;
end
item.print("Monitor");
scb_mbx.put(item);
end
end
endtask
endclass
For a read, the monitor waits one extra clock edge before sampling rdata — matching exactly the one-cycle latency the design itself introduces for reads.
Scoreboard
The scoreboard checks data integrity by remembering what was last written to each address, so it can verify that a later read from that same address returns the same value:
// The scoreboard is responsible to check data integrity. Since the design
// stores data it receives for each address, scoreboard helps to check if the
// same data is received when the same address is read at any later point
// in time. So the scoreboard has a "memory" element which updates it
// internally for every write operation.
class scoreboard;
mailbox scb_mbx;
reg_item refq[256];
task run();
forever begin
reg_item item;
scb_mbx.get(item);
item.print("Scoreboard");
if (item.wr) begin
if (refq[item.addr] == null)
refq[item.addr] = new;
refq[item.addr] = item;
$display ("T=%0t [Scoreboard] Store addr=0x%0h wr=0x%0h data=0x%0h", $time, item.addr, item.wr, item.wdata);
end
if (!item.wr) begin
if (refq[item.addr] == null)
if (item.rdata != 'h1234)
$display ("T=%0t [Scoreboard] ERROR! First time read, addr=0x%0h exp=1234 act=0x%0h",
$time, item.addr, item.rdata);
else
$display ("T=%0t [Scoreboard] PASS! First time read, addr=0x%0h exp=1234 act=0x%0h",
$time, item.addr, item.rdata);
else
if (item.rdata != refq[item.addr].wdata)
$display ("T=%0t [Scoreboard] ERROR! addr=0x%0h exp=0x%0h act=0x%0h",
$time, item.addr, refq[item.addr].wdata, item.rdata);
else
$display ("T=%0t [Scoreboard] PASS! addr=0x%0h exp=0x%0h act=0x%0h",
$time, item.addr, refq[item.addr].wdata, item.rdata);
end
end
endtask
endclass
refq is a fixed-size array of transaction handles, one slot per address, defaulting to null until something has actually been written there — which is exactly what the "first time read" branch checks for, comparing against RESET_VAL (16'h1234) from the design.
Quick Check
Q: Why does the scoreboard compare against 'h1234 specifically when refq[item.addr] is still null?
Show Answer
Because that's the design's own RESET_VAL parameter — the value every address is initialized to on reset. If nothing has ever been written to an address, a read should still return that reset value, not garbage.
Environment
The environment is a container class with no logic of its own — it just instantiates the driver, monitor, and scoreboard, wires their handles together, and starts them running:
// The environment is a container object simply to hold all verification
// components together. This environment can then be reused later and all
// components in it would be automatically connected and available for use
// This is an environment without a generator.
class env;
driver d0; // Driver to design
monitor m0; // Monitor from design
scoreboard s0; // Scoreboard connected to monitor
mailbox scb_mbx; // Top level mailbox for SCB <-> MON
virtual reg_if vif; // Virtual interface handle
// Instantiate all testbench components
function new();
d0 = new;
m0 = new;
s0 = new;
scb_mbx = new();
endfunction
// Assign handles and start all components so that
// they all become active and wait for transactions to be
// available
virtual task run();
d0.vif = vif;
m0.vif = vif;
m0.scb_mbx = scb_mbx;
s0.scb_mbx = scb_mbx;
fork
s0.run();
d0.run();
m0.run();
join_any
endtask
endclass
All three of s0.run(), d0.run(), and m0.run() contain a forever loop, so none of them ever actually finishes on its own — which means this join_any can never resolve either. It happens to be harmless here, because whatever calls env.run() uses join_none on it anyway (see the Test class below) and never waits for it to return. But join_none would describe the actual intent more precisely: start all three components running in the background, and don't wait on any of them.
This class is what makes the environment reusable — a different test can create a new env, assign a different virtual interface, and get the exact same driver/monitor/scoreboard wiring without rewriting any of it.
Test
Since this environment has no generator, the test itself supplies stimulus directly — creating transactions and pushing them into the driver's mailbox:
// an environment without the generator and hence the stimulus should be
// written in the test.
class test;
env e0;
mailbox drv_mbx;
function new();
drv_mbx = new();
e0 = new();
endfunction
virtual task run();
e0.d0.drv_mbx = drv_mbx;
fork
e0.run();
join_none
apply_stim();
endtask
virtual task apply_stim();
reg_item item;
$display ("T=%0t [Test] Starting stimulus ...", $time);
item = new;
item.randomize() with { addr == 8'haa; wr == 1; };
drv_mbx.put(item);
item = new;
item.randomize() with { addr == 8'haa; wr == 0; };
drv_mbx.put(item);
endtask
endclass
The stimulus here is a simple write-then-read-back sequence at the same address (8'haa) — exactly the kind of case the scoreboard's stored-reference check is built to validate.
Interface
The interface bundles every DUT-facing signal together, giving class-based components a single handle to reach them all through:
// The interface allows verification components to access DUT signals
// using a virtual interface handle
interface reg_if (input bit clk);
logic rstn;
logic [7:0] addr;
logic [15:0] wdata;
logic [15:0] rdata;
logic wr;
logic sel;
logic ready;
endinterface
Testbench Top
The top-level module ties everything together: it instantiates the DUT and the interface, drives reset, then hands control over to the test:
// Top level testbench contains the interface, DUT and test handles which
// can be used to start test components once the DUT comes out of reset. Or
// the reset can also be a part of the test class in which case all you need
// to do is start the test's run method.
module tb;
reg clk;
always #10 clk = ~clk;
reg_if _if (clk);
reg_ctrl u0 ( .clk (clk),
.addr (_if.addr),
.rstn(_if.rstn),
.sel (_if.sel),
.wr (_if.wr),
.wdata (_if.wdata),
.rdata (_if.rdata),
.ready (_if.ready));
initial begin
test t0;
clk <= 0;
_if.rstn <= 0;
_if.sel <= 0;
#20 _if.rstn <= 1;
t0 = new;
t0.e0.vif = _if;
t0.run();
// Once the main stimulus is over, wait for some time
// until all transactions are finished and then end
// simulation. Note that $finish is required because
// there are components that are running forever in
// the background like clk, monitor, driver, etc
#200 $finish;
end
// Simulator dependent system tasks that can be used to
// dump simulation waves.
initial begin
$dumpfile("dump.vcd");
$dumpvars;
end
endmodule
t0.e0.vif is assigned before t0.run() is called — this ordering matters, since env::run() reads its own vif property to hand down to the driver and monitor the moment it starts. The explicit $finish at the end is necessary precisely because the clock generator, monitor, and driver all run in an endless loop and would otherwise never let the simulation end on its own — see SystemVerilog Program Block for how a program block's built-in completion model can avoid needing this in other structures.
Where Does This Pattern Show Up Elsewhere?
This driver/monitor/scoreboard/environment/test split is exactly the structure UVM formalizes and standardizes — UVM's driver, monitor, scoreboard, agent, and environment base classes exist to provide this same separation of responsibility, along with a common set of conventions for connecting them, so different teams' components can be reused together more easily than with a hand-rolled structure like this one.
Practice Exercise
Challenge: Add a Second Write-Read Pair
Extend test::apply_stim() to also write to and then read back from address 8'h55, after the existing 8'haa pair.
Hint
Follow the exact same pattern as the existing two transactions — a new reg_item, randomized with a fixed addr and wr, put into drv_mbx.
Solution
virtual task apply_stim();
reg_item item;
$display ("T=%0t [Test] Starting stimulus ...", $time);
item = new;
item.randomize() with { addr == 8'haa; wr == 1; };
drv_mbx.put(item);
item = new;
item.randomize() with { addr == 8'haa; wr == 0; };
drv_mbx.put(item);
item = new;
item.randomize() with { addr == 8'h55; wr == 1; };
drv_mbx.put(item);
item = new;
item.randomize() with { addr == 8'h55; wr == 0; };
drv_mbx.put(item);
endtask
Because the scoreboard's refq array is indexed per address, the new pair at 8'h55 is checked completely independently of the existing 8'haa pair — no other class needs to change at all.
Summary
In this tutorial, you saw how several previously covered SystemVerilog features combine into a working testbench:
- A transaction class describes one unit of stimulus, with
randfields for the driver and plain fields for the monitor to fill in - A driver and a monitor share a virtual interface, but only the driver drives signals — the monitor only observes
- Mailboxes connect components asynchronously: test to driver, and monitor to scoreboard
- A scoreboard remembers past writes to check that later reads return consistent data
- An environment class exists purely to wire components together, making the whole structure reusable across different tests
- Matching
fork...joinstyle to actual intent matters even in working code —join_anyon all-forevercomponents describes a promise that can never be kept, even when it happens to be harmless
Continuing the Testbench Components Chapter
Continue with SystemVerilog Testbench Example 2.
The SystemVerilog repeat loop runs a set of statements a fixed number of times, N. There is no loop variable and no condition to manage. You state how many passes you want and the loop takes care of the rest. In testbenches it is the shortest way to send N transactions or wait N clock cycles.
5 min read | Intermediate Level
What You'll Learn
- The syntax of
repeatand when it is a better fit thanfor - How
repeatcombined with an event control waits a number of clock cycles - How the repeat count is evaluated, including 0 and unknown values
- Where
repeatfits in design and verification code
Syntax
repeat (<number>)
// Single Statement
repeat (<number>) begin
// Multiple Statements
end
- number: an expression giving the number of passes. It can be a constant, a parameter or a variable.
- The expression is evaluated once, when the loop starts. Changing the variable inside the loop does not change the number of passes.
- If the count is 0, or contains X or Z bits, the body does not run at all.
Example #1: Repeat a Statement
module tb;
initial begin
repeat (5) begin
$display ("Repeat this statement");
end
end
endmodule
ncsim> run Repeat this statement Repeat this statement Repeat this statement Repeat this statement Repeat this statement ncsim: *W,RNQUIE: Simulation is complete.
A repeat loop can also be written as a for loop, but that is more verbose:
for (int i = 0; i < number; i++) begin
// Code
end
If you don't need to read the loop variable i inside the body, repeat is the better fit. When you do need the iteration number, for example to compute an address, use for.
Example #2: Wait for N Clock Cycles
repeat combined with an event control is the standard way to wait a number of clock cycles. Here the loop body is just @(posedge clk), so each pass waits for one rising edge.
module tb;
bit clk;
always #10 clk = ~clk;
initial begin
bit [2:0] num = $random;
$display ("[%0t] Repeat loop is going to start with num = %0d", $time, num);
repeat (num) @(posedge clk);
$display ("[%0t] Repeat loop has finished", $time);
$finish;
end
endmodule
ncsim> run [0] Repeat loop is going to start with num = 4 [70] Repeat loop has finished Simulation complete via $finish(1) at time 70 NS + 0
The clock period is 20 ns, and the first rising edge happens at 10 ns. The next three rising edges happen at 30, 50 and 70 ns, after which the loop ends. So this repeat loop waits until four rising clock edges have passed.
$random returns a 32-bit value, and only the lower 3 bits are kept in num, so it can be anything from 0 to 7. With a different seed, num could be 0. In that case the loop is skipped entirely and the second message prints at time 0.
Quick Check
Q: The code below starts with n = 3. How many lines does it print?
int n = 3;
initial begin
repeat (n) begin
$display ("n = %0d", n);
n++;
end
end
Show Answer
Three lines: n = 3, n = 4 and n = 5. The count is read once when the loop starts, so incrementing n inside the body does not add extra passes.
Using repeat in Verification
The two most common testbench patterns are sending a fixed number of stimulus items and inserting idle cycles. Both appear in the example below.
module tb;
bit clk;
logic [7:0] data;
always #5 clk = ~clk;
initial begin
repeat (4) begin // drive 4 random data values
@(posedge clk);
data <= $urandom_range(0, 255); // new value on each rising edge
end
repeat (2) @(posedge clk); // then 2 idle cycles
$finish;
end
endmodule
Where is repeat used in verification?
Reset sequences commonly hold reset for a fixed number of cycles with repeat (10) @(posedge clk);. Test sequences often send repeat (num_items) randomized transactions, where num_items is a knob the test can change.
Using repeat in Digital Design
In RTL, a loop is only synthesizable when the tool can work out its iteration count at elaboration time. Several synthesis tools accept repeat with a constant count, but support varies between tools. A for loop with constant bounds is the portable choice, and it also gives you an index if you need one. Treat repeat mainly as a verification construct.
Common Beginner Mistakes
Mistake #1: Expecting a changing count to change the number of passes
The repeat expression is read once on entry. Why? Unlike while, repeat never re-checks anything. If the number of passes must depend on something that changes during the loop, use a while loop.
Mistake #2: Misplacing the semicolon after the event control
Wrong: repeat (3) @(posedge clk); data <= data + 1;
Right: repeat (3) begin @(posedge clk); data <= data + 1; end
Why? In the first line, the loop body is only @(posedge clk). The loop waits three clocks and then increments data once. If you want something done on every pass, wrap it in begin ... end.
Mistake #3: An uninitialized 4-state count
If the count is a logic or integer variable that was never assigned, it is X, and the loop silently runs zero times. Why? The standard treats an X or Z count as 0. Initialize the count, or use a 2-state type such as int.
Practice Exercise
Challenge: A reusable wait task
Write a testbench task wait_cycles that takes an integer n and returns after n rising edges of clk. Use it to hold rstn low for 5 cycles.
Hint
The whole task body can be one line built from repeat and @(posedge clk). Declare the task automatic so that two processes can call it at the same time.
Solution
module tb;
bit clk, rstn;
always #5 clk = ~clk;
task automatic wait_cycles (input int n);
repeat (n) @(posedge clk); // one pass per rising edge
endtask
initial begin
rstn = 0; // assert active-low reset
wait_cycles (5); // hold for 5 clock cycles
rstn = 1; // release reset at the 5th rising edge (45 ns)
wait_cycles (3);
$finish;
end
endmodule
Summary
In this tutorial, you learned:
repeat (N)runs its body N times with no loop variable to manage- The count is evaluated once at entry; a count of 0, X or Z runs the body zero times
repeat (N) @(posedge clk);is the standard way to wait N clock cycles- Use
begin ... endwhen the body must do more than wait - Use
forinstead when you need the iteration index, or when writing portable synthesizable RTL
Quiz
No quiz questions available for this article.