---
title: Simulation and synthesis pitfalls
heading: Verilog that simulates one way and builds another: assignments, sensitivity, latches, widths and X
eyebrow: S3 · Lesson 5 · Simulation and synthesis pitfalls
xp: 50
---

::: hook
Verilog describes hardware but runs as a simulation program, and the two readings can disagree. Code that passes every simulation can synthesize into different hardware: a shift register that collapses to one flip-flop, a "combinational" block that grows latches, an adder that silently drops its carry. Lessons 2 to 4 wrote correct RTL; this lesson collects the classic ways to write incorrect RTL that looks correct, each with the rule that prevents it. Lint tools check most of these rules automatically, but only for a designer who knows what they mean.
:::

::: play
- A three-stage shift register written with nonblocking assignments (`<=`). On each clock every flip-flop takes its neighbor's *old* value, so a pulse on D walks through Q0, Q1, Q2 one clock at a time.
- Written with blocking assignments (`=`) in the order Q0, Q1, Q2, each line would see the value just assigned above it, and D would reach Q2 in the same clock: the three flip-flops would act as one, in simulation and, often, in synthesis.
:::

```sim logic
input D
output Q0, Q1, Q2
clock CLK 4
stim D 0@0 1@5 0@9
always @(posedge CLK) begin Q2 <= Q1; Q1 <= Q0; Q0 <= D; end
wave: CLK, D, Q0, Q1, Q2
time: 40
```

::: predict
## In Verilog, `reg [7:0] s;` is assigned `s = a + b;` with 8-bit `a` = 200 and `b` = 100. What does `s` hold?

- [ ] 300
- [x] 44
- [ ] 255
- [ ] x (unknown)

::: reveal
44: the sum is computed at least 8 bits wide, but `s` is 8 bits, so the carry is dropped: 300 − 256 = 44. No error, no warning in simulation. If the carry matters, `s` must be 9 bits wide, or `{c, s} = a + b`. Width mismatches are among the most common bugs lint tools flag.
:::
:::

::: nameit
## Blocking and nonblocking assignments

In a clocked `always` block, use **nonblocking** (`<=`) assignments: every right-hand side is evaluated with the values from before the clock edge, then all registers update together, as real flip-flops do. **Blocking** (`=`) assignments update immediately, so later lines see new values, and the result depends on statement order. In combinational blocks, use blocking assignments. Mixing them, or assigning the same variable from two blocks, creates simulation races.

## Sensitivity lists

A combinational block must re-evaluate whenever any input changes. Old-style lists that omit a signal make the simulation hold a stale output, while synthesis builds the full logic: simulation and hardware disagree. Use `always @*` (or SystemVerilog's `always_comb`).

## Inferred latches

If a combinational block doesn't assign an output on every path, such as an `if` without an `else` or a `case` missing values without a `default`, the output must keep its old value, and synthesis builds a **latch**. Latches bring timing problems and are almost never intended. Give every output a default at the top of the block.

## Widths and signedness

Verilog silently truncates and zero-extends. An expression's width is set by its largest operand and its destination, so carries vanish and signed values lose their sign when mixed with unsigned ones. Size every result deliberately.

## X-optimism

In simulation, `if (sel)` with `sel` unknown (x) takes the `else` branch, hiding the fact that the hardware's behavior is undefined. Uninitialized registers and floating inputs can pass simulation this way and fail in silicon. Resets on all control state, and assertions that check for x, guard against it.
:::

::: example
## A designer writes a 3-stage shift register as `always @(posedge clk) begin q0 = d; q1 = q0; q2 = q1; end`. What does it do?

::: solution
1. **Follow the blocking assignments in order.** `q0` takes `d`, then `q1` takes the *new* `q0`, which is `d`, then `q2` takes `d`.
2. **What that builds.** After each clock all three equal `d`: a single flip-flop with three copies, and a delay of one clock instead of three.
3. **Reversed order.** Writing the lines as `q2 = q1; q1 = q0; q0 = d;` happens to work, which is exactly why the rule is to use nonblocking assignments: correctness shouldn't depend on line order.

**Answer:** it acts as one flip-flop copied three times, delaying `d` by one clock instead of three.
:::
:::

::: example
## A combinational block decodes a 2-bit `sel` with `case (sel) 2'b00: y = a; 2'b01: y = b; 2'b10: y = c; endcase` and no default. What does synthesis build?

::: solution
1. **Find the unassigned case.** For `sel` = 2'b11 the block doesn't assign `y`, so `y` must hold its previous value.
2. **What synthesis infers.** A latch on `y`, enabled when `sel` isn't 11.
3. **The fix.** Adding `default: y = 1'b0;` (or `y = 1'b0;` before the `case`) makes it a pure 4-to-1 multiplexer with a constant input. One missing line turns combinational logic into a level-sensitive storage element with its own timing hazards.

**Answer:** a latch on `y`, enabled whenever `sel` isn't 11; a default assignment turns it back into a multiplexer.
:::
:::

::: example
## `wire signed [7:0] a = -8'sd3;` and `wire [7:0] b = 8'd2;`. What is `a < b` in Verilog, and why?

::: solution
1. **The comparison's type.** Mixing a signed and an unsigned operand makes the whole comparison unsigned.
2. **Read −3 as unsigned.** As an 8-bit pattern, −3 is
   $$256 - 3 = 253$$
   so the comparison is 253 < 2, which is false.
3. **The fix.** Make both operands signed, or compare explicitly sized values:

```verilog
a < $signed(b)
```

4. **Why it slips through.** Bugs like this survive simulation when test values never go negative.

**Answer:** `a < b` is false, because the comparison is unsigned and −3 reads as 253.
:::
:::

::: check
given: n = 4 | 6 | 8; a = 200 | 3000 | 9000; b = 100 | 2000 | 9000
answer: a + b - 2^n*floor((a + b)/2^n)

## An {n}-bit register is assigned the sum of two values, {a} and {b} (wider operands, already in range of their own widths). What does it hold after truncation?

::: right
Right: {answer}, the sum modulo $2^{\given{n}}$.
:::

::: misses
- [a + b] The destination is only {n} bits wide: the upper bits are dropped.
- [any] Not yet. Keep the low {n} bits: $(a + b) \bmod 2^{\given{n}}$.
:::
:::

::: check
given: k = 3 | 4 | 6 | 8
answer: 1 + 0*k

## A {k}-stage shift register is written with blocking assignments in the order stage 0, stage 1, …, stage {k} − 1 inside one clocked block. How many clock cycles of delay does it give from input to the last stage?

::: right
Right: 1. Each line sees the value just written above it, so the input ripples through every stage in the same clock.
:::

::: misses
- [k] That's with nonblocking assignments; blocking ones in this order collapse the chain.
- [any] Not yet. Trace one clock: what does each line see?
:::
:::

::: check
given: o = 4 | 5 | 7; m = 1 | 3
answer: m

## A combinational block has {o} outputs. A `case` statement without a default leaves {m} of them unassigned in some branch; the rest are assigned in every branch. How many latches does synthesis infer?

::: right
Right: {answer}, one latch per output that isn't assigned on every path.
:::

::: misses
- [o] Only the outputs some path leaves unassigned need latches.
- [o - m] Those are the outputs that are always assigned; they stay combinational.
- [any] Not yet. Count the outputs that some path leaves unassigned.
:::
:::

::: check
given: v = 1 | 3 | 7 | 100; n = 8 | 16
answer: 2^n - v

## In an {n}-bit signed-unsigned comparison, the signed operand holds −{v}. Verilog treats the comparison as unsigned. What unsigned value does −{v} become?

::: right
Right: $2^{\given{n}} - $ {v} = {answer}, so it compares as a large positive number.
:::

::: misses
- [v] Two's complement of −{v} is $2^{\given{n}} - $ {v}, not {v}.
- [2^(n - 1) - v] It wraps around the full $2^{\given{n}}$ range.
- [any] Not yet. $2^n - v$.
:::
:::

::: check
kind: choice

## A combinational block written `always @(a or b) y = a & b | c;` simulates correctly in every test, yet the gate-level simulation disagrees with RTL simulation when only `c` changes. Why?

- [x] `c` is missing from the sensitivity list, so the RTL simulation doesn't re-evaluate `y` when `c` changes, while the synthesized gates do
- [ ] Synthesis optimized away `c`
- [ ] The gate-level simulation has delays
- [ ] `|` binds tighter than `&`

::: right
Right. Synthesis ignores sensitivity lists and builds the full expression. Using `always @*` makes the simulator infer the complete list.
:::

::: misses
- [2] Synthesis keeps `c`; that's why the gates respond to it.
- [3] Delays shift timing, but here the RTL output simply never updates.
- [4] `&` binds tighter than `|` in Verilog; precedence isn't the issue.
:::
:::

::: check
kind: choice

## Which coding style prevents inferred latches in a combinational `always @*` block?

- [x] Assign a default value to every output at the top of the block
- [ ] Use nonblocking assignments
- [ ] Add every signal to the sensitivity list
- [ ] Use a synchronous reset

::: right
Right. With a default at the top, every path assigns every output, so nothing needs to be remembered and no latch is inferred.
:::

::: misses
- [2] Nonblocking assignments are for clocked blocks; they don't prevent latches.
- [3] `always @*` already does that; latches come from unassigned paths.
- [4] A combinational block has no clock, so a synchronous reset doesn't apply.
:::
:::

::: check
kind: python
given: n = 4 | 8 | 16

## Write two Python models of an `n`-stage ({n}) shift register's clock edge, given the list of stage values `q` and input `d`: `clock_nonblocking(q, d)` (all stages update from the old values) and `clock_blocking(q, d)` (statements in order stage 0, 1, …, each seeing updates above it). Both return the new list. Starting from all zeros, feed the input sequence 1, 0, 0, … for `n + 2` clocks and set `out_nb` and `out_b`, the lists of the last stage's value after each clock.

```python starter
def clock_nonblocking(q, d):
    return [d] + q[:-1]
def clock_blocking(q, d):
    return [d] + q[:-1]
out_nb = out_b = []
```

```python solution
def clock_nonblocking(q, d):
    return [d] + q[:-1]
def clock_blocking(q, d):
    q = list(q)
    for k in range(len(q)):
        q[k] = d if k == 0 else q[k - 1]
    return q
def run(step):
    q, out = [0] * n, []
    for i in range(n + 2):
        q = step(q, 1 if i == 0 else 0)
        out.append(q[-1])
    return out
out_nb = run(clock_nonblocking)
out_b = run(clock_blocking)
```

```python tests
nb = [0] * n; nb[n - 1] = 1; nb += [0, 0]
assert out_nb == [0] * (n - 1) + [1, 0, 0], "Nonblocking: the pulse reaches the last stage after n clocks."
assert out_b == [1] + [0] * (n + 1), "Blocking in forward order: the pulse reaches the last stage on the first clock."
assert clock_blocking([0] * n, 1) == [1] * n, "Every stage sees the new value in the same edge."
```

::: right
Right. The blocking version passes the pulse through every stage in one clock, the classic collapsed shift register.
:::
:::

::: explain
## A team's design passes all RTL simulations but fails on the FPGA: a state machine occasionally jumps to an undefined state after power-up. The state register has no reset, and the RTL simulation started with it at x. Explain how X-optimism let the bug through, and the fix.

::: model
Uninitialized flip-flops start at x in simulation, but Verilog's `if` and `case` treat an x condition as false or as no match, so the simulator quietly takes the else branch or the default and behaves as if the state were some legal value. The real hardware powers up with arbitrary bits, possibly an encoding outside the defined states; with no reset and incomplete case coverage, the machine can stay there or wander. The simulation never showed it because x was resolved optimistically. The fix is to reset every control register to a known state, make the state machine's case statement cover unused encodings (a default that returns to the idle state), and add assertions that flag x on control signals in simulation, or run X-pessimistic simulation.
:::
:::

::: practice

::: check
given: n = 8 | 10; a = 500 | 1500; b = 700 | 900
answer: a + b - 2^n*floor((a + b)/2^n)

## An {n}-bit register receives {a} + {b}. What does it hold?

::: misses
- [a + b] It keeps only {n} bits.
- [any] $(a + b) \bmod 2^n$.
:::
:::

::: check
given: v = 5 | 60; n = 8 | 32
answer: 2^n - v

## As an {n}-bit unsigned value, what is −{v}?

::: misses
- [v] Two's complement wraps: $2^n - v$.
- [any] $2^n - v$.
:::
:::
:::
