COMPILER="loongarch32r-linux-gnusf-gcc"
LINKER="loongarch32r-linux-gnusf-ld"
ASSEMBLER="loongarch32r-linux-gnusf-as"
OBJCOPY="loongarch32r-linux-gnusf-objcopy"
OBJDUMP="loongarch32r-linux-gnusf-objdump"


#
ITERATIONS=
TICKS_PER_SEC=

USAGE="Usage: $0 [-I ITERATIONS] [-T TICKS_PER_SEC]"

while getopts "hI:T:" OPT; do
    case $OPT in
        h) echo $USAGE;;
        I) ITERATIONS="-DITERATIONS=$OPTARG";;
        T) TICKS_PER_SEC="-DEE_TICKS_PER_SEC=$OPTARG";;
        ?) echo $USAGE; exit 1;;
    esac
done

#
BUILD_PATH="build-la32r"
BUILD_FILE="coremark"

BUILD_ARGS=" \
-nostdlib -mabi=ilp32s -g -O3 \
-fno-builtin -fno-tree-loop-distribute-patterns \
-DPERFORMANCE_RUN=1 $ITERATIONS $TICKS_PER_SEC"

BUILD_ARGS_PASSTHROUGH="$BUILD_ARGS \
-DCOMPILER_FLAGS='\"$BUILD_ARGS\"' \
-DCOMPILER_VERSION='\"$COMPILER\"' \
-DBUILD_LA32R_NSCSCC"

#
eval "rm -rf $BUILD_PATH"
eval "mkdir $BUILD_PATH"

# Compile objects
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c la_init.S        -o $BUILD_PATH/la_init.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c core_list_join.c -o $BUILD_PATH/core_list_join.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c core_main.c      -o $BUILD_PATH/core_main.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c core_matrix.c    -o $BUILD_PATH/core_matrix.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c core_portme.c    -o $BUILD_PATH/core_portme.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c core_state.c     -o $BUILD_PATH/core_state.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c core_util.c      -o $BUILD_PATH/core_util.o"
eval "$COMPILER $BUILD_ARGS_PASSTHROUGH -c ee_printf.c      -o $BUILD_PATH/ee_printf.o"

# Link
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/la_init.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/core_main.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/core_list_join.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/core_matrix.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/core_portme.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/core_state.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/core_util.o"
FILES_TO_LINK="$FILES_TO_LINK $BUILD_PATH/ee_printf.o"

eval "$LINKER -Ttext 0x0 -N -T la_init.ld -Map $BUILD_PATH/memmap.txt -o $BUILD_PATH/coremark.elf $FILES_TO_LINK"

# Generate binary file
eval "$OBJCOPY -O binary $BUILD_PATH/coremark.elf $BUILD_PATH/coremark.bin"

# Disassemble
eval "$OBJDUMP -D $BUILD_PATH/coremark.elf > $BUILD_PATH/coremark.txt"
