Using functions inside constraints

 rand bit tmp1, tmp2;
  function bit my_f(tmp);
   return tmp;
  endfunction
  constraint tmp_cnstr {
    my_f(tmp1 + tmp2) == 2;
  }

It sounds like tmp1 and tmp2 are solved before the constraint is applied and are assigned to 0. How can I use a function inside constraints?

my_f( .tmp( ( tmp1 + tmp2 ) ) ) (U1) SOLVED EARLY 0 (0x0)
tmp1 (U1) SOLVED EARLY 0 (0x0)
tmp2 (U1) SOLVED EARLY 0 (0x0)

You are very limited in how you can use a user defined function inside a constraint.

Either the function input arguments cannot reference any random variables, or the function return value cannot have any constraints that restrict the function inputs.

rand bit [7:0] tmp1, tmp2;
  function bit [7:0] my_f(tmp);
   return tmp+1;
  endfunction
  constraint c1 {
    tmp1 < 10;  tmp2 < 10;
  }
  constraint c2 {
    my_f(tmp1)+ tmp2 == 10;
  }

In this example, you could not constrain the sum in c2 to anything other than 10 because my_f(tmp1) could return any value between 1 and 10.

Thank you, Dave.
Below is what I am trying to do. But it seems that the array is randomized before the constraint takes affect. Is there a way to make it work?

rand bit arr[5][5];
function int sum_2d_array(int arr[5][5]);
    int sum = 0;
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            sum += arr[i][j];
        }
    }
    return sum;
endfunction

constraint sum_constraint {
    sum_2d_array(arr) == target_sum;
}

If you are looking to constrain the sum of all the elements in a 2D array, you can use the built-in array reduction method, sum().

rand bit arr[5][5];
constraint c_sum { arr.sum(D1) with (D1.sum(D2))== target_sum; }

Unlike user defined function, the built-in reduction methods get expanded into one big constraint equasion. See section 18.5.8.2 Array reduction iterative constraints in the IEEE 1800-2017 LRM.

Thank you, Dave

I thought that it worked, but it didn’t.
“Identifier ‘D2’ has not been declared yet.” with VCS
“‘with’ clause not specified for the iterator argument.” with Xrun
Any idea why?

I switched to 1D array, which solved the constraint issue, but it would be nice to have the constraint with 2D array.

D2 is unnessary in theis example, but there appears to be tool issues

See 2D array constraint randomization - #7 by dave_59

Thank you, Dave!