A SystemVerilog case statement checks whether an expression matches one of several case items and branches to the matching one. On its own it behaves exactly as in Verilog. SystemVerilog adds three qualifiers, unique, unique0 and priority, which declare whether the items may overlap and whether every possible value must be covered. Simulators check that intent at run time, and synthesis tools use it to build parallel or simplified logic.
7 min read | Intermediate Level
What You'll Learn
- What
unique case,unique0 caseandpriority casecheck - How a
defaultitem interacts with each check - How the qualifiers replace the old
full_caseandparallel_casesynthesis pragmas - How to pick the right qualifier for decoders and FSMs
Syntax
unique case (expression) item1: stmt; item2: stmt; [default: stmt;] endcase
unique0 case (expression) item1: stmt; item2: stmt; [default: stmt;] endcase
priority case (expression) item1: stmt; item2: stmt; [default: stmt;] endcase
The qualifiers also work with casez and casex, for example unique casez (opcode).
| Qualifier | Violation if more than one item matches | Violation if no item matches and there is no default | Item that runs |
|---|---|---|---|
unique | Yes | Yes | The matching item; with overlap, the first match |
unique0 | Yes | No | The matching item; with overlap, the first match |
priority | No | Yes | The first matching item, in source order |
These are the same rules as for unique and priority if-else. Violations are reported at run time, usually as warnings, and simulation continues.
unique and unique0 case
unique and unique0 declare that the case items do not overlap, so they can be evaluated in parallel. They do not prevent overlap. They check for it and report a violation when it happens:
- If more than one case item matches the expression, a violation is reported and the first matching item is executed.
- If no case item matches and there is no
default, a violation is reported foruniqueonly.
unique0 does not report a violation when no item matches.
unique: No items match for given expression
module tb;
bit [1:0] abc;
initial begin
abc = 1;
// None of the case items match the value in "abc"
// A violation is reported here
unique case (abc)
0 : $display ("Found to be 0");
2 : $display ("Found to be 2");
endcase
end
endmodule
ncsim> run
ncsim: *W,NOCOND: Unique case violation: Every case item expression was false.
File: ./testbench.sv, line = 9, pos = 14
Scope: tb
Time: 0 FS + 1
ncsim: *W,RNQUIE: Simulation is complete.
abc is 1, which matches neither 0 nor 2, and there is no default. The NOCOND violation tells you a value occurred that the designer declared impossible. With unique0 case, or with a default item, nothing would be reported.
unique: More than one case item matches
module tb;
bit [1:0] abc;
initial begin
abc = 0;
// Multiple case items match the value in "abc"
// A violation is reported here
unique case (abc)
0 : $display ("Found to be 0");
0 : $display ("Again found to be 0");
2 : $display ("Found to be 2");
endcase
end
endmodule
ncsim> run
Found to be 0
ncsim: *W,MCONDE: Unique case violation: Multiple matching case item expressions at {line=10:pos=6 and line=11:pos=6}.
File: ./testbench.sv, line = 9, pos = 14
Scope: tb
Time: 0 FS + 1
ncsim: *W,RNQUIE: Simulation is complete.
Two items match the value 0. The first one runs, and MCONDE reports the overlap with the line numbers of both items. Duplicate constants like these are easy to spot, but overlaps between casez wildcard patterns are not, and that is where this check earns its keep.
Quick Check
Q: If you add default: $display("Other"); to the multiple-match example, does the MCONDE violation go away?
Show Answer
No. A default only covers the "no match" case. Two items still match 0, so the overlap violation is still reported.
priority case
priority declares that the items must be evaluated in order, with the first match winning, and that at least one item must match. Overlap is allowed and not reported. A violation is reported only when nothing matches and there is no default.
module tb;
bit [1:0] abc;
initial begin
abc = 0;
// First match is executed
priority case (abc)
0 : $display ("Found to be 0");
0 : $display ("Again found to be 0");
2 : $display ("Found to be 2");
endcase
end
endmodule
ncsim> run Found to be 0 ncsim: *W,RNQUIE: Simulation is complete.
This is the same overlapping code as before, but with priority no violation is reported. Only the first match runs. If abc were 1 or 3, nothing would match, and because there is no default, a NOCOND priority case violation would be reported.
Using unique and priority case in Digital Design
All three qualifiers are synthesizable and are widely used in RTL decoders and FSMs.
Before SystemVerilog, designers steered synthesis with comment pragmas: // synopsys parallel_case to say items never overlap, and // synopsys full_case to say every possible value is covered. Simulators ignore comments, so a wrong pragma caused silent simulation-versus-synthesis mismatches. The qualifiers express the same intent, and simulation checks it:
| Qualifier | Synthesis meaning | Equivalent pragmas |
|---|---|---|
unique | Parallel logic; unlisted values are don't-care | full_case parallel_case |
unique0 | Parallel logic only | parallel_case |
priority | Order kept; unlisted values are don't-care | full_case |
The example below decodes a 3-state FSM encoded in 2 bits. The value 2'b11 is never used, so unique lets synthesis treat it as don't-care. Simulation flags it if it ever appears.
typedef enum logic [1:0] {IDLE, READ, WRITE} state_t; // 2'b11 unused
module ctrl_decode (
input state_t state,
output logic rd_en,
output logic wr_en
);
always_comb begin
rd_en = 1'b0; // defaults: outputs always assigned
wr_en = 1'b0;
unique case (state) // items never overlap; 2'b11 is impossible
IDLE : ; // nothing to drive
READ : rd_en = 1'b1;
WRITE : wr_en = 1'b1;
endcase
end
endmodule
Synthesis trusts the qualifier, but only simulation checks it. If an illegal value such as 2'b11 could really reach this logic on silicon, the gates may behave in ways no RTL branch describes. Fix every violation you see in simulation; do not just filter it out of the log.
Where are unique and priority case used?
Instruction decoders in CPU and DSP cores use unique casez so that overlapping opcode patterns are caught early in simulation. FSM output and next-state logic commonly uses unique case on the state variable. Address decoders whose regions are deliberately nested, with a small register window inside a larger memory region, use priority casez so the more specific region wins.
Common Beginner Mistakes
Mistake #1: Violations before reset from an X case expression
A 4-state state register is X until reset is applied. An X matches no case item, so a unique case or priority case without a default reports a violation at time 0 or during reset. Why? The check sees "no item matched", which is what happened. Apply reset at time 0, or recognize these early warnings for what they are, but investigate any violation that appears after reset.
Mistake #2: Assuming default disables all checks
default satisfies only the "no match" check. Why? The overlap check of unique and unique0 is separate, and overlapping items are still reported.
Mistake #3: Using priority when the items cannot overlap
Weaker: priority case (sel) with items 0, 1, 2, 3
Better: unique case (sel)
Why? If the items are exclusive by construction, priority throws away both the overlap check and the parallel-logic optimization. Use priority only when overlap is intended and order matters.
Practice Exercise
Challenge: Opcode decoder with overlapping patterns
A 4-bit opcode selects a 2-bit unit: patterns 11?? select the branch unit (2), any other 1??? selects the ALU (1), and 0??? selects the load/store unit (0). Write the decoder with casez and the right qualifier.
Hint
11?? is a subset of 1???, so the patterns overlap, and the more specific one must win.
Solution
always_comb begin
priority casez (opcode)
4'b11?? : unit = 2'd2; // branch: most specific pattern first
4'b1??? : unit = 2'd1; // ALU: overlaps with the line above
4'b0??? : unit = 2'd0; // load/store
endcase
end
unique would report MCONDE for every opcode starting with 11, so priority is correct. The three patterns cover all 16 values, so no "no match" violation can occur.
Summary
In this tutorial, you learned:
unique casechecks that items never overlap and that some item, or thedefault, always matchesunique0 casechecks only for overlappriority casekeeps source order and checks only that something matches- A
defaultsatisfies the "no match" check, never the overlap check - The qualifiers replace the
full_caseandparallel_casepragmas, with the advantage of being checked in simulation - The qualifiers work with
casezandcasextoo, where overlapping wildcard patterns are common
A modport list defines signal directions inside an interface, restricting how a particular module is allowed to access that interface's signals. The keyword modport means the directions are declared as if looking from inside the module using that view.
7 min read | Intermediate Level
What You'll Learn
- What a modport is, and the driver-conflict problem it solves
- The basic syntax for declaring one or more modports inside an interface
- The difference between a named port bundle and a connecting port bundle, and when a module gets its modport view
- How a module can accept a generic interface and still receive a specific modport view at connection time
- How a modport and a clocking block work together in the same interface, and why some signals (like reset) are usually left out of the clocking block
Syntax
modport [identifier] (
input [port_list],
output [port_list]
);
Below is an interface myInterface with a few signals and two modport declarations. dut0 states that ack and sel are inputs, and gnt and irq0 are outputs, to whatever module uses that modport. dut1 declares the mirror image: gnt and irq0 are inputs, and ack and sel are outputs, for any module using it instead:
interface myInterface;
logic ack;
logic gnt;
logic sel;
logic irq0;
// ack and sel are inputs to the dut0, while gnt and irq0 are outputs
modport dut0 (
input ack, sel,
output gnt, irq0
);
// ack and sel are outputs from dut1, while gnt and irq0 are inputs
modport dut1 (
input gnt, irq0,
output ack, sel
);
endinterface
Example of a Named Port Bundle
In this style, the design takes the required, correct modport definition directly from the interface type named in its own port list. The testbench only needs to provide the whole interface object:
module dut0 ( myInterface.dut0 _if);
...
endmodule
module dut1 ( myInterface.dut1 _if);
...
endmodule
module tb;
myInterface _if ();
dut0 d0 ( .* );
dut1 d1 ( .* );
endmodule
Example of a Connecting Port Bundle
In this style, the design simply accepts whatever directional view it's handed — the testbench is responsible for supplying the correct modport:
module dut0 ( myInterface _if);
...
endmodule
module dut1 ( myInterface _if);
...
endmodule
module tb;
myInterface _if ();
dut0 d0 ( ._if (_if.dut0));
dut1 d1 ( ._if (_if.dut1));
endmodule
Quick Check
Q: In the named port bundle style versus the connecting port bundle style, which one determines the modport view: the design's own port list, or the testbench's instantiation?
Show Answer
In the named port bundle style, the design's own port list fixes the modport (myInterface.dut0) — the testbench just hands over the whole interface object. In the connecting port bundle style, the design accepts a generic view of the interface, and the testbench decides which modport to apply at instantiation (._if(_if.dut0)).
What Is the Need for a Modport?
Nets declared within a plain interface are inout by default, so any module connected to the same net can either drive values onto it or read values from it — there are no restrictions on the direction of value propagation. You could end up with an X on the net because both the testbench and the design are driving two different values onto the same interface net at once. Special care would otherwise be needed by the testbench writer to avoid this. A modport avoids the problem inherently, by restricting each connected module to only the directions its own modport declares.
Example of Connecting to a Generic Interface
A module can also have a generic interface as its port list. The generic handle accepts any modport passed down to it from the hierarchy above:
module dut0 ( interface _if);
...
endmodule
module dut1 ( interface _if);
...
endmodule
module tb;
myInterface _if;
dut0 d0 ( ._if (_if.dut0));
dut1 d1 ( ._if (_if.dut1));
endmodule
Where Are Modports Used?
Modports are what let a single interface serve both sides of a connection safely — a bus master and a bus slave, or a DUT and its testbench monitor, all sharing the exact same physical signals while each only being able to drive the direction it's actually supposed to.
Design Example
Consider two modules, master and slave, connected by a simple bus. The bus sends an address and data which the slave is expected to capture and store in its internal registers. The master always initiates the transfer, and the slave indicates via sready whether it's ready to accept data.
Interface
Below is the interface shared between master and slave:
interface ms_if (input clk);
logic sready; // Indicates if slave is ready to accept data
logic rstn; // Active low reset
logic [1:0] addr; // Address
logic [7:0] data; // Data
modport slave ( input addr, data, rstn, clk,
output sready);
modport master ( output addr, data,
input clk, sready, rstn);
endinterface
Design
The master iterates the address from 0 to 3 and sends data equal to the address multiplied by 4, only sending when the slave indicates it's ready via sready:
// This module accepts an interface with modport "master"
// Master sends transactions in a pipelined format
// CLK 1 2 3 4 5 6
// ADDR A0 A1 A2 A3 A0 A1
// DATA D0 D1 D2 D3 D4
module master ( ms_if.master mif);
always @ (posedge mif.clk) begin
// If reset is applied, set addr and data to default values
if (! mif.rstn) begin
mif.addr <= 0;
mif.data <= 0;
// Else increment addr, and assign data accordingly if slave is ready
end else begin
// Send new addr and data only if slave is ready
if (mif.sready) begin
mif.addr <= mif.addr + 1;
mif.data <= (mif.addr * 4);
// Else maintain current addr and data
end else begin
mif.addr <= mif.addr;
mif.data <= mif.data;
end
end
end
endmodule
Note how data lags addr by one cycle in the timing comment above: since both assignments are non-blocking and both read mif.addr's current value in the same clock edge, data is computed from the address before it increments — matching the pipelined ADDR/DATA table shown in the comment.
The slave accepts data for every address and stores it into internal registers. When the address wraps from 3 back to 0, the slave requires one additional clock to become ready again:
module slave (ms_if.slave sif);
reg [7:0] reg_a;
reg [7:0] reg_b;
reg reg_c;
reg [3:0] reg_d;
reg dly;
reg [3:0] addr_dly;
always @ (posedge sif.clk) begin
if (! sif.rstn) begin
addr_dly <= 0;
end else begin
addr_dly <= sif.addr;
end
end
always @ (posedge sif.clk) begin
if (! sif.rstn) begin
reg_a <= 0;
reg_b <= 0;
reg_c <= 0;
reg_d <= 0;
end else begin
case (addr_dly)
0 : reg_a <= sif.data;
1 : reg_b <= sif.data;
2 : reg_c <= sif.data;
3 : reg_d <= sif.data;
endcase
end
end
assign sif.sready = ~(sif.addr[1] & sif.addr[0]) | ~dly;
always @ (posedge sif.clk) begin
if (! sif.rstn)
dly <= 1;
else
dly <= sif.sready;
end
endmodule
The two design modules are tied together at the top level — note that both are connected to the same single ms_if instance, which is correct here, since a master and slave genuinely need to share the exact same physical bus signals:
module d_top (ms_if tif);
// Pass the "master" modport to master
master m0 (tif.master);
// Pass the "slave" modport to slave
slave s0 (tif.slave);
endmodule
Testbench
The testbench passes the interface handle to the design, which assigns the master and slave modports to its own sub-modules:
module tb;
reg clk;
always #10 clk = ~clk;
ms_if if0 (clk);
d_top d0 (if0);
// Let the stimulus run for 20 clocks and stop
initial begin
clk <= 0;
if0.rstn <= 0;
repeat (5) @ (posedge clk);
if0.rstn <= 1;
repeat (20) @ (posedge clk);
$finish;
end
endmodule
The master initiates bus transactions, and the slave captures data and stores it in its internal registers (reg_a through reg_d) for the corresponding address.
Combining a Modport with a Clocking Block
In practice, a testbench-facing modport very often references a clocking block directly, instead of listing plain signal directions itself. This gets you both benefits at once: the clocking block's race-free timing (covered in Clocking Blocks) and the modport's access restriction, in a single named view.
interface req_gnt_if (input logic clk);
logic req;
logic gnt;
logic rstn;
clocking cb @(posedge clk);
default input #1step output #2ns;
output req; // testbench drives: goes into design
input gnt; // testbench reads: comes from design
endclocking
// TB gets the clocking block's timed view of req/gnt, plus a direct
// (unclocked) handle on rstn, since reset is typically async
modport TB (clocking cb, output rstn);
// DUT gets a plain, undirected-by-clock view - it doesn't need skew,
// it just needs correct signal directions
modport DUT (input req, rstn, clk, output gnt);
endinterface
rstn is deliberately left out of the clocking block and declared directly on the TB modport instead. Reset is usually asynchronous by design, so driving it through a clocking block's synchronous skew doesn't make sense — a modport can mix a clocking reference with ordinary input/output signals side by side, exactly as shown here.
The design side only ever sees the plain DUT modport — it has no idea a clocking block even exists on the testbench side:
module des (input logic clk, req, rstn, output logic gnt);
always @ (posedge clk or negedge rstn)
if (!rstn) gnt <= 0;
else gnt <= req;
endmodule
module d_top (req_gnt_if.DUT dif);
des dut0 (.clk(dif.clk), .req(dif.req), .rstn(dif.rstn), .gnt(dif.gnt));
endmodule
The testbench drives req and reads gnt through the clocking block, while driving rstn directly:
module tb;
logic clk;
always #10 clk = ~clk;
req_gnt_if vif (.clk(clk));
d_top d0 (vif.DUT);
initial begin
vif.rstn <= 0;
vif.cb.req <= 0;
repeat (3) @(vif.cb);
vif.rstn <= 1;
repeat (2) @(vif.cb);
vif.cb.req <= 1;
repeat (5) @(vif.cb);
$finish;
end
endmodule
Note that d0 is instantiated with vif.DUT specifically, giving the design module only the plain directional view — the clocking block itself is only ever referenced from the testbench side.
Quick Check
Q: Why isn't rstn included inside the clocking cb block above, even though it's still part of the TB modport?
Show Answer
Reset is typically asynchronous, and a clocking block's whole purpose is to apply synchronous sampling/driving skew relative to a clock edge. Driving an async reset through a clocking block would force it to follow a clock-relative timing scheme it isn't meant to have — so it's declared as a plain signal on the modport instead, alongside the clocking cb reference.
Common Beginner Mistakes
Mistake #1: A case-sensitivity typo in the interface or modport name
myinterface and myInterface are two entirely different identifiers to SystemVerilog. Why? A single mismatched letter's case is enough to turn a working port declaration into a compile error — always double-check that the interface name used at every module's port list exactly matches its declaration, capitalization included.
Mistake #2: Skipping modports on a shared interface
Without a modport, every net in an interface is inout by default, so nothing stops two connected modules from both trying to drive the same signal. Why? This can silently produce X values on a net whenever both sides happen to drive conflicting values — modports exist specifically to make that impossible by restricting each module to only its intended direction.
Mistake #3: Confusing which side chooses the modport
In the named port bundle style, the design's own port list fixes which modport it gets; in the connecting port bundle style, the testbench chooses at instantiation time. Why? Mixing these up leads to writing a generic-looking port list but then never actually specifying a modport anywhere, or vice versa — pick one style deliberately rather than blending the two.
Mistake #4: Putting every signal, including reset, inside the clocking block
Not every signal on a testbench-facing modport needs to go through the clocking block. Why? Asynchronous signals like reset don't have a meaningful relationship to a clock edge, so forcing them through a clocking block's skew is unnecessary at best and misleading at worst — declare them as plain input/output on the modport instead, alongside the clocking reference.
Practice Exercise
Challenge: Add a Read-Only monitor Modport
Using the ms_if interface from the design example, add a third modport called monitor that declares every signal (addr, data, rstn, clk, sready) as input — a passive observer that can watch the bus without ever driving anything.
Hint
A modport that only reads declares every signal it lists as input, even ones that other modports (like slave) declare as output.
Solution
interface ms_if (input clk);
logic sready;
logic rstn;
logic [1:0] addr;
logic [7:0] data;
modport slave ( input addr, data, rstn, clk,
output sready);
modport master ( output addr, data,
input clk, sready, rstn);
// A passive observer - every signal is an input, nothing is ever driven
modport monitor ( input addr, data, rstn, clk, sready );
endinterface
monitor declares sready as input even though slave declares it as output — each modport is just a different view over the same underlying signals, so a monitor module can watch the entire bus transaction without risking driving anything itself.
Summary
In this tutorial, you learned:
- A modport defines signal directions inside an interface, from the perspective of whatever module uses that particular view
- Without a modport, interface nets are
inoutby default, leaving no protection against two modules driving the same net at once - In a named port bundle, the design's own port list fixes the modport; in a connecting port bundle, the testbench chooses the modport at instantiation
- A module can accept a generic
interfaceport and still be handed a specific modport view by whatever instantiates it - Multiple modules (like a bus master and slave) can safely share one interface instance when each is restricted to its own modport
- A modport can reference a
clockingblock directly for timed signals, while still declaring other signals (like an async reset) as plaininput/outputalongside it
A module that accepts an interface as a port can reference that interface in one of two ways: by naming the exact interface type it expects, or by using a generic placeholder that accepts any interface passed to it. Which one you reach for depends on whether the module needs to work with one specific interface definition, or stay flexible as that definition evolves.
6 min read | Intermediate Level
What You'll Learn
- The difference between a named interface bundle and a generic interface bundle in a module's port list
- Why a generic interface bundle is useful when interface definitions change over time
- The ANSI-style port declaration restriction that applies to generic interface ports
- How partial implicit port connections (
.*) work alongside a generic interface port
Named vs Generic Interface Bundles
There are two ways a design can accept an interface:
- By using an existing interface name, to specifically require only that one interface
- By using a generic interface handle, to which any interface can be passed
The generic method works best when interface definitions get updated to newer versions under a different name, while older designs still need to keep working against whatever interface they were built for.
Example Using a Named Bundle
Here, the design references the actual interface name to access its signals. Both myDesign and yourDesign declare a port in their port list called if0, of type myInterface:
module myDesign ( myInterface if0,
input logic clk);
always @ (posedge clk)
if (a.ack)
if0.gnt <= 1;
...
endmodule
module yourDesign ( myInterface if0,
input logic clk);
...
endmodule
module tb;
logic clk = 0;
myInterface _if;
myDesign md0 (_if, clk);
yourDesign yd0 (_if, clk);
endmodule
The condition inside myDesign checks a.ack, but the interface port declared in this module's port list is named if0, not a — a is never declared anywhere in this module, so this line as written wouldn't compile. It should read if0.ack, matching the port name used on the very next line (if0.gnt). Whatever name you give the interface port is the name you must use everywhere inside the module body to access its signals.
Example Using a Generic Bundle
Here, the design uses the interface keyword itself as a placeholder for the actual interface type. Both myDesign and yourDesign use that placeholder handle to reference signals, and the actual interface is passed in during module instantiation. A generic interface reference like this can only be declared using ANSI-style port declaration syntax — it's illegal otherwise:
module myDesign ( interface a,
input logic clk);
always @ (posedge clk)
if (if0.ack)
if0.gnt <= 1;
...
endmodule
module yourDesign ( interface b,
input logic clk);
...
endmodule
module tb;
logic clk = 0;
myInterface _if;
myDesign md0 ( .*, .a(_if)); // use partial implicit port connections
yourDesign yd0 ( .*, .b(_if));
endmodule
This time the port is declared as a (the generic interface placeholder), but the body references if0.ack and if0.gnt — there's no port named if0 here at all. It should read a.ack and a.gnt, matching the port name a that the instantiation below (.a(_if)) actually connects to.
In the testbench, md0 uses .* to implicitly connect any port whose name matches a same-named local signal — here, clk — while explicitly connecting the generic interface port a to the local interface instance _if with .a(_if), since _if and a don't share the same name for .* to match automatically.
Quick Check
Q: Why can't .* alone connect the generic interface port in the example above, without also writing .a(_if)?
Show Answer
Even setting naming aside, .* can never connect a generic interface port at all — the language flatly requires an explicit named connection for any generic interface port. So the .a(_if) connection would still be required here even if the port happened to be named _if to match the local instance exactly.
Where Are Generic Interface Bundles Used?
Generic bundles are useful when a reusable checker or monitor module needs to work against more than one version of an interface — for example, supporting both an older protocol interface and its newer revision without maintaining two nearly-identical copies of the same module, one per interface name.
Common Beginner Mistakes
Mistake #1: Referencing a different name than the one declared in the port list
As both examples above illustrate, the interface port's declared name is the only name you can use to access its signals inside that module. Why? It's an easy copy-paste mistake when adapting a named-bundle example into a generic one (or vice versa) — always double-check that every signal reference inside the module body matches the exact port name declared at the top.
Mistake #2: Declaring a generic interface port with non-ANSI syntax
A generic interface port can only be declared using ANSI-style port declarations (directly in the module's port list, as shown above). Why? Older, non-ANSI Verilog-style port declarations (separate input/output statements in the module body) simply aren't legal for a generic interface port — this is a hard restriction in the language, not a style preference.
Mistake #3: Assuming .* connects every port, including a generic interface port
.* is convenient, but it's not a catch-all. Why? For an ordinary port, a name that doesn't exactly match a visible local signal still needs its own explicit connection. A generic interface port is stricter still: the language disallows connecting one implicitly at all, so it always needs an explicit named connection — even on the rare occasion its name happens to match a local signal.
Practice Exercise
Challenge: Write a Correct Generic Bundle Module
Write a module called checker that accepts a generic interface port named chk_if and a clk input, and drives chk_if.gnt high whenever chk_if.ack is high on a clock edge — without the naming mismatch shown in the examples above.
Hint
Whatever you name the generic interface port in the port list is exactly the name you must use every time you access its signals inside the module body.
Solution
module checker ( interface chk_if,
input logic clk);
always @ (posedge clk)
if (chk_if.ack)
chk_if.gnt <= 1;
endmodule
module tb;
logic clk = 0;
myInterface _if;
checker chk0 ( .*, .chk_if(_if) );
endmodule
Every reference inside checker uses chk_if, matching the port name declared in the port list exactly — there's no stray reference to a name that was never declared, unlike both examples earlier in this article.
Summary
In this tutorial, you learned:
- A module can accept an interface either by naming the exact interface type, or through a generic
interfaceplaceholder that accepts any interface passed to it - A generic interface bundle is useful when an interface definition changes over time, letting one module support multiple interface versions
- A generic interface port can only be declared using ANSI-style port syntax
- Whatever name is declared for an interface port in the port list must be used consistently everywhere that port's signals are accessed inside the module
.*only auto-connects ports whose names exactly match a visible local signal; a generic interface port needs an explicit named connection unconditionally, even on the rare occasion its name happens to match
Continuing the Interfaces & Modports Chapter
Continue with SystemVerilog Clocking Blocks.
Declaring an interface is only half the story — this article covers the formal syntax, how the same interface connects a testbench to either a plain Verilog design or a SystemVerilog design, why traditional port-by-port connections don't scale as a design grows, how to declare an array of interface instances, and how tasks, functions, assertions, and coverage can live directly inside an interface.
10 min read | Intermediate Level
What You'll Learn
- Why Verilog's traditional one-signal-at-a-time port connections get unwieldy at scale, and how an interface fixes that
- The formal syntax for declaring an interface, and what it can contain beyond plain signals
- How the same interface connects a testbench to either a plain Verilog design, or a SystemVerilog design that accepts the interface directly as a port
- How to declare and connect an array of interface instances
- How tasks, functions, assertions, and coverage can be declared right inside an interface, alongside the signals they work with
- A parsing gotcha with interfaces that have no port list
Interface Syntax
Interface blocks are defined between interface and endinterface. Like a module, an interface can be instantiated with or without ports:
interface [name] ([port_list]);
[list_of_signals]
endinterface
Interfaces can also have functions, tasks, variables, and parameters, making them more like a class template. They can define port directions for different modules via modport, along with testbench synchronization via clocking blocks. An interface can also contain assertions, coverage recording, and other protocol-checking elements, plus initial and always procedures and continuous assign statements.
A module cannot be instantiated inside an interface. An interface, however, can be instantiated inside a module.
Connecting an Interface to a Verilog Design
The design below is an up-down counter written in plain Verilog. It accepts a parameter deciding the counter's width, and an input load value that's loaded into the counter only when load_en is 1. It counts down when down is 1, and otherwise counts up; rollover is asserted whenever the counter sits at its maximum value (all 1s) — the point right before it would wrap back to 0 while counting up, or right after wrapping from 0 while counting down.
module counter_ud
#(parameter WIDTH = 4)
(
input clk,
input rstn,
input wire [WIDTH-1:0] load,
input load_en,
input down,
output rollover,
output reg [WIDTH-1:0] count
);
always @ (posedge clk or negedge rstn) begin
if (!rstn)
count <= 0;
else
if (load_en)
count <= load;
else begin
if (down)
count <= count - 1;
else
count <= count + 1;
end
end
assign rollover = &count;
endmodule
An interface called cnt_if is declared below with a parameterizable width for the counter signal:
interface cnt_if #(parameter WIDTH = 4) (input bit clk);
logic rstn;
logic load_en;
logic [WIDTH-1:0] load;
logic [WIDTH-1:0] count;
logic down;
logic rollover;
endinterface
module tb;
reg clk;
// TB Clock Generator used to provide the design
// with a clock -> here half_period = 10ns => 50 MHz
always #10 clk = ~clk;
cnt_if cnt_if0 (clk);
counter_ud c0 ( .clk (cnt_if0.clk),
.rstn (cnt_if0.rstn),
.load (cnt_if0.load),
.load_en (cnt_if0.load_en),
.down (cnt_if0.down),
.rollover (cnt_if0.rollover),
.count (cnt_if0.count));
initial begin
bit load_en, down;
bit [3:0] load;
$monitor("[%0t] down=%0b load_en=%0b load=0x%0h count=0x%0h rollover=%0b",
$time, cnt_if0.down, cnt_if0.load_en, cnt_if0.load, cnt_if0.count, cnt_if0.rollover);
// Initialize testbench variables
clk <= 0;
cnt_if0.rstn <= 0;
cnt_if0.load_en <= 0;
cnt_if0.load <= 0;
cnt_if0.down <= 0;
// Drive design out of reset after 5 clocks
repeat (5) @(posedge clk);
cnt_if0.rstn <= 1;
// Drive stimulus -> repeat 5 times
for (int i = 0; i < 5; i++) begin
// Drive inputs after some random delay
int delay = $urandom_range (1,30);
#(delay);
// Randomize input values to be driven
std::randomize(load, load_en, down);
// Assign tb values to interface signals
cnt_if0.load <= load;
cnt_if0.load_en <= load_en;
cnt_if0.down <= down;
end
// Wait for 5 clocks and finish simulation
repeat(5) @ (posedge clk);
$finish;
end
endmodule
Output
ncsim> run [0] down=0 load_en=0 load=0x0 count=0x0 rollover=0 [96] down=1 load_en=1 load=0x1 count=0x0 rollover=0 [102] down=0 load_en=0 load=0x9 count=0x0 rollover=0 [108] down=1 load_en=1 load=0x1 count=0x0 rollover=0 [110] down=1 load_en=1 load=0x1 count=0x1 rollover=0 [114] down=1 load_en=0 load=0xc count=0x1 rollover=0 [120] down=1 load_en=0 load=0x7 count=0x1 rollover=0 [130] down=1 load_en=0 load=0x7 count=0x0 rollover=0 [150] down=1 load_en=0 load=0x7 count=0xf rollover=1 [170] down=1 load_en=0 load=0x7 count=0xe rollover=0 [190] down=1 load_en=0 load=0x7 count=0xd rollover=0 Simulation complete via $finish(1) at time 210 NS + 0
Notice that even here, cnt_if0 doesn't eliminate the per-signal connection at the DUT instantiation — c0 still lists every port individually. The interface's real payoff shows up once the DUT itself is written to accept an interface handle directly, which is exactly what the next example does.
Quick Check
Q: Looking at the output log, why does rollover read 1 at [150] but 0 at [170], even though down is 1 in both rows?
Show Answer
rollover is driven by assign rollover = &count;, so it's only high when count equals all 1s. At [150], count=0xf (the maximum for this 4-bit counter), so rollover is 1. By [170], the counter has decremented to 0xe, so count is no longer all 1s and rollover drops back to 0.
Connecting an Interface to a SystemVerilog Design
SystemVerilog allows a module to accept an interface as its entire port list, instead of individual signals. In the design below, the port list of counter_ud has been replaced with a single interface handle used to define the same design functionality:
`timescale 1ns/1ns
// This module accepts an interface object as the port list
module counter_ud #(parameter WIDTH = 4) (cnt_if _if);
always @ (posedge _if.clk or negedge _if.rstn) begin
if (!_if.rstn)
_if.count <= 0;
else
if (_if.load_en)
_if.count <= _if.load;
else begin
if (_if.down)
_if.count <= _if.count - 1;
else
_if.count <= _if.count + 1;
end
end
assign _if.rollover = &_if.count;
endmodule
The design instance is passed an interface handle called cnt_if, used both to drive inputs from the testbench and to monitor outputs from the design:
// Interface definition is the same as before
module tb;
reg clk;
// TB Clock Generator used to provide the design
// with a clock -> here half_period = 10ns => 50 MHz
always #10 clk = ~clk;
cnt_if cnt_if0 (clk);
// Note that here we just have to pass the interface handle
// to the design instead of connecting each individual signal
counter_ud c0 (cnt_if0);
// Stimulus remains the same as before
Output
ncsim> run [0] down=0 load_en=0 load=0x0 count=0x0 rollover=0 [96] down=1 load_en=1 load=0x1 count=0x0 rollover=0 [102] down=0 load_en=0 load=0x9 count=0x0 rollover=0 [108] down=1 load_en=1 load=0x1 count=0x0 rollover=0 [110] down=1 load_en=1 load=0x1 count=0x1 rollover=0 [114] down=1 load_en=0 load=0xc count=0x1 rollover=0 [120] down=1 load_en=0 load=0x7 count=0x1 rollover=0 [130] down=1 load_en=0 load=0x7 count=0x0 rollover=0 [150] down=1 load_en=0 load=0x7 count=0xf rollover=1 [170] down=1 load_en=0 load=0x7 count=0xe rollover=0 [190] down=1 load_en=0 load=0x7 count=0xd rollover=0 Simulation complete via $finish(1) at time 210 NS + 0
Same stimulus, same output — but now c0 is instantiated with a single handle, cnt_if0, instead of seven individual port connections. That's the difference an interface-as-port makes.
What Makes It Different From Verilog?
Verilog connects between different modules through its module ports. For large designs, this connection method can become time-consuming and repetitive. Some of these ports may include signals related to bus protocols like AXI/AHB, clock and reset pins, and signals to and from RAM/memory or other peripheral devices.
Using Verilog Ports
This is the traditional way of port connection in Verilog:
module d_slave ( input clk,
reset,
enable,
// Many more input signals
output gnt,
irq,
// Many more output signals);
// Some design functionality
endmodule
module d_top ( [top_level_ports] );
reg [`NUM_SLAVES-1:0] clk; // Assume `NUM_SLAVES is a macro set to 2
reg [`NUM_SLAVES-1:0] tb_reset;
// Other declarations
d_slave slave_0 ( .clk (d_clk[0]), // These connections have to be
.reset (d_reset[0]) // repeated for all other slave instances
...
.gnt (d_gnt[0]),
... );
d_slave slave_1 ( ... );
d_slave slave_2 ( ... );
endmodule
Consider a scenario where there are twelve slaves in this design. If a change is made to the d_slave module's ports, that change has to be reflected in all twelve slave instance connections in d_top as well.
Disadvantages
Some downsides of the Verilog port connection method:
- Tedious to trace, debug, and maintain
- Too easy to make or break design functionality with a small edit
- Changes in design requirements may require modifications across multiple modules
- Duplication needed across multiple modules, communication protocols, and other places
Using SystemVerilog Interface
Here, d_top simply uses the interface to connect with the slave instances, instead of repetitively declaring a connection to each signal of the slave block:
interface slave_if (input logic clk, reset);
reg clk;
reg reset;
reg enable;
reg gnt;
// Declarations for other signals follow
endinterface
module d_slave (slave_if s_if);
// Design functionality
always (s_if.enable & s_if.gnt) begin // interface signals are accessed by the handle "s_if"
// Some behavior
end
endmodule
module d_top (input clk, reset);
// Create an instance of the slave interface
slave_if slave_if_inst ( .clk (clk),
.reset (reset));
d_slave slave_0 (.s_if (slave_if_inst));
d_slave slave_1 (.s_if (slave_if_inst));
d_slave slave_2 (.s_if (slave_if_inst));
endmodule
Now, if a signal in the slave interface changes, that change is automatically applied to every instance connected to it. The module port list can also have a port of interface type instead of the usual input, output, and inout.
This example connects all three d_slave instances to the same single interface instance, slave_if_inst, purely to keep the syntax comparison simple — all three slaves would end up sharing the same physical enable/gnt signals. In a real multi-slave design, each slave normally needs its own independent control signals, which means its own interface instance (or an array of interfaces, covered next) rather than one instance shared by all.
Quick Check
Q: If the d_slave module above gains a new input signal, how many places does that change need to be made using the interface approach, versus the traditional Verilog port approach with twelve slave instances?
Show Answer
With the interface, one place — add the signal to slave_if, and it's automatically available everywhere the interface is used. With traditional ports, the new signal has to be added to d_slave's port list and then to all twelve individual instance connections in d_top.
Interface Arrays
An interface can be declared as an array, the same way any other object can, letting a testbench connect to several identical design instances without writing a separate interface handle for each one. SystemVerilog Interface Array covers this in depth, including a parsing gotcha with port-less interfaces that's easy to trip over.
Tasks, Functions, Assertions, and Coverage Inside an Interface
The Interface Syntax section earlier mentioned that an interface can hold more than just signals — functions, tasks, assertions, and coverage can all live inside one too, right alongside the signals they operate on. Here's that claim demonstrated, extending the cnt_if interface from earlier in this article:
interface cnt_if #(parameter WIDTH = 4) (input bit clk);
logic rstn;
logic load_en;
logic [WIDTH-1:0] load;
logic [WIDTH-1:0] count;
logic down;
logic rollover;
// A task other testbench code can call to pulse reset for a few clocks
task automatic reset (input int cycles = 3);
rstn <= 0;
repeat (cycles) @ (posedge clk);
rstn <= 1;
endtask
// A function other testbench code can call to check if count is at its max value
function automatic bit is_max ();
return &count;
endfunction
// A lightweight assertion: count should stay at 0 while rstn is low
property p_reset_holds_count;
@(posedge clk) !rstn |-> count == 0;
endproperty
assert property (p_reset_holds_count);
// A minimal coverpoint tracking whether load_en was ever exercised
covergroup cg_load_en @ (posedge clk);
coverpoint load_en;
endgroup
cg_load_en cg_inst = new();
endinterface
Once declared, the task and function are called directly through the interface handle, the same way you'd access any other signal:
initial begin
cnt_if0.reset(); // pulse reset for 3 clocks
if (cnt_if0.is_max())
$display("counter is at its max value");
end
Bundling a reset() task with the interface means every testbench that uses cnt_if gets the exact same reset sequence for free, instead of each one re-implementing its own version — one more way an interface centralizes logic that would otherwise be duplicated.
The assertion and covergroup declared above work exactly like they would anywhere else — declaring them inside the interface just means they travel with the signals automatically, with no separate wiring needed. SystemVerilog Assertions and SystemVerilog Covergroup and Coverpoint cover the full syntax and semantics of each in depth.
Quick Check
Q: Why put p_reset_holds_count and cg_load_en inside the interface instead of inside the testbench module that uses it?
Show Answer
Because they check and measure the interface's own signals, keeping them inside the interface means every module that instantiates cnt_if automatically gets the same checking and coverage, with nothing extra to wire up or duplicate — the same reuse benefit as the reset() task above.
Common Beginner Mistakes
Mistake #1: Omitting () when instantiating a port-less interface
As shown just above, mif m_if; fails to compile, while mif m_if(); succeeds. Why? Without the parentheses, the parser can't distinguish the statement from other kinds of declarations — always include () at instantiation, even for an interface with nothing in its own port list.
Mistake #2: Assuming one shared interface instance gives each module its own signals
Connecting multiple module instances to the same interface instance means they share the exact same physical signals. Why? If each instance needs independent control signals — its own enable, its own gnt, and so on — you need a separate interface instance per module instance, or an array of interfaces, not one instance reused everywhere.
Mistake #3: Trying to instantiate a module inside an interface
Interfaces can contain tasks, functions, variables, parameters, assertions, and coverage — but not a module instance. Why? The direction only goes one way: an interface can be instantiated inside a module, never the reverse.
Practice Exercise
Challenge: Give Each Slave Its Own Interface
Using the slave_if interface from earlier, fix the sharing problem noted above: declare an array of 3 slave_if instances instead of 1, and connect each d_slave to its own array element.
Hint
Follow the same interface_name array_name [N:0] (...) pattern covered in SystemVerilog Interface Array, then index into it per instance.
Solution
module d_top (input clk, reset);
// One interface instance per slave, instead of one shared instance
slave_if slave_if_inst [2:0] ( .clk (clk),
.reset (reset));
d_slave slave_0 (.s_if (slave_if_inst[0]));
d_slave slave_1 (.s_if (slave_if_inst[1]));
d_slave slave_2 (.s_if (slave_if_inst[2]));
endmodule
Each d_slave now has its own independent enable/gnt signals, since each is connected to a different element of the slave_if_inst array instead of all three sharing one instance.
Summary
In this tutorial, you learned:
- An interface can contain not just signals, but tasks, functions, variables, parameters, assertions, and coverage — and can be instantiated inside a module, though never the reverse
- The same interface can connect a testbench to a plain Verilog design (still one signal at a time at the DUT instantiation) or to a SystemVerilog design that accepts the interface directly as its port list (a single handle)
- Traditional Verilog port connections require every signal change to be repeated across every module instance; an interface centralizes that in one place
- Multiple module instances connected to the same interface instance share the exact same signals — use an array of interfaces when each instance needs independent control signals
- Bundling a task, function, assertion, or coverage model inside the interface means every module that uses it gets the same behavior automatically, instead of duplicating it elsewhere
- An interface with no port list still needs
()at instantiation, or it fails to compile
Continuing the Interfaces & Modports Chapter
Continue with SystemVerilog Interface Array, SystemVerilog Interface Parameters, and Interface Bundles.
When values need to be assigned between two different data type variables, ordinary assignment might not be valid — instead, a system task called $cast should be used. $cast can be called as either a task or a function, and it becomes especially useful in handling invalid assignments gracefully.
9 min read | Intermediate Level
What You'll Learn
- Why ordinary assignment can fail between two different data types, and what
$castsolves - The difference between calling
$castas a task versus as a function - What happens when the source value doesn't actually fit the destination type
- How this same
$castmechanism also applies to class objects, not just enums
Syntax
function int $cast (targ_var, source_exp);
task $cast (targ_var, source_exp);
targ_var is the target variable, and source_exp is the source expression evaluated and assigned to it.
Calling as a Task vs a Function
| Called as | On success | On failure |
|---|---|---|
| task | Assigns the value | Runtime error; target variable left unchanged |
| function | Assigns the value, returns 1 | Returns 0, no error at all; target variable left unchanged |
Either way, a failed cast never leaves the target variable in some corrupted or partially-updated state — it's simply left exactly as it was before the attempt.
Using $cast
Assigning an integer value to an enumerated variable using $cast:
typedef enum { PENNY=1, FIVECENTS=5, DIME=10, QUARTER=25, DOLLAR=100 } Cents;
module tb;
Cents myCent;
initial begin
$cast (myCent, 10 + 5 + 10);
$display ("Money=%s", myCent.name());
end
endmodule
Output
ncsim> run Money=QUARTER ncsim: *W,RNQUIE: Simulation is complete.
The source expression 10 + 5 + 10 is first evaluated to 25, which matches QUARTER exactly, so the cast succeeds and myCent takes that value.
Quick Check
Q: What would $cast(myCent, 5) alone produce?
Show Answer
myCent.name() would return "FIVECENTS" — 5 matches that enum value exactly.
Without $cast
Here's what happens with a plain assignment instead:
initial begin
myCent = 10 + 5 + 10;
...
end
Behavior here genuinely varies by simulator, since an integer being assigned to an enumerated variable violates SystemVerilog's strong typing rules for enums. From Aldec Riviera Pro, this is a hard compile error:
ERROR VCP2694 "Assignment to enum variable from expression of different type." "testbench.sv" 7 1 FAILURE "Compile failure 1 Errors 0 Warnings Analysis time: 0[s]."
From Cadence's ncsim, it's only a warning — elaboration and simulation still proceed, and the assignment still takes effect:
myCent = 10 + 5 + 10; | ncelab: *W,ENUMERR (./testbench.sv,7|18): This assignment is a violation of SystemVerilog strong typing rules for enumeration datatypes. ncsim> run Money=QUARTER ncsim: *W,RNQUIE: Simulation is complete. ncsim> exit
Relying on this kind of assignment without $cast means the exact same code can behave very differently depending on which simulator runs it — from a hard failure to a silent (if warned-about) success.
Casting Invalid Values (as a Task)
Now trying a value that doesn't fall inside the enumerated range at all, with $cast called as a task (its return value ignored):
initial begin
$cast (myCent, 75);
...
end
Output
ncsim> run $cast (myCent, 75); | ncsim: *E,INVCST (./testbench.sv,7|6): Invalid cast: the source expression can not be cast to the type of the destination variable. Money= ncsim: *W,RNQUIE: Simulation is complete.
The cast fails with a runtime error, and myCent is left at its default value — 0, which isn't one of the named enum values here (they start at 1), so myCent.name() prints an empty string.
Quick Check
Q: Why does Money= print with nothing after it, rather than some fallback text like "INVALID"?
Show Answer
An enum variable that never gets successfully assigned defaults to the value 0. Since none of this enum's named values happen to be 0 (they start at PENNY=1), .name() simply has no name to return for that value — it's not a special "invalid" marker, just an unnamed numeric value.
$cast as a Function
The same out-of-range attempt, this time with $cast called as a function and its return value checked:
initial begin
if ($cast (myCent, 75))
$display ("Cast passed");
else
$display ("Cast failed");
...
end
Output
ncsim> run Cast failed Money= ncsim: *W,RNQUIE: Simulation is complete.
This time, the simulation completes with no runtime error at all — the failure is caught cleanly through the if/else, and myCent is left unchanged, exactly as it was in the task version.
Quick Check
Q: What's the key practical difference in program flow between the task version and the function version of this same failed cast?
Show Answer
The task version produces an unconditional runtime error message the moment the cast fails, with no way to intercept it beforehand. The function version lets the code decide exactly what to do on failure — here, printing "Cast failed" — with no error message generated at all.
Where Is $cast Used?
Casting also applies to class objects, allowing a base class handle pointing to a child object to be assigned to another handle of that specific child type — exactly the downcasting pattern covered in SystemVerilog Polymorphism. This shows up constantly in UVM, where objects are frequently passed around as generic base-class handles and need to be safely recovered as their specific derived type.
Common Beginner Mistakes
Mistake #1: Assuming task-style $cast always fails gracefully
Calling $cast as a task means a failed cast produces a runtime error, not a silent, catchable failure. Why? If there's a real chance the cast might fail, calling $cast as a function and checking its return value avoids an unconditional runtime error appearing in the log.
Mistake #2: Assuming ordinary assignment is just as safe as $cast
As the "Without $cast" example shows, a plain assignment between mismatched types can behave completely differently across simulators — a hard compile error on one, a warning-but-still-works on another. Why? $cast gives consistent, well-defined behavior regardless of which simulator runs the code, instead of relying on how strictly each tool happens to enforce enum typing rules.
Mistake #3: Assuming a failed cast sets some special "invalid" value
As both failure examples show, a failed cast simply leaves the target variable completely unchanged. Why? There's no special sentinel value assigned on failure — whatever the variable held before the attempt (often its plain default value) is exactly what it still holds afterward.
Mistake #4: Assuming $cast only works with enums
The enum examples in this article are just the simplest illustration. Why? $cast is used just as commonly with class object handles, for safely recovering a specific derived type from a more generally-typed base class handle — a pattern covered in depth in SystemVerilog Polymorphism.
Practice Exercise
Challenge: Cast a Valid and an Invalid Value
Using the same Cents enum, write code that attempts $cast as a function for two different source expressions: one that equals DOLLAR (100), and one that equals 50 (which doesn't match any enum value). Print whether each cast passed or failed.
Hint
Follow the same if ($cast(...)) ... else ... pattern from the "$cast as a Function" example, just with two separate attempts instead of one.
Solution
typedef enum { PENNY=1, FIVECENTS=5, DIME=10, QUARTER=25, DOLLAR=100 } Cents;
module tb;
Cents myCent;
initial begin
if ($cast (myCent, 50 + 50))
$display ("Cast passed: %s", myCent.name());
else
$display ("Cast failed");
if ($cast (myCent, 50))
$display ("Cast passed: %s", myCent.name());
else
$display ("Cast failed");
end
endmodule
The first cast (50 + 50 = 100) succeeds, printing Cast passed: DOLLAR. The second (50) fails, since 50 doesn't match any of the enum's named values, printing Cast failed — and myCent stays at whatever DOLLAR left it at from the first successful cast, since a failed cast never changes the target.
Summary
In this tutorial, you learned:
$castis used when assigning between two different data types where ordinary assignment might not be valid- Called as a task, a failed cast produces a runtime error; called as a function, it silently returns 0 with no error, letting the code check the result itself
- A failed cast always leaves the target variable completely unchanged, never some special "invalid" value
- Relying on plain assignment instead of
$castbetween mismatched types can produce different behavior across different simulators $castapplies to class object handles too, not just enums — the same mechanism used for safe downcasting covered in SystemVerilog Polymorphism
Quiz
No quiz questions available for this article.