#!/bin/sh
# tms-clang -- C IR pipeline: clang IR, --scale to bit addresses, optimize,
# then --scale the late byte-indexed GEPs.
#
# Usage: tms-clang [-O0|-O2] [-I dir] -o OUT.ll IN.c
#
# -O0: clang IR -> --scale -> OUT (bit-addressed; no optimizer).
# -O2 (the default): clang IR -> --scale -> opt -> --scale -> OUT.
#
# The pre-opt --scale is required by the M0/M2 pointer model: pointers are bit
# addresses, so `(int)(p + n) - (int)p` must be 8n at run time (the optimizer's
# DataLayout would otherwise fold it to n).  The optimizer consequently sees
# bit-addressed IR.  It creates new byte-indexed GEPs (SROA's aggregate splits
# and switch tables), so the post-opt --scale is still needed.  `--normalize`
# is not used there: it would treat those byte offsets as already-scaled bits,
# which an aggregate return's `.fca.N.gep` load (+4 bytes, not +4 bits) turns
# into an 8x address bug.
#
# Known M6 limitation: InstCombine can canonicalize a bit-offset
# inttoptr(add(ptrtoint p, n*8)) back into a getelementptr i8 whose index is a
# bit count.  The post-opt --scale treats that index as bytes and multiplies it
# by 8 again, so an -O2 C `p += n` whose derived pointer is only used as an
# integer can be over-scaled.  The shared conformance shim's memmove avoids the
# shape by advancing end pointers with constant 8-bit steps; a proper fix needs
# a target bit-pointer semantic barrier and is M7 work (see README.md and
# tools/tms-bitaddr/bitscale.cpp).
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 has no
# matching opt, so it is not a usable default.
TMS_CLANG=${TMS_CLANG:-$ROOT/build/llvm-clean-build/bin/clang}
TMS_OPT=${TMS_OPT:-$ROOT/build/llvm-clean-build/bin/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}

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

OPTIMIZE=1
INCLUDES=
OUT=
IN=

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

while [ $# -gt 0 ]; do
    case "$1" in
    -O0) OPTIMIZE=0; shift ;;
    -O2) OPTIMIZE=1; 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

TMP=$(mktemp -d "${TMPDIR:-/tmp}/tms-clang.XXXXXX")
trap 'rm -rf "$TMP"' EXIT HUP INT TERM

# shellcheck disable=SC2086
"$TMS_CLANG" --target=tms34010-unknown-none -O0 -Xclang -disable-O0-optnone \
    -S -emit-llvm -ffreestanding -fno-builtin -nostdinc $INCLUDES \
    -o "$TMP/step1.ll" "$IN"

# A `static` variadic definition is local, so DeadArgumentElimination removes
# its `...` when nothing keeps the varargs alive and rewrites every call site
# to drop the extra arguments.  The M4 contiguous-stack walk in the body still
# reads those slots, so -O2 silently miscompiles it.  Reject that shape before
# opt, but leave a definition that genuinely uses a va_list alone (M6):
# llvm.va_start/va_arg keep `...` through DAE, and the target lowers the walk
# from the named argument area rather than the last fixed parameter.  -O0
# (which M4's varargs gate uses) and external definitions such as sprintf are
# unaffected.
if [ "$OPTIMIZE" -eq 1 ]; then
    STATIC_VARARG=$(awk '
        /^define / {
            in_def = 1
            sig = $0
            va_start = 0
            next
        }
        in_def && /llvm\.va_start|va_arg ptr/ { va_start = 1 }
        in_def && /^}/ {
            if (!va_start &&
                sig ~ /[^A-Za-z0-9_](internal|private)[^A-Za-z0-9_]/ &&
                sig ~ /\.\.\./) {
                print sig
                exit
            }
            in_def = 0
        }
    ' "$TMP/step1.ll")
    if [ -n "$STATIC_VARARG" ]; then
        NAME=$(printf '%s\n' "$STATIC_VARARG" |
            sed -n 's/.*@\([A-Za-z0-9_.$-]*\)(.*/\1/p')
        echo "tms-clang: error: static variadic definition '${NAME:-?}' loses its" \
            "'...' arguments at -O2 (dead argument elimination); remove 'static'" \
            "or compile with -O0" >&2
        exit 1
    fi
fi

# Scale before the optimizer so integer pointer casts keep the bit-addressed
# model (M0/M2 `int_diff`); the post-opt scale handles the byte-indexed GEPs
# opt creates (SROA aggregate splits, switch tables).
"$TMS_BITADDR" --scale "$TMP/step1.ll" "$TMP/scaled.ll" 2>/dev/null

if [ "$OPTIMIZE" -eq 1 ]; then
    # This target has no i64 and no multiply-high.  IndVarSimplify's exit-value
    # replacement (which rewrites a loop's final value into a closed-form i33
    # multiply, e.g. n*(n+1)/2 for sumto) is therefore an unsupported shape.
    # -replexitval is an option of IndVarSimplify; disabling only that rewrite
    # keeps the loop, which is what ordinary -O2 code needs.  This is a driver
    # policy, not a target TTI policy: opt runs without a target machine here.
    # It stays until i64/M6 removes the workaround; llc diagnoses the raw i33
    # shape reached by an opt run that omits this flag (m5-policy.ll).
    "$TMS_OPT" -passes='default<O2>' -replexitval=never \
        -S "$TMP/scaled.ll" -o "$TMP/opt.ll"
    mkdir -p "$(dirname "$OUT")"
    # The optimizer may create new byte-indexed GEPs (SROA aggregate splits,
    # switch tables), so scale the optimized IR once more.  Known M6
    # limitation: this same pass can over-scale a bit-offset GEP that
    # InstCombine canonicalized from inttoptr(add) -- see the header.
    "$TMS_BITADDR" --scale "$TMP/opt.ll" "$OUT" 2>/dev/null
else
    # `scaled.ll` is already the final bit-offset IR; do not scale it twice.
    mkdir -p "$(dirname "$OUT")"
    cp "$TMP/scaled.ll" "$OUT"
fi
