Tackling a constraint in post_randomize()

Hi All,
I need to write a constraint for 32 bit address, to generate continuous 10 bits as 0 and remaining bits as 1.

I can do it two ways:

//No post_randomize use
class Example;
	rand bit[31:0] num;
	rand int start_bit;

	constraint c0{ start_bit inside {[0:22]};}
	constraint c2 {num[start_bit+:9] ==0;}
    constraint c3 {foreach(num[i]) {
		if (!(i inside {[start_bit:start_bit+9]})) 
			num[i] == 1;
	}};


endclass 



//Use of post_randomize()
class Example;
	rand bit[31:0] num;
	rand int start_bit;
    constraint c0{ start_bit inside {[0:22]};}
    constraint c1 {foreach(num[i]) {
			num[i] == 1;
	}};

	function void post_randomize();
		num[start_bit+:9] = 0;
	endfunction

endclass


Is one way better than the other or it does not matter? Thanks in advance for your input.

A simpler way to do the post_randomize code is declare only one variable as “rand”

class Example;
    bit [31:0] num;
    rand int start_bit;
    constraint c0 {start_bit inside {[0:22]};}

    function void post_randomize;
        num = '1;
        num[start_bit +: 9] = 0;
    endfunction
endclass

I suggest avoiding pre/post_randomize() if possible. It is easier to manage all constraint dependencies that way.

If you are going to iterate of all bits of num anyways, it would be simpler to write

constraint c0{ start_bit inside {[0:22]};}
constraint c3 {foreach(num[i]) 
		if (i inside {[start_bit:start_bit+9]})
			num[i] == 1;
        else 
			num[i] == 0;
	}
1 Like

I tried with a different approach:

class abc;
  
  rand bit[31:0] addr;
  rand bit[31:0] val;
  constraint addr_c{
    val inside {[1:21]};
   addr == 10'b1111_1111_11 << val;
  }

    function void post_randomize();
      addr = ~addr;
      $display("value of array = %b val =%0p",addr, val);
    endfunction   
endclass: abc

module tb;
   abc abc_inst;
  initial begin 
    abc_inst = new();
    repeat(10)
    abc_inst.randomize();

  end
endmodule