Unique Constraint

SystemVerilog Unique Constraint


On randomization, unique values to set of variables or unique elements to an array can be generated by using unique constraint.

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)

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


class unique_elements;
  rand bit [3:0] var_1,var_2,var_3;
  rand bit [7:0] array[6];
  
  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}

Execute the above code on 




unique array elements example


In below example,
Unique elements for array is generated by using unique keyword. Also considered that 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}

Execute the above code 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.