#!/bin/bash

# hc-host-assemble host-bitcode host-object (options)

# enable bash debugging
KMDBSCRIPT="${KMDBSCRIPT:=0}"

# dump the LLVM bitcode
KMDUMPLLVM="${KMDUMPLLVM:=0}"

if [ $KMDBSCRIPT == "1" ]
then
  set -x
fi

BINDIR=$(dirname "$0")
CLANG=$BINDIR/hcc
OPT=$BINDIR/opt
LLVM_AS=$BINDIR/llvm-as
LLVM_DIS=$BINDIR/llvm-dis
LIBPATH=$BINDIR/../lib

# Add error handling functions
. $BINDIR/error-check

if [ "$#" -lt 2 ]; then
  echo "Usage: $0 kernel-bitcode object (options)" >&2
  exit_with_code -1
fi

if [ ! -f "$1" ]; then
  echo "kernel-bitcode $1 is not valid" >&2
  exit_with_code -1
fi

CXXFLAGS=
# Pass down compiler options
if [ "$#" -ge 2 ]; then
  num=2
  while [ $num -lt $# ]
  do
    (( num++ ))
    ARG="${!num}"
    CXXFLAGS=$CXXFLAGS' '"\"$ARG\""
  done
fi

CO="-c -o"

ln -s "$1" "$1.bc"
eval "$CLANG $CXXFLAGS \"$1.bc\" $CO \"$2\" "
check_exit_status "eval $CLANG"
