如果不希望组中的任何两个成员在随机化后具有相同的值,需要使用“unique”constraint。“unique”是一个关键词,使用“unique”将生成受约束的 rand 变量的唯一值。它不仅适用于静态数组,在关联数组,动态数组,队列中都可以使用。
看一个例子:
class distClass;
rand bit [1:0] data1, data2, data3, data4;
rand bit [1:0] addr1, addr2, addr3, addr4;
constraint distr { unique {data1, data2, data3, data4}; }
//'unique' random
constraint distr1 { {addr1, addr2, addr3, addr4}; }
//non-unique random
endclass
module top;
distClass dc = new ();
initial begin
for (int i = 0; i < 5; i++) begin
dc.randomize();
$display ("data1=%0d data2=%0d data3=%0d data4=%0d",dc.
data1, dc.data2, dc.data3, dc.data4);
$display ("addr1=%0d addr2=%0d addr3=%0d addr4=%0d",dc.
addr1, dc.addr2, dc.addr3, dc.addr4);
$display("\n");
end
end
endmodule
模拟结果:
Compiler version S-2021.09; Runtime version S-2021.09; Aug 20 09:33 2022
data1=3 data2=1 data3=0 data4=2
addr1=3 addr2=2 addr3=3 addr4=1
data1=2 data2=1 data3=0 data4=3
addr1=1 addr2=1 addr3=0 addr4=1
data1=0 data2=2 data3=3 data4=1
addr1=2 addr2=2 addr3=0 addr4=1
data1=0 data2=1 data3=2 data4=3
addr1=3 addr2=1 addr3=3 addr4=2
data1=2 data2=1 data3=3 data4=0
addr1=3 addr2=1 addr3=3 addr4=2
V C S S i m u l a t i o n R e p o r t
data1 到 data4 是随机的,但不会在集合中有重复值出现。但是 addr1 到 addr4 似乎常规随机化,可能会有重复值出现。
队列,动态数组,和关联数组的例子:
class aClass;
rand bit [1:0] addr [ ] = {1,2,3,4}; //dynamic array
rand bit [7:0] St [string] = '{"Peter":26, "Paul":24};
//associative array
rand bit [7:0] dq2[$] = { 3, 2, 7, 1 }; //queue
constraint addrC {unique {addr};}
constraint strC {unique {St};}
constraint dq2C {unique {dq2};}
endclass
module tb;
initial begin
aClass aC = new ( );
for (int i = 0; i < 4; i++) begin
aC.randomize();
$display ("addr=%p St=%p dq2=%p", aC.addr, aC.St, aC.dq2);
end
end
endmodule
仿真结果:
Compiler version S-2021.09; Runtime version S-2021.09; Aug 20 09:38 2022
addr='{'h3, 'h1, 'h0, 'h2} St='{"Paul":'h97, "Peter":'heb} dq2='{'hc3, 'hbc, 'h5a, 'h5f}
addr='{'h2, 'h1, 'h0, 'h3} St='{"Paul":'h37, "Peter":'h7} dq2='{'h80, 'ha5, 'h49, 'hec}
addr='{'h0, 'h2, 'h3, 'h1} St='{"Paul":'h91, "Peter":'h44} dq2='{'h10, 'h14, 'he3, 'hff}
addr='{'h0, 'h1, 'h2, 'h3} St='{"Paul":'h2f, "Peter":'hbb} dq2='{'h41, 'ha6, 'h56, 'h49}
V C S S i m u l a t i o n R e p o r t