mkdir -pv "$SRCDIR"/build
cd "$SRCDIR"/build

abinfo "Removing certain search path in PATH to avoid issues ..."
# LLVM will not be able to find Python 3 otherwise
PATH="${PATH/:\/bin/}"
PATH="${PATH/:\/sbin/}"

CPP_TRIPLE="$(gcc -dumpmachine)"
if [[ "$USECLANG" = '1' ]]; then
    abinfo "Selecting ${CPP_TRIPLE} for Clang ..."
    clang -target "${CPP_TRIPLE}" -v
    export CFLAGS="${CFLAGS} -target ${CPP_TRIPLE}"
    export CXXFLAGS="${CXXFLAGS} -target ${CPP_TRIPLE}"
    # only clang will have this idiotic issue
    if ab_match_arch riscv64; then
        abinfo 'Setting -D__LONG_WIDTH__=64 to workaround a Clang bug ...'
        export CFLAGS="${CFLAGS} -D__LONG_WIDTH__=64"
        export CXXFLAGS="${CXXFLAGS} -D__LONG_WIDTH__=64"
    fi
fi

if ab_match_arch loongarch64; then
    abinfo "Adding -mcmodel=medium for compiler-rt ..."
    export CFLAGS="${CFLAGS} -mcmodel=medium"
    export CXXFLAGS="${CXXFLAGS} -mcmodel=medium"
fi

# Remove this when uleb128 relocation support is landed
if ab_match_arch riscv64; then
    abinfo "Stripping debug symbols from libc_nonshared.a for ULEB128 relocation ..."
    strip --strip-debug /usr/lib/libc_nonshared.a
fi

abinfo "Running CMake for LLVM ..."
cmake "$SRCDIR" \
    ${CMAKE_DEF[@]} ${CMAKE_AFTER[@]} \
    -DCMAKE_INSTALL_PREFIX=/usr/lib/llvm-${PKGVER%%.*} \
    -DLLVM_DEFAULT_TARGET_TRIPLE=${CPP_TRIPLE} \
    -DLLVM_HOST_TRIPLE=${CPP_TRIPLE} \
    -DCMAKE_SKIP_RPATH=NO \
    -DCMAKE_SKIP_INSTALL_RPATH=NO

# FIXME: LLVM builds break with Ninja due to an unidentified race condition.
# Fallback to GNU Make for now.
#
# Ref: https://github.com/llvm/llvm-project/issues/87553
abinfo "Building LLVM ..."
make

abinfo "Installing LLVM to a temporary installation directory ..."
make install \
    DESTDIR="$SRCDIR"/fakeroot

abinfo "Installing runtime libraries ..."
install -vd "$PKGDIR"/usr/lib/llvm-${PKGVER%%.*}/lib
cp -Pv \
    "$SRCDIR"/fakeroot/usr/lib/llvm-${PKGVER%%.*}/lib/lib{clang,LLVM,LTO}*.so* \
    "$SRCDIR"/fakeroot/usr/lib/llvm-${PKGVER%%.*}/lib/LLVMgold.so \
    "$PKGDIR"/usr/lib/llvm-${PKGVER%%.*}/lib/
# Note: not all targets have libunwind, libcxx and libcxxabi
for i in "$SRCDIR"/fakeroot/usr/lib/llvm-${PKGVER%%.*}/lib/lib{unwind,c++}*.so*; do
    if [ -e "$i" ]; then
        cp -Pv "$i" \
            "$PKGDIR"/usr/lib/llvm-${PKGVER%%.*}/lib/
    fi
done

abinfo "Installing version-specific runtime libraries to the default location ..."
cd "$PKGDIR"/usr/lib
# The major sover must match the first segment of PKGVER to be considered
# version-specific
ln -sv llvm-"${PKGVER%%.*}"/lib/*.so."${PKGVER%%.*}"* .
ln -sv llvm-"${PKGVER%%.*}"/lib/libLLVM-"${PKGVER%%.*}".so .
