# ============================================================================
#  Makefile - build the 344S0602-A GLUE for iCE40HX1K-TQ144
#  Needs: yosys, nextpnr-ice40, icepack, icetime (icestorm), iverilog
# ============================================================================
TOP   := glue_ice40_top
SRC   := vgc_cells_ice40.v glue_344s0602.v glue_ice40_top.v
PCF   := glue_hx1k_tq144.pcf
FREQ  := 31.3344            # MHz, C32M

all: glue_hx1k.bin

# synthesis (also writes a post-synthesis netlist for gate-level simulation)
glue.json: $(SRC)
	yosys -q -l synth.log -p "read_verilog $(SRC); \
	    synth_ice40 -top $(TOP) -json $@; write_verilog -noattr glue_syn.v"

# place & route
#  --ignore-loops        : X24 (LAE02 transparent latch) becomes a LUT feedback
#                          loop - iCE40 has no latch primitive
#  --no-promote-globals  : keep the ripple-counter clocks on local routing;
#                          C32M already has its SB_GB_IO
glue.asc: glue.json $(PCF)
	nextpnr-ice40 --hx1k --package tq144 --json $< --pcf $(PCF) --asc $@ \
	    --freq $(FREQ) --ignore-loops --no-promote-globals --log pnr.log

glue_hx1k.bin: glue.asc
	icepack $< $@

# gate-level simulation of the synthesised iCE40 netlist with the same
# testbench as the RTL (tb instantiates glue_344s0602 -> retarget to the top)
sim: glue.json
	sed 's/glue_344s0602 dut/glue_ice40_top dut/' tb_glue_344s0602.v > tb_ice40.v
	iverilog -g2012 -o sim_ice40 $$(dirname $$(which yosys))/../share/yosys/ice40/cells_sim.v \
	    glue_syn.v tb_ice40.v
	vvp -n sim_ice40

prog: glue_hx1k.bin            # program the SPI flash via the iceprog header
	iceprog $<

clean:
	rm -f glue.json glue.asc glue_hx1k.bin glue_syn.v synth.log pnr.log tb_ice40.v sim_ice40 glue.vcd

.PHONY: all sim prog clean
