I am trying to come up with a way to add individual bits of a register.
eg, if regA = 111000 then regB = 3
(Sum of bits of regA
).
1) Is there any synthesizable function/operator in Verilog or SystemVerilog which I can directly use to do this operation?
If not, then maybe the problem is a little interesting, especially because the operation has to be done in one clock cycle (pure combinational logic) and the register width is parameterizable.
2) In case there is no inbuilt Verilog or SystemVerilog operator then what can be done?
Thanks,
Ujjwal
Verilog (IEEE Std 1364-2001 or newer):
integer i;
always @* begin
B = WIDTH_LOG2'b0;
for (i=0; i<WIDTH; i=i+1)
B = B + A[i];
end
SystemVerilog (IEEE Std 1800-2005 or newer):
always_comb begin
B = '0; // fill 0
foreach(A[i])
B += A[i];
end
Both will synthesize to combination logic. No latches or flops.
SystemVerilog does have $countones()
, but I'm unsure if it is synthesizable. Ff it is then: always_comb B = $countones(A)
You can try something like this. I am not exactly sure what it will synthesize to but it should work.
int i;
reg [`WIDTH-1:0] A;
reg [`WIDTH_LOG2:0] B;
B = 0;
for(i = 0; i < `WIDTH; i = i + 1)
begin
B = B + A[i];
end
Of course there are more complex ways that may have better performance, depending on on your tool flow and what is available, where you can create your own adders and cascade them in parallel reducing the size each step. Assuming the width was 32-bits, something like:
adder1bit_1(output1, A[31:24]);
adder1bit_2(output2, A[23:16]);
adder1bit_3(output3, A[15:8]);
adder1bit_4(output4, A[7:0]);
adder3bit_1(output5, output1, output2);
adder3bit_2(output6, output3, output4);
adder4bit(final_ouput, output5, output6);