SystemVerilog Unique Constraint

Unique Constraint

SystemVerilog constraint defined with the keyword unique is called as a unique constraint. On randomization, unique values to set of variables or unique elements to an array can be generated by using unique constraints.

Unique constraint allows us to,

  • Generate unique values across the variables
  • Generate unique elements in an array (Fixed Size Array, Dynamic Array, Associative array and Queue)
constraint c_name { unique {variable's/array}; }

Below example shows,

  • Generation of random unique values to the variables var_1, var_2 and var_3
  • Generation of random unique elements to an array array

Unique constraint example

Unique elements

In the below example,
On randomization unique values to a variable var_1, var_2, var_3 can be obtained by writing unique constraints. Also, a unique constraint is written to an array to get unique array elements.

class unique_elements;
  rand bit [3:0] var_1,var_2,var_3;
  rand bit [7:0] array[6];
  constraint varis_c {unique {var_1,var_2,var_3};}
  constraint array_c {unique {array};}
  
  function void display();
    $display("var_1 = %p",var_1);
    $display("var_2 = %p",var_2);
    $display("var_3 = %p",var_3);
    $display("array = %p",array);
  endfunction
endclass

program unique_elements_randomization;
  unique_elements pkt;

  initial begin
    pkt = new();
    pkt.randomize();
    pkt.display();   
  end
endprogram

Simulator Output

var_1 =  8 
var_2 = 14
var_3 = 11
array = '{'h81, 'h7b, 'h4, 'h47, 'he1, 'h17}

Click to execute on   

unique array of elements example

In below example,
Unique elements for an array is generated by using a unique keyword. Also considered that the value of elements is less than 10.

class unique_elements;
  rand bit [31:0] array[10];
  
  constraint array_c {unique {array};
                      foreach(array[i]) array[i] < 10;}
  
  function void display();
    $display("array = %p",array);
  endfunction
endclass

program unique_elements_randomization;
  unique_elements pkt;

  initial begin
    pkt = new();
    pkt.randomize();
    pkt.display();   
  end
  
endprogram

Simulator Output

array = '{'h5, 'h7, 'h8, 'h1, 'h6, 'h9, 'h2, 'h3, 'h4, 'h0}

Click to execute on   

TODO:
To see the difference, remove “unique {array};” and execute.
Below is the result on removing the “unique {array};” from constraint.

array = '{'h8, 'h4, 'h3, 'h2, 'h3, 'h0, 'h4, 'h8, 'h6, 'h2}

without unique, we can see the repeated values.

❮ Previous Next ❯