Randomization and Constraints

Constraints are used in SystemVerilog to guide or limit the process of randomization. In order to use constraints, you must first declare the variables that you want to randomize using the rand or randc keyword.

rand: Declares a variable that can be randomized, each randomization is independent and values can be repeated.

randc: Similar to rand, but once a variable has been randomized to a certain value, it will not repeat that value until all possible values have been used.

Here is an example of a class with a rand variable:

class MyClass;
    rand bit [3:0] data;
endclass

In this example, data is a variable that can be randomized. Without any constraints, data can take any value from 0 to 15 (since it is a 4-bit wide variable).

To restrict the possible values that data can take during randomization, you can define a constraint within the class. A constraint is a set of conditions that a randomized variable must meet. If a variable cannot meet these conditions, it will not be assigned that value during randomization.

Here is an example of a class with a constrained rand variable:

class MyClass;
    rand bit [3:0] data;
    constraint data_c {data < 10;}
endclass

In this example, data_c is a constraint that limits the value of data to be less than 10 during randomization. Therefore, data can only take values from 0 to 9 during randomization.

You can also have more than one constraint in a class, and you can have more complex expressions within your constraints:

class MyClass;
    rand bit [3:0] data;
    rand bit enable;
    constraint data_c {
        data < 10;
        enable -> data > 5;
    }
endclass

In this example, the constraint data_c is made up of two separate conditions. The first condition, data < 10, is the same as before. The second condition, enable -> data > 5, is an implication. This means that if enable is 1, then data must be greater than 5.

Note that the expressions within a constraint are separated by semicolons, and the whole constraint is enclosed within braces {}. The name of the constraint is followed by _c by convention, but you can name your constraints anything you want.

To randomize the variables in a class, you use the randomize() method:

MyClass my_obj = new();
my_obj.randomize();

In this code, my_obj is an object of MyClass. When my_obj.randomize() is called, SystemVerilog will try to find values for data and enable that meet the conditions specified in data_c. If no such values can be found, randomize() will return 0 to indicate failure.

Have a Question?

Feel free to ask your question in the comments below.

Please Login to ask a question.

Login Now