I noticed the following in the Verilog 2005 standard (5.1.8 Equality operators):
If the operands are of unequal bit lengths and if one or both operands are unsigned, the smaller operand shall be zero-extended to the size of the larger operand. If both operands are signed, the smaller operand shall be sign-extended to the size of the larger operand.
and then in (3.5.1 Integer constants):
Simple decimal numbers without the size and the base format shall be treated as signed integers
I've actually had a bit of trouble finding the bit size of integers in verilog, although this website says:
integer is typically a 32 bit twos complement integer.
So, given that and the fact that the equality operation is performed bitwise (also stated in 5.1.8), does using an unsized integer cost more in the sense that the bit comparison is forced to use all 32 bits?
Take the following example as an illustration:
`default_nettype none
`timescale 1ns/1ps
module top;
reg [3:0] ctr = 0;
reg clk = 0;
reg some_reg = 0;
always #1 clk = !clk;
initial begin
$dumpfile("top.vcd");
$dumpvars(0, top);
#20 $finish;
end
always @(posedge clk) begin
ctr <= ctr + 1;
// if (ctr == 4'd5) // cheaper?
if (ctr == 5)
some_reg <= 1;
end
endmodule
What are the implications for comparisons with parameters? ie
`default_nettype none
`timescale 1ns/1ps
module top;
localparam SIZE = 5;
reg [3:0] ctr = 0;
reg clk = 0;
reg some_reg = 0;
always #1 clk = !clk;
initial begin
$dumpfile("top.vcd");
$dumpvars(0, top);
#20 $finish;
end
always @(posedge clk) begin
ctr <= ctr + 1;
if (ctr == SIZE)
some_reg <= 1;
end
endmodule
Should we specify the bit widths of parameters then? i.e.
`default_nettype none
`timescale 1ns/1ps
module top;
localparam [3:0] SIZE = 5;
reg [3:0] ctr = 0;
reg clk = 0;
reg some_reg = 0;
always #1 clk = !clk;
initial begin
$dumpfile("top.vcd");
$dumpvars(0, top);
#20 $finish;
end
always @(posedge clk) begin
ctr <= ctr + 1;
if (ctr == SIZE)
some_reg <= 1;
end
endmodule
Are there any good guidelines about when its safe to use unsized integer constants in expressions? For instance, I use them on the rhs of expressions above since the standard states (5.6 Assignments and truncation):
If the width of the right-hand expression is larger than the width of the left-hand side in an assignment, the MSBs of the right-hand expression will always be discarded to match the size of the left-hand side.
I assumed this means that ctr <= ctr + 1
adds ctr
to 1'b1
or 4'd1
. Or, does it add ctr
to 32'd1
and then discard the top 28 bits?