Tutorials

Learn More

As the name suggests, a unique constraint is useful to generate unique values for variables and elements in an array (Fixed array, associative array, dynamic array, and queue)

Syntax:

constraint <constraint name> {unique {array or variable};}

Unique constraint example

typedef enum {M0, M1, M2, M3} scale_e;
class seq_item;
  rand bit [7:0] value_a[scale_e];
  rand bit [3:0] array[5];
  rand bit [2:0] val1, val2, val3, val4;
  scale_e scale;
  
  constraint array_c { unique {array}; }
  constraint value_a_c { unique {value_a}; 
                        value_a.size == scale.num;
                        foreach (value_a[i]) value_a[i] inside {[50:60]}; }
  constraint val_c {unique {val1, val2, val3, val4}; }
endclass

module constraint_example;
  seq_item item;
  
  initial begin
    item = new();
    
    repeat(5) begin
      item.randomize();
      $display("val1 = %0d, val2 = %0d, val3 = %0d, val4 = %0d", item.val1, item.val2, item.val3, item.val4);
      foreach(item.value_a[i]) $display("value_a[%s] = %0d", i.name(), item.value_a[i]);
      foreach(item.array[i]) $display("array[%0d] = %0d", i, item.array[i]);
    end
  end
endmodule

Output:

val1 = 5, val2 = 6, val3 = 4, val4 = 1
value_a[M0] = 54
value_a[M1] = 59
value_a[M2] = 57
value_a[M3] = 55
array[0] = 15
array[1] = 13
array[2] = 14
array[3] = 8
array[4] = 1
val1 = 6, val2 = 3, val3 = 5, val4 = 0
value_a[M0] = 60
value_a[M1] = 56
value_a[M2] = 50
value_a[M3] = 51
array[0] = 12
array[1] = 14
array[2] = 1
array[3] = 15
array[4] = 3
val1 = 7, val2 = 2, val3 = 4, val4 = 6
value_a[M0] = 56
value_a[M1] = 50
value_a[M2] = 53
value_a[M3] = 52
array[0] = 4
array[1] = 15
array[2] = 11
array[3] = 2
array[4] = 0
val1 = 0, val2 = 5, val3 = 7, val4 = 1
value_a[M0] = 55
value_a[M1] = 56
value_a[M2] = 60
value_a[M3] = 54
array[0] = 15
array[1] = 12
array[2] = 13
array[3] = 11
array[4] = 1
val1 = 1, val2 = 5, val3 = 3, val4 = 7
value_a[M0] = 57
value_a[M1] = 51
value_a[M2] = 54
value_a[M3] = 52
array[0] = 11
array[1] = 8
array[2] = 12
array[3] = 6
array[4] = 10

System Verilog Tutorials