Module 510 min

Randomization and Constraints

Let the tool invent test cases you never thought of

Writing test cases by hand misses the ones you did not imagine - and those are where bugs hide. The fix is to let the tool generate random inputs automatically, but inside rules you set. This is called constrained random verification, and it is how modern chips are tested.

Making a field random

Mark a class field rand, and a single call fills it with a fresh random value that obeys your constraints.

systemverilog
class Packet;
  rand bit [7:0] addr;
  rand bit [7:0] data;

  // Rules the random values must obey
  constraint addr_range { addr inside {[0:127]}; }  // addr 0..127
  constraint not_zero   { data != 0; }              // data never 0
endclass

Packet p = new();
if (!p.randomize())
  $error("could not satisfy constraints");
// now p.addr is 0..127 and p.data is non-zero, randomly

What constraints can express

ConstraintMeaning
addr inside {[0:127]}Value must be in this range
data != 0Value must not equal something
len dist {1:=80, 8:=20}Pick 1 about 80% of the time, 8 about 20%
a < bRelationship between two fields
Pro tip

Constrained random is powerful because it explores combinations a human would never list by hand. Run a thousand randomized packets overnight and the tool tries address-data mixes you never thought of. Bugs that hid for months in directed tests often fall out in the first random run.

Directed vs random - use both

  • Directed test - you hand-pick exact inputs. Best for a specific known case ("what happens at the maximum address?").
  • Random test - the tool generates many cases inside your rules. Best for finding the unknown.
Watch out

Always check the return value of randomize(). If your constraints contradict each other (say, x > 10 and x < 5), randomization fails and your fields keep their old values - your test silently does nothing useful. if (!p.randomize()) $error(...) catches that immediately.