Is there any way to implemnt $countones functionality without system function in constraints ?
I see many examples leads to unravelling (bit(0) + bit(1) +… bit(n) ==1 ) which is not feasible for all.
Is there any way to implemnt $countones functionality without system function in constraints ?
I see many examples leads to unravelling (bit(0) + bit(1) +… bit(n) ==1 ) which is not feasible for all.
How about posting a constraint which does use $countones (or other system functions), so we can see the problem you’re trying to solve?
Iam not trying anything specific, but a general question.
class pkt;
rand logic [31:0] val;
constraint count_ones_c {$countones(val) == 6;}
endclass
We do not know the conditions that make a constraint feasible or not.
For your example, a sum()
method can be used.
class pkt;
rand logic [31:0] val;
rand bit helper[$bits(val)]
constraint count_ones_c {helper.sum() with (int'(item)== 6;
foreach(helper[i]) helper[i] == val[i]; }
endclass
Here’s a hard to understand solution, just thought I’d try out the log2(n) algorithm from Hacker’s Delight :
class countones;
rand bit [31:0] val, val1, val2, val3, val4, val5;
constraint c1 {
val1 == (val & 'h5555_5555) + ((val >> 1) & 'h5555_5555);
val2 == (val1 & 'h3333_3333) + ((val1 >> 2) & 'h3333_3333);
val3 == (val2 & 'h0F0F_0F0F) + ((val2 >> 4) & 'h0F0F_0F0F);
val4 == (val3 & 'h00FF_00FF) + ((val3 >> 8) & 'h00FF_00FF);
val5 == (val4 & 'h0000_FFFF) + ((val4 >> 16) & 'h0000_FFFF);
val5 == 6;
}
function void print;
$display("val: 'h%0x (bit count: %0d)", val, $countones(val));
endfunction
endclass
module top;
countones c = new;
initial
repeat (10) begin
c.randomize();
c.print;
end
endmodule