What the Simulator Does with Your RTL: Event Regions and Races

Follow one clock edge through the simulator's event regions, and predict which value each statement reads.

You Will Be Able To

  • Explain what compilation and elaboration fix before time 0.
  • Predict which value a statement reads from the region it runs in.
  • Find a race that no single block shows: two processes, or a clock made by an assignment.
  • Choose between $display, $strobe and $monitor for a value at a clock edge.
Lesson
R11.1
Time
30 min
Runs on
Your browser
Check
5 questions

A block takes every second sample from a stream. Each register uses a nonblocking assignment, as the rule says. The capture register still takes the sample one edge too early.

Every Assignment Is Nonblocking, and the Hand-Off Still FailsThe lab bench, 1 ns after edges 2 to 7. q (clock made by <=) is the shipped design. q (enable) is the same block with one clock and an enable.
012345clkd123456s_q123456q (clock made by <=)135q (enable)024earlyearlyearly
Scroll horizontally ↔
  1. Cycle 0

    Edge 2: s_q takes 1. The brief says q takes the value s_q held before the edge, which is 0.

  2. Cycle 0

    The shipped q shows 1. It read s_q after the update of this same edge.

  3. Cycle 2

    Edge 4: the same again. q shows 3, the new s_q, where the brief gives 2.

  4. Cycle 2

    The enable version reads the old s_q every time. Both versions build 10 cells.

Icarus 12 and Verilator 5.052 print the same lines. The cause is the order of events inside one time slot.

Before Time 0: Compilation and Elaboration

A simulator does two jobs before it runs anything. Compilation checks each file against the language rules. Elaboration builds the design tree: it binds each instance to its module, fixes every parameter and expands every generate.

After elaboration, widths and instance names can no longer change. A synthesizer elaborates in the same way before it builds gates.

Icarus 12 prints tb.g[0] exists, tb.g[1] exists, tb.u7: W=7 bits(s)=8 and tb.u4: W=4 bits(s)=5. One module became two different adders.
module add #(parameter int W = 4) (
  input  logic [W-1:0] a, b,
  output logic [W:0]   s
);
  if (W < 2) $error("W must be at least 2");   // checked at elaboration
  assign s = a + b;
  initial $display("%m: W=%0d bits(s)=%0d", W, $bits(s));
endmodule
module tb;
  logic [7:0] s8;
  logic [4:0] s4;
  add #(.W(7)) u7 (.a(7'd100), .b(7'd100), .s(s8));
  add          u4 (.a(4'd9),   .b(4'd9),   .s(s4));
  for (genvar i = 0; i < 2; i++) begin : g
    initial $display("%m exists");
  end
endmodule
Fixed at elaborationExample aboveSo in RTL
Parameter valuesW is 7 in u7 and 4 in u4a parameter can size a vector; a signal cannot
Generate blocksg[0] and g[1] exist as two scopesa generate loop makes copies, never iterations in time
Checks on parametersthe $error under if (W < 2)a bad parameter can stop the tool before any run
Compile ordera package or typedef comes before its userlesson R9.3 covers file order

An elaboration check is only as strong as the tool. See the note below.

Time, Units and Precision

Simulated time moves in steps. The time unit says what #1 means. The precision says how finely a delay is rounded.

With a unit of 1 ns and a precision of 100 psResult
#1.26rounded to 1.3 ns: $realtime prints 1.30
#0.04 after itrounded to 0: $realtime still prints 1.30
RTL with no delaysevery assignment takes zero time; only the clock moves time

Measured on Icarus 12 and Verilator 5.052 with the directive timescale 1ns/100ps.

The directive timescale applies to every file compiled after it, so its effect depends on file order. The keywords timeunit and timeprecision sit inside a module and affect only that module.

Synthesizable RTL has no delays. All of its work at a clock edge happens at one instant, so the order inside that instant decides the result.

One Time Slot, Several Regions

A time slot is everything that happens at one simulated time. The simulator splits it into event regions and empties them in a fixed order.

The Regions of One Time SlotArrows show the order in which the simulator empties the regions. The two arrows that point back are deltas: new events send it round again.
  • Step
  • Structure
CallValueReturnWaiting
The regions of one time slotArrows show the order in which the simulator empties the regions. The two arrows that point back are deltas: new events send it round again. step Preponed assertions sample step Active =, assign, right sideof <= step Inactive #0 waits here step NBA left side of <=updates step Observed assertions evaluate step Reactive program blocks,actions step Postponed $strobe, $monitor step Next time slot time moves on new eventsnew events
  1. step Active=, assign, right side of <=
    • Inactive
  2. step Inactive#0 waits here
    • NBA
  3. step NBAleft side of <= updates
    • Observed
    • new events → Active
  4. step Observedassertions evaluate
    • Reactive
  5. step Reactiveprogram blocks, actions
    • Postponed
    • new events → Active
  6. step Postponed$strobe, $monitor
    • Next time slot
  7. step Next time slottime moves on
  8. step Preponedassertions sample
    • Active
  1. clk rises: Active

    Every block waiting on clk runs, in an order the simulator picks. Each <= reads its right side now and waits.

    Follow the calls, values and waits
    1. call s_q <= d: read d: Preponed → Active
  2. NBA

    Active and Inactive are empty. Every left side updates together: s_q takes d, and clk2 flips.

    Follow the calls, values and waits
    1. data s_q takes d: Active → Inactive
    2. data s_q takes d: Inactive → NBA
  3. A delta: back to Active

    The updates are new events. A block waiting on clk2 wakes now. It reads s_q after the update.

    Follow the calls, values and waits
    1. data clk2 rises: NBA → Active
    2. call q <= s_q: reads new s_q: NBA → Active
  4. Observed and Reactive

    Concurrent assertions evaluate the values they sampled in Preponed. Testbench program code and assertion actions run after the design has settled.

  5. Postponed

    Nothing can change any more. $strobe and $monitor print the final values of the slot, and time moves on.

Read the diagram as text
  • Preponed: assertions sample
  • Active: =, assign, right side of <=
  • Inactive: #0 waits here
  • NBA: left side of <= updates
  • Observed: assertions evaluate
  • Reactive: program blocks, actions
  • Postponed: $strobe, $monitor
  • Next time slot: time moves on
  • Preponed → Active
  • Active → Inactive
  • Inactive → NBA
  • NBA → Observed
  • Observed → Reactive
  • Reactive → Postponed
  • Postponed → Next time slot
  • NBA → Active: new events
  • Reactive → Active: new events

RTL lives in Active and NBA. A pass from one region to the next is a delta; a slot can take many.

This order is why <= makes flops safe. Every block reads old values in Active. The new values appear only in NBA, when all the reading is done.

Processes Run in Any Order

Inside one begin-end, statements run top to bottom. Between two blocks there is no such rule. Both wake on the same edge, and the simulator may run either one first.

b first in the file

always @(posedge clk) b = a;
always @(posedge clk) c = b;

With a = 1 and b = c = 0 before the edge: Icarus 12 prints b=1 c=0. Verilator 5.052 prints b=1 c=1.

c first in the file

always @(posedge clk) c = b;
always @(posedge clk) b = a;

Icarus 12 prints b=1 c=1. Verilator 5.052 prints b=1 c=1. Swapping two lines changed one simulator's result.

All four results are legal. The code has a race: its result depends on an order that the language leaves open. Synthesis sees two flops in a row and builds the same hardware each time.

Also left openIcarus 12Verilator 5.052
An assign w = a & b; fed by blocking writes, read later in the same blockthe block sees the old value of wthe block sees the new value
Which initial block of two instances prints firstu7 before u4u4 before u7
$monitor when a = and a <= change at one edgeone line, with the final valuestwo lines, the first with the old q

Three more orders measured on this site. None of them is wrong.

A delay of #0 looks like a way to choose the order. It moves the rest of the block to the Inactive region, behind every Active process of the slot.

A Clock Made by an Assignment Arrives One Delta Late

Return to the opening figure. clk2 is written with <=, so it changes in the NBA region. s_q changes in that same region.

The block on posedge clk2 wakes one delta later, back in Active. By then s_q already holds its new value. The nonblocking rule protects readers on the same clock only.

A second clock

always_ff @(posedge clk or negedge rst_n)
  if (!rst_n) clk2 <= 1'b0;
  else        clk2 <= ~clk2;

always_ff @(posedge clk2 or negedge rst_n)
  if (!rst_n) q <= 4'h0;
  else        q <= s_q;

q reads s_q after the update. On this flow: 10 cells, 9 flops, and the q flops have their own clock net.

One clock and an enable

always_ff @(posedge clk or negedge rst_n)
  if (!rst_n) en_q <= 1'b1;
  else        en_q <= ~en_q;

always_ff @(posedge clk or negedge rst_n)
  if (!rst_n)    q <= 4'h0;
  else if (en_q) q <= s_q;

q reads the old s_q. On this flow: 10 cells, 9 flops, every flop on clk.

In silicon the left version is a hold-time race. The divided clock is late by one flop delay, and the data is late by one flop delay. Which wins depends on the layout.

Printing from a Clocked Block

The three print tasks differ only in the region where they read the values.

Before the first edge q is 0 and r is 0. The first edge loads 3 into q and 4 into r.
module tb;
  logic clk = 0;
  logic [3:0] d = 4'd3, q = 4'd0, r = 4'd0;
  always @(posedge clk) begin
    q <= d;                                  // nonblocking
    r = d + 4'd1;                            // blocking
    $display("display: q=%0d r=%0d", q, r);
    $strobe ("strobe:  q=%0d r=%0d", q, r);
  end
  initial $monitor("monitor: t=%0t q=%0d r=%0d", $time, q, r);
  initial begin
    #5 clk = 1;
    #5 clk = 0; d = 4'd7;
    #5 clk = 1;
    #5 $finish(0);
  end
endmodule
TaskPrints inFirst edge, Icarus 12Reads
$displayActive, where the statement standsdisplay: q=0 r=4the old q, the new r
$strobePostponed, once per callstrobe: q=3 r=4the final values of the slot
$monitorPostponed, in every slot where an argument changedmonitor: t=5 q=3 r=4the final values of the slot

The whole run prints seven lines on Icarus 12. Only one $monitor can be active at a time.

A Loop with No Delay Never Lets Time Move

A time slot ends only when every region is empty. Combinational logic that feeds itself keeps making new events, so the slot never ends.

A wire that inverts itself

module osc (input logic en, output logic y);
  assign y = en & ~y;
endmodule

With en at 1, Icarus 12 prints nothing more and the site stops the run at its time limit. Verilator 5.052 reports %Error-DIDNOTCONVERGE: Active region did not converge.

The same toggle through a flop

module osc (input logic clk, en, output logic y);
  always_ff @(posedge clk)
    if (en) y <= ~y;
endmodule

One change per clock edge. The flop breaks the loop, so each slot ends and time moves on.

Synthesize refuses the left module as a logic loop, as lesson R1.3 showed for a latch written by accident.

The Lab: One Clock, and an Enable

Design brief
PortDirectionWidthMeaning
clkinput1clock
rst_ninput1reset, asynchronous, active-low
dinput[3:0]the sample stream
s_qoutput[3:0]registers d at every edge
qoutput[3:0]at every second edge, takes the value s_q held before that edge
Clock
rising edge
Reset
rst_n asynchronous, active-low. q first loads at the first edge after reset
Corner cases
the edge where s_q and q both load. Done when: Run shows q as 0, 0, 2, 2, 4, 4, and Synthesize still reports 10 cells
  1. Run as shipped

    q reads 1, 1, 3, 3, 5, 5. At edge 2 it already shows the 1 that s_q took at that same edge.

  2. Find the late clock

    Every assignment is nonblocking. Look at the event lists: two blocks wake on clk, and the third wakes on clk2, which changes in the NBA region.

  3. Use one clock

    Replace clk2 with the enable shown below and Run. q reads 0, 0, 2, 2, 4, 4: the old s_q each time.

  4. Check the gates

    Synthesize both. Each is 10 cells and 9 flops. In the enable version every flop shares one clock, so timing analysis sees one clock domain.

The fix: an enable on the one clock
On this flow: 4 $_DFFE_PN0P_, 4 $_DFF_PN0_, 1 $_DFF_PN1_ and 1 $_NOT_. The shipped design has 9 $_DFF_PN0_ and 1 $_NOT_.
  logic en_q;                    // 1 on every second edge

  always_ff @(posedge clk or negedge rst_n)
    if (!rst_n) en_q <= 1'b1;
    else        en_q <= ~en_q;

  always_ff @(posedge clk or negedge rst_n)
    if (!rst_n) s_q <= 4'h0;
    else        s_q <= d;

  always_ff @(posedge clk or negedge rst_n)    // one clock; the enable picks the edges
    if (!rst_n)    q <= 4'h0;
    else if (en_q) q <= s_q;
Asked in interviews
  1. Why does a nonblocking assignment prevent a race between two flops?

    Its right side is read in the Active region and its left side updates in the NBA region. Every block on that clock reads old values first, so the order of blocks does not matter.

  2. What is the difference between $display and $strobe?

    $display prints where it stands, in the Active region, so it shows a register's old value. $strobe prints in the Postponed region, after every update of the time slot.

  3. What is a delta cycle?

    One pass through the event regions with no change of simulated time. An update in the NBA region can wake more processes, and the simulator loops until none are left.

Try It

The bench changes d 1 ns after an edge and prints 1 ns after the next one. s_q shows the d of its edge on every line, as it should.

q loads at edges 2, 4 and 6. Each time it shows the value on the same line as s_q. It read s_q one delta after the update.

Synthesize reports 10 cells: 9 $_DFF_PN0_ and 1 $_NOT_, with 0 latches and 1 level of logic. Lint prints nothing.

RTLIcarus Verilog · in your browser · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: e2 d=1 s_q=1 q=1 e3 d=2 s_q=2 q=1 e4 d=3 s_q=3 q=3 e5 d=4 s_q=4 q=3 e6 d=5 s_q=5 q=5 e7 d=6 s_q=6 q=5

Original design · 10 cells · 9 flip-flops · 0 latches · 1 logic levels. Synthesis uses Yosys; counts depend on the toolchain.

Read included file: tb.sv
`timescale 1ns/1ps
module tb;
  logic clk = 0;
  always #5 clk = ~clk;                   // rising edges at 5, 15, 25, ...
  logic rst_n = 1;                        // falls at 1 ns, rises 1 ns after edge 1
  int edge_n = -1;
  always @(posedge clk) edge_n = edge_n + 1;
  logic [3:0] d = 0;
  logic [3:0] s_q, q;
  half_rate dut (.*);
  task automatic tick();
    @(posedge clk); #1;
    if (rst_n) $display("e%0d d=%h s_q=%h q=%h", edge_n, d, s_q, q);
  endtask
  initial begin
    #1 rst_n = 0; tick(); tick(); rst_n = 1;
    d = 4'h1; tick();
    d = 4'h2; tick();
    d = 4'h3; tick();
    d = 4'h4; tick();
    d = 4'h5; tick();
    d = 4'h6; tick();
    $finish(0);
  end
endmodule

Check Yourself

Predict the outputA toggle t is used as a clock for cap. The bench gives three rising edges of clk. What does it print?
module tb;
  logic clk = 0, t = 0;
  logic [3:0] n = 4'd0, cap = 4'd0;
  always @(posedge clk) t <= ~t;
  always @(posedge clk) n <= n + 4'd1;
  always @(posedge t)   cap <= n;
  initial begin
    repeat (3) begin #5 clk = 1; #5 clk = 0; end
    $display("n=%0d cap=%0d", n, cap);
    $finish(0);
  end
endmodule
Spot the bugEach option is the body of one clocked block. At every edge b must take a, and c must take the value b held before the edge. Which option fails?
ConceptTwo blocks wake on posedge clk. One runs b = a; and the other runs c = b;. What does the standard say about c after the edge?
ConceptA bench calls $display and $strobe in the block that runs q <= d;. Before the edge q is 2 and d is 9. Which values of q do they print?
ConceptAn instance sets a width parameter to 7 and a second instance leaves it at 4. When are the two port widths fixed?

Common Mistakes

Wrong Sample a design output in the bench at the same clock edge that updates it.

The bench process and the design process run in the same region, in an order the simulator picks.

Fix Sample after the edge, as the lab bench does 1 ns later, or print with $strobe.

Wrong Put the timescale directive in one file and assume that every module uses it.

The directive applies only to files compiled after it, so a new file order changes the delays.

Fix State timeunit and timeprecision inside each module that has delays.

Wrong Add #0 to push a statement behind the one it races with.

#0 only moves the statement to the Inactive region of the same slot, and a second #0 elsewhere brings the race back.

Fix Remove the cause: write the register with <=, so its readers see the old value in the Active region. Synthesize refuses a #0 in any case.

Before
always @(posedge clk) #0 c = b;
always @(posedge clk) b = a;
After
always_ff @(posedge clk) c <= b;
always_ff @(posedge clk) b <= a;

Wrong Rely on an elaboration $error to stop a bad parameter in every tool.

Icarus 12 and Verilator 5.052 on this site ignored the check and ran the simulation.

Fix Keep the check, and read the synthesis log too: Synthesize does stop on it.

Remember

  • Elaboration fixes parameters, widths and generate copies before time 0. Simulators and synthesizers both do it.
  • RTL runs in two regions: Active reads and computes, NBA updates. That split is what makes <= safe.
  • Ready processes run in any order. A result that depends on the order is a race, even if today's simulator hides it.
  • A clock written by an assignment arrives one delta late. Use one clock and an enable.
  • $display shows values in mid-slot. $strobe and $monitor show them when the slot ends.

Practice

Report a problem with this page