SystemVeilog Randomization Methods


The randomize() method is a virtual function that generates random values for all the active random variables in the object, subject to the active constraints.

The randomize() method returns 1 if it successfully sets all the random variables and objects to valid values, otherwise it returns 0.

 pre_randomize(); and post_randomize();  

Every class contains built-in pre_randomize() and post_randomize() functions.
on calling randomize(), pre_randomize() and post_randomize() functions will get called before and after the randomize call respectivley.

Users can override the pre_randomize() and post_randomize() in any classes.

pre_randomize function can be used to set pre-conditions before the object randomization.
user can disable the randomization of particular variables based on test conditions.

post_randomization function can be used to check perform post-conditions after the object randomization.
user can override the randomized values or can print the randomized variables.   


In the example below,
paket has two variables, addr and wr_rd. 
assume that wr_rd = 0 read operation.
                    wr_rd = 1 write operation.
In order to perform write followed by read to the same addr, randomization of addr is controlled based on the previous randomization value of wr_rd.

class packet;
  rand  bit [7:0] addr;
  randc bit       wr_rd;
        bit       tmp_wr_rd;     

  //pre randomization function - disabling randomization of addr,
  //if the prevoius operation is write.
  function void pre_randomize();
    if(tmp_wr_rd==1) addr.rand_mode(0);
    else                 addr.rand_mode(1);

  //post randomization function - store the wr_rd value to tmp_wr_rd
  //and display randomized values of addr and wr_rd
  function void post_randomize();
    tmp_wr_rd = wr_rd;
    $display("POST_RANDOMIZATION:: Addr = %0h,wr_rd = %0h",addr,wr_rd);

module rand_methods;
  initial begin
    packet pkt;
    pkt = new();

    repeat(4) pkt.randomize();

 Simulator Output  

POST_RANDOMIZATION:: Addr = 6e,wr_rd = 1
POST_RANDOMIZATION:: Addr = 6e,wr_rd = 0
POST_RANDOMIZATION:: Addr = 88,wr_rd = 1
POST_RANDOMIZATION:: Addr = 88,wr_rd = 0

Execute the above code on