2
\$\begingroup\$

When creating logic using a for loop, Verilog requires the loop index to be declared. I've seen examples where it's done with either "int" or "genvar" keywords. For example:

// Using genvar:
for (genvar x = 0 ; x < some_value ; x++) begin
// do something with reference to x
end 

// Using int:
for (int x = 0 ; x < some_value ; x++) begin
// do something with reference to x
end 

When should I choose one over the other ?

\$\endgroup\$
0

2 Answers 2

5
\$\begingroup\$

This is somewhat historical. Prior to SystemVerilog, you had to declare the loop index separately, and prior to Verilog-2001, you had to enclose a generate-for loop with the keywords generate/endgenerate

module top;
  generate 
    genvar i;
    for (i=0; i<4 ; i = i + 1) begin
       integer j;
       reg [i+1:0] value;
       initial for(j=0; j<4; j = j + 1) $display("i:%0d j:%0d value:%b",i,j, value);
    end
  endgenerate
endmodule

This was to indicate that i was not an index variable, but was part of an elaboration unrolling construct. Verilog-2001 got rid of the need for the extra keywords because it could determine that the outer for-loop was a not procedural loop, and the inner for-loop was procedural.

SystemVerilog added the ability to declare the loop iteration index variable inside the for-loop, but it still requires you to use the genvar index declaration to inidicate that it is not really a variable.

module top;
    for (genvar i=0; i<4 ; i++) begin
           reg [i+1:0] value;
           initial for(int j=0; j<4; j++) $display("i:%0d j:%0d value:%b",i,j, value);
    end
endmodule
\$\endgroup\$
1
\$\begingroup\$

You should use genvar only when the for loop is part of a generate construct. A for loop need not be part of a generate construct. Refer to IEEE Std 1800-2017, section 27. Generate constructs.

Here is example code which illustrates 2 scenarios:

module tb;

wire [3:0] a, b;
reg  [3:0] c;

// Must use genvar for this generate construct
genvar i;
for (i=0; i<4; i++) begin
    assign a[i] = i;
end

// Must not use genvar since this is not a generate construct
int j;
always @* begin
    for (j=0; j<4; j++) begin
        c[j] = b[j];
    end
end

endmodule

The generate/endgenerate keywords are optional.

\$\endgroup\$
1
  • \$\begingroup\$ What if I want the logic to be generated inside an "always_ff" block ? always_ff @ ( posedge clock ) begin for ("genvar/int ?" i=0;i<8,i++) begin y[i+1]<=x[i]. Should I declare i as an "int" or as a "genvar" ? \$\endgroup\$
    – shaiko
    Sep 9, 2020 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.