Randomization of array of basic type, vs randomization of array of structs

In the following code (edaplaground):

  • when we’re randomizing an array of plain bit, array size is randomized with array contents → no contradiction
  • when we’re randomizing an array of structs, array size is randomized before array contents → occasional contradiction

Questions:

  • What is the SystemVerilog rule that dictates this cross-simulator behavior?
  • Is there a way to get the struct array to behave similar to the bit array? I’ve been adding a rand valid bit to each struct via a template class, but I wonder if there’s a better way.

module rand_lists();
  typedef struct {
    rand bit x;
  } some_struct_t;
  
  class rand_bit_array;
    rand bit q[];
    
    constraint c_q_size {
      q.size() <= 5;
    };
    
    constraint c_q_val {
      q.sum(item) with (32'(item)) == 5;
    };
    
    function new();
      q = new[10];
    endfunction
  endclass

  class rand_struct_array;
    rand some_struct_t q[];
    
    constraint c_q_size {
      q.size() <= 5;
    };
    
    constraint c_q_val {
      q.sum(item) with (32'(item.x)) == 5;
    };
    
    function new();
      q = new[10];
    endfunction
  endclass
  
  initial begin
    rand_struct_array struct_array_i;
    rand_bit_array bit_array_i;

    bit_array_i = new();
    bit_array_i.randomize();
    
    $display("%p", bit_array_i.q);
    
    
    struct_array_i = new();
    struct_array_i.randomize();
    
    $display("%p", struct_array_i.q);
  end
endmodule

In reply to avidan_apple:

Hello,

I faced a somewhat similar issue with all 3 simulators with unpacked structures, I know this does not provide any answer to your question but have you tried to used packed structures
unpacked structs randomization using std:randomize | Verification Academy .

HTH,
R

In reply to avidan_apple:

Hi Avidan,

This issue was recently clarified in the next revision of the LRM.

The size of an array may be solved before the iterative constraints. Unfortunately this doesn’t give the user any clarity or guarantees when it will or won’t be solved before. Apparently, some tools have found a few cases where they can solve the array size and it contents concurrently, but you should never depend on it.

What this means is that you have to carefully calculate the constraints on the array size based on what you expect the constraints on the element will be, you modify the constraints on the elements based on the size of the array.

In reply to rgarcia07:

ah, an interesting proposal, but gives me the exact same results…perhaps I’m missing something

In reply to dave_59:

Thanks a lot Dave, that clarifies it.