Synchronous FIFO in Verilog: Code, Testbench and Results

A synchronous FIFO (first-in, first-out) in Verilog is a buffer that stores data in the order it arrives and returns the oldest unread entry first. Its read and write operations use the same clock. A typical implementation combines a memory array, two address pointers, an occupancy counter, and full and empty flags.
The tricky part is not storing the data. It is deciding which requests are accepted when the buffer is full or empty, and what happens when a producer and consumer act on the same edge. Those choices affect both the RTL and the testbench.
This guide implements a 32-bit, 16-entry synchronous FIFO from an explicit specification. The complete SystemVerilog implementation and self-checking testbench come from SiliCode run #489. Its exported simulation log records 12,292 checked clock cycles, including 12,000 randomized cycles, with zero data mismatches or reported errors.
The complete example uses SystemVerilog (.sv), not Verilog-2001. Enable SystemVerilog support in your simulator and synthesis tool.
Jump to: FIFO RTL code · Self-checking testbench · Simulation results
What Is a Synchronous FIFO?
A FIFO decouples a producer from a consumer. The producer can write data while the consumer is busy, provided that storage is available. Later, the consumer can read the buffered entries in their original order.
For example, if a producer writes A, B and C, the consumer must receive A first, then B, then C. It does not matter how many idle cycles occur between those operations.
Common uses include buffering samples in DSP pipelines, holding commands for a peripheral controller, buffering packets between stages of a streaming datapath, and absorbing short differences in processing rate. A FIFO can absorb a burst, but it cannot indefinitely compensate for a producer whose average rate exceeds the consumer's.
Synchronous vs. Asynchronous FIFO
| Feature | Synchronous FIFO | Asynchronous FIFO |
|---|---|---|
| Clocking | One shared clock | Separate read and write clocks |
| Status logic | Can use a shared occupancy counter | Must account for information crossing clock domains |
| Typical use | Buffering inside one clock domain | Transferring data between clock domains |
| Verification focus | Ordering, boundaries and cycle timing | Ordering, boundaries and CDC correctness |
The example in this article is strictly single-clock. Do not connect its read and write sides to unrelated clocks. An asynchronous FIFO requires a different architecture, usually including synchronized pointer information and clock-domain-specific status flags.
How a Synchronous FIFO Works
Think of the storage as a circular array. The write pointer identifies the next location to fill; the read pointer identifies the oldest unread entry. Each pointer advances only when its corresponding operation is accepted.
| Component | Purpose |
|---|---|
| Memory array | Stores DEPTH words of DATA_WIDTH bits |
| Write pointer | Addresses the next write location |
| Read pointer | Addresses the next unread word |
| Occupancy counter | Tracks how many valid entries are stored |
| Full and empty flags | Indicate whether another write or read can be accepted |
| Read-data register | Captures the oldest word on an accepted read |
When either pointer reaches the end of the array, it wraps to address zero. The data itself does not move around the memory. Only the pointers change.
For this implementation, pointer equality cannot distinguish an empty buffer from a full one: the pointers can coincide in either situation. The occupancy counter resolves that ambiguity.
Define the FIFO Specification Before Writing RTL
This example implements the FIFO contract introduced in our RTL design specification guide. The default data width is 32 bits and the depth is 16 entries. Only power-of-two depths of at least two and positive data widths are supported by the pointer arithmetic; the module does not enforce these parameter restrictions at elaboration time.
| Signal | Direction | Default width | Meaning |
|---|---|---|---|
clk |
Input | 1 | Rising-edge sampling clock |
rst_n |
Input | 1 | Synchronous active-low reset |
wr_en |
Input | 1 | Write request |
wr_data |
Input | 32 | Word to enqueue |
rd_en |
Input | 1 | Read request |
rd_data |
Output | 32 | Registered word from an accepted read |
full |
Output | 1 | Occupancy equals depth |
empty |
Output | 1 | Occupancy is zero |
count |
Output | 5 | Number of valid entries |
Reset has priority over all requests. On a rising edge with reset asserted, the FIFO becomes logically empty, both pointers return to zero, and the read output clears. Outside reset, acceptance is determined from the occupancy before the edge. The read output changes only on an accepted read or reset.
These rules are part of this particular design, not universal FIFO behavior. A different FIFO may allow bypass or replacement at a boundary. Make that decision in the specification rather than discovering it in simulation.
Calculating FIFO Pointer and Counter Widths
A 16-entry memory requires four address bits, representing addresses 0 through 15. The occupancy counter must also represent 16, which requires five bits.
PTR_W = $clog2(DEPTH) = 4
CNT_W = $clog2(DEPTH) + 1 = 5
For power-of-two depths, incrementing a fixed-width address pointer naturally wraps it at the end of the array. At depth 16, the four-bit value 15 increments to zero. At a depth such as 10, the same arithmetic would incorrectly allow addresses 10 through 15. A non-power-of-two design needs explicit wrap logic and appropriate parameter handling.
Do not make the occupancy counter the same width as the address pointer. A four-bit counter would wrap when incremented from 15, making a completely full FIFO look empty.
Generating Full and Empty Flags
The current flags determine which operations are accepted. When the FIFO is not in reset, the combinational acceptance conditions are:
do_wr = wr_en && !full;
do_rd = rd_en && !empty;
The next count increases for a write alone, decreases for a read alone, and stays unchanged when both or neither are accepted.
count_nxt = count;
if (do_wr && !do_rd) count_nxt = count + 1'b1;
else if (do_rd && !do_wr) count_nxt = count - 1'b1;
At the clock edge, the count and flags are updated together using nonblocking assignments. The flags are computed from count_nxt, not from the old count. Otherwise, they could lag the occupancy by one cycle. See our blocking and nonblocking assignment guide for the underlying scheduling semantics.
Three Ways to Distinguish FIFO Full and Empty
Equal address pointers are ambiguous when all memory slots can be used. For a power-of-two, single-clock FIFO, three common approaches resolve this in different ways.
| Method | Empty condition | Full condition | Usable entries |
|---|---|---|---|
| Occupancy counter (this design) | count = 0 | count = DEPTH | DEPTH |
| Extra wrap bit on each pointer | Extended pointers equal | Address bits equal, wrap bits differ | DEPTH |
| Leave one slot unused | Address pointers equal | Next write address equals read address | DEPTH − 1 |
The counter method exposes occupancy directly, which makes threshold flags straightforward. Extended pointers distinguish full from empty without a separate occupancy counter, although an occupancy output needs additional logic. Leaving one slot unused simplifies the pointer comparison but reduces usable capacity: a 16-entry array holds only 15 words. For registered flags, calculate the relevant conditions from the next values. These methods do not by themselves determine whether simultaneous requests are accepted at a boundary. See these alternative synchronous FIFO implementations for examples.
Simultaneous Read and Write: Full and Empty Cases
When both requests are asserted on the same clock edge, the pre-edge occupancy matters. The following table assumes reset is inactive.
| Occupancy before edge | Write accepted? | Read accepted? | Occupancy after edge |
|---|---|---|---|
| 0 (empty) | Yes | No | 1 |
| 1 through DEPTH−1 | Yes | Yes | Unchanged |
| DEPTH (full) | No | Yes | DEPTH−1 |
At empty, the incoming word is stored but not returned by the read output on that edge. A later read is needed. This is the no-bypass policy.
At full, the read frees a slot but the simultaneous write is rejected. A producer can use the slot on a subsequent edge. This is the no-replacement policy.
At intermediate occupancy, both operations proceed. The oldest word is read, the new word is appended, and the number of stored entries remains constant. The FIFO can sustain one accepted read and one accepted write per cycle while remaining away from the boundaries.
Allowing replacement at full could improve throughput for some workloads, but it changes the acceptance rule. It may also require deliberate handling of read-during-write behavior when both addresses coincide. Do not enable it by changing a flag expression alone.
When both requests are asserted, this FIFO accepts only a write when empty, both operations at intermediate occupancy, and only a read when full.
Registered Read vs. First-Word Fall-Through
The FIFO in this article uses registered read data. When a read is accepted at a rising edge, the oldest word is captured in rd_data. If no read is accepted, the output holds its previous value, even when the FIFO is empty. That retained value does not represent a newly valid word.
A first-word fall-through (FWFT) FIFO exposes the first available entry before an explicit read consumes it. Its data-valid timing is therefore different. These are interface choices, not interchangeable ways to describe the same hardware.
AMD's XPM_FIFO_SYNC documentation describes standard and FWFT modes, with output and status latency depending on configuration. Do not assume that a vendor FIFO has exactly the same latency as this example.
Complete Synchronous FIFO Verilog Code
Save the following exported RTL as sync_fifo.sv. It uses SystemVerilog constructs, including logic, always_comb, always_ff and a sized cast, so use a compiler with SystemVerilog support. The code is reproduced unchanged from run #489.
`default_nettype none
module sync_fifo #(
parameter int DATA_WIDTH = 32,
parameter int DEPTH = 16 // power of two, >= 2
) (
input wire clk,
input wire rst_n,
input wire wr_en,
input wire [DATA_WIDTH-1:0] wr_data,
input wire rd_en,
output logic [DATA_WIDTH-1:0] rd_data,
output logic full,
output logic empty,
output logic [$clog2(DEPTH):0] count
);
localparam int PTR_W = $clog2(DEPTH);
localparam int CNT_W = $clog2(DEPTH) + 1;
logic [DATA_WIDTH-1:0] mem [0:DEPTH-1];
logic [PTR_W-1:0] wr_ptr;
logic [PTR_W-1:0] rd_ptr;
logic do_wr;
logic do_rd;
logic [CNT_W-1:0] count_nxt;
// Acceptance based on occupancy before the clock edge
always_comb begin
do_wr = wr_en && !full;
do_rd = rd_en && !empty;
count_nxt = count;
if (do_wr && !do_rd) count_nxt = count + 1'b1;
else if (do_rd && !do_wr) count_nxt = count - 1'b1;
end
// Storage: no reset, written only on accepted writes
always_ff @(posedge clk) begin
if (rst_n && do_wr) mem[wr_ptr] <= wr_data;
end
always_ff @(posedge clk) begin
if (!rst_n) begin
wr_ptr <= '0;
rd_ptr <= '0;
count <= '0;
full <= 1'b0;
empty <= 1'b1;
rd_data <= '0;
end else begin
if (do_wr) wr_ptr <= wr_ptr + 1'b1; // natural wrap (power of two)
if (do_rd) begin
rd_ptr <= rd_ptr + 1'b1;
rd_data <= mem[rd_ptr];
end
count <= count_nxt;
full <= (count_nxt == CNT_W'(DEPTH));
empty <= (count_nxt == '0);
end
end
endmodule
`default_nettype wire
The memory has its own clocked write process. The second clocked process handles pointers, occupancy, flags and the read-data register. The combinational process calculates the acceptance signals and next count.
Notice that the storage array is not reset. Reset invalidates the stored contents by clearing occupancy and pointers. No stale word is exposed by a valid read until new data has been written. This is a logical flush, not a physical erasure of the memory. If secure erasure is a requirement, this design does not provide it.
Avoiding a reset on the entire storage array can help preserve RAM inference. AMD discusses this in its UG949 memory-reset guidance. The synchronous reset on the interface is explained further in our Verilog reset guide.
Reading the FIFO Cycle by Cycle
The following is an illustrative timing example, not a captured waveform. A, B and C represent distinct words. Both requests are evaluated before the edge; all output columns show values after the edge.
| Edge | Request | Accepted | Queue after edge | count | rd_data |
|---|---|---|---|---|---|
| 0 | Reset | None | Empty | 0 | 0 |
| 1 | Write A + read | Write only | A | 1 | 0 |
| 2 | Write B | Write | A, B | 2 | 0 |
| 3 | Write C + read | Both | B, C | 2 | A |
| 4 | Read | Read | C | 1 | B |
| 5 | Read | Read | Empty | 0 | C |
| 6 | Read | None | Empty | 0 | C |
Edge 1 is an important test: a read request coincides with a write into an empty FIFO, but the new word does not bypass the memory. Edge 6 shows why a nonzero read output is not proof that a word is available. The empty flag says whether another read can be accepted.
How to Verify a Synchronous FIFO
Checking that two words come out in the right order is useful, but it is not enough. A FIFO testbench must exercise the occupancy boundaries, simultaneous operations, pointer wraparound, and reset while data is pending.
The reference model in this run uses a separate circular buffer with integer indices and an integer occupancy count. It calculates acceptance using that count instead of reading the DUT's flags. It updates its expected read word only on an accepted read or reset.
| Test group | Behavior checked |
|---|---|
| Single read/write and ordering | Correct word, original order and output retention |
| Fill and drain | All 16 slots usable, correct full and empty flags |
| Boundary requests | Writes blocked at full and reads blocked at empty |
| Simultaneous requests | Intermediate occupancy, full and empty policies |
| Pointer wrap | Repeated writes and reads across the end of storage |
| Reset | Partial/full queues and active requests during reset |
| Random traffic | 12,000 cycles with varied traffic and occasional reset |
| Final drain | Remaining words checked and queue empty at completion |
After every checked rising edge, the testbench waits one nanosecond and compares count, full, empty and rd_data against the reference model. It also checks for unexpected unknown or high-impedance outputs. The delay belongs to the testbench, not the synthesizable FIFO.
This verifies the sampled, post-edge interface. It does not independently monitor every between-edge output change or establish the absence of physical glitches. It also cannot distinguish synchronous from asynchronous reset: after startup, reset is driven shortly after a clock edge, and outputs are checked only after the next rising edge. To verify synchronous reset timing, first establish a nonzero occupancy and a known read output, assert reset between edges, check that the outputs remain unchanged before the next rising edge, and then check that they clear as specified after that edge. More demanding interfaces may require additional assertions. For the general checking technique, see our self-checking Verilog testbench guide.
Complete Self-Checking FIFO Testbench
Save this original exported testbench as tb_sync_fifo.sv. It tests the default 32-bit, 16-entry configuration. The hard-coded 32-bit stimulus and local parameters are deliberate here; testing additional widths and depths requires a suitable parameterized testbench.
`default_nettype none
`timescale 1ns/1ps
module tb_sync_fifo;
localparam int DATA_WIDTH = 32;
localparam int DEPTH = 16;
localparam int CNT_W = $clog2(DEPTH) + 1;
localparam logic [31:0] RAND_SEED = 32'hC0FFEE01; // documented seed for random phase
localparam int RAND_CYCLES = 12000;
logic clk;
logic rst_n;
logic wr_en;
logic [DATA_WIDTH-1:0] wr_data;
logic rd_en;
wire [DATA_WIDTH-1:0] rd_data;
wire full;
wire empty;
wire [CNT_W-1:0] count;
sync_fifo #(.DATA_WIDTH(DATA_WIDTH), .DEPTH(DEPTH)) dut (
.clk(clk), .rst_n(rst_n), .wr_en(wr_en), .wr_data(wr_data),
.rd_en(rd_en), .rd_data(rd_data), .full(full), .empty(empty), .count(count)
);
initial clk = 1'b0;
always #5 clk = ~clk;
// Reference model (circular buffer with integer indices, independent of DUT)
logic [DATA_WIDTH-1:0] ref_mem [0:DEPTH-1];
integer ref_wp, ref_rp, ref_cnt;
logic [DATA_WIDTH-1:0] exp_rd;
// Statistics
integer cycles, acc_wr, acc_rd, rej_wr, rej_rd, simul, mism, errors;
integer rst_cycles;
logic [31:0] rng;
logic [31:0] dctr;
integer i, k, phase;
logic m_w, m_r;
integer wr_prob, rd_prob, rst_prob;
function automatic logic [31:0] xorshift(input logic [31:0] s);
logic [31:0] x;
begin
x = s;
x = x ^ (x << 13);
x = x ^ (x >> 17);
x = x ^ (x << 5);
xorshift = x;
end
endfunction
task automatic err(input [255:0] msg);
begin
errors = errors + 1;
$display("ERROR t=%0t cycle=%0d: %0s", $time, cycles, msg);
end
endtask
// One clock cycle: drive inputs, update model, check after the edge.
task automatic step(input logic r_n, input logic we, input logic re, input logic [31:0] d);
begin
rst_n = r_n;
wr_en = we;
rd_en = re;
wr_data = d;
// model update using occupancy before the edge
if (!r_n) begin
ref_wp = 0; ref_rp = 0; ref_cnt = 0; exp_rd = '0;
rst_cycles = rst_cycles + 1;
end else begin
m_w = we && (ref_cnt < DEPTH);
m_r = re && (ref_cnt > 0);
if (we && !m_w) rej_wr = rej_wr + 1;
if (re && !m_r) rej_rd = rej_rd + 1;
if (m_w) acc_wr = acc_wr + 1;
if (m_r) acc_rd = acc_rd + 1;
if (m_w && m_r) simul = simul + 1;
if (m_r) begin
exp_rd = ref_mem[ref_rp];
ref_rp = (ref_rp + 1) % DEPTH;
end
if (m_w) begin
ref_mem[ref_wp] = d;
ref_wp = (ref_wp + 1) % DEPTH;
end
ref_cnt = ref_cnt + (m_w ? 1 : 0) - (m_r ? 1 : 0);
end
@(posedge clk);
#1;
cycles = cycles + 1;
if ((^{count, full, empty, rd_data}) === 1'bx) begin
err("X/Z on outputs");
$display(" count=%b full=%b empty=%b rd_data=%h", count, full, empty, rd_data);
end
if (count !== ref_cnt[CNT_W-1:0]) begin
err("count mismatch"); $display(" exp=%0d got=%0d", ref_cnt, count);
end
if (full !== (ref_cnt == DEPTH)) begin
err("full mismatch"); $display(" exp=%0d got=%b", (ref_cnt == DEPTH), full);
end
if (empty !== (ref_cnt == 0)) begin
err("empty mismatch"); $display(" exp=%0d got=%b", (ref_cnt == 0), empty);
end
if (rd_data !== exp_rd) begin
mism = mism + 1;
err("rd_data mismatch"); $display(" exp=%h got=%h", exp_rd, rd_data);
end
end
endtask
task automatic idle(input integer n);
integer j;
begin for (j = 0; j < n; j = j + 1) step(1'b1, 1'b0, 1'b0, 32'hDEAD_BEEF); end
endtask
task automatic wr(input logic [31:0] d);
begin step(1'b1, 1'b1, 1'b0, d); end
endtask
task automatic rd;
begin step(1'b1, 1'b0, 1'b1, 32'h0); end
endtask
initial begin
$dumpfile("tb_sync_fifo.vcd");
$dumpvars(0, tb_sync_fifo);
cycles = 0; acc_wr = 0; acc_rd = 0; rej_wr = 0; rej_rd = 0;
simul = 0; mism = 0; errors = 0; rst_cycles = 0;
ref_wp = 0; ref_rp = 0; ref_cnt = 0; exp_rd = '0;
for (i = 0; i < DEPTH; i = i + 1) ref_mem[i] = '0;
rst_n = 1'b0; wr_en = 1'b0; rd_en = 1'b0; wr_data = '0;
// Test 1: initial reset (X-check applies from first reset edge)
step(1'b0, 1'b0, 1'b0, 32'h0);
step(1'b0, 1'b0, 1'b0, 32'h0);
if (count !== 0 || empty !== 1'b1 || full !== 1'b0 || rd_data !== 32'h0)
err("post-reset state wrong");
idle(2);
// Test 2: single write and read; Test 14: rd_data registered/retained
wr(32'hA5A5_0001);
if (rd_data !== 32'h0) err("rd_data changed on write");
idle(2);
rd();
if (rd_data !== 32'hA5A5_0001) err("rd_data not registered after read");
idle(3);
if (rd_data !== 32'hA5A5_0001) err("rd_data not retained");
rd(); // read while empty: retained
if (rd_data !== 32'hA5A5_0001) err("rd_data changed on empty read");
// Test 3: ordering
for (i = 0; i < 5; i = i + 1) wr(32'h1000_0000 + i * 32'h111);
for (i = 0; i < 5; i = i + 1) rd();
// Test 4: fill to capacity, Test 5: writes while full
for (i = 0; i < DEPTH; i = i + 1) wr(32'h2000_0000 + i);
if (full !== 1'b1 || count !== DEPTH) err("not full after fill");
for (i = 0; i < 4; i = i + 1) wr(32'hBAD0_0000 + i);
// Test 6: drain; Test 7: reads while empty
for (i = 0; i < DEPTH; i = i + 1) rd();
if (empty !== 1'b1) err("not empty after drain");
for (i = 0; i < 4; i = i + 1) rd();
// Test 8: simultaneous at intermediate occupancy
for (i = 0; i < 6; i = i + 1) wr(32'h3000_0000 + i);
for (i = 0; i < 10; i = i + 1) step(1'b1, 1'b1, 1'b1, 32'h3100_0000 + i);
if (count !== 6) err("count changed during simultaneous op");
for (i = 0; i < 6; i = i + 1) rd();
// Test 9: simultaneous while empty (write only, no bypass)
step(1'b1, 1'b1, 1'b1, 32'h4000_0001);
if (rd_data === 32'h4000_0001) err("bypass detected");
if (count !== 1) err("count after empty simul");
rd();
// Test 10: simultaneous while full (read only, no replacement)
for (i = 0; i < DEPTH; i = i + 1) wr(32'h5000_0000 + i);
step(1'b1, 1'b1, 1'b1, 32'h5FFF_FFFF);
if (count !== DEPTH-1 || full !== 1'b0) err("simul at full wrong");
for (i = 0; i < DEPTH; i = i + 1) rd();
// Test 11: multiple pointer wraparounds
for (k = 0; k < 6; k = k + 1) begin
for (i = 0; i < 11; i = i + 1) wr(32'h6000_0000 + k * 256 + i);
for (i = 0; i < 11; i = i + 1) rd();
end
// Test 12: reset while partially full
for (i = 0; i < 7; i = i + 1) wr(32'h7000_0000 + i);
step(1'b0, 1'b0, 1'b0, 32'h0);
idle(1);
rd();
// Test 13: reset while full with requests active
for (i = 0; i < DEPTH; i = i + 1) wr(32'h8000_0000 + i);
step(1'b0, 1'b1, 1'b1, 32'h8FFF_FFFF);
if (count !== 0 || empty !== 1'b1 || full !== 1'b0 || rd_data !== 32'h0)
err("reset with active requests wrong");
step(1'b0, 1'b1, 1'b1, 32'h8FFF_FFFE);
wr(32'h9000_0001);
rd();
// Test 15: randomized, documented seed RAND_SEED
rng = RAND_SEED;
dctr = 32'hD000_0000;
for (i = 0; i < RAND_CYCLES; i = i + 1) begin
phase = (i / 1500) % 4;
case (phase)
0: begin wr_prob = 50; rd_prob = 50; end
1: begin wr_prob = 80; rd_prob = 30; end
2: begin wr_prob = 30; rd_prob = 80; end
default: begin wr_prob = 90; rd_prob = 90; end
endcase
rst_prob = 1; // percent... of 1000 below
rng = xorshift(rng); m_w = ((rng[15:8] % 100) < wr_prob);
rng = xorshift(rng); m_r = ((rng[15:8] % 100) < rd_prob);
rng = xorshift(rng);
dctr = dctr + 32'h0000_0101 + {24'h0, rng[7:0]};
step(((rng[25:16] % 1000) >= 3), m_w, m_r, dctr);
end
// Test 16: final drain and integrity
step(1'b1, 1'b0, 1'b0, 32'h0);
while (ref_cnt > 0) rd();
idle(2);
if (count !== 0 || empty !== 1'b1) err("final drain not empty");
$display("---- SUMMARY (seed=0x%h) ----", RAND_SEED);
$display("Total checked cycles : %0d", cycles);
$display("Accepted writes : %0d", acc_wr);
$display("Accepted reads : %0d", acc_rd);
$display("Rejected writes : %0d", rej_wr);
$display("Rejected reads : %0d", rej_rd);
$display("Simultaneous accepted: %0d", simul);
$display("Reset cycles : %0d", rst_cycles);
$display("Data mismatches : %0d", mism);
$display("Total errors : %0d", errors);
if (errors == 0) $display("SIMULATION PASSED");
else $display("SIMULATION FAILED");
$finish;
end
initial begin
#50000000;
$display("TIMEOUT");
$finish;
end
endmodule
`default_nettype wire
The random traffic uses xorshift32 with seed 0xC0FFEE01. Traffic changes every 1,500 cycles, cycling through balanced, write-heavy, read-heavy and high-activity phases. The nominal write/read thresholds are 50/50, 80/30, 30/80 and 90/90. Modulo bias changes the approximate write/read request probabilities to 59/59, 84/35, 35/84 and 92/92 percent, respectively, assuming uniformly distributed source bits. These are request probabilities, not acceptance rates. The reset calculation has six matching values out of 1,024, giving a nominal probability of about 0.59%, nearly twice the 0.3% suggested by the threshold. This seed produces 69 reset cycles during the 12,000-cycle random phase (0.575%); the full test includes 74 reset cycles.
Using a fixed seed makes this run reproducible. Additional seeds and parameter configurations would broaden the test scope. Also, this exported testbench prints failure or timeout messages but calls $finish; for CI, use $fatal or explicitly check the log so a failing run cannot be mistaken for success based on its exit status alone.
Running the FIFO Simulation: Actual Results
With Icarus Verilog, compile the two files and run the resulting simulation:
iverilog -g2012 -s tb_sync_fifo -o sim sync_fifo.sv tb_sync_fifo.sv
vvp sim
The exported simulation summary from SiliCode run #489 is shown below. These are recorded results, not an example of what a passing log might look like.
VCD info: dumpfile tb_sync_fifo.vcd opened for output.
---- SUMMARY (seed=0xc0ffee01) ----
Total checked cycles : 12292
Accepted writes : 7066
Accepted reads : 6598
Rejected writes : 1148
Rejected reads : 1618
Simultaneous accepted: 4314
Reset cycles : 74
Data mismatches : 0
Total errors : 0
SIMULATION PASSED
| Metric | Recorded result |
|---|---|
| Checked cycles | 12,292 |
| Randomized cycles | 12,000 |
| Accepted writes | 7,066 |
| Accepted reads | 6,598 |
| Rejected writes | 1,148 |
| Rejected reads | 1,618 |
| Cycles with both operations accepted | 4,314 |
| Reset cycles | 74 |
| Data mismatches | 0 |
| Total errors | 0 |

SiliCode run #489 completed 12,292 checked cycles, including 7,066 accepted writes and 6,598 accepted reads, with zero reported errors.
The rejected operations are useful evidence: both full-write and empty-read paths were exercised. The simultaneous counter counts cycles, not additional transactions, so those operations are already included in the accepted write and read totals. Requests during reset are excluded from the acceptance and rejection counters.
The write total exceeds the read total by 468. That does not indicate lost data during normal operation. Reset intentionally discards pending entries, and the testbench drains the FIFO before finishing. With an empty starting and ending queue, the difference accounts for the 468 entries discarded by reset.
The passing log establishes agreement with the reference model for the executed tests at the default parameter values. It is not exhaustive verification of all sequences, widths or depths, and it does not establish hardware timing closure.
Inspecting FIFO Waveforms in GTKWave
The testbench requests tb_sync_fifo.vcd, and the simulator log confirms that the dump file was opened. The VCD itself was not included in the exported ZIP. To inspect a fresh trace, run the testbench locally and open the resulting file:
gtkwave tb_sync_fifo.vcd
Start with clk, rst_n, wr_en, rd_en, wr_data, rd_data, count, full and empty. Add dut.wr_ptr, dut.rd_ptr, dut.do_wr and dut.do_rd when debugging acceptance and wraparound.
At a failing edge, first determine whether the request should have been accepted. Then compare the occupancy before and after the edge. Only investigate storage contents after confirming that the correct pointer advanced. This separates acceptance bugs from data-ordering bugs. Our Verilog waveform debugging guide explains how to follow the first wrong cycle.
FPGA Synthesis Results: LUTRAM vs. Block RAM
Yosys 0.52 synthesized the exported RTL for AMD/Xilinx 7-series. The mapped cell report contains these resources:
| Resource | Count |
|---|---|
| Logic LUT cells | 15 (3 LUT2, 5 LUT4, 7 LUT6) |
| Flip-flops | 47 (46 FDRE, 1 FDSE) |
| Carry cells | 6 CARRY4 |
| Distributed RAM | 6 RAM32M (24 LUT resources) |
| Estimated total LUT resources | 39 (15 logic + 24 RAM) |
| Block RAM | 0 |
| DSP | 0 |
| Total mapped cells | 207, including buffers, inverters and multiplexers |
The storage array holds 512 logical bits. Yosys maps it to six RAM32M primitives rather than to dedicated block RAM. AMD's RAM32M documentation (UG953) identifies this primitive as LUT-based memory using four LUT6 resources per primitive, not block RAM. The six RAM32M cells account for 24 LUT resources. Adding the 15 logic LUT cells gives an estimated total of 39 LUT resources (15 for logic and 24 for distributed RAM), with zero dedicated block RAM primitives in the mapped netlist. This is an estimate from the primitive counts, not a placed-and-routed utilization report.
That distinction matters for FPGA resource planning. A deeper or wider FIFO may map differently, depending on the target, read architecture, synthesis settings and memory inference. There is no universal depth threshold that guarantees block RAM inference.
To investigate how depth affects memory mapping, rerun synthesis with a different power-of-two DEPTH while keeping DATA_WIDTH fixed at 32. For example, in Yosys:
yosys -p 'read_verilog -sv sync_fifo.sv; chparam -set DEPTH 256 sync_fifo; synth_xilinx -family xc7 -top sync_fifo; stat; check'
Compare the mapped RAM primitives rather than assuming a particular memory type. A synthesis sweep is separate from functional verification: the supplied testbench checks only the default depth and width.
The full log reports that no latch was inferred for the three combinational signals. It also includes an ABC warning noting its combinational network. The Yosys design check reports zero problems. These are synthesis estimates, not placed-and-routed resource counts, timing closure or power results.
See the original SiliCode run for the design and reported verification results.
Common Synchronous FIFO Design Mistakes
| Mistake | Better approach |
|---|---|
| Counter too narrow to represent DEPTH | Allocate enough bits for every occupancy from zero to depth. |
| Advancing a pointer on a rejected request | Advance only on an accepted operation. |
| Computing registered flags from the old count | Compute flags from the next occupancy. |
| Updating count on simultaneous accepted read/write | Keep count unchanged when both are accepted. |
| Resetting all memory entries without a requirement | Reset logical validity and control state; consider RAM inference. |
| Assuming read data is always valid | Define registered read timing and acceptance explicitly. |
| Using this single-clock design for CDC | Use an asynchronous FIFO or another suitable crossing mechanism. |
| Testing only ordinary traffic | Check full, empty, simultaneous operations, wrap and reset. |
Designing and Verifying a FIFO With SiliCode
A request to build a FIFO leaves several implementation choices unanswered. State the clock domain, data width, depth, reset behavior, read timing and simultaneous-operation policy before generating the RTL. Those same requirements should guide the reference model.
In this example, SiliCode generated the FIFO and its self-checking testbench, ran functional simulation, and synthesized the design. The exported evidence makes it possible to review both the interface behavior and the mapped resources. It does not replace engineering review, additional verification or timing analysis.
Try SiliCode with your own FIFO specification →
Frequently Asked Questions
Can a synchronous FIFO read and write at the same time?
Yes. This design accepts both at intermediate occupancy. At empty it accepts only the write, and at full it accepts only the read. Other FIFO architectures may define different boundary behavior.
Can this FIFO support a non-power-of-two depth?
Not as written. Its pointers wrap naturally at a power of two. For other depths of at least two, explicitly wrap each pointer from DEPTH minus one to zero, size the count to represent zero through DEPTH, and verify the modified design at the intended depths.
How do I add almost-full and almost-empty flags?
Choose occupancy thresholds that match the producer and consumer response times. For example, with depth 16, almost-full could assert at count 14 or above, and almost-empty at count two or below. If the flags are registered, compare against the next occupancy so they align with the updated count. Test the threshold crossings and reset behavior.
How can I convert this FIFO to first-word fall-through (FWFT)?
Define an interface in which the oldest valid word is visible before a read request consumes it. A combinational memory read may work with distributed RAM; synchronous-read block RAM typically needs prefetch or an output buffer. Update the empty and data-valid timing and reference model, including first-write and last-read cases. Changing the read-enable condition alone is not enough.
Does this example work with a Verilog-2001 compiler?
No. The RTL and testbench use SystemVerilog constructs. A Verilog-2001 port would require changes such as replacing logic, always_ff, always_comb, parameter int and sized casts, and supplying a compatible width-calculation function instead of $clog2. Compile and retest the converted design before using it.
Should FIFO memory be reset?
For ordinary FIFOs, reset can clear the occupancy, pointers and output without clearing each storage word. This logically invalidates previous data and can help preserve memory inference. Physical erasure is a separate requirement.
Does a synchronous FIFO always use block RAM?
No. Synthesis may use distributed RAM, block RAM or registers depending on the target and implementation. This example maps to RAM32M distributed-memory primitives.
Conclusion: Verify the FIFO at Its Boundaries
A reliable synchronous FIFO starts with a precise acceptance policy, correctly sized pointers and counter, and clearly defined read timing. Once those decisions are made, the implementation is small enough to follow edge by edge.
Test both accepted and rejected operations, not just ordinary enqueue and dequeue traffic. Check the storage order, occupancy, flags and reset against a separate reference model. Then review the synthesis report to understand how the memory and control logic were mapped before moving on to implementation timing.