PROJECT = cpu
BOARD = tangnano20k
FAMILY = GW2A-18C
DEVICE = GW2AR-LV18QN88C8/I7

# Source files
VERILOG_SRC = cpu.v register_file.v sequencer.v alu.v sram_srom.v
TOP_MODULE = cpu

# Constraint file
CST = tangnano20k.cst

# Synthesis
$(PROJECT).json: $(VERILOG_SRC)
	yosys -p "read_verilog $(VERILOG_SRC); \
	          synth_gowin -top $(TOP_MODULE) -json $@"

# Place & Route
$(PROJECT)_pnr.json: $(PROJECT).json
	nextpnr-gowin --json $< \
	              --write $@ \
	              --device $(DEVICE) \
	              --family $(FAMILY) \
	              --cst $(CST)

# Generate bitstream
$(PROJECT).fs: $(PROJECT)_pnr.json
	gowin_pack -d $(FAMILY) -o $@ $

# Program FPGA
load: $(PROJECT).fs
	openFPGALoader -b $(BOARD) $

# Flash to FPGA
flash: $(PROJECT).fs
	openFPGALoader -b $(BOARD) -f $

# Clean
clean:
	rm -f $(PROJECT).json $(PROJECT)_pnr.json $(PROJECT).fs

tsim:
	./uasm.py ucode.src
	customasm -f readmemh,width:32 hope.asm -o sromr.hex
	./revhex.py sromr.hex srom.hex
	iverilog -o cpu_sim cpu_tb2.v cpu.v register_file.v alu.v sequencer.v sram_srom.v
	./cpu_sim|more

.PHONY: load flash clean tsim
