RTL Reference

generate Loops and Parameters

A generate loop repeats hardware at elaboration time. A parameter sets how many copies you get.

Syntax

module pipe #(parameter int N = 4) (...);
  for (genvar i = 0; i < N; i++) begin : g_stage
    stage u (.d(x[i]), .q(x[i+1]));
  end
endmodule

Rules

  • The loop variable is a genvar. It exists only while the design is built.
  • Name the block (begin : g_stage). Each copy is then g_stage[0], g_stage[1] and so on.
  • The loop bound must be a constant: a parameter or a localparam.
  • A generate if or case picks hardware by parameter.
  • Set a parameter at the instance: pipe #(.N(8)) u (...);.
  • Use localparam for values derived from parameters, such as $clog2(N).

Example

module xor_chain #(parameter int N = 4) (input logic [N-1:0] d, output logic y);
  logic [N:0] x;
  assign x[0] = 1'b0;
  for (genvar i = 0; i < N; i++) begin : g_bit
    assign x[i+1] = x[i] ^ d[i];
  end
  assign y = x[N];
endmodule

module tb;
  logic [3:0] d4;
  logic [7:0] d8;
  logic y4, y8;
  xor_chain #(.N(4)) u4 (.d(d4), .y(y4));
  xor_chain #(.N(8)) u8 (.d(d8), .y(y8));

  initial begin
    d4 = 4'b1011; d8 = 8'b1100_0011;
    #1 $display("parity of %b = %b", d4, y4);
    $display("parity of %b = %b", d8, y8);
  end
endmodule
Output on Icarus Verilog 12
parity of 1011 = 1
parity of 11000011 = 0

Run It in the Playground

Common Mistake

A loop bound that is a signal

for (genvar i = 0; i < count; i++) ...   // count is a signal: error

Hardware cannot appear or vanish while the circuit runs. The number of copies must be known when the design is built.

Fix: Build the largest size with a parameter, and enable the stages you need with logic.

Learn It Properly

These lessons teach it step by step, with practice problems.

Standard

IEEE 1800-2023, 27.4.