#!/usr/bin/env bash
# Build CoreMark for W65816.  Compiles the 5 core .c files plus our
# porting layer (core_portme.c).  Iteration count baked at compile
# time via -DITERATIONS=N (default 1 — runs ~1 sec at 1 MHz IIgs).
#
# Output: build/*.o for each TU.
#
# Pass --layer2 to enable the dbr-safe-ptrs flag.  CoreMark's data is
# all malloc/stack-allocated, so it's safe in this benchmark.

set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CM_SRC="$SCRIPT_DIR/coremark-src"
OUT="$SCRIPT_DIR/build"
CLANG="$PROJECT_ROOT/tools/llvm-mos-build/bin/clang"
# Auto-fall-back to basic regalloc on the single-accumulator deadlock
# instead of hard-failing the build -- see scripts/ccRegallocFallback.sh.
CC="$PROJECT_ROOT/scripts/ccRegallocFallback.sh"

ITERATIONS="${ITERATIONS:-1}"

LAYER2=()
for arg in "$@"; do
    case "$arg" in
        --layer2) LAYER2=(-mllvm -w65816-dbr-safe-ptrs) ;;
    esac
done

mkdir -p "$OUT"

CFLAGS=(--target=w65816 -O2 -ffunction-sections
        -I "$PROJECT_ROOT/runtime/include"
        -I "$CM_SRC" -I "$SCRIPT_DIR"
        "-DITERATIONS=$ITERATIONS"
        "-DPERFORMANCE_RUN=1"
        "${LAYER2[@]}")

CORE_FILES="core_list_join core_main core_matrix core_state core_util"
for f in $CORE_FILES; do
    echo "  CC  $f.c"
    "$CC" "$CLANG" "${CFLAGS[@]}" -c "$CM_SRC/$f.c" -o "$OUT/$f.o"
done

echo "  CC  core_portme.c"
"$CC" "$CLANG" "${CFLAGS[@]}" -c "$SCRIPT_DIR/core_portme.c" -o "$OUT/core_portme.o"

echo ""
echo "CoreMark built: $(ls "$OUT"/*.o | wc -l) objects, $(du -sh "$OUT" | cut -f1) total"
echo "  ITERATIONS = $ITERATIONS"
echo "  Layer 2:     ${LAYER2[*]:-off}"
