Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท SystemVerilog Features

Classes and Constrained Randomization

Learn SystemVerilog classes for verification: objects, inheritance, rand and randc variables, constraints, randomize(), mailboxes, covergroups and a mini scoreboard.

Directed tests check what you thought of. Constrained-random verification checks what you did not: it generates thousands of legal but surprising transactions, and a checker tells you whether the design handled them. The enabling feature is the SystemVerilog class: an object-oriented building block for testbenches (it is not synthesizable). Classes, rand fields and constraints are the foundation of UVM, the industry-standard verification methodology.

This lesson shows classes, randomization and constraints, a driver-monitor-scoreboard sketch, and how mailboxes and coverage tie them together. The SystemVerilog is read-only here (no simulator runs on this site); the C programs are labelled stand-ins that implement constrained random generation by hand with a seeded generator.

A class in SystemVerilog

SYSTEMVERILOG
class packet;
  rand bit [7:0]  addr;
  rand bit [31:0] data;
  rand bit        write;

  function new();                 // constructor
    // fields start at 0 (2-state bit)
  endfunction

  function void print();
    $display("pkt: %s addr=%0h data=%0h", write ? "WR" : "RD", addr, data);
  endfunction
endclass

module tb;
  initial begin
    packet p;
    p = new();
    p.addr = 8'h10;
    p.print();
  end
endmodule

Key facts:

  • A variable of class type is a handle (like a pointer or a Java reference); new() creates the object.
  • Objects live on the heap and are garbage collected; you never free them.
  • Classes support inheritance (class special_packet extends packet;), virtual methods (polymorphism), static members and parameters.
  • Class code runs in simulation only: use classes in testbenches, never in RTL.

rand and randc

A field marked rand receives a new random value each time you call obj.randomize(). randc is random-cyclic: it cycles through all values in a random order before repeating (useful for IDs and for covering all addresses of a small range).

SYSTEMVERILOG
class packet;
  rand  bit [7:0] addr;
  randc bit [2:0] id;            // 0..7, each exactly once per cycle
  rand  bit [31:0] data;
  rand  bit       write;
endclass

initial begin
  packet p = new();
  repeat (10) begin
    if (!p.randomize()) $fatal(1, "randomize failed");
    p.print();
  end
end

randomize() returns 1 on success and 0 if the constraints cannot be satisfied, so always check the result.

Constraints

A constraint block restricts the values the solver may choose. It is declarative: you describe what is legal, the solver finds values.

SYSTEMVERILOG
class packet;
  rand bit [7:0]  addr;
  rand bit [31:0] data;
  rand bit        write;
  rand int unsigned len;

  constraint c_addr  { addr inside {[8'h00:8'h7F]}; }            // lower half only
  constraint c_len   { len inside {1, 2, 4, 8}; }
  constraint c_write { write dist {1 := 70, 0 := 30}; }          // 70% writes
  constraint c_align { addr % 4 == 0; }
  constraint c_big   { (len > 4) -> (addr[7] == 0); }            // implication
endclass

Operators worth knowing:

  • inside {...}: membership, supports ranges.
  • dist: weighted distribution. := gives each value that weight, :/ splits the weight across a range.
  • -> (implication): if the left side is true then the right side must hold.
  • solve a before b; guides how probabilities are distributed between variables.
  • unique {a, b, c}; forces distinct values.

You can switch constraints on and off at run time (p.c_align.constraint_mode(0);) and add one-off constraints with randomize() with { addr == 8'h40; }.

Hand-written constrained random in C

SystemVerilog does the solving for you. The stand-in below does it the hard way: a seeded linear congruential generator, and a generate-and-test loop that rejects values violating the constraints. It builds 8 packets constrained like the example (address in the lower half and 4-byte aligned, length one of 1, 2, 4, 8, 70% writes) and reports statistics.

C Stand-in: constrained random packets with a seeded generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Run it twice: the output is identical, because the seed is fixed. That reproducibility is precisely what simulators offer through their seed option; every failing random run must be re-runnable with the same seed.

A tiny verification environment

Class-based environments split responsibilities into small components that talk through mailboxes (thread-safe queues):

flowchart LR
  G["Generator<br/>(randomize)"] -->|mailbox| DR["Driver"]
  DR -->|"virtual interface"| DUT["DUT"]
  DUT -->|"virtual interface"| MON["Monitor"]
  MON -->|mailbox| SB["Scoreboard<br/>(compare with model)"]
  DR -->|expected| SB

Generator creates random transactions; the driver applies them; the monitor observes the DUT; the scoreboard compares.

SYSTEMVERILOG
class generator;
  mailbox #(packet) gen2drv;
  task run(int count);
    repeat (count) begin
      packet p = new();
      assert (p.randomize());
      gen2drv.put(p);               // blocks if the mailbox is full
    end
  endtask
endclass

class driver;
  mailbox #(packet) gen2drv;
  virtual bus_if vif;
  task run();
    forever begin
      packet p;
      gen2drv.get(p);               // blocks until a packet arrives
      vif.write_word(p.addr, p.data);
    end
  endtask
endclass

fork ... join_none starts the components concurrently. The vif is a virtual interface as in interfaces and modports.

Scoreboard: queue of expected values

A scoreboard stores what the reference model predicts and compares it with what the monitor sees. A queue ($) is the natural container:

SYSTEMVERILOG
class scoreboard;
  packet expected[$];                      // queue
  int errors;

  function void predict(packet p);  expected.push_back(p); endfunction

  function void check(packet actual);
    packet e;
    if (expected.size() == 0) begin errors++; $error("unexpected packet"); return; end
    e = expected.pop_front();
    if (e.data !== actual.data) begin
      errors++;
      $error("mismatch: expected %0h, got %0h", e.data, actual.data);
    end
  endfunction
endclass

The next stand-in is the same scoreboard idea in C with a circular queue: expected values are pushed in order, actual results popped and compared, with one deliberately wrong value in the DUT stream.

C Stand-in: scoreboard comparing expected and actual values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The report flags item 3: the model predicted 60 and the DUT produced 61.

Functional coverage

Random tests need a measure of what they achieved, otherwise "10,000 tests passed" may only mean the same case 10,000 times. A covergroup samples values and reports which bins were hit:

SYSTEMVERILOG
covergroup cg @(posedge clk);
  cp_len  : coverpoint pkt.len { bins small = {1,2}; bins big = {4,8}; }
  cp_wr   : coverpoint pkt.write;
  cross cp_len, cp_wr;                  // all combinations
endgroup

The goal is 100% coverage of the interesting bins; holes tell you which constraints to adjust or which directed tests to add. Assertions and coverage are developed further in assertions and coverage.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a class variable hold?

    Class variables are handles. Until you call new() the handle is null.
  2. 2. What is the difference between rand and randc?

    randc is random-cyclic: each value occurs once per cycle in random order. rand may repeat a value immediately.
  3. 3. What should you always do with the return value of randomize()?

    Conflicting constraints cause randomize() to fail and leave the object unchanged, which silently ruins a test if unchecked.
  4. 4. Why is a seed important in constrained-random tests?

    Pseudo-random generators are deterministic for a given seed, so failures can be replayed and debugged.

Summary

  • Classes are testbench-only objects with handles, inheritance and virtual methods.
  • rand/randc fields plus constraint blocks (inside, dist, ->) generate legal random transactions via randomize().
  • Environments connect generator, driver, monitor and scoreboard with mailboxes and virtual interfaces.
  • Covergroups measure what the random tests actually exercised.

Next: The Synthesizable Subset and Common Pitfalls