verilog

How can I calculate a generate loop control value from a module parameter?


I have a module which has an integer parameter. This parameter controls a generate loop. When the parameter value is 0, then it cannot be used but must be replaced by 1. I tried to use a function, but the function can only initialize a variable, which cannot be used for the control of the generate loop. This is my example code which gave this error message

Unable to bind parameter `number'

for the code line with the generate instruction:

module test
    #(parameter
        g_latency = 8
    )
    ;
    function integer get_number;
        begin
            if (g_latency==0) begin
                get_number = 1;
            end else begin
                get_number = g_latency;
            end
        end
    endfunction

    genvar i;
    integer number;

    initial begin
        number = get_number;
    end
    generate for (i=0; i<=number-1; i=i+1)
        begin: step_g
            // comment
        end
    endgenerate
endmodule

So, how can I calculate a generate control value from a module parameter?


Solution

  • You can use another parameter instead of a function to create the compile-time constant:

    module test
        #(parameter
            g_latency = 8
        );
    
        localparam NUMBER = (g_latency==0) ? 1 : g_latency;
    
        genvar i;
        generate for (i=0; i<=NUMBER-1; i=i+1)
            begin: step_g
                initial $display("%m i=%0d g_latency=%0d", i, g_latency);
            end
        endgenerate
    endmodule
    
    module tb;
        test #(0) i0 ();
        test      i1 ();
    endmodule
    

    Output:

    tb.i0.step_g[0] i=0 g_latency=0
    tb.i1.step_g[0] i=0 g_latency=8
    tb.i1.step_g[1] i=1 g_latency=8
    tb.i1.step_g[2] i=2 g_latency=8
    tb.i1.step_g[3] i=3 g_latency=8
    tb.i1.step_g[4] i=4 g_latency=8
    tb.i1.step_g[5] i=5 g_latency=8
    tb.i1.step_g[6] i=6 g_latency=8
    tb.i1.step_g[7] i=7 g_latency=8