Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly handle zero bit width case?

When I write generic module, I often encounter 0-bit width case.

module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
    always_comb begin
        y = x[WIDTH - 1 : 0];
    end
endmodule

For example, the above module extracts lowest WIDTH bits from x. When WIDTH is 0, output is don't care. However, when the module is instantiated with WIDTH 0, I get the following error in Modelsim:

# ** Fatal: (vsim-3373) test.sv(8): Range of part-select [-1:0] into 'x' [31:0] is reversed.

I tried the following code hoping for the bad part to be optimized out at compile time, but the error remains.

if (WIDTH == 0) y = 0;
else y = x[WIDTH - 1 : 0];

Is there any remedy to this situation?

like image 686
csehydrogen Avatar asked Sep 04 '25 17:09

csehydrogen


1 Answers

Your procedural code needs to compile, even if the branch with the bad range is never taken.

module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
    always_comb
       if (WIDTH == 0) y = 'x;
       else y = x[WIDTH - 1 + (WIDTH==0): 0];
endmodule

You could also do

module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
if (WIDTH==0)
  assign y = 'x;
else
  assign  y = x[WIDTH - 1: 0];
endmodule
like image 153
dave_59 Avatar answered Sep 07 '25 19:09

dave_59