#!/bin/sh
# tms-clang -- thin flag mapper onto the fork's clang driver.
#
# Usage: tms-clang [-O0|-O2] [-g] [-I dir] -o OUT.ll IN.c
#
# The TMS34010 ToolChain now supplies this target's compile defaults
# (`-ffreestanding`, `-fno-builtin`, no system includes,
# `-mllvm -replexitval=never`, `-disable-O0-optnone`), and the bit-pointer
# barrier / lowering pipeline runs inside clang's own pipeline (guarded by the
# `"tms.bitaddr"` module flag), so this script no longer drives `tms-bitaddr`
# or `opt`.  It maps its historical CLI onto a single clang invocation:
#
#   clang --target=tms34010 [-O0|-O2] [-g] [-I dir] -S -emit-llvm -o OUT.ll IN.c
#
# `-disable-O0-optnone` keeps the -O0 pipeline running the barrier/lowering
# passes, so `-O0` objects stay byte-identical to the M9 tms-clang + opt path
# (proven by scripts/tests/m10/equivalence.sh against the frozen
# legacy-tms-clang oracle).  `-g` passes through to the IR; the barrier passes
# copy !dbg locations, so llc -filetype=obj emits the DWARF `.debug_*` sections.
#
# The `static` variadic rejection that used to live here (the awk guard) is now
# owned by the barrier pass, which rejects the shape at every non-`-O0` level.
set -eu

ROOT=$(cd "$(dirname "$0")/.." && pwd)
# The fork build (TMS34010 target + clang bit-address changes).  The older
# `build/llvm-build` tree is a stock clang without the target and is not a
# usable default.
TMS_CLANG=${TMS_CLANG:-$ROOT/build/llvm-clean-build/bin/clang}
# Extra language flags from the caller (M4_EXTRA_CFLAGS).  The conformance
# c-torture sweep uses this for -std=gnu89; shipped gates leave it empty.
TMS_CLANG_EXTRA_FLAGS=${TMS_CLANG_EXTRA_FLAGS:-}

if [ ! -x "$TMS_CLANG" ]; then
    echo "tms-clang: missing tool: $TMS_CLANG" >&2
    echo "tms-clang: build the fork (build/llvm-clean-build/bin) or set" \
         "TMS_CLANG" >&2
    exit 1
fi

OPT_FLAGS=-O2
DEBUG_FLAGS=
INCLUDES=
OUT=
IN=

usage() {
    echo "usage: $0 [-O0|-O2] [-g] [-I dir] -o OUT.ll IN.c" >&2
    exit 2
}

while [ $# -gt 0 ]; do
    case "$1" in
    -O0) OPT_FLAGS=-O0; shift ;;
    -O2) OPT_FLAGS=-O2; shift ;;
    -g) DEBUG_FLAGS=-g; shift ;;
    -I) [ $# -ge 2 ] || usage; INCLUDES="$INCLUDES -I $2"; shift 2 ;;
    -I*) INCLUDES="$INCLUDES $1"; shift ;;
    -o) [ $# -ge 2 ] || usage; OUT=$2; shift 2 ;;
    -*) usage ;;
    *) [ -z "$IN" ] || usage; IN=$1; shift ;;
    esac
done

[ -n "$IN" ] || usage
[ -n "$OUT" ] || usage

mkdir -p "$(dirname "$OUT")"

# shellcheck disable=SC2086
exec "$TMS_CLANG" --target=tms34010 $OPT_FLAGS $DEBUG_FLAGS $INCLUDES \
    $TMS_CLANG_EXTRA_FLAGS -S -emit-llvm -o "$OUT" "$IN"
