1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::core::prelude::*;
use crate::widgets::dff::DFF;

// A synchronous FIFO of depth 1, backed by a pair of registers
#[derive(LogicBlock, Default)]
pub struct RegisterFIFO<T: Synth> {
    pub data_in: Signal<In, T>,
    pub data_out: Signal<Out, T>,
    pub write: Signal<In, Bit>,
    pub read: Signal<In, Bit>,
    pub full: Signal<Out, Bit>,
    pub empty: Signal<Out, Bit>,
    pub clock: Signal<In, Clock>,
    value: DFF<T>,
    filled: DFF<Bit>,
    error: DFF<Bit>,
}

impl<T: Synth> Logic for RegisterFIFO<T> {
    #[hdl_gen]
    fn update(&mut self) {
        // Connect the clocks
        self.value.clk.next = self.clock.val();
        self.filled.clk.next = self.clock.val();
        self.error.clk.next = self.clock.val();
        // Latch prevention
        self.value.d.next = self.value.q.val();
        self.filled.d.next = self.filled.q.val();
        self.error.d.next = self.error.q.val();
        // There are two states to consider.  The first is the
        // empty state (no internal data)
        if self.write.val() {
            self.value.d.next = self.data_in.val();
        }
        self.data_out.next = self.value.q.val();
        self.full.next = self.filled.q.val() & !self.read.val();
        self.empty.next = !self.filled.q.val();
        if !self.filled.q.val() {
            // We are empty.  This means our empty flag is true, and
            // should be no read.
            if self.write.val() {
                self.value.d.next = self.data_in.val();
                self.filled.d.next = true;
            }
            // If we have a read with no data, this is an error condition !
            if self.read.val() {
                self.error.d.next = true;
            }
        } else {
            // We have data.  It is possible we can get both a
            // read and a write (pipeline)
            // If we have a write with no read, this is an error condition!
            if self.write.val() & !self.read.val() {
                self.error.d.next = true;
            }
            // If we have a read with no write, then we will be empty next cycle
            if self.read.val() & !self.write.val() {
                self.filled.d.next = false;
            }
        }
    }
}

#[test]
fn test_register_fifo_is_synthesizable() {
    let mut uut = RegisterFIFO::<Bits<16>>::default();
    uut.clock.connect();
    uut.write.connect();
    uut.read.connect();
    uut.data_in.connect();
    uut.connect_all();
    let vlog = generate_verilog(&uut);
    println!("{}", vlog);
    yosys_validate("fifo_reg", &vlog).unwrap();
}