# Maintainer: Martell Malone <martellmalone@gmail.com>
# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Ray Donnelly <mingw.android@gmail.com>
# Contributor: Mateusz Mikuła <mati865@gmail.com>
# Contributor: wirx6 <wirx654@gmail.com>
# Contributor: Yuui Tanabe <yuuitanabe@163.com>
# Contributor: Oscar Fuentes <ofv@wanadoo.es>
# Contributor: Adrian Pop <adrian.pop@liu.se>

_compiler=gcc
if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _clangprefix=1
  _compiler=clang
fi
# "Ninja" is too efficient for i686, causing out of memory
# (address space) errors when linking
if [[ $MINGW_PACKAGE_PREFIX == *-clang-i686 ]]; then
  _generator="MSYS Makefiles"
else
  _generator="Ninja"
fi
_realname=clang
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-clang-analyzer"
         "${MINGW_PACKAGE_PREFIX}-clang-tools-extra"
         "${MINGW_PACKAGE_PREFIX}-compiler-rt"
         "${MINGW_PACKAGE_PREFIX}-libc++"
         "${MINGW_PACKAGE_PREFIX}-libc++abi"
         "${MINGW_PACKAGE_PREFIX}-libunwind"
         "${MINGW_PACKAGE_PREFIX}-lld"
         "${MINGW_PACKAGE_PREFIX}-lldb"
         "${MINGW_PACKAGE_PREFIX}-llvm"
         $([[ "$CARCH" == "i686" || "$CARCH" == "x86_64" ]] && echo \
           "${MINGW_PACKAGE_PREFIX}-openmp")
         "${MINGW_PACKAGE_PREFIX}-polly")
pkgver=12.0.0
pkgrel=8
pkgdesc="C language family frontend for LLVM (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://llvm.org/"
license=("custom:Apache 2.0 with LLVM Exception")
groups=($( (( _clangprefix )) && echo "${MINGW_PACKAGE_PREFIX}-toolchain"))
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake>=3.4.3"
             "${MINGW_PACKAGE_PREFIX}-z3"
             "${MINGW_PACKAGE_PREFIX}-libffi"
             "${MINGW_PACKAGE_PREFIX}-libxml2"
             "${MINGW_PACKAGE_PREFIX}-lua"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python-sphinx"
             "${MINGW_PACKAGE_PREFIX}-python"
             "${MINGW_PACKAGE_PREFIX}-swig"
             $([[ "$CARCH" == "i686" || "$CARCH" == "x86_64" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-uasm")
             "tar"
             "groff"
             $([[ "$_compiler" == "clang" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-clang" \
               "${MINGW_PACKAGE_PREFIX}-compiler-rt" \
               "${MINGW_PACKAGE_PREFIX}-libc++")
             $([[ "$_generator" == "Ninja" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-ninja")
             $([[ "$_compiler" == "gcc" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-gcc")
             )
options=('!debug' 'strip')
_url=https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver}
source=("https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver}/llvm-project-${pkgver}.src.tar.xz"{,.sig}
        "0001-Use-posix-style-path-separators-with-MinGW.patch"
        "0002-Fix-GetHostTriple-for-mingw-w64-in-msys.patch"
        "0004-llvm-config-look-for-unversioned-shared-lib-on-win32.patch"
        "0005-add-pthread-as-system-lib-for-mingw.patch"
        "0008-enable-emutls-for-mingw.patch"
        "0010-mbig-obj-for-all.patch"
        "0011-nm-version-option.patch"
        "0012-windres.patch"
        "0013-Dlltool-use-default-LLVM-target-unless-specified.patch"
        "0014-llvm-rc-Don-t-rewrite-the-arch-in-the-default-triple.patch"
        "0015-Use-TerminateProcess-to-exit-without-running-destruc.patch"
        "0101-Disable-fPIC-errors.patch"
        "0103-Use-posix-style-path-separators-with-MinGW.patch"
        "0104-link-pthread-with-mingw.patch"
        "0105-Dont-mark-emutls-variables-as-DSO-local.patch"
        "0201-Provide-a-SEH-specific-__gcc_personality_seh0.patch"
        "0301-fix-including-the-personality-function-for-dwarf.patch"
        "0302-ignore-no-undefined-flag.patch"
        "0303-LLD-MinGW-Add-fatal-warnings-and-no-fatal-warnings-f.patch"
        "0304-ignore-new-bfd-options.patch"
        "0306-LLD-MinGW-Pass-the-canExitEarly-parameter-through-pr.patch"
        "0307-lld-MinGW-Introduce-aliases-for-Bdynamic-and-Bstatic.patch"
        "0308-LLD-COFF-Fix-automatic-export-of-symbols-from-LTO-ob.patch"
        "0310-backport-2b01a41.patch"
        "0311-backport-82de4e0.patch"
        "0312-LLD-COFF-Fix-autoexport-from-LTO-objects-with-comdat.patch"
        "0313-LLD-COFF-Fix-handling-of-LTO-comdats.patch"
        "0314-LLD-COFF-std-async-deferred-on-32-bit.patch"
        "0401-libcxx-fs.patch"
        "0402-make-the-visibility-attributes-consistent-for-__narr.patch"
        "0601-libunwind-Install-the-DLL-when-doing-ninja-install.patch"
        "0710-backport-05b3716.patch"
        "0901-cast-to-make-gcc-happy.patch")
# Some patch notes :)
#0001-0099 -> llvm
#0101-0199 -> clang
#0201-0299 -> rt
#0301-0399 -> lld
#0401-0499 -> libc++
#0501-0599 -> lldb
#0601-0699 -> libunwind
#0701-0799 -> libc++abi
#0801-0899 -> polly
#0901-0999 -> openmp
sha256sums=('9ed1688943a4402d7c904cc4515798cdb20080066efa010fe7e1f2551b423628'
            'SKIP'
            '988a22053c1cc3fa52b1242b3a7cec591ca69b57eb5531c37ce9c74157db62a0'
            '8831c6ea72baa315b20e5f1a9008a9bf4098ba8a18d5331f05216604489063a4'
            '7e7974bbe9ef754be544e5a2a78ab43a1d898c7c9601e7b8d53f8d900df16977'
            '7f0c64cd87b61e894be632f180ae5291e1aa9f1d9d382608f659067eeeda7146'
            '3837bd707d3d99a742e874d5c59a1e7d5502811d6926319974c5d9db86020039'
            'b38c502a113018b934d607d4c92c3e907f92b418c6da1d4425c3fa614f983f10'
            '5d0d8653c95a2d74a4ae531370c3d0584054d15cfef16eb4c45b1d8e5c0fcb4c'
            'e8a6c9e32848dcb9bc16e509516556ced4a5fe888d9b92929e83d0b55c05647b'
            '567307cb8d2a9072ba521b9daaf448d73ca213d9a4f2f4e07485f4be4ac9881d'
            '9152929e1ef94172c11d6d1e4f4c8c106032691a34bfab85ca2b165262092a8e'
            '29b698b06ce1b5a6e8a0850914d335dd30d99a9b4feb1ff9617e69a3038453f1'
            '63b2bda6a487ec69e257c3b7a14d71f6bec649fca058a5a54804f213d45c7c70'
            '2d1dc7f7cd6bd61f275cd0be6650f3086aee622074ac786ff5a921bf8ecaada2'
            '715cb8862753854b2d9256e0b70003e2d1f57083d83eaeaf5a095fc72b8a4e26'
            '7a3453dfdb6992fc226f7e44522e8098c7eab8a80ed8ba7dbda9764f3a5eb191'
            '70382de2120c1de08f86400576188ecd3759612eb8457f2d8be936eb6fa2765f'
            'c4d778c90569a80c3b8fe7c7c53430d456f83f4a65f393f862184375bcb77bc8'
            '0b6756ce06b6439aa9c620ac95e169a08e130b5a50e07eb15eecd3e1e8a0a7af'
            '83951bbd1e90381904096b0d30d1c96c13eaae90326c26d30eb6c5dcf3729fa5'
            '778e0db0a5b0657ab05e2a81d83241347a4a41af2b0f9903422f651fa58e8d40'
            '949180afa030ca95500eae81790b0478b7080ed93ebbe9283cb95f90e6667f2f'
            'b2f3a925f18c1465b43eb57c685e885670cf3360c4d4cb5f6cf27d3bf80fe043'
            '6e861b010fd42d44fddbf12376f3899b0ac17b1b0cfa6033aa2ac9edcf2e310e'
            'd35a234f266c7fd05f1b6415e195dd4ec4e0b41cf50f547a8f5ee5485a57ac3f'
            '99b86abc0218c2e6768212bade513f98aa01dec39489356e0d77e84e0ebcd748'
            '95d0c97547a62e3e2b91688153ade62659c4ce0874facc86244d5040b0593a9c'
            'dfa9b68cbb5017f2856d35bcf9a733139f0223d48f9eb9b265d8ba8a82b24b25'
            '3da6fe01b919a373164de834e4893ea341ac7fc2fb6f3c265c0d74e007ee5ff0'
            '6cb5d425e36b24a8eb2776ba0e297ea0a986a4086f96a0e60ca3a4ebc1a9d386'
            '3abb69e6dc9ad367240409d2df3c3cd6ddc89325de994195fc7222493baaaa44'
            '9ab6c628eccf0155cebdc73e4f5297820bef54d8f30022ed0c1cbb6ab8ad67b8'
            '63b09e0b58a3a100fdd348b5f38f594e3c94cd54030a13b821f7a91ece3e1de0'
            '11352ffbe7559a7170f2abd52b3552c877fbcf8fc82cff77b421e8b130a4dd66')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A') # Tom Stellard
noextract=(llvm-project-${pkgver}.src.tar.xz)

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  plain "Extracting llvm-project-${pkgver}.src.tar.xz due to symlink(s) without pre-existing target(s)"
  cd "${srcdir}"
  rm -rf llvm clang clang-tools-extra compiler-rt lld lldb libcxx libcxxabi libunwind openmp polly || true
  tar --strip-components=1 -xJf ${srcdir}/llvm-project-${pkgver}.src.tar.xz -C ${srcdir} || true

  cd "${srcdir}/llvm"
  apply_patch_with_msg \
    "0001-Use-posix-style-path-separators-with-MinGW.patch" \
    "0002-Fix-GetHostTriple-for-mingw-w64-in-msys.patch" \
    "0004-llvm-config-look-for-unversioned-shared-lib-on-win32.patch" \
    "0010-mbig-obj-for-all.patch" \
    "0011-nm-version-option.patch" \
    "0012-windres.patch" \
    "0013-Dlltool-use-default-LLVM-target-unless-specified.patch" \
    "0014-llvm-rc-Don-t-rewrite-the-arch-in-the-default-triple.patch" \
    "0015-Use-TerminateProcess-to-exit-without-running-destruc.patch"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0005-add-pthread-as-system-lib-for-mingw.patch" \
      "0008-enable-emutls-for-mingw.patch"
  fi

  cd "${srcdir}/clang"
  apply_patch_with_msg \
    "0101-Disable-fPIC-errors.patch" \
    "0103-Use-posix-style-path-separators-with-MinGW.patch" \
    "0105-Dont-mark-emutls-variables-as-DSO-local.patch"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0104-link-pthread-with-mingw.patch"
  fi

  cd "${srcdir}/compiler-rt"
  apply_patch_with_msg \
    "0201-Provide-a-SEH-specific-__gcc_personality_seh0.patch"

  cd "${srcdir}/lld"

  apply_patch_with_msg \
    "0301-fix-including-the-personality-function-for-dwarf.patch" \
    "0302-ignore-no-undefined-flag.patch" \
    "0303-LLD-MinGW-Add-fatal-warnings-and-no-fatal-warnings-f.patch" \
    "0304-ignore-new-bfd-options.patch" \
    "0306-LLD-MinGW-Pass-the-canExitEarly-parameter-through-pr.patch" \
    "0307-lld-MinGW-Introduce-aliases-for-Bdynamic-and-Bstatic.patch" \
    "0308-LLD-COFF-Fix-automatic-export-of-symbols-from-LTO-ob.patch" \
    "0310-backport-2b01a41.patch" \
    "0311-backport-82de4e0.patch" \
    "0312-LLD-COFF-Fix-autoexport-from-LTO-objects-with-comdat.patch" \
    "0313-LLD-COFF-Fix-handling-of-LTO-comdats.patch" \
    "0314-LLD-COFF-std-async-deferred-on-32-bit.patch"

  cd "${srcdir}/libcxx"
  apply_patch_with_msg \
    "0401-libcxx-fs.patch" \
    "0402-make-the-visibility-attributes-consistent-for-__narr.patch"

  cd "${srcdir}/libunwind"
  apply_patch_with_msg \
    "0601-libunwind-Install-the-DLL-when-doing-ninja-install.patch"

  cd "${srcdir}/libcxxabi"
  apply_patch_with_msg \
    "0710-backport-05b3716.patch"

  cd "${srcdir}/openmp"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0901-cast-to-make-gcc-happy.patch"
  fi
}

build() {
  cd "${srcdir}"

  [[ -d build-${MSYSTEM} ]] && rm -rf build-${MSYSTEM}
  mkdir build-${MSYSTEM} && cd build-${MSYSTEM}

  case "${CARCH}" in
    i?86|armv7)
      # lld needs all the address space it can get.
      LDFLAGS+=" -Wl,--large-address-aware"
      ;;
  esac

  local -a extra_config
  local -a common_cmake_args

  if check_option "debug" "y"; then
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Debug)
    VERBOSE="VERBOSE=1"
  else
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Release)
  fi
  common_cmake_args+=(-Wno-dev
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe
    -DPython3_FIND_REGISTRY=NEVER
    -DPython3_ROOT_DIR=${MINGW_PREFIX})

  # Include location of libffi headers in CPPFLAGS
  FFI_INCLUDE_DIR="$(pkg-config --cflags libffi)"
  FFI_INCLUDE_DIR=$(echo $FFI_INCLUDE_DIR | sed 's|-I||g')

  if [ "${_compiler}" == "clang" ]; then
    export CC='clang'
    export CXX='clang++'
    extra_config+=(-DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON
      -DLLVM_ENABLE_LIBCXX=ON)
  fi

  if (( _clangprefix )); then
    # A bit hacky but it works
    local _clang_links="clang++;clang-cpp;as;c++;cc;cpp;g++;gcc;${MINGW_CHOST}-cc;${MINGW_CHOST}-c++;${MINGW_CHOST}-clang;${MINGW_CHOST}-clang++;${MINGW_CHOST}-g++;${MINGW_CHOST}-gcc"

    extra_config+=(-DCLANG_DEFAULT_RTLIB=compiler-rt
      -DCLANG_DEFAULT_UNWINDLIB=libunwind
      -DCLANG_DEFAULT_CXX_STDLIB=libc++
      -DCLANG_DEFAULT_LINKER=lld
      -DLLVM_ENABLE_LLD=ON
      -DCLANG_LINKS_TO_CREATE="${_clang_links}"
      -DLLVM_INSTALL_BINUTILS_SYMLINKS=ON)
  fi

  local _projects="clang;clang-tools-extra;compiler-rt;lld;lldb;polly"
  local -a platform_config

  case "${CARCH}" in
    x86_64)
      export ASM_COMPILER_FLAGS=-win64
      platform_config+=(-DLIBOMP_ASMFLAGS="${ASM_COMPILER_FLAGS}")
      ;& # fall-through
    i?86)
      export ASM_COMPILER="${MINGW_PREFIX}/bin/uasm.exe"
      platform_config+=(-DCMAKE_ASM_MASM_COMPILER="${ASM_COMPILER}"
        -DCOMPILER_RT_BUILD_SANITIZERS=$( (( _clangprefix )) && echo "ON" || echo "OFF"))
      _projects+=";openmp"
      ;;
    armv7|aarch64)
      platform_config+=(-DCOMPILER_RT_BUILD_MEMPROF=OFF
        -DCOMPILER_RT_BUILD_SANITIZERS=OFF
        -DCOMPILER_RT_BUILD_XRAY=OFF)
      ;;
  esac

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"$_generator" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib \
    -DFFI_INCLUDE_DIR="${FFI_INCLUDE_DIR}" \
    -DLIBCLANG_BUILD_STATIC=ON \
    -DLIBOMP_FORTRAN_MODULES=$( (( _clangprefix )) && echo "OFF" || echo "ON" ) \
    -DLLD_DEFAULT_LD_LLD_IS_MINGW=ON \
    -DLLDB_ENABLE_LIBEDIT=OFF \
    -DLLDB_USE_SYSTEM_SIX=ON \
    -DLLVM_BUILD_LLVM_DYLIB=ON \
    -DLLVM_BUILD_STATIC=OFF \
    -DLLVM_ENABLE_ASSERTIONS=OFF \
    -DLLVM_ENABLE_FFI=ON \
    -DLLVM_ENABLE_PROJECTS="${_projects}" \
    -DLLVM_ENABLE_SPHINX=ON \
    -DLLVM_ENABLE_THREADS=ON \
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu" \
    -DLLVM_INCLUDE_EXAMPLES=OFF \
    -DLLVM_INSTALL_UTILS=ON \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    -DLLVM_POLLY_LINK_INTO_TOOLS=OFF \
    -DLLDB_EMBED_PYTHON_HOME=OFF \
    "${common_cmake_args[@]}" \
    "${platform_config[@]}" \
    "${extra_config[@]}" \
    ../llvm

  # sed away the bad windows style command line parameters (they are translated by msys from /bad to c:\msys\bad
  # Ninja doesn't need fixing them.
  if [[ "$_generator" != "Ninja" ]]; then
    case "${CARCH}" in
      i?86|x86_64)
        sed -i.orig 's/\/c \/Fo/-c -Fo/' projects/openmp/runtime/src/CMakeFiles/omp.dir/build.make
        sed -i.orig 's/\/safeseh \/coff/-safeseh -coff/' projects/openmp/runtime/src/CMakeFiles/omp.dir/build.make
        ;;
    esac
  fi

  ${MINGW_PREFIX}/bin/cmake.exe --build .

  # Disable automatic installation of components that go into subpackages
  # -i.orig to check what has been removed in-case it starts dropping more than it should
  #
  sed -i.orig '/\(clang\|lld\|lldb\|polly\)\/cmake_install.cmake/d' tools/cmake_install.cmake
  sed -i.orig '/\(extra\|scan-build\|scan-view\)\/cmake_install.cmake/d' tools/clang/tools/cmake_install.cmake
  sed -i.orig '/\(compiler-rt\|libcxxabi\|libcxx\|openmp\|libunwind\)\/cmake_install.cmake/d' projects/cmake_install.cmake

  # Use newly built compiler because GCC/binutils doesn't play nicely
  if (( _clangprefix )); then
    common_cmake_args+=(-DLIBCXX_USE_COMPILER_RT=ON
      -DLIBCXXABI_USE_COMPILER_RT=ON
      -DLIBCXXABI_USE_LLVM_UNWINDER=ON)
  else
    export CC="${srcdir}/build-${MSYSTEM}/bin/clang"
    export CXX="${srcdir}/build-${MSYSTEM}/bin/clang++"
    common_cmake_args+=(-DCMAKE_AR=${srcdir}/build-${MSYSTEM}/bin/llvm-ar
      -DCMAKE_RANLIB=${srcdir}/build-${MSYSTEM}/bin/llvm-ranlib)
  fi

  common_cmake_args+=(-DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX}
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib
    -DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON
    -DLIBCXX_HAS_WIN32_THREAD_API=ON
    -DLIBCXXABI_HAS_WIN32_THREAD_API=ON
    -DLIBCXXABI_ENABLE_SHARED=OFF
    -DLIBCXXABI_ENABLE_STATIC=ON
    -DLIBUNWIND_USE_COMPILER_RT=ON
    -DLLVM_ENABLE_LLD=ON
    -DLLVM_ENABLE_PROJECTS="libcxx;libcxxabi;libunwind"
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu")

  cd "${srcdir}"

  [[ -d build-libcxx-shared-${MSYSTEM} ]] && rm -rf build-libcxx-shared-${MSYSTEM}
  mkdir build-libcxx-shared-${MSYSTEM} && cd build-libcxx-shared-${MSYSTEM}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"$_generator" \
    -DCMAKE_CXX_FLAGS="${CXXFLAGS} -D_LIBCPP_BUILDING_LIBRARY -U_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS" \
    -DLIBCXX_ENABLE_EXPERIMENTAL_LIBRARY=OFF \
    -DLIBCXX_ENABLE_SHARED=ON \
    -DLIBCXX_ENABLE_STATIC=OFF \
    -DLIBUNWIND_ENABLE_SHARED=ON \
    -DLIBUNWIND_ENABLE_STATIC=OFF \
    "${common_cmake_args[@]}" \
    ../llvm

  ${MINGW_PREFIX}/bin/cmake.exe --build . -- unwind cxx

  cd "${srcdir}"

  [[ -d build-libcxx-static-${MSYSTEM} ]] && rm -rf build-libcxx-static-${MSYSTEM}
  mkdir build-libcxx-static-${MSYSTEM} && cd build-libcxx-static-${MSYSTEM}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"$_generator" \
    -DCMAKE_CXX_FLAGS="${CXXFLAGS} -D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS" \
    -DLIBCXX_ENABLE_SHARED=OFF \
    -DLIBCXX_ENABLE_STATIC=ON \
    -DLIBCXXABI_ENABLE_STATIC_UNWINDER=ON \
    -DLIBUNWIND_ENABLE_SHARED=OFF \
    -DLIBUNWIND_ENABLE_STATIC=ON \
    "${common_cmake_args[@]}" \
    ../llvm

  ${MINGW_PREFIX}/bin/cmake.exe --build . -- unwind cxxabi cxx cxx_experimental
}

check() {
 cd "${srcdir}"/build-${MSYSTEM}
 # Remove || true once testcase doesn't cause failures.
#  make check || true
#  make check-clang || true
#  make check-polly || true
  ${MINGW_PREFIX}/bin/cmake.exe --build . -- check-lld || true
}

package_clang() {
  pkgdesc="C language family frontend for LLVM (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}-${pkgrel}"
           $( ((_clangprefix)) && echo \
             "${MINGW_PACKAGE_PREFIX}-compiler-rt=${pkgver}-${pkgrel}" \
             "${MINGW_PACKAGE_PREFIX}-crt" \
             "${MINGW_PACKAGE_PREFIX}-headers" \
             "${MINGW_PACKAGE_PREFIX}-lld=${pkgver}-${pkgrel}" \
             "${MINGW_PACKAGE_PREFIX}-winpthreads" \
             || echo "${MINGW_PACKAGE_PREFIX}-gcc"))
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-gcc" \
             || true ))

  cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang" --prefix "${pkgdir}${MINGW_PREFIX}"
}

package_clang-analyzer() {
  pkgdesc="A source code analysis framework (mingw-w64)"
  url="https://clang-analyzer.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}-${pkgrel}"
           "${MINGW_PACKAGE_PREFIX}-python")

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/scan-build"
  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/scan-view"

  # Compile Python scripts
  ${MINGW_PREFIX}/bin/python -m compileall "${pkgdir}"${MINGW_PREFIX}/bin/clang-analyzer
  ${MINGW_PREFIX}/bin/python -O -m compileall "${pkgdir}"${MINGW_PREFIX}/lib/clang-analyzer
  install -Dm644 "${srcdir}/clang/LICENSE.TXT" "${pkgdir}"${MINGW_PREFIX}/share/licenses/clang-analyzer/LICENSE
}

package_clang-tools-extra() {
  pkgdesc="Extra tools built using Clang's tooling APIs (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}-${pkgrel}")

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/extra"
}

package_compiler-rt() {
  pkgdesc="Runtime libraries for Clang and LLVM (mingw-w64)"
  url="https://compiler-rt.llvm.org/"
  depends=($( (( _clangprefix )) || echo "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/projects/compiler-rt"
  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin/"
  find "${pkgdir}${MINGW_PREFIX}/lib/clang/${pkgver}/lib/windows/" \
    -name '*.dll' -exec mv '{}' "${pkgdir}${MINGW_PREFIX}/bin/" \;
  # remove bin dir we created if it is still empty
  rmdir "${pkgdir}${MINGW_PREFIX}/bin/" 2>/dev/null || true
}

package_libc++() {
  pkgdesc="C++ Standard Library (mingw-w64)"
  url="https://libcxx.llvm.org/"
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-gcc-libs" \
             || true))
  depends=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-libunwind" \
             || echo "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-libcxx-shared-${MSYSTEM}/projects/libcxx"
  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-libcxx-static-${MSYSTEM}/projects/libcxx"
}

package_openmp() {
  pkgdesc="OpenMP library (mingw-w64)"
  url="https://openmp.llvm.org/"
  depends=($( (( _clangprefix )) || echo "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/projects/openmp"
}

package_libc++abi() {
  pkgdesc="C++ Standard Library Support (mingw-w64)"
  url="https://libcxxabi.llvm.org/"
  depends=($( (( _clangprefix )) || echo \
             "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-libcxx-static-${MSYSTEM}/projects/libcxxabi"
}

package_libunwind() {
  pkgdesc='A new implementation of a stack unwinder for C++ exceptions (mingw-w64)'
  url='https://llvm.org/'
  depends=($( (( _clangprefix )) || echo "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-libcxx-shared-${MSYSTEM}/projects/libunwind"
  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-libcxx-static-${MSYSTEM}/projects/libunwind"
}

package_lld() {
  pkgdesc="Linker tools for LLVM (mingw-w64)"
  url="https://lld.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}-${pkgrel}")
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-binutils" \
             || true))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/lld"
  if (( _clangprefix )); then
    install -Dm755 "${pkgdir}${MINGW_PREFIX}/bin/lld.exe" "${pkgdir}${MINGW_PREFIX}/bin/ld.exe"
  fi
}

package_lldb() {
  pkgdesc="Next generation, high-performance debugger (mingw-w64)"
  url="https://lldb.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}-${pkgrel}"
           "${MINGW_PACKAGE_PREFIX}-libxml2"
           "${MINGW_PACKAGE_PREFIX}-lua"
           "${MINGW_PACKAGE_PREFIX}-python"
           "${MINGW_PACKAGE_PREFIX}-xz")

  cd "${srcdir}/lldb"

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/lldb"

  # Compile Python scripts
   local _pyver=$(${MINGW_PREFIX}/bin/python -c "import sys;sys.stdout.write('.'.join(map(str, sys.version_info[:2])))")
  ${MINGW_PREFIX}/bin/python -m compileall "${pkgdir}${MINGW_PREFIX}/lib/python${_pyver}/site-packages/lldb"
  ${MINGW_PREFIX}/bin/python -O -m compileall "${pkgdir}${MINGW_PREFIX}/lib/python${_pyver}/site-packages/lldb"

  install -Dm644 "${srcdir}/lldb/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/share/licenses/lldb/LICENSE"
}

package_llvm() {
  pkgdesc="Low Level Virtual Machine (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-libffi"
           "${MINGW_PACKAGE_PREFIX}-gcc-libs"
           "${MINGW_PACKAGE_PREFIX}-zlib"
           "${MINGW_PACKAGE_PREFIX}-libxml2")

  cd "${srcdir}"/llvm

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}"

  install -Dm644 "${srcdir}/llvm/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/share/licenses/llvm/LICENSE"

  # Install CMake stuff
  install -d "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/{modules,platforms}
  install -Dm644 "${srcdir}"/llvm/cmake/modules/*.cmake "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/modules/
  install -Dm644 "${srcdir}"/llvm/cmake/platforms/*.cmake "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/platforms/

  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i ${pkgdir}/${MINGW_PREFIX}/lib/cmake/llvm/LLVMExports.cmake
}

package_polly() {
  pkgdesc="Polly - Polyhedral optimizations for LLVM (mingw-w64)"
  url="https://polly.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}-${pkgrel}")

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/polly"
  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  local SRC_WIN=$(cygpath -wm ${srcdir})
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}/|g" \
    -e "s|${SRC_WIN}/build-${MSYSTEM}/lib|${MINGW_PREFIX}/lib|g" \
    -i "${pkgdir}/${MINGW_PREFIX}/lib/cmake/polly/PollyConfig.cmake"
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
