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