# Description: LLVM compiler backend
# URL: https://llvm.org/
# Maintainer: CRUX System Team, core-ports at crux dot nu
# Depends on: libxml2 ninja python3-setuptools
# Optional: lld

name=llvm
version=18.1.4
release=1
source=(https://github.com/llvm/llvm-project/releases/download/llvmorg-$version/llvm-$version.src.tar.xz
	https://github.com/llvm/llvm-project/releases/download/llvmorg-$version/cmake-$version.src.tar.xz
	https://github.com/llvm/llvm-project/releases/download/llvmorg-$version/third-party-$version.src.tar.xz
	install-prefix.patch
	rust-feature-tables.patch
	llvm-config.h)

build() {
	prt-get isinst ccache && PKGMK_LLVM+=' -D LLVM_CCACHE_BUILD=ON' && \
		export PATH="$(echo ${PATH} | awk -v RS=: -v ORS=: '/ccache/ {next} {print}' | sed 's/:*$//')"

	cp -r $SRC/cmake-$version.src/Modules/* $name-$version.src/cmake/modules/.
	mv $SRC/cmake-$version.src/ $SRC/cmake
	mv $SRC/third-party-$version.src/ $SRC/third-party

	grep -rl '#!.*python' | xargs sed -i '1s/python$/python3/'

	patch -Np2 -d $name-$version.src -i $SRC/rust-feature-tables.patch
	patch -Np2 -d $name-$version.src -i $SRC/install-prefix.patch

	cmake -S $name-$version.src -B build -G Ninja $PKGMK_LLVM \
		-D CMAKE_INSTALL_PREFIX=/usr \
		-D CMAKE_BUILD_TYPE=Release \
		-D CMAKE_C_FLAGS_RELEASE="$CFLAGS" \
		-D CMAKE_CXX_FLAGS_RELEASE="$CXXFLAGS" \
		-D LLVM_BINUTILS_INCDIR=/usr/include \
		-D LLVM_BUILD_LLVM_DYLIB=ON \
		-D LLVM_LINK_LLVM_DYLIB=ON \
		-D FFI_INCLUDE_DIR=/usr/include \
		-D LLVM_BUILD_RUNTIME=ON \
		-D LLVM_BUILD_EXTERNAL_COMPILER_RT=ON \
		-D LLVM_ENABLE_FFI=ON \
		-D LLVM_ENABLE_RTTI=ON \
		-D LLVM_INCLUDE_UTILS=ON \
		-D LLVM_INSTALL_UTILS=ON \
		-D LLVM_ENABLE_PIC=ON \
		-D LLVM_ENABLE_TERMINFO=ON \
		-D LLVM_ENABLE_ZLIB=ON \
		-D LLVM_ENABLE_ZSTD=ON \
		-D LLVM_OPTIMIZED_TABLEGEN=ON \
		-D LLVM_BUILD_TOOLS=ON \
		-D LLVM_UTILS_INSTALL_DIR=/usr/bin \
		-D LLVM_INCLUDE_EXAMPLES=OFF \
		-D LLVM_INCLUDE_TESTS=OFF \
		-D LLVM_ENABLE_OCAMLDOC=OFF \
		-D LLVM_ENABLE_LIBCXX=OFF \
		-D LLVM_ENABLE_LLD="$(prt-get isinst lld >/dev/null && echo ON || echo OFF)" \
		-D LLVM_INCLUDE_BENCHMARKS=OFF \
		-D LLVM_APPEND_VC_REV=OFF \
		-Wno-dev

	cmake --build build --target LLVM -j ${JOBS:-1}
	cmake --build build -j ${JOBS:-1}
	DESTDIR=$PKG cmake --install build

	# multilib stub
	mv $PKG/usr/include/llvm/Config/llvm-config{,-64}.h
	install -m 0644 $SRC/llvm-config.h $PKG/usr/include/llvm/Config/

	install -d $PKG/usr/lib/bfd-plugins
	ln -s ../LLVMgold.so $PKG/usr/lib/bfd-plugins/
	ln -s ../libLTO.so $PKG/usr/lib/bfd-plugins/

	/usr/bin/python3 $name-$version.src/utils/lit/setup.py build
	/usr/bin/python3 $name-$version.src/utils/lit/setup.py install --prefix=/usr --root=$PKG
	/usr/bin/python3 -m compileall -d $name-$version.src/utils/lit $PKG
	/usr/bin/python3 -O -m compileall -d $name-$version.src/utils/lit $PKG
	/usr/bin/python3 -OO -m compileall -d $name-$version.src/utils/lit $PKG
}
