HDL for synthesis · Lesson 2 of 4

Verilog and SystemVerilog for synthesis

Write synthesizable Verilog and SystemVerilog: modules, ports, parameters, logic, always_ff and always_comb, blocking vs non-blocking assignment and generate.

beginner45 minUpdated Free

What you will learn

  • Write a parameterised SystemVerilog module and instantiate it with named port connections
  • Choose between always_ff, always_comb and continuous assignment for a piece of logic
  • Apply the blocking and non-blocking assignment rules and explain what breaks when they are ignored
  • Avoid sizing and signedness mistakes in vectors, literals and arithmetic
  • Tell synthesizable constructs apart from simulation-only ones

Before you start

  • What is an FPGA (lesson 1)
  • The FPGA design flow (lesson 3)
  • Basic digital logic: gates, flip-flops, binary numbers

After this lesson you can write synthesizable SystemVerilog modules, connect them into a hierarchy, and avoid the handful of mistakes that cause most beginner bugs: wrong assignment type, silent truncation and accidental unsigned arithmetic. The examples use SystemVerilog, which every current FPGA synthesis tool accepts for design code. Plain Verilog-2001 differences are listed at the end.

An HDL describes hardware, not a program

Verilog looks like C, but it does not run line by line on a processor. Each assign statement, each always block and each module instance describes a piece of hardware. All of that hardware exists at the same time and works in parallel.

Take these two lines:

assign sum   = a + b;
assign carry = a & b;

Swapping their order changes nothing. They describe an adder and an AND gate, side by side, both connected to a and b. Order only matters inside a procedural block, and even there it matters in a specific way that this lesson explains below.

A useful habit: before writing a line of HDL, sketch the registers and the logic between them. Then write code that describes that sketch. If you cannot say what hardware a line produces, the synthesis tool may produce something you did not expect.

Modules, ports and parameters

A module is the unit of hardware. It has ports (its pins) and an implementation. Here is a counter with a synchronous reset and a count enable:

module counter #(
    parameter int WIDTH = 8
) (
    input  logic             clk,
    input  logic             rst,    // synchronous, active high
    input  logic             en,     // count enable
    output logic [WIDTH-1:0] count
);

    always_ff @(posedge clk) begin
        if (rst)
            count <= '0;
        else if (en)
            count <= count + WIDTH'(1);
    end

endmodule
Download counter.sv

The parts:

  • #(parameter int WIDTH = 8) declares a parameter with a default value. Parameters are constants fixed at elaboration time. Use them for widths, depths and clock frequencies so one module serves many uses.
  • The port list uses ANSI style: direction, type and width in one place. input, output and inout are the three directions. Reserve inout for the top-level pins that really are bidirectional.
  • '0 is SystemVerilog shorthand for “all bits zero” at whatever width the target has. '1 sets all bits to one.
  • WIDTH'(1) is a size cast. It makes the constant exactly WIDTH bits so the addition has matching widths and lint tools stay quiet.

Instantiation with named port connections

To use a module, you instantiate it inside another module. This top level cascades two counters into a 12-bit count:

module counter_top (
    input  logic        clk,
    input  logic        rst,
    input  logic        en,
    output logic [11:0] count
);

    logic [3:0] low;
    logic [7:0] high;
    logic       low_wrap;

    // The low counter wraps when it is at 4'hF and about to count.
    assign low_wrap = en && (low == 4'hF);

    counter #(.WIDTH(4)) u_low (
        .clk   (clk),
        .rst   (rst),
        .en    (en),
        .count (low)
    );

    counter #(.WIDTH(8)) u_high (
        .clk   (clk),
        .rst   (rst),
        .en    (low_wrap),
        .count (high)
    );

    assign count = {high, low};

endmodule
Download counter_top.sv

#(.WIDTH(4)) overrides the parameter for that instance. u_low and u_high are instance names; they appear in the simulator hierarchy and in synthesis reports, so give them meaningful names. .port(signal) is a named connection. Always use named connections. Positional connections (counter u0 (clk, rst, en, low);) compile fine and break silently when someone reorders the ports.

SystemVerilog also accepts .clk as shorthand for .clk(clk) and .* to connect every port to a signal of the same name. .* saves typing but hides the connections from a reader. Explicit named connections are the safer default.

Nets and variables: wire, reg and logic

Verilog-2001 has two kinds of signal:

  • wire is a net. A continuous assign or a module output drives it.
  • reg is a variable. An always or initial block assigns it.

The name reg misleads beginners. A reg assigned in a combinational always block is not a register; it is just a variable the synthesis tool turns into gates. Whether you get a flip-flop depends on how the block is written, not on the keyword.

SystemVerilog adds logic, which can be used in both places. A logic signal can be driven by one continuous assignment, or by procedural code, or connected to a module output. Use logic for almost everything. You still need a net type such as wire when a signal has more than one driver, which in FPGA design means a bidirectional top-level pin. The combinational logic lesson covers tri-states.

Vectors and literals

logic [7:0] data; declares an 8-bit vector with bit 7 as the most significant bit. Use [N-1:0] consistently; mixing [0:7] and [7:0] in one design invites bit-order bugs.

Literal syntax is <width>'<base><value>:

LiteralMeaning
8'hA58 bits, hex A5
4'b10104 bits, binary 1010
12'd10012 bits, decimal 100
8'sd58 bits, signed decimal 5
100unsized decimal, at least 32 bits, signed
'0, '1fill every bit of the target with 0 or 1
8'b1010_0101underscores are ignored and help readability

Width mismatches do not cause errors. If you assign 8'hFF to a 4-bit signal, the upper bits are dropped. If you assign a 4-bit value to an 8-bit signal, it is zero-extended (or sign-extended if the value is signed). This is legal and often a bug. Run a linter: verilator --lint-only -Wall reports width mismatches as WIDTHTRUNC or WIDTHEXPAND warnings.

Concatenation {a, b} joins vectors, and replication {4{1'b1}} repeats one. {high, low} in counter_top builds the 12-bit result.

Signed arithmetic pitfalls

Vectors are unsigned unless declared signed. The rule that catches people: if any operand in an expression is unsigned, the whole expression is evaluated as unsigned.

logic signed [7:0] a = -8'sd5;   // bit pattern 8'hFB
logic        [7:0] b = 8'd2;     // unsigned
logic signed [7:0] c = 8'sd2;    // signed

// a < b          is false: compared as 251 < 2
// a < c          is true:  compared as -5 < 2
// a < $signed(b) is true
Download tb_signed.sv

Three more cases produce an unsigned result even when the source is signed: a part-select such as a[7:0], a concatenation such as {a, 1'b0}, and any based literal written without the s marker, such as 8'd3. When you need signed arithmetic, declare every operand signed, or wrap operands in $signed(). Then check the result in simulation with negative inputs.

Continuous assignment

assign describes combinational logic that is always active:

assign y      = sel ? b : a;          // 2:1 multiplexer
assign parity = ^data;                // XOR of all bits
assign {cout, sum} = a + b;           // adder with carry out

Use assign for simple expressions. When the logic needs if or case, use always_comb.

always_ff, always_comb and always @*

Verilog-2001 has one procedural block, always, and the sensitivity list decides what it means. always @(posedge clk) describes flip-flops. always @* describes combinational logic. Nothing stops you from writing something in between that synthesizes to a latch or does not match simulation.

SystemVerilog adds three blocks that state your intent:

  • always_ff @(posedge clk) for flip-flops. Tools may warn if the body does not describe sequential logic.
  • always_comb for combinational logic. It infers its own sensitivity list, runs once at time zero, and tools may warn when the code implies a latch.
  • always_latch for the rare case where you want a latch. In FPGA design you almost never do.

always_comb has two concrete advantages over always @*. It executes at time zero, so outputs start with values computed from the inputs instead of staying x until some input changes. It also forbids any other process from writing the same variables, which catches multiple-driver mistakes before simulation starts.

always_comb begin
    y = '0;              // default value on every path
    if (en)
        y[sel] = 1'b1;
end

The sequential logic lesson covers always_ff styles for resets and enables.

Blocking and non-blocking assignment

Inside a procedural block there are two assignment operators:

  • Blocking = updates the variable immediately. The next line sees the new value.
  • Non-blocking <= evaluates the right-hand side now and schedules the update for the end of the time step. Every line in the block sees the old values.

Non-blocking assignment models what flip-flops do: on a clock edge every register samples its input at the same instant, then all outputs change together.

Worked example: a three-stage delay line

The correct version uses <=:

always_ff @(posedge clk) begin
    q1 <= d;
    q2 <= q1;
    q3 <= q2;
end

On each edge q1 takes d, q2 takes the old q1, and q3 takes the old q2. A pulse on d appears on q3 three clock edges later.

The following block is wrong. It is the same code with blocking assignments:

// WRONG: blocking assignments in a clocked block
always_ff @(posedge clk) begin
    q1 = d;
    q2 = q1;    // reads the q1 written one line above, which is d
    q3 = q2;    // reads the q2 written one line above, which is d
end
Two rows of three D flip-flops. In the top row, labelled non-blocking, d feeds the first flip-flop, its output q1 feeds the second, and q2 feeds the third, whose output is q3. In the bottom row, labelled blocking, the input d is wired to the D input of all three flip-flops.
Non-blocking assignments in a clocked block build a shift chain; the same lines written with blocking assignments make every register load d on the same edge.

Every register now loads d on the same edge, as the lower half of the figure shows. The delay line has become a single register, and a synthesis tool may merge the three identical flip-flops into one. The testbench drives a one-cycle pulse into both versions:

edge 1: d_hist=0001 q3_good=0 q3_bad=1
edge 2: d_hist=0010 q3_good=0 q3_bad=0
edge 3: d_hist=0100 q3_good=1 q3_bad=0
edge 4: d_hist=1000 q3_good=0 q3_bad=0
edge 5: d_hist=0000 q3_good=0 q3_bad=0
PASS

q3_bad shows the pulse after one edge instead of three. Verilator catches the mistake before you simulate: verilator --lint-only -Wall delay3_bad.sv reports BLKSEQ (blocking assignment in sequential logic) on all three lines.

Download delay3.sv Download delay3_bad.sv (wrong on purpose) Download tb_verilog_basics.sv

Reversing the line order (q3 = q2; q2 = q1; q1 = d;) happens to give a working shift register with blocking assignments. Do not rely on that. The code then depends on statement order, and the next person to edit it will not know.

A second failure mode involves two blocks. If always @(posedge clk) a = b; and always @(posedge clk) b = a; are in separate blocks, the simulator may run either block first, and the result depends on that order. The hardware is two registers swapping values. Non-blocking assignment removes the race.

The rules

  1. In always_ff, use only <=.
  2. In always_comb, use only =.
  3. Never mix = and <= in one block.
  4. Assign each variable from exactly one block.

Follow these four rules and simulation matches hardware for the constructs in this course.

Generate blocks

Generate constructs create hardware at elaboration time, controlled by parameters. A generate for loop replicates logic; a generate if or case picks between alternatives.

module bit_reverse #(
    parameter int WIDTH      = 8,
    parameter bit REGISTERED = 1'b1
) (
    input  logic             clk,
    input  logic [WIDTH-1:0] din,
    output logic [WIDTH-1:0] dout
);

    logic [WIDTH-1:0] rev;

    for (genvar i = 0; i < WIDTH; i++) begin : g_rev
        assign rev[i] = din[WIDTH-1-i];
    end

    if (REGISTERED) begin : g_reg
        always_ff @(posedge clk) dout <= rev;
    end else begin : g_comb
        assign dout = rev;
    end

endmodule
Download bit_reverse.sv

The loop variable is a genvar, which only exists during elaboration. Label every generate block (: g_rev). The label names the hierarchy, so the instance of bit 3 appears as g_rev[3] in the simulator and in synthesis reports. Since Verilog-2005 the generate and endgenerate keywords are optional; older code wraps these blocks in them.

A procedural for loop inside always_comb is also synthesizable when its bounds are constants. The tool unrolls it into parallel hardware. It is not a loop that runs over time.

Synthesizable and simulation-only constructs

The language has two audiences: synthesis tools and simulators. Much of it only makes sense to the simulator.

SynthesizableSimulation only (ignored or rejected by synthesis)
module, ports, parameters, localparam# delays such as #10
assign, always_ff, always_comb$display, $monitor, $finish, $random
if, case, operators, functionsfork/join, wait, force/release
for loops with constant boundswhile loops with data-dependent exit
Generate for, if, caseClasses, queues, dynamic arrays
Packed structs, enums, packagesFile I/O (except memory initialisation, below)

Two items sit on the border. initial blocks are simulation constructs in general, but FPGA tools accept initial values on registers and $readmemh/$readmemb for memory contents, because an SRAM-based FPGA loads every flip-flop and block RAM during configuration. The memory lesson uses this. Second, synthesis tools ignore # delays, often with only a warning. A design that only works in simulation because of a delay will fail in hardware.

Verilog-2001 compared with SystemVerilog

TopicVerilog-2001SystemVerilog (for design)
Signal typeswire, reglogic for nearly everything
Flip-flop blockalways @(posedge clk)always_ff @(posedge clk)
Combinational blockalways @*always_comb
Fill literals{WIDTH{1'b0}}'0, '1
Size castsnot availableWIDTH'(x), signed'(x)
Port connection shorthandnamed or positional only.clk, .*
User typesnonetypedef, enum, struct packed
Shared definitions`include filespackage and import
Case checkingtool pragmas in commentsunique case, priority case

The right-hand column is part of the synthesizable subset that FPGA vendors document. Support for individual constructs still differs between tools and versions, and the built-in SystemVerilog front end of the open-source Yosys flow covers a smaller subset. If a tool rejects a construct, check its synthesis guide.

Checking your code

Every design file in this lesson passes both of these commands with no warnings:

iverilog -g2012 -Wall -o /dev/null counter.sv
verilator --lint-only -Wall counter.sv

Two exceptions are deliberate. delay3_bad.sv triggers BLKSEQ, which is the point of the example. bit_reverse.sv with REGISTERED = 0 leaves clk unconnected internally, and Verilator reports UNUSEDSIGNAL. To run the testbench:

iverilog -g2012 -o sim tb_verilog_basics.sv counter.sv counter_top.sv \
    delay3.sv delay3_bad.sv bit_reverse.sv
vvp sim

Verilator’s -Wall is strict and catches width, signedness and assignment-type mistakes that Icarus accepts silently. Run it on every module you write. The testbenches lesson shows how to structure self-checking tests like the one above.

Exercise

Write a parameterised register with enable

Write a module en_reg with a parameter WIDTH (default 16), inputs clk, rst (synchronous, active high), en and d[WIDTH-1:0], and output q[WIDTH-1:0]. On a rising edge, reset clears q; otherwise q loads d when en is high. Then instantiate two copies in a top module: one 16 bits wide and one 4 bits wide, using named port connections. Lint both files with verilator --lint-only -Wall.

Show solution
module en_reg #(
    parameter int WIDTH = 16
) (
    input  logic             clk,
    input  logic             rst,
    input  logic             en,
    input  logic [WIDTH-1:0] d,
    output logic [WIDTH-1:0] q
);

    always_ff @(posedge clk) begin
        if (rst)
            q <= '0;
        else if (en)
            q <= d;
    end

endmodule

module en_reg_top (
    input  logic        clk,
    input  logic        rst,
    input  logic        en,
    input  logic [15:0] d16,
    input  logic [3:0]  d4,
    output logic [15:0] q16,
    output logic [3:0]  q4
);

    en_reg u_wide (
        .clk (clk),
        .rst (rst),
        .en  (en),
        .d   (d16),
        .q   (q16)
    );

    en_reg #(.WIDTH(4)) u_narrow (
        .clk (clk),
        .rst (rst),
        .en  (en),
        .d   (d4),
        .q   (q4)
    );

endmodule

u_wide uses the default WIDTH of 16. Only <= appears in the always_ff block, and every port connection is named.

Exercise

Find the bug

This block should compute y = (a + b) >> 1, the average of two 8-bit unsigned numbers, without losing the carry. It gives wrong results for large inputs. Explain why and fix it.

logic [7:0] a, b, y;
always_comb y = (a + b) >> 1;
Show solution

The expression width is set by the widest operand and the target, which are all 8 bits. The sum is computed in 8 bits, so the carry out of bit 7 is lost before the shift. For a = 200 and b = 100 the sum 300 wraps to 44 and y becomes 22 instead of 150. Make the sum 9 bits wide before shifting:

logic [8:0] sum9;
always_comb begin
    sum9 = {1'b0, a} + {1'b0, b};
    y    = sum9[8:1];
end

Summary

  • HDL code describes hardware that runs in parallel. Sketch the registers and logic first, then write code that matches the sketch.
  • Use logic, ANSI port lists, parameters for widths, and named port connections on every instance.
  • Use always_ff with <= for registers and always_comb with = for combinational logic. Never mix the two assignment types in one block.
  • Widths and signedness are silent sources of bugs. One unsigned operand makes the whole expression unsigned. Lint with verilator -Wall to catch both.
  • Generate blocks build parameterised hardware at elaboration. Delays, $display and most of the verification language are for simulation only.

Check your understanding

Pick an answer for each question, then check. Answers stay hidden until you submit.

1. Inside an always_ff block you write q1 = d; q2 = q1; with blocking assignments. What hardware results after synthesis?
2. a is declared logic signed [7:0] and holds -5. b is declared logic [7:0] and holds 2. What does (a < b) evaluate to?
3. Which statement about always_comb is correct?
4. Which of these is ignored or rejected by a synthesis tool?

Further reading

Found a mistake or something unclear?Report a correction.