Sum() in constraint

In the below example if the “addr” is declared as bit[8:0] the randomization is giving incorrect results. However, if “addr” is declared as bit[31:0] correct output is coming. Can somebody please help me to understand why is this happening?

// Incorrect output code 
class abc;
  rand bit[8:0] addr[];// declared as 9 bits
  constraint addr_c{
    addr.size == 20;
    foreach(addr[i]){
      if(i>0) addr[i] > addr[i-1];
      addr[i] <300;}
       addr.sum == 'h12c; 
  
  }
  
   function void post_randomize();
       $display("arr = %0p",addr);
  endfunction: post_randomize
endclass: abc
                    
                 

//=======================================================
//=======================================================

// Correct results
class abc;
  rand bit[31:0] addr[];// declared as 32 bits
  constraint addr_c{
    addr.size == 20;
    foreach(addr[i]){
      if(i>0) addr[i] > addr[i-1];
      addr[i] <300;}
       addr.sum == 'h12c; 
  
  }
  
   function void post_randomize();
       $display("arr = %0p",addr);
  endfunction: post_randomize
endclass: abc

Hi @dave_59
I think here the issue is I have already taken care of the overflow in the first example, but results comes correct with delcaration as bit[31:0]

How do you think you took care of the overflow in the first example? what is the largest possible sum of 20 elements?

Since each value is less than 300 and sum is 'h12c, both conditions will together make sure overflow should not happen

No it will not.

Run with this code

 abc h = new;
  initial begin
    h.randomize;
    $displayh(h.addr.sum() with (int'(item)));
  end

This is correct. However, why does “Since each value is less than 300 and sum is 'h12c, both conditions will together make sure overflow should not happen” this condition is not being followed?

the sum has the overflow, not the addr. the maximum sum is 299+298+297+296+…+280, which is larger than 'h1ff. you can set the addr as [13:0], the result is correct.

1 Like