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.
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?