Verilog Generate Blocks

Generate blocks allow conditional and iterative creation of hardware structures at elaboration time, enabling parameterized designs.

Generate-For Loop

Create multiple instances of hardware using genvar:

N-bit Ripple Carry Adder
module ripple_adder #(
    parameter WIDTH = 8
) (
    input  wire [WIDTH-1:0] a, b,
    input  wire             cin,
    output wire [WIDTH-1:0] sum,
    output wire             cout
);
    wire [WIDTH:0] carry;
    assign carry[0] = cin;
    assign cout = carry[WIDTH];
    genvar i;
    generate
        for (i = 0; i < WIDTH; i = i + 1) begin : fa_stage
            full_adder fa (
                .a    (a[i]),
                .b    (b[i]),
                .cin  (carry[i]),
                .sum  (sum[i]),
                .cout (carry[i+1])
            );
        end
    endgenerate
endmodule

Key Points

  • genvar is a special variable for generate loops
  • Each iteration creates a separate hardware instance
  • Named block (fa_stage) is required for unique paths

Generate-If (Conditional)

Conditionally include hardware based on parameters:

Conditional Instantiation
module fifo #(
    parameter DEPTH = 16,
    parameter USE_BRAM = 1  // 1=BRAM, 0=distributed RAM
) (
    input  wire clk,
    // ... other ports
);
    generate
        if (USE_BRAM) begin : bram_impl
            // Instantiate Block RAM
            bram_fifo #(.DEPTH(DEPTH)) fifo_mem (...);
        end else begin : dist_impl
            // Use distributed RAM (flip-flops)
            reg [7:0] mem [0:DEPTH-1];
            // ... logic
        end
    endgenerate
endmodule

Generate-Case

Multi-Option Selection
module multiplier #(
    parameter IMPL_TYPE = 0  // 0=sequential, 1=parallel, 2=DSP
) (
    input  wire [15:0] a, b,
    output wire [31:0] product
);
    generate
        case (IMPL_TYPE)
            0: begin : seq_mult
                // Sequential multiplier (small, slow)
                seq_multiplier mult (...);
            end
            1: begin : par_mult
                // Parallel multiplier (large, fast)
                parallel_multiplier mult (...);
            end
            2: begin : dsp_mult
                // DSP block multiplier
                dsp_multiplier mult (...);
            end
        endcase
    endgenerate
endmodule

Common Interview Questions

  1. What is genvar?

    A special loop variable that exists only during elaboration, not simulation. It's used in generate-for loops.

  2. When are generate blocks evaluated?

    At elaboration (compile) time, before simulation starts. They create static hardware structures.

  3. Can you use regular variables in generate conditions?

    No. Only parameters and genvars can be used since generate must be resolved at compile time.