In software, a line of code is a step. In RTL, a line of code describes a piece of circuit. assign becomes a group of gates, and always_ff becomes a register. Change one character and synthesis may add a latch or drop a carry.
This lesson is a syntax map that comes before F01. It assumes no Verilog background. Each of the fifteen sections covers one construct, moving from data types and operators through combinational logic to registers and FSMs, in four parts: the code, the circuit it builds, a good and a bad version, and the reason. Learn to connect code and circuit first. Later lessons add timing and verification detail.
Three conventions help from the start:
- Signal suffixes
_i,_o,_qand_dmark an input, an output, a register output and a register’s next value. They are a naming habit in this course, not keywords. - Simulation drives inputs from a testbench and checks the outputs. Synthesis turns RTL into gates and registers. A design needs to pass both.
- Hexadecimal values in the text use the 0x prefix, as in 0xF0. Code uses SystemVerilog literals such as
8'hF0.
The register, reset, counter and FSM sections only ask you to recognize the code and the circuit. F07–F10 cover the timing in full, and each section says where.
Every example is in the download package. Each testbench ends with one PASS or FAIL line. The good versions all pass, and the bad versions print each mismatch. The package also holds the Yosys commands that reproduce every error message. The tools are Icarus Verilog 12.0 and Yosys 0.33; run bash run.sh to repeat everything.
| Construct | Synthesized circuit | Lesson |
|---|---|---|
| data types, modules and ports | A block with inputs and outputs | F01, F02 |
| assign and always @* | Combinational logic, such as a mux | F01–F04 |
| literals | Constants | F02 |
| operators | Gates, reductions and wiring | F03, F05, F06 |
| arithmetic and width | Adder | F02, F05 |
| sign and extension | Wiring: copy the top bit or fill with 0 | F02, F05 |
| if, case and latches | Mux, priority mux; a missing branch adds a latch | F04 |
| multiple drivers and loops | Conflicts and loops that synthesis rejects | F02, F04 |
| function and task | Reusable combinational logic | F06, F12 |
| parameter, arrays and generate | Repeated instances | F06 |
always_ff and <= | Register | F07, F08 |
| reset and enable | Register with a feedback mux | F07, F14 |
| counter | Register, incrementer, comparator | F09 |
| FSM | State register and next-state logic | F10 |
| simulation and synthesis mismatches | Simulation and hardware disagree | F02, F04, F08 |
Data types, modules and ports
More in F01 “A module describes the circuit and its ports”, F02 “From one wire to eight bits”.
Code
module channel_select_8b (
input logic [7:0] a_i,
input logic [7:0] b_i,
input logic sel_i,
output logic [7:0] selected_o
);
assign selected_o = sel_i ? b_i : a_i;
endmodule
Each port states three things: direction (input, output), type (logic) and width ([7:0]). [7:0] holds eight bits, and a_i[0] is the least significant bit. A port without a range is one bit wide.
Verilog types serve two purposes: some describe circuits, others only appear in testbenches.
| Type | Purpose | Used in |
|---|---|---|
wire | Node of a combinational circuit, signal connection | Design, testbench |
reg | Node of a combinational or sequential circuit; a variable with a set number of bits | Design, testbench |
integer | 32-bit signed integer | Testbench |
time, real | Simulation time, real numbers | Testbench |
This course uses the SystemVerilog logic type. A logic signal can be driven by assign or written inside always, so it replaces most uses of wire and reg. A signal declaration states four things: the type, the signedness (signed means two’s complement; without it the signal is unsigned), the width [MSB:LSB] (by convention [WIDTH-1:0]) and a case-sensitive snake_case name.
Circuit
Good and bad
Bad: output without a width
output logic selected_o // missing [7:0]
...
assign selected_o = sel_i ? b_i : a_i;
Good: every port has a width
output logic [7:0] selected_o
...
assign selected_o = sel_i ? b_i : a_i;
The bad version still compiles. Icarus only warns at the instance: Port 4 (selected_o) of channel_select_8b expects 1 bits, got 8. In simulation, A=0xF0 reads as 0x00 and B=0x25 reads as 0x01. Only bit 0 survives.
Why
- A port with no range is one bit. Extra bits are cut off.
- Tools usually warn and keep going, so only a test catches it.
- A width on every port saves the reader from guessing.
assign and always @*
More in F01 “Continuous assignment keeps the relationship active”, F02 “Read the declaration together with its driver”, F03.
Code
assign selected_o = sel_i ? b_i : a_i;
assign describes a relationship that always holds. When any input on the right changes, the left side follows. After ? comes the value for a true condition; after : comes the value for a false one.
Combinational logic has two equivalent forms:
assign selected_o = sel_i ? b_i : a_i; // wire or logic, with assign
always @* begin // reg or logic, with always @*
if (sel_i) selected_o = b_i;
else selected_o = a_i;
end
Both use =. The * in always @* means “every signal the block reads”. SystemVerilog adds always_comb, which means the same and lets the tools check that no latch appears. This course writes combinational logic with assign or always_comb.
Circuit
Good and bad
Bad: a procedure writes a wire
output wire [7:0] selected_o
...
always @* selected_o = sel_i ? b_i : a_i;
Good: assign drives the net
output logic [7:0] selected_o
...
assign selected_o = sel_i ? b_i : a_i;
The bad version does not compile. Icarus reports selected_o is not a valid l-value and points to the wire declaration.
Why
- A
wireis a net. Onlyassignor an instance output can drive it. - A procedure (
always) can only write variables such aslogicorreg. logicaccepts either, but pick one driver style per signal.logic v = a & b;is only an initializer. Writeassign v = a & b;for a lasting relationship.
Literals
More in F02 “F0 and 1111_0000 spell the same pattern” and the extension “Measuring unsized literals”.
Code
raw = 8'b1111_0000; // 8 bits, binary
raw = 8'hF0; // same bits, hexadecimal
format_ok_o = (format_i == 4'b0010);
A literal has three parts: width (8), base ('b, 'o, 'd, 'h) and digits. Underscores only group digits and take no bits. In prose, hexadecimal values carry 0x, as in 0xF0, so they are not confused with signal names A and B or with decimal numbers.
Circuit
Good and bad
Bad: too many digits, or no width
narrow = 8'h1F0; // a 9-bit value
x = 'hF0; // width left to the tool
y = 240; // 32 bits, signed
Good: width matches the digits
narrow = 8'hF0;
x = 8'hF0;
y = 8'd240;
For 8'h1F0, Icarus prints two warnings, Extra digits given for sized hex constant. and Numeric constant truncated to 8 bits., and the value becomes 0xF0. $bits(240) and $bits('hF0) are both 32; $bits(8'hF0) is 8.
Why
- A literal’s width is fixed where it is written. Extra high bits are dropped there and cannot come back.
- An unsized decimal integer is signed and at least 32 bits, which changes the width and sign of expressions it joins.
- Based literals without
sare unsigned. Write8'shF0for a signed one. - An explicit width lets a reader check how many wires each value uses.
Operators
More in F03 “Each input contains a 1. Why does AND give 0000?”, “Fold four bits into a check bit” and “Where do the parentheses go?”, F05, F06.
Code
assign empty_o = (count_i == 4'd0); // comparison: 1 bit
assign parity_o = ^word_i; // reduction XOR: 1 bit
assign swapped_o = {word_i[3:0], word_i[7:4]}; // concatenation: wiring only
| Group | Syntax | Result width |
|---|---|---|
| Concatenate, repeat, select | {b, c}, {N{b}}, b[3], b[7:4], b[lsb +: 4], b[msb -: 4] | Sum of the parts |
| Shift | >> and << fill with 0; >>> copies the sign bit only when b is declared signed, and equals >> otherwise; shifting by the width or more gives all 0s (all sign bits for a signed >>>) | Same as b |
| Reduction | &b, |b, ^b (and ~&, ~|, ~^) | 1 bit |
| Bitwise | ~b, b & c, b | c, b ^ c | N bits, one per position |
| Logical | !b, b && c, b || c | 1 bit |
| Relational | <, <=, >, >=, ==, != | 1 bit |
=== also compares x and z, so it belongs in testbenches. In long expressions, add parentheses to state the intent instead of relying on precedence.
Circuit
Good and bad
Bad: a bitwise operator for a 1-bit question
assign empty_o = ~count_i; // 4 bits into 1 bit
Good: a comparison, or a reduction down to 1 bit
assign empty_o = (count_i == 4'd0);
// or assign empty_o = ~|count_i; // reduction NOR
With count_i=0, both output 1. With count_i=2 (0010), ~count_i is 1101, whose lowest bit is 1, so the bad version reports “empty”. Neither Icarus nor Yosys warns. Yosys keeps a single 1-bit $not; the good version is one $logic_not. ~|count_i ORs the four bits into one and inverts it; that version also passes all three tests in the download package. !count_i gives the same result, but logical operators should take 1-bit signals. Fold a multi-bit value to 1 bit with a comparison or a reduction first.
Why
- Bitwise operators work on each position and return N bits. Logical and relational operators answer yes or no in 1 bit.
- Assigning a wide result to a narrow signal drops the upper bits, often without a warning.
- Reductions, concatenations and constant selects cost few or no gates. A signal used as an index or shift amount becomes a mux, so keep its range inside the width.
Arithmetic and width: carry and truncation
More in F02 “Keeping eight bits discards information”, F05 “How can one addition have two correct results?” and “How can a five-bit destination still lose the carry?”.
Code
assign full_sum_o = {1'b0, a_i} + {1'b0, b_i}; // 5 bits
assign modulo_sum_o = full_sum_o[3:0]; // low 4 bits, on purpose
Two 4-bit values sum to at most 30, which needs five bits. {1'b0, a_i} prepends a 0 and widens each operand to five bits. For a modulo-16 result, write [3:0] explicitly.
Circuit
Good and bad
Bad: braces around the whole sum
assign full_sum_o = {a_i + b_i};
Good: widen first, then add
assign full_sum_o = {1'b0, a_i} + {1'b0, b_i};
For 15 + 1, the good version gives 10000 (16) and the bad version gives 00000 (0). For 15 + 15, the good version gives 30 and the bad version 14. Neither Icarus nor Yosys warns.
Why
- Braces are concatenation. Each operand inside sizes itself.
- Inside the braces,
a_i + b_iis four bits wide, so the carry is dropped there. - A wider destination cannot recover bits that are already gone.
- Without the braces,
assign full_sum_o = a_i + b_i;is evaluated at the 5-bit width of the destination, so the carry survives; that version also passes in the download package. The braces cause the bug, not a missing manual 0. - Assigning to a narrower destination silently drops the high bits.
- A sum or difference needs one bit more than the wider operand to keep the carry; a product needs the two widths added.
/and%synthesize to large, slow circuits, so avoid them in designs.
Sign and extension
More in F02 “How can the same F0 mean minus sixteen?” and “Widening follows the right-hand expression”, F05 “Set widths and signedness before applying an offset”.
Code
logic signed [7:0] sample_i; // 8'shF0 = -16
logic [15:0] wide_o;
assign wide_o = sample_i; // 16'hFFF0: sign-extended
logic [3:0] reading_i; // unsigned 0..15
logic signed [3:0] offset_i; // signed -8..7
logic signed [5:0] reading_ext, offset_ext, adjusted_o;
assign reading_ext = $signed({2'b00, reading_i}); // unsigned source: fill with 0
assign offset_ext = $signed({{2{offset_i[3]}}, offset_i}); // signed source: copy the top bit
assign adjusted_o = reading_ext + offset_ext;
The pattern 1111_0000 reads as 240 unsigned and −16 in two’s complement. When widening, a signed source copies its top bit and an unsigned source fills with 0. The second snippet is a separate example: a 4-bit unsigned reading reading_i plus a 4-bit signed offset offset_i, each widened to 6 signed bits before the addition. {2{offset_i[3]}} repeats the top bit twice.
Circuit
Good and bad
Bad: part-select of the whole signal
assign wide_o = sample_i[7:0]; // 16'h00F0
Good: use the signed source directly
assign wide_o = sample_i; // 16'hFFF0
With sample_i = 8'shF0, the good version gives 0xFFF0 (−16) and the bad version 0x00F0 (+240). A positive input such as 0x25 is correct in both, so positive-only tests miss this bug. In the offset example, 2 + (−3) gives the six-bit 111111, which is −1, and below_zero_o is 1.
Why
- The fill comes from the signedness of the right-hand expression, not the destination.
- A part-select such as
[7:0]is always unsigned, even when it covers the whole signal. - Mixing signed and unsigned operands makes the whole expression unsigned.
- Extend every operand to the same width and signedness before adding.
if, case and latches
More in the whole of F04.
Code
always_comb begin
case (sel_i)
2'b00: {valid_o, data_o} = {1'b1, a_i};
2'b01: {valid_o, data_o} = {1'b1, b_i};
2'b10: {valid_o, data_o} = {1'b1, c_i};
default: {valid_o, data_o} = {1'b0, 8'h00};
endcase
end
always_comb begin
if (req_a_i) {valid_o, data_o} = {1'b1, a_i};
else if (req_b_i) {valid_o, data_o} = {1'b1, b_i};
else {valid_o, data_o} = {1'b0, 8'h00};
end
always_comb declares combinational logic. Inside it, blocking assignments (=) compute results in program order. case compares row by row. if / else if checks from the top, and the first true condition wins.
Circuit
Good and bad
Bad: default removed
always_comb begin
case (sel_i)
2'b00: {valid_o, data_o} = {1'b1, a_i};
2'b01: {valid_o, data_o} = {1'b1, b_i};
2'b10: {valid_o, data_o} = {1'b1, c_i};
endcase
end
Good: every path assigns every output
always_comb begin
case (sel_i)
2'b00: {valid_o, data_o} = {1'b1, a_i};
2'b01: {valid_o, data_o} = {1'b1, b_i};
2'b10: {valid_o, data_o} = {1'b1, c_i};
default: {valid_o, data_o} = {1'b0, 8'h00};
endcase
end
Drive 01, 11, 00, 11 in order. The good version returns valid_o=0 and data_o=0x00 for both 11 inputs. The bad version keeps B’s 0xA5 after the first 11 and A’s 0x12 after the second, with valid_o stuck at 1. Yosys rejects the always_comb block with Latch inferred for signal … valid_o … from always_comb process. Rewritten as always @*, the same code synthesizes to a $dlatch driving data_o.
Why
- A combinational output depends only on the current inputs.
- If a path leaves an output unassigned, the hardware must hold the old value, so synthesis infers a latch.
- Add a
default, or give every output a value on the first line of the block. Write thedefaulteven when every case is listed. - With
always_comb, the tool treats the latch as an error. Withalways @*, it builds one. - A latch is level-sensitive: while it is enabled, its output follows the input, so glitches and noise get stored too. Timing analysis also handles paths through latches poorly, so synchronous designs avoid them.
Multiple drivers and combinational loops
More in F02 extension “Conflicting drivers on one wire”, F04 “What if an output feeds its own input?”.
Code
// one driver per signal
assign bus_o = a_en_i ? a_i :
b_en_i ? b_i : 8'h00;
// feedback goes through a register
always_ff @(posedge clk_i) begin
if (!rst_ni) y_q <= 1'b0;
else if (enable_i) y_q <= ~y_q;
else y_q <= 1'b0;
end
Each signal belongs to one assign or one block. When an output must return to its own input, put a register in the path.
Circuit
Good and bad
Bad: two drivers and a combinational loop
assign bus_o = a_en_i ? a_i : 8'h00;
assign bus_o = b_en_i ? b_i : 8'h00;
assign y_o = enable_i ? ~y_o : 1'b0;
Good: one driver; the loop has a register
assign bus_o = a_en_i ? a_i :
b_en_i ? b_i : 8'h00;
always_ff @(posedge clk_i)
y_q <= ...; // see the code above
With bus_o declared as a wire, Icarus resolves every bit where the two drivers differ to X; with only A enabled it prints XX. Yosys check reports multiple conflicting drivers once for each of the eight bits. When two always_ff blocks write the same logic, Icarus 12 still compiles it, and Yosys check again reports the conflict. For the loop, Yosys check -assert reports found logic loop and exits with an error.
Why
- Two outputs tied together, one pulling to 1 and one to 0, do not give a valid logic level.
y_o = ~y_ohas no stable solution. A zero-delay simulation cannot tell how the real circuit would oscillate.- Some simulators accept multiple drivers, so let the synthesis
checkcatch them.
Function and task
More in F06 (reusable combinational logic), F12 “Who drives the interface, and who decides whether it passed?” (testbench tasks).
Code
function automatic logic parity8(input logic [7:0] word);
parity8 = ^word; // the function name holds the result
endfunction
assign pa_o = parity8(a_i);
assign pb_o = parity8(b_i);
A function describes combinational logic with no timing control, and a design can call it many times. A task can have several inputs and outputs and can wait for time or an edge, so it suits testbench steps.
Circuit
Good and bad
Bad: a task with a delay inside the design
task automatic drive_parity(
input logic [7:0] word, output logic p);
#2 p = ^word;
endtask
always @* drive_parity(a_i, pa_o);
Good: a function for combinational logic
function automatic logic parity8(
input logic [7:0] word);
parity8 = ^word;
endfunction
assign pa_o = parity8(a_i);
In simulation, the bad version is still x at 1 ns and only updates after 2 ns, so the testbench prints FAIL. Yosys drops the #2 without a warning and builds two $reduce_xor cells for both versions. Simulation and hardware already disagree.
Why
- A function has no notion of time, so synthesis expands it into gates.
- The
#and@in a task only mean something to the simulator. Synthesis does not build them. - Keep variable names inside a function different from the module’s signals; matching names can cause problems in the back-end flow.
Parameter, arrays and generate
More in the whole of F06 (channel_bank, parity_reuse).
Code
module parity_bank #(
parameter int WIDTH = 8,
parameter int CHANNELS = 3,
localparam int SEL_W = (CHANNELS > 1) ? $clog2(CHANNELS) : 1
) (
input logic [CHANNELS*WIDTH-1:0] flat_i,
input logic [SEL_W-1:0] sel_i,
output logic [CHANNELS-1:0] parity_o
);
for (genvar ch = 0; ch < CHANNELS; ch++) begin : by_channel
parity_leaf #(.WIDTH(WIDTH)) u_parity (
.word_i (flat_i[ch*WIDTH +: WIDTH]),
.parity_o(parity_o[ch])
);
end
endmodule
A parameter lets the instantiating module choose a size. A localparam is derived from the sizes and cannot be overridden. The genvar loop unrolls during elaboration and creates one named instance per iteration, such as by_channel[0].u_parity. +: selects WIDTH bits upward from a start index.
Name constants in SCREAMING_SNAKE_CASE. A number without a base (such as 8) is a 32-bit integer, which suits widths and indexes; circuit values should state a width and base. The same channels can also be declared as an array, logic [WIDTH-1:0] word [CHANNELS], counted by convention from 0 to SIZE-1. A generate loop sits outside always and builds one copy of the circuit per iteration. The older style puts a for loop inside always and writes several registers in one block, which is harder to read.
Circuit
Good and bad
Bad: $clog2 used directly
localparam int SEL_W = $clog2(CHANNELS);
...
input logic [SEL_W-1:0] sel_i
Good: keep at least one bit
localparam int SEL_W =
(CHANNELS > 1) ? $clog2(CHANNELS) : 1;
...
input logic [SEL_W-1:0] sel_i
With CHANNELS=3, both versions give two bits. With CHANNELS=1, $clog2(1)=0, so the bad version declares [-1:0] and Icarus measures sel_i as two bits. The good version gives one bit. Yosys elaborates three parity_leaf instances for the good version.
Why
- Parameters are fixed at elaboration and cannot change during operation. Changing one changes instance counts and wire widths.
- Check derived widths at the edge cases, such as one channel.
[N-1:0]with N = 0 flips to a two-bit range without any error.
always_ff and nonblocking assignment
More in F07 “D can change at any time. When does Q change?”, the whole of F08.
Recognize the code and the circuit here. F07 and F08 cover timing around the edge in full.
Code
always_ff @(posedge clk_i) begin
if (!rst_ni) begin
q1_o <= 8'h00;
q2_o <= 8'h00;
end else begin
q1_o <= din_i;
q2_o <= q1_o;
end
end
always_ff @(posedge clk_i) declares registers that sample on the rising edge of clk_i. <= is a nonblocking assignment: every right-hand side is read at the edge, and all left-hand sides update afterwards. So q2_o reads q1_o from before the update.
Circuit
Good and bad
Bad: = inside always_ff
end else begin
q1_o = din_i;
q2_o = q1_o; // already the new din_i
end
Good: <= inside always_ff
end else begin
q1_o <= din_i;
q2_o <= q1_o; // q1_o before the edge
end
Feed 0x12, 0x34, 0x56. The good version gives q1=0x12, q2=0x00 at E1 and q1=0x34, q2=0x12 at E2. The bad version already has q2=0x12 at E1, one stage short. Yosys builds two eight-bit registers ($sdff) for the good version and only one for the bad version.
Why
- At an edge, every register reads the value from before that edge, then all update together.
<=models that rule.=lets the next statement see the new value at once.- Writing and reading one variable with
=in different blocks also makes the result depend on which block the simulator runs first. - Rule of thumb:
<=inalways_ff,=inalways_comb.
Reset and enable
More in F07 “Which takes priority when clearing and writing overlap?”, F14 “Separate asserting and releasing active-low reset”.
Recognize the code and the circuit here. F07 and F14 cover the full rules for reset and enable together.
Code
// synchronous reset
always_ff @(posedge clk_i) begin
if (!rst_ni) q_o <= 8'h00;
else if (en_i) q_o <= d_i;
end
// asynchronous reset
always_ff @(posedge clk_i or negedge rst_ni) begin
if (!rst_ni) q_o <= 8'h00;
else if (en_i) q_o <= d_i;
end
The _ni suffix marks an active-low input: rst_ni=0 asserts reset. The synchronous version clears only at a rising edge. The asynchronous version adds negedge rst_ni to the sensitivity list, so asserting reset clears the register at once. No final else means the register holds its value on that edge.
Both styles are common. Many design guidelines prefer an active-low asynchronous reset, because it clears even when the clock stops. From F07 on, this course specifies an active-low synchronous reset, so the register examples in F00 use the synchronous form to match the later lessons. To switch, change only the sensitivity list of the always_ff line.
Circuit
Good and bad
Bad: enable checked first
always_ff @(posedge clk_i) begin
if (en_i) q_o <= d_i;
else if (!rst_ni) q_o <= 8'h00;
end
Good: reset is the first branch
always_ff @(posedge clk_i) begin
if (!rst_ni) q_o <= 8'h00;
else if (en_i) q_o <= d_i;
end
Use row E1 from F07: rst_ni=0, en_i=1, D=0xA5. The good version clears to 0x00. The bad version stores 0xA5; the enable overrides the reset. Pull rst_ni low between two edges: the synchronous version still holds 0x3C, and the asynchronous one drops to 0x00 at once. Yosys maps them to $sdffe (synchronous reset with enable) and $adffe (asynchronous reset with enable).
Why
if / else ifis ordered; the first branch has priority.- Reset must work whatever the write condition, so it goes first.
- A synchronous reset needs an edge. If the clock stops, it cannot clear.
- Release an asynchronous reset through a synchronizer in each clock domain, so the first flop’s metastability does not reach the logic.
- The reset value must be a constant, such as
8'h00, not another signal. - Give a register one edge-triggered reset; do not put two resets in the sensitivity list.
- Connect an edge-triggered reset straight to
rst_ni; do not combine it with other signals first. - If an asynchronous reset is not the first branch, the priority is wrong and the tool also cannot map it to an asynchronously cleared register. In the download package,
s05_reg_async_bad.svstops Yosys 0.33 withERROR: Multiple edge sensitive events found for this signal!.
Counter
More in F09 “Advance on a sample event” and “How many bits does a count of four need?”.
Recognize the code and the circuit here. F09 covers counter design in full.
Code
module sample_counter #(
parameter int TARGET = 4,
localparam int WIDTH = (TARGET < 2) ? 1 : $clog2(TARGET + 1)
) ( ... );
localparam logic [WIDTH-1:0] LIMIT = WIDTH'(TARGET);
always_ff @(posedge clk_i) begin
if (!rst_ni)
count_o <= '0;
else if (sample_take_i && (count_o != LIMIT))
count_o <= count_o + 1'b1;
end
endmodule
A counter is a register plus an incrementer. It adds one only in cycles with sample_take_i=1 and stops at LIMIT. '0 fills every bit with 0. WIDTH'(TARGET) casts the constant to WIDTH bits.
Circuit
Good and bad
Bad: width holds only 0–3
localparam int WIDTH = $clog2(TARGET); // 2
Good: width holds TARGET itself
localparam int WIDTH =
(TARGET < 2) ? 1 : $clog2(TARGET + 1); // 3
With TARGET=4 and five sampling cycles in a row, the good version counts 1, 2, 3, 4 and then stays at 4. In the bad version, LIMIT = 2'(4) truncates to 0. count_o != LIMIT is false from the start, and the counter stays at 0. No tool warns.
Why
- Representing 0 to N takes
$clog2(N+1)bits, not$clog2(N). - Casting a constant to a narrower width drops its high bits.
- When the stop rule uses the truncated constant, the whole counter fails.
FSM
More in F10 “Account for every hold and transition” and “How does the next state reach the register?”.
Recognize the code and the circuit here. F10 covers drawing and testing the state diagram.
Code
typedef enum logic [1:0] {IDLE = 2'b00, COLLECT = 2'b01, REPORT = 2'b10} state_t;
state_t state_q, state_d;
always_comb begin
state_d = state_q; // hold unless an event moves us
case (state_q)
IDLE: if (start_i) state_d = COLLECT;
COLLECT: if (sample_last_i) state_d = REPORT;
REPORT: if (report_taken_i) state_d = IDLE;
default: state_d = IDLE;
endcase
end
always_ff @(posedge clk_i) begin
if (!rst_ni) state_q <= IDLE;
else state_q <= state_d;
end
assign report_valid_o = (state_q == REPORT);
An FSM has two parts. always_comb computes the next state state_d from the current state and the inputs. always_ff stores it as state_q on the rising edge. Outputs read state_q only.
An FSM whose outputs depend only on state_q is a Moore machine, like report_valid_o here. A Mealy machine also reads inputs in its outputs, for example assign done_o = (state_q == REPORT) && report_taken_i;. Its output changes in the same cycle as the input, one cycle earlier than a Moore output, but glitches on the input also reach the output. The enum also sets the state encoding: binary 00, 01 and 10 here. Another common choice is one-hot, with one bit per state.
Circuit
Good and bad
Bad: no default for state_d
always_comb begin
case (state_q)
IDLE: if (start_i) state_d = COLLECT;
...
endcase
end
Good: hold on the first line
always_comb begin
state_d = state_q;
case (state_q)
IDLE: if (start_i) state_d = COLLECT;
...
endcase
end
With start_i=0, the bad version never assigns state_d. Yosys reports Latch inferred for signal … state_d … from always_comb process and stops. The good version synthesizes a state register ($sdffe) and next-state logic with no latch.
Why
- An
ifwithoutelseleavesstate_dunassigned when the condition is false. It is the same bug as a missingdefault. - Holding on the first line gives every path a value and mirrors the state diagram.
defaultonly picks the next state for an illegal encoding. The output decode on this edge must still reject illegal states itself.
When simulation and synthesis disagree
More in F02 (initial stays in the testbench), F04 “Write all four rows for the three-channel interface” (how always_comb infers its inputs), F08 “When should the testbench read Q?” (#1ns stays in the testbench).
Code
always_comb y_o = a_i & b_i; // combinational: always_comb
always_ff @(posedge clk_i) begin // start value: reset
if (!rst_ni) ready_o <= 1'b0;
else if (start_i) ready_o <= 1'b1;
end
always_comb infers which inputs should trigger a re-evaluation. A register’s start value comes from reset. Keep initial and # delays in the testbench.
Circuit
Good and bad
Bad: incomplete list; initial and delay in RTL
always @(a_i) y_o = a_i & b_i;
initial ready_o = 1'b0;
always_ff @(posedge clk_i)
if (start_i) ready_o <= #3 1'b1;
Good: always_comb and a reset
always_comb y_o = a_i & b_i;
always_ff @(posedge clk_i)
if (!rst_ni) ready_o <= 1'b0;
else if (start_i) ready_o <= 1'b1;
Hold a_i=1 and change b_i from 1 to 0. The good version outputs 0. The bad version does not re-evaluate and still outputs 1, yet Yosys synthesizes an $and. Yosys turns the initial into an init attribute on the register (Set init value: \ready_o = 1'0), not a reset circuit. It drops #3 without any warning.
Another mismatch comes from the order of blocking assignments. Inside one always @*, a variable read before it is written returns its previous value:
Bad: read t before computing it
always @* begin
y_o = t & c_i; // reads the old t
t = a_i | b_i;
end
Good: two blocks, one result each
always @* t = a_i | b_i; // writes only t
always @* y_o = t & c_i; // writes only y_o
Hold c_i=1 and change a_i from 0 to 1. The good version outputs 1: when t changes, the block that reads it runs again, whichever block runs first. In Icarus, the bad version outputs 0 and only catches up on the next input change, so all three checks fail. Yosys builds one $or and one $and for both versions, with no warning.
Why
- The sensitivity list only controls when simulation re-evaluates. Synthesis ignores it, so the two disagree.
always_combandalways @*include every signal the block reads.- Do not rely on power-up values. Set a register’s starting value with a reset.
- Write one result per
alwaysblock. If one block must write several variables, order the blocking assignments by data dependency: computetbefore reading it. - Real delays come from cells and routing and belong to timing analysis. A
#in RTL never becomes hardware.
Review: read the circuit from the code
Ask four questions when you read RTL:
- Does this line describe a relationship that always holds, or does it update on an edge? The first is combinational logic. The second is a register.
- Does every output get a value in every case? Miss one and you get a latch.
- Do the widths and signedness match? When they do not, the tools often stay silent.
- What does this line cost?
ifandcasebecome muxes, a multiplier is large and slow, and shifts and concatenations are only wiring. State the design intent clearly and leave the details to synthesis.
F01 starts from a one-bit mux and writes the first module and testbench.
Sources and further reading
- IEEE Std 1800-2017: §6 (data types), §9.2.2 (
always_comb,always_ff), §10.3–10.4 (continuous and procedural assignments), §11.6–11.8 (expression width and signedness), §27 (generate). - Tools: results in this lesson come from Icarus Verilog 12.0 and Yosys 0.33;
run.logkeeps the full output. Yosys check · Icarus command-line flags