# check RISCV environment variable
ifndef RISCV
$(error Please set environment variable RISCV. Please take a look at README)
endif

MODEL ?= TestHarness
PROJECT ?= freechips.rocketchip.system
CFG_PROJECT ?= $(PROJECT)
CONFIG ?= $(CFG_PROJECT).DefaultConfig
# TODO: For now must match rocketchip.Generator
comma := ,
space := $() $()
splitConfigs := $(subst $(comma), ,$(CONFIG))
configBases := $(foreach config,$(splitConfigs),$(lastword $(subst ., ,$(config))))
CONFIG_STR := $(subst $(space),_,$(configBases))
long_name ?= $(PROJECT).$(CONFIG_STR)

VLSI_MEM_GEN ?= $(base_dir)/scripts/vlsi_mem_gen

CXX ?= g++
CXXFLAGS := -O1
JVM_MEMORY ?= 2G

EMPTY :=
SPACE := $(EMPTY) $(EMPTY)
COMMA := ,

# Running with sbt-launch.jar doesn't read .sbtopts by default
# Set if the file exists (if it exists, we're building chisel3 and firrtl from source)
sbtopts_file := $(base_dir)/.sbtopts
ifneq (,$(wildcard $(sbtopts_file)))
	SBT_OPTS ?= $(shell cat $(sbtopts_file))
endif
SBT ?= java -Xmx$(JVM_MEMORY) -Xss8M -jar $(base_dir)/sbt-launch.jar
SHELL := /bin/bash

FIRRTL_TRANSFORMS := \
	firrtl.passes.InlineInstances \

FIRRTL_TEST_JAR ?= $(base_dir)/firrtl/utils/bin/firrtl-test.jar

JAVA ?= java -Xmx$(JVM_MEMORY) -Xss8M
FIRRTL ?= $(JAVA) -cp $(ROCKET_CHIP_JAR) firrtl.stage.FirrtlMain
GENERATOR ?= $(JAVA) -cp $(ROCKET_CHIP_JAR) $(PROJECT).Generator

# Extracting this information from SBT would be more robust
# api-config-chipsalliance does not use standard SBT src/main/scala, but has no resources
scala_srcs := $(shell find $(base_dir) -name "*.scala" -o -name "*.sbt")
resource_dirs := $(shell find $(base_dir) -type d -path "*/src/main/resources")
resources := $(foreach d,$(resource_dirs),$(shell find $(d) -type f))
all_srcs := $(scala_srcs) $(resources)

ROCKET_CHIP_JAR := $(base_dir)/rocketchip.jar
$(ROCKET_CHIP_JAR): $(all_srcs)
	cd $(base_dir) && $(SBT) $(SBT_OPTS) assembly

rc_resource_dir := $(base_dir)/src/main/resources
csrc := $(rc_resource_dir)/csrc
vsrc := $(rc_resource_dir)/vsrc

disasm := 2>
which_disasm := $(shell which spike-dasm 2> /dev/null)
ifneq ($(which_disasm),)
	disasm := 3>&1 1>&2 2>&3 | $(which_disasm) $(DISASM_EXTENSION) >
endif

timeout_cycles = 100000000

bootrom_img = $(base_dir)/bootrom/bootrom.img

#--------------------------------------------------------------------
# Build Tests
#--------------------------------------------------------------------

%.hex:
	$(MAKE) -C $(dir $@) $(notdir $@)

%.riscv.hex: %.riscv
	$(MAKE) -C $(dir $@) $(notdir $@)

clean-run-output:
	rm -f $(output_dir)/{*.out,*.run,*.vpd}
