VERILATOR = verilator
VERILATOR_FLAGS = --cc --exe --build -Wall --trace -Wno-fatal
VERILATOR_FLAGS += -CFLAGS "-std=c++14 -O2"
SBT = env SBT_OPTS="-Dsbt.boot.directory=/tmp/sbt-boot -Dsbt.ivy.home=/tmp/sbt-ivy" COURSIER_CACHE=/tmp/coursier-cache sbt

CHISEL_DIR = ../..
GENERATED_DIR = $(CHISEL_DIR)/generated
SRC_FILES = testbench.cpp memory.cpp

VERILOG_FILES = $(GENERATED_DIR)/Core.sv

TARGET = obj_dir/VCore

.PHONY: all verilog compile run clean

all: compile

verilog:
	@echo "Generating Verilog from Chisel..."
	cd $(CHISEL_DIR) && $(SBT) "runMain Core"

compile: verilog
	@echo "Compiling with Verilator..."
	$(VERILATOR) $(VERILATOR_FLAGS) \
		-I$(GENERATED_DIR) \
		--top-module Core \
		-o VCore \
		$(VERILOG_FILES) $(SRC_FILES)

run: compile
	@if [ -z "$(TEST)" ]; then \
		echo "Usage: make run TEST=<path/to/test>"; \
		exit 1; \
	fi
	./$(TARGET) $(TEST)

test-simple: compile
	@echo "Running simple test..."
	./$(TARGET) ../../riscv-tests/isa/rv64ui-p-simple

clean:
	rm -rf obj_dir
	rm -rf $(GENERATED_DIR)
