IVERILOG ?= iverilog
VVP ?= vvp
VERILATOR ?= verilator
YOSYS ?= yosys
BUILD ?= build

SPI_RTL := rtl/axil_spi.sv rtl/spi_master_mode0.sv

.PHONY: all test lint synth clean
all: test

test: $(BUILD)/arbiter $(BUILD)/spi $(BUILD)/fifo2 $(BUILD)/fifo8 $(BUILD)/fifo8-fast-read
	$(VVP) $(BUILD)/arbiter
	$(VVP) $(BUILD)/spi
	$(VVP) $(BUILD)/fifo2
	$(VVP) $(BUILD)/fifo8
	$(VVP) $(BUILD)/fifo8-fast-read

$(BUILD):
	mkdir -p $@

$(BUILD)/arbiter: rtl/round_robin_arbiter.sv tb/tb_round_robin_arbiter.sv | $(BUILD)
	$(IVERILOG) -g2012 -Wall -s tb_round_robin_arbiter -o $@ $^

$(BUILD)/spi: $(SPI_RTL) tb/tb_axil_spi.sv | $(BUILD)
	$(IVERILOG) -g2012 -Wall -s tb_axil_spi -o $@ $^

$(BUILD)/fifo2: rtl/async_fifo.sv tb/tb_async_fifo.sv | $(BUILD)
	$(IVERILOG) -g2012 -Wall -s tb_async_fifo -Ptb_async_fifo.ADDR_WIDTH=1 -o $@ $^

$(BUILD)/fifo8: rtl/async_fifo.sv tb/tb_async_fifo.sv | $(BUILD)
	$(IVERILOG) -g2012 -Wall -s tb_async_fifo -Ptb_async_fifo.ADDR_WIDTH=3 -o $@ $^

$(BUILD)/fifo8-fast-read: rtl/async_fifo.sv tb/tb_async_fifo.sv | $(BUILD)
	$(IVERILOG) -g2012 -Wall -s tb_async_fifo -Ptb_async_fifo.WRITE_HALF_PERIOD=7 -Ptb_async_fifo.READ_HALF_PERIOD=5 -o $@ $^

lint:
	$(VERILATOR) --lint-only -Wall --top-module round_robin_arbiter rtl/round_robin_arbiter.sv
	$(VERILATOR) --lint-only -Wall --top-module axil_spi $(SPI_RTL)
	$(VERILATOR) --lint-only -Wall --top-module async_fifo rtl/async_fifo.sv

synth:
	$(YOSYS) -Q -q -p 'read_verilog -sv rtl/round_robin_arbiter.sv; synth -top round_robin_arbiter; check -assert'
	$(YOSYS) -Q -q -p 'read_verilog -sv $(SPI_RTL); synth -top axil_spi; check -assert'
	$(YOSYS) -Q -q -p 'read_verilog -sv rtl/async_fifo.sv; synth -top async_fifo; check -assert'

clean:
	rm -f $(BUILD)/arbiter $(BUILD)/spi $(BUILD)/fifo2 $(BUILD)/fifo8 $(BUILD)/fifo8-fast-read
