A unique constraint guarantees that a set of variables, or every element of an array, will all come out mutually distinct from one another after randomization. It's a far more concise way to express "no two of these should ever be equal" than writing out a pairwise != comparison between every possible pair by hand.
12 min read | Intermediate Level
What You'll Learn
- What
uniqueguarantees, for both an explicit list of variables and an array - Why
uniquecan makerandomize()fail outright when the legal range is too small for the number of values that need to be distinct - How
uniqueinteracts with other constraints that already pin some of the values - How to exclude a specific value from a
uniqueset using an auxiliary variable
Syntax
// A list of variables, all mutually distinct
constraint c_name { unique {var1, var2, var3}; }
// Every element of an array, all mutually distinct
constraint c_name { unique {array}; }
unique on a List of Variables
Combined with other constraints, unique narrows down exactly what's still possible for the remaining variables. Here, two of three variables sharing a 2-bit range are pinned to specific values:
class ABC;
rand bit [1:0] a, b, c;
constraint c_unique { unique {a, b, c}; }
constraint c_pin { a == 0; b == 1; }
endclass
With a fixed at 0 and b fixed at 1, unique requires c to differ from both — out of the four legal 2-bit values (0 through 3), only 2 and 3 remain available. c will always land on one of those two, chosen freely between them.
Quick Check
Q: If a third pinning constraint, c_pin2 { c == 2; }, were added to this same class, would anything about it be illegal?
Show Answer
No — c == 2 is one of the two values c was already free to take, so this simply removes the remaining choice, making the whole class fully deterministic: a=0, b=1, c=2, every single time.
unique on an Array
Applied to an array, every element must differ from every other element:
class ABC;
rand bit [1:0] arr[4];
constraint c_unique { unique {arr}; }
endclass
arr has exactly 4 elements, and a 2-bit element can only hold 4 possible values (0 through 3) — an exact match. This means arr is guaranteed to contain all four of those values, each exactly once, in some order — effectively a random permutation of {0, 1, 2, 3}.
Quick Check
Q: If arr were declared with only 3 elements instead of 4, keeping the same 2-bit element type, would every one of the 4 possible values (0–3) still appear somewhere in the array?
Show Answer
No. With only 3 elements needing to be mutually distinct out of 4 possible values, exactly one of the four values simply won't be used — unique only guarantees the elements present are distinct from each other, not that every legal value gets used.
When Uniqueness Becomes Impossible
If the number of items that need to be mutually distinct exceeds the number of values actually available, unique can never be satisfied — and randomize() fails every single time, regardless of seed:
class ABC;
rand bit a, b, c; // each is a single bit: only 0 or 1 possible
constraint c_unique { unique {a, b, c}; }
endclass
a, b, and c are each only 1 bit wide — just two possible values between them. Three variables can never be pairwise distinct when only two distinct values exist to assign — there's no seed, no amount of retrying, that makes this satisfiable. randomize() will fail on every call.
The exact same principle applies to arrays — a 5-element array of the same 2-bit type used earlier would also fail unconditionally, since only 4 distinct values exist for 5 elements that all need to differ.
Quick Check
Q: Would widening a, b, and c to 2 bits each (4 possible values) make the original three-variable example satisfiable?
Show Answer
Yes. With 4 possible values and only 3 variables needing to be mutually distinct, there's now room to spare — exactly one of the four legal values simply won't be used, the same situation as the 3-element array Quick Check above.
Excluding a Specific Value From unique
unique's own list can only hold variables, not a bare literal — so excluding one specific value from the set means adding an extra variable and pinning it to that value with its own constraint, rather than writing the literal directly inside the braces:
class ABC;
rand bit [1:0] a, b;
rand bit [1:0] excluded;
constraint c_unique { unique {a, b, excluded}; }
constraint c_exclude { excluded == 2'd2; }
endclass
Here, a and b both have to differ from excluded (pinned to 2), and from each other. Out of the four legal 2-bit values, only {0, 1, 3} remain available once 2 is excluded — a and b will always end up as two different values drawn from that remaining set of three.
Where Is This Used?
Generating a set of unique transaction IDs or tags for several outstanding, in-flight requests is a canonical use case — a protocol commonly requires that no two simultaneously active transactions share the same tag, and unique {tag_array} expresses that requirement directly, without hand-writing a pairwise comparison for every combination of outstanding requests.
Common Beginner Mistakes
Mistake #1: Assuming unique always succeeds regardless of range
As the pigeonhole example shows, it doesn't — if more distinct values are required than actually exist for the variable's type, randomize() fails every time. Why? Before reaching for unique, it's worth a quick sanity check that the type's range can actually hold enough distinct values for however many items need to be unique.
Mistake #2: Forgetting other constraints can narrow what's left for unique to work with
As the pinned-variable example shows, fixing some values ahead of time can shrink the pool unique has to draw from for the rest. Why? It's easy to reason about unique in isolation and forget that other active constraints are quietly removing options from the same shared range.
Mistake #3: Writing out pairwise != comparisons instead of using unique
unique {a, b, c} says the same thing as a != b; a != c; b != c;, just far more concisely — and it scales cleanly to arrays, where hand-writing every pairwise comparison would be impractical. Why? There's no downside to using unique whenever mutual distinctness is genuinely the requirement.
Mistake #4: Confusing unique with randc's cross-call behavior
unique only guarantees distinctness within the values produced by a single randomize() call — it says nothing about whether the same set of values might come up again on a later call. Why? That kind of no-repeat-across-calls guarantee is what randc provides instead, for a single variable cycling through its whole range before repeating — a genuinely different guarantee from what unique offers.
Practice Exercise
Challenge: Is It Satisfiable?
Given rand bit [2:0] tag[6]; and constraint c_unique { unique {tag}; }, is this satisfiable? If so, how many of the possible values would go unused? Then consider the same question if the array had 9 elements instead of 6.
Hint
Work out how many distinct values a 3-bit element can hold, and compare that against how many array elements need to be mutually distinct.
Solution
With 6 elements: satisfiable. A 3-bit element holds 8 possible values (0 through 7); with only 6 elements needing to be distinct, there's room to spare — exactly 8 - 6 = 2 values will go unused in any given result.
With 9 elements: impossible. 9 elements would need 9 mutually distinct values, but only 8 exist for a 3-bit type — the same pigeonhole failure demonstrated earlier in this article, just with different numbers. randomize() would fail on every call.
Summary
In this tutorial, you learned:
unique {var1, var2, ...}guarantees every listed variable is mutually distinct from every other;unique {array}applies the same guarantee to every element of an array- If more distinct values are required than a type's range can actually provide,
randomize()fails unconditionally, regardless of seed - Other active constraints can narrow the pool of values
uniquehas left to work with, sometimes down to just one remaining option - Excluding one specific value from a
uniqueset means adding an auxiliary variable and pinning it with its own constraint, not writing the literal directly inside the braces uniqueonly guarantees distinctness within a singlerandomize()call — it's unrelated torandc's guarantee of no repeats across multiple calls
A complete quick-reference for SystemVerilog. Covers every major language construct beyond Verilog — data types, always blocks, interfaces, classes, assertions, coverage, randomization, packages, and more. Designed for engineers who know Verilog and want to leverage the full power of SystemVerilog for both design and verification.
What SystemVerilog Adds to Verilog
SystemVerilog (IEEE 1800) is a superset of Verilog (IEEE 1364). Everything valid in Verilog is valid in SystemVerilog. This cheat sheet focuses on what SystemVerilog adds: improved data types, explicit always blocks, interfaces, packages, OOP for verification, constrained randomization, assertions, and functional coverage.
Data Types
Two-State vs Four-State
| Type | Width | Values | Signed? | Use |
|---|---|---|---|---|
logic | User-defined | 0, 1, x, z | Unsigned | Replaces both wire and reg |
reg | User-defined | 0, 1, x, z | Unsigned | Legacy — use logic instead |
integer | 32 | 0, 1, x, z | Signed | Legacy — use int instead |
bit | User-defined | 0, 1 | Unsigned | Two-state for testbench (faster simulation) |
byte | 8 | 0, 1 | Signed | Small signed integers |
shortint | 16 | 0, 1 | Signed | 16-bit signed |
int | 32 | 0, 1 | Signed | Loop variables, counters |
longint | 64 | 0, 1 | Signed | 64-bit signed |
real | 64 | float | — | Floating-point (not synthesizable) |
shortreal | 32 | float | — | 32-bit float (not synthesizable) |
string | Dynamic | chars | — | Text manipulation (not synthesizable) |
logic is the single most important SystemVerilog improvement. It replaces both wire and reg — you no longer need to think about which to use. Use logic everywhere except for signals with multiple drivers (which still need wire).
logic [7:0] data; // replaces both wire and reg
logic clk, rst_n;
bit [31:0] tb_counter; // two-state — faster in simulation
byte b = 8'hFF; // 8-bit signed
int i = -42; // 32-bit signed
longint l; // 64-bit signed
string s = "hello"; // dynamic string
Enumerations
// Basic enum (default type: int)
typedef enum {IDLE, RUN, DONE, ERROR} state_t;
state_t state, next_state;
// Explicit encoding
typedef enum logic [2:0] {
S_IDLE = 3'b001,
S_RUN = 3'b010,
S_DONE = 3'b100
} state_e;
// Enum methods
state.name(); // returns string: "IDLE"
state.next(); // next value in enumeration
state.prev(); // previous value
state.num(); // number of values in enum
state.first(); // first value
state.last(); // last value
For synthesizable FSMs, always specify the base type explicitly (e.g., enum logic [2:0]). This controls the encoding width and avoids synthesis warnings.
Structs & Unions
// Packed struct — maps to a contiguous bit vector (synthesizable)
typedef struct packed {
logic [3:0] opcode;
logic [11:0] address;
logic [7:0] data;
} instruction_t; // total: 24 bits
instruction_t instr;
assign instr.opcode = 4'hA;
assign instr.address = 12'h100;
logic [23:0] raw = instr; // can cast to plain vector
// Unpacked struct — fields may have gaps (for testbench modeling)
typedef struct {
int id;
string name;
real score;
} student_t;
// Packed union — all members share same bits
typedef union packed {
logic [31:0] word;
logic [3:0][7:0] bytes; // 4 bytes
struct packed {
logic [15:0] upper;
logic [15:0] lower;
} halves;
} word_u;
word_u w;
w.word = 32'hDEAD_BEEF;
// w.bytes[3] == 8'hDE, w.halves.lower == 16'hBEEF
Use packed structs/unions for synthesizable RTL. Unpacked structs are for verification only — they cannot map to a bit vector.
typedef
typedef logic [7:0] byte_t;
typedef logic [31:0] word_t;
typedef logic [15:0] addr_t;
// Parameterized types (via macros or packages)
typedef struct packed {
addr_t addr;
word_t data;
logic valid;
} bus_req_t;
Arrays — Fixed, Dynamic, Associative, Queues
// Packed array — contiguous bits (synthesizable)
logic [3:0][7:0] packed_arr; // 32 bits: 4 bytes packed together
// Unpacked fixed-size array (synthesizable)
logic [7:0] mem [0:255]; // 256 entries of 8 bits
logic [7:0] rom [256]; // same thing — shorthand
// Multidimensional
logic [7:0] matrix [4][4];
// Dynamic array (not synthesizable — verification)
int dyn[];
initial begin
dyn = new[10]; // allocate 10 elements
dyn = new[20](dyn); // resize, preserve contents
dyn.delete(); // free
end
// Associative array (not synthesizable — verification)
int lookup [string]; // string-indexed
int sparse [int]; // integer-indexed
initial begin
lookup["alpha"] = 1;
lookup["beta"] = 2;
if (lookup.exists("alpha")) $display("found");
lookup.delete("beta");
end
// Queue (not synthesizable — verification)
int q [$]; // unbounded queue
int bq [$:255]; // bounded queue (max 256 entries)
initial begin
int val, sz;
q.push_back(10); // append
q.push_front(5); // prepend
val = q.pop_front(); // remove & return first
q.insert(1, 7); // insert at index 1
q.delete(0); // delete index 0
sz = q.size(); // current size
end
Array Manipulation Methods
int arr[] = '{3, 1, 4, 1, 5, 9};
// Locator methods — return queues
int q[$];
q = arr.find with (item > 3); // {4, 5, 9}
q = arr.find_index with (item == 1); // {1, 3}
q = arr.find_first with (item > 4); // {5}
q = arr.find_last with (item > 4); // {9}
q = arr.min(); // {1}
q = arr.max(); // {9}
q = arr.unique(); // {3, 1, 4, 5, 9}
// Reduction methods
int s = arr.sum(); // 23
int p = arr.product(); // 540
// Ordering
arr.sort(); // ascending
arr.rsort(); // descending
arr.reverse(); // reverse order
arr.shuffle(); // randomize order
Strings
string s = "Hello";
int len = s.len(); // 5
s = {s, " World"}; // concatenation: "Hello World"
string up = s.toupper(); // "HELLO WORLD"
string lo = s.tolower(); // "hello world"
byte c = s.getc(0); // 'H' (ASCII 72)
s.putc(0, "h"); // "hello World"
string sub = s.substr(0, 4); // "hello"
int idx = s.atoi(); // string to integer
s.itoa(42); // integer to string
Casting & Type Conversions
// Static cast — compile-time check
int i = int'(3.14); // real → int: 3
logic [7:0] b = 8'(some_wider_signal); // truncate
logic signed [7:0] sb = signed'(b); // unsigned → signed
// Cast between enum and int
state_e s = state_e'(3); // int → enum
// $cast — dynamic cast with runtime check (returns 1 on success)
if (!$cast(child_handle, base_handle))
$error("Cast failed");
// Type query
$typename(variable) // returns type name as string (for debug)
$bits(type_or_expr) // number of bits
Packages
// Definition
package bus_pkg;
typedef enum logic [1:0] {READ, WRITE, IDLE} cmd_e;
typedef struct packed {
cmd_e cmd;
logic [15:0] addr;
logic [31:0] data;
} bus_req_t;
parameter int BUS_WIDTH = 32;
function automatic logic [3:0] encode(input logic [15:0] val);
return val[3:0] ^ val[7:4];
endfunction
endpackage
// Usage — wildcard import (most common)
import bus_pkg::*;
// Usage — explicit import
import bus_pkg::bus_req_t;
import bus_pkg::BUS_WIDTH;
// Usage — fully qualified (no import needed)
bus_pkg::cmd_e my_cmd;
Use packages for shared types, parameters, and utility functions. Wildcard import (::*) is convenient but explicit imports are safer in large projects to avoid name collisions.
Module Declaration — SystemVerilog Style
module my_module
import bus_pkg::*; // package import before ports
#(
parameter int WIDTH = 8,
parameter int DEPTH = 16,
parameter type DATA_T = logic [7:0] // parameterized type
)(
input logic clk,
input logic rst_n,
input DATA_T data_in,
output DATA_T data_out,
output logic valid
);
localparam int ADDR_W = $clog2(DEPTH);
// ...
endmodule
Implicit Port Connections
// .* — connect all ports by matching name (SystemVerilog)
my_module u_mod (
.clk, // .name is shorthand for .name(name)
.rst_n,
.data_in (fifo_data), // explicit when names differ
.data_out,
.valid
);
// Or even shorter with .*
my_module u_mod (
.*, // connect all matching names automatically
.data_in (fifo_data) // override specific ports
);
.* is powerful but dangerous — it silently connects signals you may not intend. Use with caution in large designs. Explicit connections are safer for RTL; .* is fine in testbenches.
Always Blocks — Explicit Intent
| Block | Purpose | Assignment | Sensitivity |
|---|---|---|---|
always_comb | Combinational logic | = (blocking) | Automatic (all reads) |
always_ff | Sequential logic (flip-flops) | <= (non-blocking) | Explicit edge list |
always_latch | Intentional latches | = (blocking) | Automatic |
// Combinational — replaces always @(*)
always_comb begin
y = a & b; // tool warns if latch is inferred
case (sel)
2'b00: out = in_a;
2'b01: out = in_b;
default: out = '0;
endcase
end
// Sequential — synchronous reset
always_ff @(posedge clk) begin
if (!rst_n) q <= '0;
else q <= d;
end
// Sequential — asynchronous reset
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) q <= '0;
else q <= d;
end
// Intentional latch (rare — makes intent clear)
always_latch begin
if (enable) q = d;
// no else — intentionally latching
end
Always use always_comb, always_ff, and always_latch instead of the old always. Tools check the intent of each block: they should warn when an always_comb infers a latch or when an always_ff does not describe sequential logic. This catches bugs at compile time.
unique, priority, and Enhanced case/if
// unique — asserts all cases are mutually exclusive (no overlap)
// and that one case always matches (full)
always_comb begin
unique case (sel)
2'b00: y = a;
2'b01: y = b;
2'b10: y = c;
2'b11: y = d;
endcase
end
// priority — asserts at least one case matches (full)
// but allows overlap (first match wins)
always_comb begin
priority case (1'b1)
req[3]: grant = 4'b1000;
req[2]: grant = 4'b0100;
req[1]: grant = 4'b0010;
req[0]: grant = 4'b0001;
default: grant = 4'b0000;
endcase
end
// unique if / priority if
always_comb begin
unique if (sel == 2'b00) y = a;
else if (sel == 2'b01) y = b;
else if (sel == 2'b10) y = c;
else y = d;
end
always_comb begin
priority if (req[3]) grant = 4'b1000;
else if (req[2]) grant = 4'b0100;
else if (req[1]) grant = 4'b0010;
else if (req[0]) grant = 4'b0001;
else grant = 4'b0000;
end
| Keyword | Full? | Parallel? | Simulation Check |
|---|---|---|---|
unique | Yes | Yes | Warns if no match or multiple matches |
unique0 | No | Yes | Warns only on multiple matches |
priority | Yes | No | Warns if no match |
| (none) | No | No | No runtime checks |
Use unique case for one-hot muxes and decoders. Use priority case or priority if for priority encoders. These replace the unreliable Verilog full_case/parallel_case pragmas with proper language semantics and runtime checks.
Interfaces
// Interface definition
interface axi_lite_if #(
parameter int ADDR_W = 32,
parameter int DATA_W = 32
)(
input logic clk,
input logic rst_n
);
logic [ADDR_W-1:0] awaddr;
logic awvalid;
logic awready;
logic [DATA_W-1:0] wdata;
logic wvalid;
logic wready;
logic [1:0] bresp;
logic bvalid;
logic bready;
// Modport — defines port directions from each perspective
modport master (
input clk, rst_n,
output awaddr, awvalid, wdata, wvalid, bready,
input awready, wready, bresp, bvalid
);
modport slave (
input clk, rst_n,
input awaddr, awvalid, wdata, wvalid, bready,
output awready, wready, bresp, bvalid
);
modport monitor (
input clk, rst_n,
input awaddr, awvalid, awready,
wdata, wvalid, wready,
bresp, bvalid, bready
);
endinterface
// Module using interface
module axi_slave (
axi_lite_if.slave bus // interface with modport
);
always_ff @(posedge bus.clk or negedge bus.rst_n) begin
if (!bus.rst_n) begin
bus.awready <= 1'b0;
end else begin
bus.awready <= bus.awvalid & ~bus.awready;
end
end
endmodule
// Top-level instantiation
module top;
logic clk, rst_n;
axi_lite_if #(.ADDR_W(16)) u_bus (.clk, .rst_n);
axi_master u_master (.bus(u_bus.master));
axi_slave u_slave (.bus(u_bus.slave));
endmodule
Interfaces bundle related signals into a single port, reducing port list verbosity and connection errors. Use modport to enforce correct signal directions for each connected module.
Clocking Blocks
// Clocking block — defines timing for testbench signal access
interface bus_if (input logic clk);
logic [7:0] data;
logic valid;
logic ready;
clocking driver_cb @(posedge clk);
default input #1step output #0; // sample before edge, drive at edge
output data;
output valid;
input ready;
endclocking
clocking monitor_cb @(posedge clk);
default input #1step;
input data;
input valid;
input ready;
endclocking
modport driver (clocking driver_cb);
modport monitor (clocking monitor_cb);
endinterface
// Usage in testbench
task automatic drive(virtual bus_if.driver drv);
drv.driver_cb.data <= 8'hAB;
drv.driver_cb.valid <= 1'b1;
@(drv.driver_cb); // wait one clock cycle
wait (drv.driver_cb.ready == 1);
drv.driver_cb.valid <= 1'b0;
endtask
Clocking blocks eliminate timing races in testbenches by defining exact sample/drive times relative to the clock edge. Always use them in UVM drivers and monitors.
Tasks & Functions — Enhanced
// Functions in a module are static by default - add "automatic" for per-call storage
function automatic int max(int a, int b);
return (a > b) ? a : b; // 'return' statement (new)
endfunction
// void function — no return value
function void print_hex(logic [31:0] val);
$display("0x%08h", val);
endfunction
// Default argument values
function automatic int clamp(int val, int lo = 0, int hi = 255);
if (val < lo) return lo;
if (val > hi) return hi;
return val;
endfunction
int x = clamp(300); // uses defaults: lo=0, hi=255 → returns 255
int y = clamp(50, .hi(100)); // named argument: lo=0, hi=100
// ref arguments — pass by reference (like C++ &)
function automatic void swap(ref int a, ref int b);
int temp = a;
a = b;
b = temp;
endfunction
// Tasks - no return value; results go through output, inout or ref arguments
task automatic drive_burst(
ref logic [7:0] bus,
input int count,
input logic [7:0] data[]
);
for (int i = 0; i < count; i++) begin
@(posedge clk);
bus = data[i]; // a ref argument can't be written with <=
end
endtask
Function vs Task (SystemVerilog Updates)
| Feature | Function | Task |
|---|---|---|
Timing controls (#, @) | No | Yes |
| Return value | Single value or void | None - results go through output, inout or ref arguments |
| Can call tasks | No | Yes |
ref arguments | Yes | Yes |
| Default arguments | Yes | Yes |
| Synthesizable | Yes (combinational) | Only if no timing |
Processes & Fork/Join
// fork...join — all threads must complete before continuing
fork
begin : thread_a
#10 $display("A done");
end
begin : thread_b
#20 $display("B done");
end
join // waits for both threads (resumes at t=20)
// fork...join_any — continue when ANY thread completes
fork
begin #10 $display("fast"); end
begin #50 $display("slow"); end
join_any // resumes at t=10 (slow thread still running)
// fork...join_none — launch threads and continue immediately
fork
begin #10 $display("background"); end
join_none // continues immediately, thread runs in background
// Controlling threads
disable fork; // kill all child threads of current process
// wait fork — wait for all forked threads to complete
fork
task_a();
task_b();
join_none
// ... do other work ...
wait fork; // block until task_a and task_b both finish
disable fork kills ALL child threads, including those from outer scopes. To limit scope, wrap the fork in a named begin...end block and disable that block instead.
Classes (OOP for Verification)
class Transaction;
// Properties
rand bit [7:0] addr; // randomizable
rand bit [31:0] data;
randc bit [3:0] id; // cyclic random — covers all values before repeating
bit is_write;
static int count = 0; // shared across all instances
// Constraints
constraint addr_range { addr inside {[8'h00:8'h7F]}; }
constraint data_align { data[1:0] == 2'b00; }
// Constructor
function new(bit is_write = 0);
this.is_write = is_write;
count++;
endfunction
// Methods
function void display();
$display("Txn id=%0d addr=0x%02h data=0x%08h wr=%0b",
id, addr, data, is_write);
endfunction
// Virtual method — can be overridden by subclass
virtual function bit is_valid();
return (addr != '0);
endfunction
// Copy
function Transaction copy();
Transaction t = new();
t.addr = this.addr;
t.data = this.data;
t.id = this.id;
t.is_write = this.is_write;
return t;
endfunction
endclass
// Inheritance
class WriteTransaction extends Transaction;
rand bit [3:0] byte_enable;
constraint be_valid { $countones(byte_enable) inside {1, 2, 4}; }
function new();
super.new(1); // call parent constructor
endfunction
// Override virtual method
function bit is_valid();
return (super.is_valid() && byte_enable != 0);
endfunction
endclass
// Usage
Transaction t = new();
t.randomize(); // randomize with constraints
t.display();
WriteTransaction wt = new();
wt.randomize() with { addr < 8'h40; }; // inline constraint
Polymorphism
// Virtual methods enable polymorphism
Transaction t;
WriteTransaction wt = new();
t = wt; // parent handle pointing to child object
t.is_valid(); // calls WriteTransaction::is_valid() (virtual dispatch)
// $cast for downcasting
WriteTransaction wt2;
if ($cast(wt2, t)) // runtime check: is t actually a WriteTransaction?
wt2.byte_enable = 4'hF;
Parameterized Classes
class Stack #(type T = int, int DEPTH = 32);
T data[$:DEPTH-1];
function void push(T val);
if (data.size() < DEPTH) data.push_back(val);
endfunction
function T pop();
return data.pop_front();
endfunction
function int size();
return data.size();
endfunction
endclass
Stack #(bit [7:0], 64) byte_stack = new();
Stack #(Transaction) txn_stack = new();
Constrained Randomization
class Packet;
rand bit [7:0] length;
rand bit [15:0] addr;
rand bit [7:0] payload[];
randc bit [2:0] channel; // cyclic — all values visited before repeat
// Simple constraints
constraint len_range { length inside {[1:64]}; }
constraint addr_align { addr[1:0] == 2'b00; } // 4-byte aligned
constraint payload_sz { payload.size() == length; }
// Weighted distribution
constraint len_dist {
length dist {
[1:8] := 50, // equal weight per value in range
[9:32] :/ 30, // weight divided among values in range
[33:64] := 20
};
}
// Implication
constraint wr_addr {
(channel == 0) -> addr inside {[16'h0000:16'h0FFF]};
}
// Conditional constraint
constraint cond_c {
if (length > 32) addr > 16'h1000;
else addr < 16'h1000;
}
// Foreach on arrays
constraint ordered {
foreach (payload[i])
if (i > 0) payload[i] >= payload[i-1];
}
// Solve order — control randomization order
constraint order { solve length before addr; }
endclass
// Randomization calls
Packet p = new();
assert(p.randomize()); // basic randomize
assert(p.randomize() with { // inline constraints (added on top)
length < 16;
addr == 16'h0100;
});
// Constraint control
p.constraint_mode(0); // disable ALL constraints
p.len_range.constraint_mode(0); // disable specific constraint
p.rand_mode(0); // disable ALL randomization
p.addr.rand_mode(0); // disable specific field randomization
// Pre/post randomize callbacks
class SmartPacket extends Packet;
function void pre_randomize();
// called before randomize()
endfunction
function void post_randomize();
// called after randomize() — compute CRC, etc.
endfunction
endclass
Assertions (SVA)
Immediate Assertions
// Simple immediate assertion — checked procedurally
always_comb begin
assert (state != ILLEGAL_STATE) else $error("Illegal state reached");
end
// With action blocks
always_ff @(posedge clk) begin
assert (fifo_count <= DEPTH)
$display("FIFO OK, count=%0d", fifo_count); // pass action
else
$fatal(1, "FIFO overflow! count=%0d", fifo_count); // fail action
end
// Deferred assertion — checked at end of time step (avoids glitches)
always_comb begin
assert #0 (onehot(grant)) else $error("Grant not one-hot");
end
Concurrent Assertions
// Property — a reusable temporal expression
property p_req_ack;
@(posedge clk) disable iff (!rst_n)
req |-> ##[1:3] ack; // if req, ack must come within 1-3 cycles
endproperty
assert property (p_req_ack)
else $error("Req not acknowledged within 3 cycles");
// Sequence — a pattern of events over time
sequence s_handshake;
req ##1 ack ##1 !req ##1 !ack; // four-cycle handshake
endsequence
property p_handshake;
@(posedge clk) disable iff (!rst_n)
req |-> s_handshake;
endproperty
assert property (p_handshake);
SVA Operators
| Operator | Meaning | Example |
|---|---|---|
##N | Delay N cycles | a ##2 b — a, then b 2 cycles later |
##[M:N] | Delay range | a ##[1:3] b — b within 1-3 cycles |
|-> | Overlapping implication | a |-> b — if a, b must hold same cycle |
|=> | Non-overlapping implication | a |=> b — if a, b must hold next cycle |
[*N] | Consecutive repetition | a[*3] — a for 3 consecutive cycles |
[*M:N] | Repetition range | a[*1:3] — a for 1 to 3 cycles |
[->N] | Goto repetition | a[->3] — 3rd occurrence of a |
[=N] | Non-consecutive repetition | a[=3] — a occurs 3 times (not necessarily consecutive) |
not | Property negation | not (a |-> b) |
$rose() | Signal rose this cycle | $rose(req) |
$fell() | Signal fell this cycle | $fell(ack) |
$stable() | Signal unchanged | $stable(data) |
$past() | Value in previous cycle | $past(data, 2) — value 2 cycles ago |
$onehot() | Exactly one bit set | $onehot(grant) |
$onehot0() | Zero or one bit set | $onehot0(req) |
$countones() | Count set bits | $countones(mask) |
Common Assertion Patterns
// Request must be acknowledged
assert property (@(posedge clk) disable iff (!rst_n)
req |-> ##[1:5] ack
);
// Signal must be stable while valid
assert property (@(posedge clk) disable iff (!rst_n)
valid |-> $stable(data)
);
// Two signals are mutually exclusive
assert property (@(posedge clk) disable iff (!rst_n)
not (signal_a && signal_b)
);
// Data must change after write
assert property (@(posedge clk) disable iff (!rst_n)
(wr_en && addr == TARGET) |=> (rdata == $past(wdata))
);
// No back-to-back requests
assert property (@(posedge clk) disable iff (!rst_n)
req |=> !req
);
// Cover — check that a scenario CAN occur (not that it must)
cover property (@(posedge clk) req ##1 ack);
// Assume — constrain inputs in formal verification
assume property (@(posedge clk) $onehot0(req));
Functional Coverage
// Covergroup — tracks value coverage during simulation
covergroup cg_bus @(posedge clk);
option.per_instance = 1;
// Coverpoint — which values were seen
cp_addr: coverpoint addr {
bins low = {[0:63]};
bins mid = {[64:191]};
bins high = {[192:255]};
bins zero = {0};
illegal_bins reserved = {[240:255]}; // error if hit
ignore_bins unused = {[200:239]}; // don't count
}
cp_cmd: coverpoint cmd {
bins read = {READ};
bins write = {WRITE};
}
cp_len: coverpoint length {
bins short_pkt = {[1:8]};
bins medium_pkt = {[9:32]};
bins long_pkt = {[33:64]};
bins powers[] = {1, 2, 4, 8, 16, 32, 64}; // one bin per value
}
// Cross coverage — combinations of coverpoints
addr_x_cmd: cross cp_addr, cp_cmd;
// Transition coverage
cp_state: coverpoint state {
bins idle_to_run = (IDLE => RUN);
bins run_to_done = (RUN => DONE);
bins any_to_idle = (RUN, DONE => IDLE);
}
endgroup
// Instantiate and sample
cg_bus bus_cov = new();
// Explicit sampling (alternative to automatic @(posedge clk))
covergroup cg_txn;
coverpoint txn.addr;
coverpoint txn.data;
endgroup
cg_txn txn_cov = new();
// ... later ...
txn_cov.sample(); // manually trigger sampling
// Query coverage
$display("Coverage: %.1f%%", bus_cov.get_coverage());
Processes & Synchronization
Events
event done;
event error;
// Trigger
-> done; // trigger event (non-blocking)
->> done; // non-blocking trigger (for use in always_ff)
// Wait
@(done); // wait for trigger
wait(done.triggered); // level-sensitive — doesn't miss same-timestep trigger
Mailboxes
// Typed mailbox — thread-safe FIFO
mailbox #(Transaction) mbx = new(16); // bounded: max 16 entries
mailbox #(Transaction) ubx = new(); // unbounded
// Producer
Transaction t = new();
t.randomize();
mbx.put(t); // blocking if full
mbx.try_put(t); // non-blocking, returns 0 if full
// Consumer
Transaction rx;
mbx.get(rx); // blocking if empty
mbx.try_get(rx); // non-blocking, returns 0 if empty
mbx.peek(rx); // get without removing
int n = mbx.num(); // number of entries
Semaphores
semaphore sem = new(1); // 1 key = mutex
// Acquire
sem.get(1); // blocking — wait for key
sem.try_get(1); // non-blocking, returns 0 if unavailable
// Release
sem.put(1); // return key
// Example: mutual exclusion
task automatic critical_section();
sem.get(1);
// ... exclusive access ...
sem.put(1);
endtask
Virtual Interfaces
// Virtual interface — a handle to an interface instance
// Allows class-based testbenches to drive/sample physical signals
class Driver;
virtual axi_lite_if vif; // virtual interface handle
function new(virtual axi_lite_if vif);
this.vif = vif;
endfunction
task run();
forever begin
@(posedge vif.clk);
vif.awaddr <= txn.addr;
vif.awvalid <= 1'b1;
@(posedge vif.clk iff vif.awready);
vif.awvalid <= 1'b0;
end
endtask
endclass
// In testbench top
module tb;
logic clk, rst_n;
axi_lite_if u_if (.clk, .rst_n);
axi_slave dut (.bus(u_if.slave));
Driver drv = new(u_if); // pass interface to class
initial drv.run();
endmodule
Classes cannot have ports, so virtual interface is the bridge between class-based verification (OOP) and the signal-level world of modules. Every UVM component uses virtual interfaces to access DUT signals.
Program Block
// program — separates testbench from DUT timing
// Executes in the "reactive" region (after all design updates)
program automatic test (
input logic clk,
bus_if.driver drv_if
);
initial begin
repeat (10) @(posedge clk);
drv_if.driver_cb.data <= 8'hAB;
drv_if.driver_cb.valid <= 1'b1;
@(drv_if.driver_cb);
drv_if.driver_cb.valid <= 1'b0;
$display("Test complete");
end
endprogram
The program block avoids race conditions by scheduling testbench code in the Reactive region, after all RTL always blocks have executed. In UVM-based flows, program blocks are less common since UVM handles phasing internally.
Generate Blocks — SystemVerilog Style
// generate/endgenerate keywords are optional in SystemVerilog
// Loop generate
for (genvar g = 0; g < N; g++) begin : stage
assign pipe[g+1] = pipe[g] & enable[g];
end
// Conditional generate
if (USE_PARITY) begin : gen_par
parity_checker u_par (.data(bus), .par(par_bit));
end else begin : gen_nopar
assign par_ok = 1'b1;
end
// Case generate
case (IMPL)
"FAST": fast_adder u_add (.*);
"SMALL": small_adder u_add (.*);
default: basic_adder u_add (.*);
endcase
Loops — Enhanced
// C-style for loop (declare loop variable inline)
always_comb begin
parity = 1'b0;
for (int i = 0; i < 8; i++) begin
parity ^= data[i];
end
end
// foreach — iterate over arrays
int arr[4] = '{10, 20, 30, 40};
foreach (arr[i]) begin
$display("arr[%0d] = %0d", i, arr[i]);
end
// foreach on multidimensional arrays
int matrix[3][4];
foreach (matrix[i, j]) begin
matrix[i][j] = i * 4 + j;
end
// do...while
int count = 0;
do begin
// body executes at least once
count++;
end while (count < 10);
// break and continue
for (int i = 0; i < 100; i++) begin
if (skip_condition) continue; // skip rest of this iteration
if (stop_condition) break; // exit loop entirely
// ...
end
System Tasks & Functions — SystemVerilog Additions
Severity System Tasks
$info("Informational message"); // severity: info
$warning("Something unusual: %0d", val); // severity: warning
$error("Protocol violation at %0t", $time); // severity: error
$fatal(1, "Unrecoverable: FIFO overflow"); // severity: fatal (stops simulation)
// $fatal first argument sets the diagnostic level (0 prints nothing, 1 time and location, 2 adds statistics); the simulation always finishes
Array Query Functions
int arr[4][8];
$dimensions(arr) // 2 (number of dimensions)
$left(arr, 1) // 0 (left bound of dimension 1)
$right(arr, 1) // 3 (right bound of dimension 1)
$low(arr, 1) // 0
$high(arr, 1) // 3
$size(arr, 1) // 4 (size of dimension 1)
$increment(arr, 1) // 1 or -1 depending on range direction
$bits(arr) // total bits
Type & Conversion
$typename(var) // returns type name as string
$itor(int_val) // integer to real
$rtoi(real_val) // real to integer
$signed(val) // cast to signed
$unsigned(val) // cast to unsigned
$bitstoreal(bits) // bit pattern to real
$realtobits(r) // real to bit pattern
Direct Programming Interface (DPI)
// Import C function into SystemVerilog
import "DPI-C" function int c_sqrt(input int val);
import "DPI-C" function void c_print(input string msg);
import "DPI-C" context function void c_callback();
// Export SystemVerilog function to C
export "DPI-C" function sv_get_data;
function int sv_get_data(input int addr);
return mem[addr];
endfunction
// Usage
initial begin
int result = c_sqrt(144); // calls C function
$display("sqrt(144) = %0d", result);
end
DPI enables calling C/C++ functions from SystemVerilog and vice versa. Use it for complex math, file parsing, or connecting to external models. The context keyword allows the C function to call back into SystemVerilog.
Compiler Directives — Additions
// Same as Verilog, plus:
`begin_keywords "1800-2012" // restrict to specific SV version keywords
`end_keywords
`__FILE__ // current filename (string)
`__LINE__ // current line number (integer)
`pragma protect begin // IP encryption
`pragma protect end
Common RTL Patterns — SystemVerilog Style
FSM with Enum
typedef enum logic [1:0] {
IDLE = 2'b00,
RUN = 2'b01,
DONE = 2'b10
} state_e;
state_e state, next_state;
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) state <= IDLE;
else state <= next_state;
end
always_comb begin
next_state = state;
busy = 1'b0;
valid = 1'b0;
unique case (state)
IDLE: if (start) next_state = RUN;
RUN: begin
busy = 1'b1;
if (done) next_state = DONE;
end
DONE: begin
valid = 1'b1;
next_state = IDLE;
end
default: next_state = IDLE;
endcase
end
Parameterized FIFO
module sync_fifo #(
parameter type DATA_T = logic [7:0],
parameter int DEPTH = 16
)(
input logic clk,
input logic rst_n,
input logic wr_en,
input DATA_T wr_data,
input logic rd_en,
output DATA_T rd_data,
output logic full,
output logic empty
);
localparam int ADDR_W = $clog2(DEPTH);
DATA_T mem [DEPTH];
logic [ADDR_W:0] wr_ptr, rd_ptr; // extra bit for full/empty
assign full = (wr_ptr[ADDR_W] != rd_ptr[ADDR_W]) &&
(wr_ptr[ADDR_W-1:0] == rd_ptr[ADDR_W-1:0]);
assign empty = (wr_ptr == rd_ptr);
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
wr_ptr <= '0;
rd_ptr <= '0;
end else begin
if (wr_en && !full) begin
mem[wr_ptr[ADDR_W-1:0]] <= wr_data;
wr_ptr <= wr_ptr + 1'b1;
end
if (rd_en && !empty) begin
rd_ptr <= rd_ptr + 1'b1;
end
end
end
assign rd_data = mem[rd_ptr[ADDR_W-1:0]];
endmodule
AXI-Style Handshake
// Valid/ready handshake — transfer occurs when both asserted
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
valid <= 1'b0;
data <= '0;
end else if (valid && ready) begin
// Transfer accepted — load next
valid <= next_valid;
data <= next_data;
end else if (!valid) begin
// Load new data when idle
valid <= next_valid;
data <= next_data;
end
end
// Assertion to verify protocol
assert property (@(posedge clk) disable iff (!rst_n)
valid && !ready |=> valid && $stable(data)
) else $error("Valid data changed without ready");
Packed Struct Bus
package bus_pkg;
typedef enum logic [1:0] {
CMD_READ = 2'b00,
CMD_WRITE = 2'b01,
CMD_NOP = 2'b10
} cmd_e;
typedef struct packed {
cmd_e cmd;
logic [15:0] addr;
logic [31:0] data;
logic [3:0] strobe;
} bus_req_t;
typedef struct packed {
logic [31:0] data;
logic [1:0] resp;
logic valid;
} bus_resp_t;
endpackage
module bus_master
import bus_pkg::*;
(
output bus_req_t req,
input bus_resp_t resp
);
always_comb begin
req.cmd = CMD_WRITE;
req.addr = 16'h1000;
req.data = 32'hDEAD_BEEF;
req.strobe = 4'hF;
end
endmodule
Edge Detector (SystemVerilog Style)
logic sig_q;
always_ff @(posedge clk) sig_q <= sig;
logic rising; assign rising = sig & ~sig_q;
logic falling; assign falling = ~sig & sig_q;
// Or use $rose/$fell in assertions and procedural code
always_ff @(posedge clk)
if ($rose(sig)) count <= count + 1;
UVM Essentials (Quick Reference)
SystemVerilog classes power the Universal Verification Methodology. Here are the key building blocks.
UVM Component Hierarchy
| Class | Purpose |
|---|---|
uvm_test | Top-level test — configures the environment |
uvm_env | Contains agents, scoreboards, coverage |
uvm_agent | Contains driver, monitor, sequencer |
uvm_driver | Drives stimulus onto DUT interface |
uvm_monitor | Observes DUT interface passively |
uvm_sequencer | Routes sequence items to driver |
uvm_sequence | Generates sequence items (stimulus) |
uvm_sequence_item | Transaction-level data object |
uvm_scoreboard | Checks DUT output against expected |
Minimal UVM Skeleton
// Sequence item
class my_txn extends uvm_sequence_item;
`uvm_object_utils(my_txn)
rand bit [7:0] addr;
rand bit [31:0] data;
function new(string name = "my_txn");
super.new(name);
endfunction
endclass
// Sequence
class my_seq extends uvm_sequence #(my_txn);
`uvm_object_utils(my_seq)
function new(string name = "my_seq");
super.new(name);
endfunction
task body();
my_txn txn;
repeat (10) begin
txn = my_txn::type_id::create("txn");
start_item(txn);
assert(txn.randomize());
finish_item(txn);
end
endtask
endclass
// Driver
class my_driver extends uvm_driver #(my_txn);
`uvm_component_utils(my_driver)
virtual bus_if vif;
function new(string name, uvm_component parent);
super.new(name, parent);
endfunction
task run_phase(uvm_phase phase);
forever begin
seq_item_port.get_next_item(req);
// drive signals via vif
@(posedge vif.clk);
vif.addr <= req.addr;
vif.data <= req.data;
@(posedge vif.clk);
seq_item_port.item_done();
end
endtask
endclass
Synthesis Golden Rules — SystemVerilog Edition
- Use
logicinstead ofwire/reg— except for multi-driver nets - Use
always_comb,always_ff,always_latch— never plainalways - Use
=inalways_comb,<=inalways_ff— the convention that lint tools check - Use
unique caseorpriority case— replacesfull_case/parallel_case - Use
typedef enum logic [N:0]for FSM states — explicit encoding width - Use packed structs for bus bundles — cleaner than raw vectors
- Use packages for shared types and parameters — avoid
`defines - Use interfaces for complex bus protocols — reduce port clutter
- Use
$clog2()for address widths - Use
'0,'1,'x,'zfor context-width fill `default_nettype noneat the top of every file- One module per file, filename matches module name
What Is Synthesizable?
| Feature | Synthesizable? | Notes |
|---|---|---|
logic, wire, packed structs/unions | Yes | Core RTL types |
enum, typedef | Yes | Use for FSMs, type clarity |
always_comb, always_ff, always_latch | Yes | Preferred over always |
unique/priority case/if | Yes | Synthesis directives + runtime checks |
| Interfaces & modports | Yes | Major synthesis tools support |
| Packages | Yes | Types, parameters, functions |
| Generate blocks | Yes | Parameterized hardware |
Inline variable declarations (for (int i...)) | Yes | C-style loops |
bit, int, byte, shortint | Partial | Some tools support; prefer logic in RTL |
Assertions (assert property) | Ignored | Stripped by synthesis, valuable for formal |
| Classes, dynamic arrays, queues, strings | No | Verification only |
| Randomization, coverage, mailboxes, semaphores | No | Verification only |
DPI, program block | No | Simulation/verification only |
Common Pitfalls
| Mistake | Result | Fix |
|---|---|---|
Using int/bit in RTL ports | Two-state: no x-propagation | Use logic for RTL signals |
| Unpacked struct on port | Tool-specific behavior | Use packed structs for RTL ports |
Missing unique/priority | No synthesis/sim checks | Annotate every case statement |
logic with multiple drivers | Compile error | Use wire for tri-state/multi-driver |
| Enum without explicit width | Defaults to int (32-bit) | Use enum logic [N:0] |
Blocking in always_ff | Legal, but flagged by lint and prone to race conditions | Use <= non-blocking |
Using always @(*) in SV | No latch checking | Use always_comb |
Forgetting disable iff in assertions | False failures during reset | Always add disable iff (!rst_n) |
An interface can be parameterized the same way a module can — letting the same interface definition adapt its signal widths, depths, or other configuration to whatever design it's connected to, instead of writing a separate interface for every bus width you need to support.
6 min read | Intermediate Level
What You'll Learn
- The basic syntax for declaring a parameter on an interface
- How to override a parameter's default value at instantiation
- How to connect a parameterized interface to a design that shares the same parameter
- What happens when an interface's parameter and a design's parameter don't match
Basic Syntax
A parameter is declared the same way you would for a module — between #( and ), right after the interface name:
interface myBus #(parameter D_WIDTH=31) (input clk);
logic [D_WIDTH-1:0] data;
logic enable;
endinterface
D_WIDTH defaults to 31 here, so data ([D_WIDTH-1:0], or [30:0]) is 31 bits wide unless something overrides it.
Overriding the Default at Instantiation
Just like a module, an interface's parameter is overridden with #(...) at the point of instantiation:
module tb;
logic clk;
// Uses the default: D_WIDTH = 31, so data is 31 bits wide
myBus bus_default (clk);
// Overrides D_WIDTH to 8, so data is only 8 bits wide
myBus #(.D_WIDTH(8)) bus_narrow (clk);
endmodule
bus_default keeps the interface's own default of 31, giving it a 31-bit data signal. bus_narrow overrides D_WIDTH to 8, shrinking data down to 8 bits — the same interface definition, sized two different ways in two different instances.
Quick Check
Q: If D_WIDTH is overridden to 15 at instantiation, how many bits wide is data?
Show Answer
15 bits. data is declared [D_WIDTH-1:0], so with D_WIDTH = 15, that's [14:0] — bit 14 down to bit 0 inclusive, which is 15 bits total.
Connecting a Parameterized Interface to a Design
The design that uses the interface typically declares a matching parameter of its own, so both sides agree on the width being used:
module bus_slave #(parameter D_WIDTH = 31) (myBus.slave bus_if);
logic [D_WIDTH-1:0] captured_data;
always @ (posedge bus_if.clk)
if (bus_if.enable)
captured_data <= bus_if.data;
endmodule
module d_top;
logic clk;
// Both the interface and the design agree on an 8-bit width
myBus #(.D_WIDTH(8)) bus_if (clk);
bus_slave #(.D_WIDTH(8)) slave0 (bus_if);
endmodule
Here, both bus_if and slave0 are instantiated with D_WIDTH(8), so captured_data inside bus_slave is declared the same width as bus_if.data — 8 bits, matching on both sides.
Nothing automatically keeps an interface's parameter and a connected design's parameter in sync — they're two separate parameter overrides that happen to use the same value here because both were written consistently. If one is overridden and the other is forgotten, the two sides can end up with mismatched widths without any compile-time error in many cases, since a narrower signal simply truncates or a wider one zero-extends at the connection.
Where Is Interface Parameterization Used?
A parameterized bus interface is what lets the same VIP support an 8-bit, 16-bit, or 32-bit version of a protocol without maintaining a separate interface file for each width — the design and testbench both instantiate the same interface definition, just with a different parameter override, keeping the signal widths consistent between them.
Common Beginner Mistakes
Mistake #1: Overriding the interface's parameter but not the design's
Since the interface and the connected design each declare their own parameter independently, overriding one without the other leaves them out of sync. Why? This can silently produce a width mismatch at the connection instead of a clear compile-time error, which is much harder to debug than a straightforward mismatch message.
Mistake #2: Assuming the interface's parameter automatically appears on the design side
A design module doesn't inherit a parameter value just because it's connected to a parameterized interface. Why? The design needs its own matching parameter declaration and its own explicit override — the interface and the module are two separate parameterized entities that simply happen to be connected.
Mistake #3: Forgetting the default value entirely
An interface parameter without a default (or with a default that doesn't match common usage) forces every instantiation to explicitly override it, even when most instances would want the same value. Why? Choosing a sensible default, like the most common bus width in a project, keeps most instantiations simple while still allowing the occasional override where it's actually needed.
Practice Exercise
Challenge: Add a Second Parameter
Extend myBus with a second parameter, ADDR_WIDTH, defaulting to 16, and add an addr signal sized [ADDR_WIDTH-1:0]. Then instantiate it with D_WIDTH overridden to 8 and ADDR_WIDTH left at its default.
Hint
Multiple parameters are comma-separated inside the same #(...) list, both when declaring the interface and when overriding values at instantiation — you don't need to override every parameter just because you're overriding one.
Solution
interface myBus #(parameter D_WIDTH=31, parameter ADDR_WIDTH=16) (input clk);
logic [D_WIDTH-1:0] data;
logic [ADDR_WIDTH-1:0] addr;
logic enable;
endinterface
module tb;
logic clk;
// D_WIDTH overridden to 8 (8-bit data); ADDR_WIDTH left at its default of 16 (16-bit addr)
myBus #(.D_WIDTH(8)) bus_if (clk);
endmodule
Only D_WIDTH needed to be named in the override — ADDR_WIDTH simply keeps its declared default of 16 (a 16-bit addr, since [15:0] is 16 bits) since it wasn't mentioned at instantiation.
Summary
In this tutorial, you learned:
- An interface is parameterized the same way a module is, with
#(parameter ...)right after its name - A parameter's default is overridden at instantiation with
#(.PARAM(value)), the same syntax used for modules - A design connected to a parameterized interface needs its own matching parameter declaration and override — nothing links the two automatically
- Mismatched parameters between an interface and its connected design can silently produce a width mismatch instead of a clear error
- Multiple parameters are declared and overridden as a comma-separated list; any parameter left out of an override simply keeps its default
Continuing the Interfaces & Modports Chapter
See SystemVerilog Interface for the broader set of interface capabilities, and SystemVerilog Interface Array for connecting multiple instances of the same interface.
A single interface handle connects a testbench to one instance of a design. When a design itself is replicated — multiple identical DUT instances, multiple lanes on a wide bus, multiple channels on a peripheral — the interface connecting to it can be replicated the same way, using an array of interface instances instead of one instance per connection.
6 min read | Intermediate Level
What You'll Learn
- How to declare and instantiate an array of interface instances
- How to connect individual array elements to individual design instances
- How implicit port connections (
.*) work with an interface port - A parsing gotcha with interfaces that have no port list
Declaring an Interface Array
Below, an interface named myInterface with an empty port list is created and instantiated within the top-level testbench module. It's also fine to omit the parentheses for an empty port list and simply end the statement with a semicolon — but see the note later in this article before doing that.
// interface myInterface;
interface myInterface ();
reg gnt;
reg ack;
reg [7:0] irq;
...
endinterface
module tb;
// Single interface handle
myInterface if0 ();
// An array of interfaces
myInterface wb_if [3:0] ();
// Rest of the testbench
endmodule
A single interface called if0 can be instantiated, and its signals accessed by referencing that handle — used to drive and sample signals going to the DUT. You can also have an array of interfaces; here, wb_if has 4 instances, declared with the same [3:0] array syntax you'd use for any other array.
Connecting Individual Array Elements to a Design
Each element of an interface array can be connected to its own design instance individually, the same way you'd index into any other array:
module myDesign ( myInterface dut_if,
input logic clk);
always @(posedge clk)
if (dut_if.ack)
dut_if.gnt <= 1;
endmodule
module tb;
reg clk;
// Single interface handle connection
myInterface if0;
myDesign top (if0, clk);
// Or connect by name
// myDesign top (.dut_if(if0), .clk(clk));
// Multiple design instances connected to the appropriate
// interface handle
myDesign md0 (wb_if[0], clk);
myDesign md1 (wb_if[1], clk);
myDesign md2 (wb_if[2], clk);
myDesign md3 (wb_if[3], clk);
endmodule
md0 through md3 are four separate instances of the same design, each wired to its own independent interface instance — wb_if[0] through wb_if[3] — so each one has its own ack, gnt, and irq signals rather than sharing a single set.
Quick Check
Q: If md0 and md1 above were both connected to wb_if[0] instead of separate array elements, what would change?
Show Answer
Both design instances would share the exact same ack, gnt, and irq signals — whatever one instance drives, the other would see too. That's rarely what you want when the two instances are meant to behave independently, which is exactly why an array of interfaces exists.
Implicit Port Connections
When an interface is referenced as a port, its variables and nets are assumed to have ref and inout access respectively. If the same identifier is used as both the interface instance name and the port name in the design, implicit port connections can also be used:
module tb;
reg clk;
myInterface dut_if();
// Can use implicit port connection when all port signals have same name
myDesign top (.*);
endmodule
An error will occur if an interface without ports is instantiated without parentheses (), even though the interface itself was declared with an empty port list:
// Declare an interface without ports
interface mif;
logic m_a;
endinterface
module tb;
mif m_if; // ERROR !
mif m_if(); // Okay
endmodule
Output
mif m_if;
|
xmvlog: *E,NOIPRT (testbench.sv,12|10): Unrecognized declaration 'm_if' could be an unsupported keyword, a spelling mistake or missing instance port list '()' [SystemVerilog].
Where Are Interface Arrays Used?
Interface arrays are the natural fit for anything replicated across a design — connecting to N identical peripheral instances, a multi-lane SerDes or multi-channel DMA engine, or verifying several parallel instances of the same block in a single testbench without hand-writing a separate interface declaration for each one.
Common Beginner Mistakes
Mistake #1: Connecting multiple design instances to the same array element
Every design instance meant to behave independently needs its own interface array element. Why? Two instances sharing one element share every signal on it too, which silently merges behavior that was supposed to stay separate — exactly the scenario in the Quick Check above.
Mistake #2: Omitting () when instantiating a port-less interface
As shown 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, and even for each element of an array.
Mistake #3: Assuming .* connects a mismatched interface port name
.* only auto-connects ports whose names exactly match a visible local signal. Why? If the local interface instance and the module's port aren't named identically, .* silently skips that connection instead of erroring, which can leave a port unconnected without any obvious warning.
Practice Exercise
Challenge: Connect an Array of 8 Design Instances
Using the myInterface and myDesign declarations from earlier, declare an 8-element array of myInterface instances called ch_if, and connect 8 instances of myDesign (ch0 through ch7) to it, one per element.
Hint
Follow the same myInterface name [N:0] (); array declaration pattern shown for wb_if, then index into it the same way md0 through md3 did.
Solution
module tb;
reg clk;
// An array of 8 interface instances
myInterface ch_if [7:0] ();
// 8 design instances, each connected to its own array element
myDesign ch0 (ch_if[0], clk);
myDesign ch1 (ch_if[1], clk);
myDesign ch2 (ch_if[2], clk);
myDesign ch3 (ch_if[3], clk);
myDesign ch4 (ch_if[4], clk);
myDesign ch5 (ch_if[5], clk);
myDesign ch6 (ch_if[6], clk);
myDesign ch7 (ch_if[7], clk);
endmodule
Each myDesign instance gets its own independent set of ack/gnt/irq signals via its own ch_if element — the same one-array-element-per-instance pattern as wb_if earlier, just scaled up to 8 channels.
Summary
In this tutorial, you learned:
- An interface array is declared with the same array syntax as any other array, and instantiated with
()per element - Each array element is an independent interface instance with its own signals — connecting more than one design instance to the same element merges their signals together
.*auto-connects ports only when the local signal name exactly matches the port name- An interface with no port list still needs
()at instantiation, or it fails to compile
Continuing the Interfaces & Modports Chapter
See SystemVerilog Interface Intro for how the same interface connects to both a Verilog and a SystemVerilog design, and SystemVerilog Modport for restricting signal directions per module.
A struct and a class both group related data together, but they solve genuinely different problems. A struct is a plain, synthesizable value type for organizing data — nothing more. A class is a reference type built for verification, bundling data together with behavior, inheritance, and dynamic construction. Confusing the two — especially around assignment and equality — is a common source of subtle bugs.
10 min read | Intermediate Level
What You'll Learn
- The core distinction: a struct is a value type, a class is a reference type
- Why assigning one struct to another copies its fields, while assigning one class handle to another just shares the same object
- Why comparing two structs with
==checks their contents, while comparing two class handles checks identity - Which features — methods, constructors, inheritance — exist on a class but not a struct, and why only one of the two is synthesizable
At a Glance
| struct | class | |
|---|---|---|
| Type category | Value type | Reference type (handle) |
Assignment (a = b) | Copies every field | Copies the handle; both point to the same object |
Equality (a == b) | Compares field values | Compares handle identity (same object?) |
| Methods (functions/tasks) | Not supported | Supported |
| Constructor | None — initialized directly | new() |
Inheritance (extends) | Not supported | Supported |
Access control (local/protected) | Not supported | Supported |
| Synthesizable | Yes, especially when packed | No — simulation and testbench only |
| Memory | Exists wherever declared | Allocated dynamically via new(), garbage collected once unreferenced |
Assignment: Copy vs Share
This is the single most important difference, and the one most likely to cause a real bug if missed:
typedef struct {
int addr;
} packet_t;
class Packet;
int addr;
endclass
module tb;
packet_t s1, s2;
Packet c1, c2;
initial begin
s1.addr = 10;
s2 = s1; // struct assignment COPIES every field
s2.addr = 99;
$display ("s1.addr=%0d, s2.addr=%0d", s1.addr, s2.addr);
c1 = new (); c1.addr = 10;
c2 = c1; // class assignment copies only the HANDLE
c2.addr = 99;
$display ("c1.addr=%0d, c2.addr=%0d", c1.addr, c2.addr);
end
endmodule
This prints s1.addr=10, s2.addr=99 for the struct — changing s2 after the assignment has no effect on s1, since s2 got its own independent copy of every field the moment s2 = s1; ran. For the class, it prints c1.addr=99, c2.addr=99 — c2 = c1; only copied the handle, so c1 and c2 point to the exact same object, and changing one changes both. See SystemVerilog Copying Objects for how to actually get an independent copy of a class object when you need one.
Equality: Comparing Values vs Comparing Identity
This follows directly from the same value-vs-reference distinction, and it's the part most likely to catch someone off guard:
typedef struct {
int addr;
int data;
} packet_t;
class Packet;
int addr;
int data;
endclass
module tb;
packet_t s1, s2;
Packet c1, c2;
initial begin
// Two SEPARATE structs, with identical field values
s1.addr = 10; s1.data = 20;
s2.addr = 10; s2.data = 20;
// Two SEPARATE class objects, also with identical property values
c1 = new (); c1.addr = 10; c1.data = 20;
c2 = new (); c2.addr = 10; c2.data = 20;
if (s1 == s2)
$display ("Structs are equal");
else
$display ("Structs are NOT equal");
if (c1 == c2)
$display ("Classes are equal");
else
$display ("Classes are NOT equal");
end
endmodule
This prints Structs are equal, then Classes are NOT equal — even though c1 and c2 hold exactly the same data. == on a struct compares every field's value; == on a class handle only checks whether both handles reference the same object in memory. c1 and c2 are two genuinely separate objects that simply happen to contain matching data — as far as == is concerned, that doesn't count as equal.
Quick Check
Q: If the code were changed to c2 = c1; instead of constructing c2 separately, would c1 == c2 now return true?
Show Answer
Yes. c2 = c1; makes both handles point to the exact same object, so the identity check == performs succeeds — it's not that the data happens to match anymore, it's that there's only one object for both handles to compare against.
Methods, Constructors, and Inheritance
A struct is data only — it can't have a method, a constructor, or a base type:
// Not legal - a struct cannot contain a method
typedef struct {
int addr;
// function void display(); ... endfunction <- not allowed
} packet_t;
A class supports all of this: methods (covered in SystemVerilog Functions), a constructor (see SystemVerilog Class Constructor), and inheritance via extends (see SystemVerilog Inheritance). If you find yourself wanting to bundle behavior together with data — or reuse a data structure across a hierarchy of related types — that's the signal you need a class, not a struct.
Synthesizability
A struct — especially a packed struct with a well-defined bit layout — is fully synthesizable and commonly used to describe register fields or bus transaction layouts directly in RTL. A class is never synthesizable, under any circumstances; it exists purely for simulation and testbench code.
Where Does Each One Fit?
A packed struct is a natural fit for describing a fixed bit-field layout that both the design and the testbench need to agree on — a bus transaction's raw header format, for instance. A class fits a rich testbench transaction object that needs randomization, methods, and reuse across a family of related transaction types through inheritance — something a struct simply has no mechanism for.
Common Beginner Mistakes
Mistake #1: Assuming struct assignment shares data the way class assignment does
As the first example shows, these behave oppositely. Why? A struct is a value type, so assignment always copies every field independently; a class handle is a reference, so assignment only copies the reference itself — expecting one to behave like the other is a common source of confusing, hard-to-trace bugs.
Mistake #2: Assuming class equality checks field contents
As the equality example shows, == on two class handles checks identity, not content. Why? Two separately constructed objects with identical data are still considered unequal — if you actually need to compare a class object's contents field by field, you have to write that comparison logic yourself.
Mistake #3: Trying to add a method directly to a struct
A struct can only hold data members — no functions, no tasks. Why? If you need behavior bundled together with data, that's exactly what a class is for; a struct simply has no mechanism for it.
Mistake #4: Assuming a class can be used anywhere a struct can
A class is never synthesizable, regardless of what it contains. Why? If the same data structure needs to exist in both the design and the testbench — or in synthesizable RTL at all — it has to be a struct (typically packed), not a class.
Practice Exercise
Challenge: Predict Three Comparisons
Given two structs with identical field values, two separately-constructed class objects with identical property values, and a third class handle assigned directly from one of those two objects (c3 = c1;), predict the result of: s1 == s2, c1 == c2, and c1 == c3.
Hint
Only one of these three comparisons depends on whether the two sides are the exact same object in memory — the other two questions have already been answered directly in this article.
Solution
s1 == s2 is true — struct equality compares field values, and they match. c1 == c2 is false — two separate objects, even with matching data, aren't the same object. c1 == c3 is true — c3 = c1; made c3 point to the exact same object as c1, so the identity check succeeds.
Summary
In this tutorial, you learned:
- A struct is a value type; a class is a reference type accessed through a handle
- Assigning one struct to another copies every field independently; assigning one class handle to another only shares the same underlying object
==on structs compares field values;==on class handles compares identity — whether both sides reference the same object, not whether their data matches- Only a class supports methods, a constructor, and inheritance; a struct is data only
- A struct (especially
packed) is synthesizable; a class is never synthesizable, and exists purely for simulation and testbench code
Quiz
No quiz questions available for this article.