Randomizing Fields of Register with Constraints

Have you ever found yourself working on a project where the widths of the fields in registers keep changing sizes or positions, and you constantly have to modify your code in order to keep track of the changes? 

Let’s say, you had a register in your register model called FRUIT which contained fields:

  • Apple
  • Banana
  • Pear
  • Orange
Randomizing Fields of Register 1

Your job is to create a fruit salad with 3 bananas, 2 oranges, 4 pears, and 5 apples. 

Randomizing Fields of Register with Constraints

If you are just starting to learn SystemVerilog, you might be tempted to create a variable and manually calculate the data you need to write inside your register. Something like this:

bit [31:0] reg_data;

reg_data = {3’h0, 5’h3, 3’h0, 5’h2, 3’h0, 5’h4, 3’h0,  5’h5 };

//3 bananas, 2 oranges, 4 pears, 5 apples

reg_model.FRUIT.write(.status(status), .value(reg_data), .map(map));

Now: let’s say that at some point the fields in the register changed positions and sizes as shown below, and you need more random salad ingredients.

Your fruit salad now requires 3 to 5 bananas, 2 to 4 oranges, 4 to 6 pears and exactly 7 apples.

Randomizing Fields of Register with Constraints 2

The code above becomes unusable.

There is a simple way to randomize a register, and constraint its fields, without caring about the position of each field:

assert(reg_model.FRUIT.randomize() with {

 

    banana.value inside {[3:5]};

    orange.value inside {[2:4]};

    pear.value inside {[4:6]};

    apple.value == 7;


});

This will randomize the desired value of your register, and after that you can use get() method to obtain the value you want to write in your register.

reg_model.FRUIT.write(.status(status), .value(reg_model.FRUIT.get()), .map(map));

NOTE: randomize() returns a value for successful randomization, thus we use assert() to avoid compilation warnings

 

Using this method you can create clean and reusable code and simplify your life.

Contact Us

Please, enter your details below. We will get back to you as fast as we can.

This website uses cookies to ensure you get the best experience on our website.

Get Cogita

Please, enter your details below. We will get back to you as fast as we can.

Thank you!

We will get in touch soon.

Get a Quote

Please, enter your details below. We will get back to you as fast as we can.