#!/bin/sh
 
# LLVM/Clang toolchain cross-compilation script for QNX 8.0 by Pierre-Marie Baty <pm@pmbaty.com>
 
 
 
# NOTE TO SELF: DO NOT USE $0 AS THIS SCRIPT CAN BE RUN *OR* SOURCED! (see build-llvm.sh in the VM)
 
 
 
export QNXSDK_VERSION="8.0.0" # version of the QNX SDK in use, in <major>.<minor>.<revision> format
 
export QNXSDK_PATH="../qnx800" # relative location from the path of this script where to find the QNX platform SDK
 
export QNXSDK_HOSTPATH="host/linux/x86_64" # relative location in QNXSDK_PATH of the tree containing the build tools that are runnable on the build host
 
export QNXSDK_TARGETPATH="target/qnx" # relative location in QNXSDK_PATH of the tree containing the QNX8 system header files
 
 
 
export BUILD_DIR_NAME="llvm-build" # name of the directory on the build host's desktop where the LLVM sources will be built
 
export BUILD_TARGET_ARCH="x86_64" # CPU architecture to build LLVM for, either "x86_64" or "aarch64"
 
 
 
export LLVM_VERSION="16.0.6" # version of LLVM that will be built (ideally the same version as the libc++ supplied by QNX in their platform SDK)
 
export LLVM_SOURCES_FILE="llvmorg-${LLVM_VERSION}.tar.gz" # name of the file containing LLVM version LLVM_VERSION sources
 
export LLVM_SOURCES_URL="https://github.com/llvm/llvm-project/archive/refs/tags/${LLVM_SOURCES_FILE}" # download URL of LLVM_SOURCES_FILE
 
export LLVM_SOURCES_DIR="llvm-project-llvmorg-${LLVM_VERSION}" # name of directory created when extracting LLVM_SOURCES_FILE
 
 
 
export LLVM_PROJECTS_TO_BUILD="clang;lld;polly" # semicolon-separated list of LLVM projects to build (full list: "clang;clang-tools-extra;cross-project-tests;libc;libclc;lld;lldb;openmp;polly;pstl")
 
export LLVM_RUNTIMES_TO_BUILD="compiler-rt" # semicolon-separated list of LLVM runtimes to build (full list: "compiler-rt;libc;libcxx;libcxxabi;libunwind;openmp")
 
export LLVM_BUILD_CONFIGURATION_TYPE="MinSizeRel" # build configuration, one of "Debug", "Release", "RelWithDebugInfo" or "MinSizeRel"
 
 
 
export REQUIRED_TOOLS="wget python3 cmake gcc g++ ninja ccache" # list of build tools required to build all this on the build host
 
 
 
# see where we are
 
export CURRENT_DIR="$(pwd)"
 
 
 
print_error_and_die()
 
{
 
        # a handy function that does what it says. Args: error strings to print, one line per argument
 
        test -z "${COLUMNS}" && COLUMNS=80
 
        echo ""
 
        while [ -n "${1}" ]; do
 
                echo "${1}"|fold -s -w "${COLUMNS}"
 
                shift
 
        done
 
        echo ""
 
        exit 1
 
}
 
 
 
# verify we're a x86_64 Linux host
 
if [ ! "$(uname)" = "Linux" ] || [ ! "$(uname -m)" = "x86_64" ]; then
 
        print_error_and_die "Error: this script requires a x86_64 Linux machine (possibly a virtual machine, or WSL) as the build host."
 
fi
 
 
 
# verify that we have the required tools
 
for REQUIRED_TOOL in ${REQUIRED_TOOLS}; do
 
        "${REQUIRED_TOOL}" --version > /dev/null 2>&1 || print_error_and_die \
 
                "Error: this script requires at the very least the following tools installed:" \
 
                "       $(echo "${REQUIRED_TOOLS}"|sed 's/ /\n  /g')" \
 
                "Please install them (possibly as binary packages with apt-get) and try again." \
 
                "More specifically, the following tool was not found: '${REQUIRED_TOOL}'"
 
done
 
 
 
# verify that we have the QNX platform SDK
 
if [ ! -d "${QNXSDK_PATH}/${QNXSDK_HOSTPATH}" ] || [ ! -d "${QNXSDK_PATH}/${QNXSDK_TARGETPATH}" ]; then
 
        print_error_and_die "Error: the ${QNXSDK_PATH} path doesn't contain a QNX SDK. It must contain the 'host' and 'target' directories of the QNX SDP for the targeted version of QNX and the ${BUILD_TARGET_ARCH} platform. Please deploy these directories and try again."
 
fi
 
 
 
# change to an immediately visible path, i.e. the user's desktop (failsafe to $HOME if xdg-user-dir is unavailable or points to a nonexistent directory)
 
STAGING_PATH="$(xdg-user-dir DESKTOP 2>/dev/null || echo "${HOME}")"
 
test -d "${STAGING_PATH}" || STAGING_PATH="${HOME}"
 
cd "${STAGING_PATH}"
 
 
 
# are we running the Windows Subsystem for Linux, instead of a real Linux ?
 
if [ -n "${WSL_DISTRO_NAME}" ]; then
 
        # yes. In order to avoid the horrible 9p protocol for file interchange between NTFS and ext4 (a remarkably bad idea by Microsoft),
 
        # use the copy of the QNX SDP that our caller is supposed to have put in our $HOME in the WSL2 filesystem. The speed gain is considerable.
 
        QNXSDK_CANONICAL_PATH="${HOME}/$(basename "${QNXSDK_PATH}")"
 
        if [ ! -d "${QNXSDK_CANONICAL_PATH}/${QNXSDK_HOSTPATH}" ] || [ ! -d "${QNXSDK_CANONICAL_PATH}/${QNXSDK_TARGETPATH}" ]; then
 
                print_error_and_die "Error: the QNX SDP hasn't been deployed to ${QNXSDK_CANONICAL_PATH}. Please do so and run this script again."
 
        fi
 
else
 
        # we're not in WSL. We can expect reasonably good file access speeds to the QNX SDP that's bundled with this repository, so just use it.
 
        QNXSDK_CANONICAL_PATH="$(realpath "${CURRENT_DIR}/${QNXSDK_PATH}")"
 
fi
 
 
 
# verify that the symlinks are deployed in the SDK -- just test one of them in each relevant directory ($QNX_HOST for the tools, $QNX_TARGET for the sysroot)
 
if [ ! -e "${QNXSDK_CANONICAL_PATH}/${QNXSDK_HOSTPATH}/usr/bin/ntox86_64-gcc" ] || [ ! -e "${QNXSDK_CANONICAL_PATH}/${QNXSDK_TARGETPATH}/usr/include/readline.h" ]; then
 
        print_error_and_die \
 
                "Error: the toolchain platform-specific symbolic links have not been deployed in this QNX SDK. Please run" \
 
                "(on a POSIX machine:)" \
 
                "       cd ${QNXSDK_CANONICAL_PATH}" \
 
                "       find . -name symlinks.lst -exec ./symlinks.sh {} create \\; && printf 'present' > .symlinks-state" \
 
                "(else on a Windows machine:)" \
 
                "       cd ${QNXSDK_CANONICAL_PATH}" \
 
                "       host\\win64\\x86_64\\usr\\bin\\busybox.exe sh -c \"find . -name symlinks.lst -exec ./symlinks.sh {} create \\; && printf 'present' > .symlinks-state\"" \
 
                "Note that this step WILL take time on a Win32 machine, but is only done once."
 
fi
 
 
 
# Create a symlink in /tmp that will lead to the QNX platform SDK so as to avoid spaces in paths if it doesn't exist already
 
# (this is totally prohibitive with the official QNX toolchain)
 
if [ ! -L /tmp/qnxsdk ] || [ ! "$(readlink /tmp/qnxsdk)" = "${QNXSDK_CANONICAL_PATH}" ]; then
 
        echo "Creating symlink to QNX toolchain in /tmp/qnxsdk..."
 
        rm -rf /tmp/qnxsdk 2>/dev/null
 
        ln -fs "${QNXSDK_CANONICAL_PATH}" /tmp/qnxsdk || exit 1
 
fi
 
 
 
# setup the environment
 
export QNX_HOST="/tmp/qnxsdk/${QNXSDK_HOSTPATH}"
 
export QNX_TARGET="/tmp/qnxsdk/${QNXSDK_TARGETPATH}"
 
export MAKEFLAGS="-I${QNX_TARGET}/usr/include"
 
export PATH="${QNX_HOST}/usr/bin:${PATH}"
 
 
 
# print the build environment
 
echo "QNX_HOST=${QNX_HOST}"
 
echo "QNX_TARGET=${QNX_TARGET}"
 
echo "MAKEFLAGS=${MAKEFLAGS}"
 
 
 
# construct the target triple (actually a quadruple)
 
export TARGET_ARCH="${BUILD_TARGET_ARCH}"
 
test "${BUILD_TARGET_ARCH}" = "x86_64" && export TARGET_VENDOR="pc" || export TARGET_VENDOR="unknown"
 
export TARGET_KERNEL="nto"
 
export TARGET_SYSTEM="qnx${QNXSDK_VERSION}"
 
export TARGET_TRIPLE="${TARGET_ARCH}-${TARGET_VENDOR}-${TARGET_KERNEL}-${TARGET_SYSTEM}"
 
echo "Will build for ${TARGET_TRIPLE}"
 
 
 
# download the involved source packages and unpack them if not done yet
 
download_and_unpack_if_necessary()
 
{
 
        # helper function that downloads a sources tarball, extracts it and patches it if necessary
 
        # args: <sources dirname> <sources filename> <download URL> [optional patchset URL]
 
        test -d "${1}" && return 0 # if sources directory already exists, nothing to do
 
        if [ ! -s "${CURRENT_DIR}/${2}" ]; then # if sources archive isn't a nonempty file...
 
                echo "Downloading ${1} sources from ${3}..."
 
                if ! wget -O "${CURRENT_DIR}/${2}" "${3}"; then
 
                        # remove output file in case an error occurs
 
                        rm -f "${CURRENT_DIR}/${2}"
 
                        exit 1
 
                fi
 
        fi
 
        echo "Extracting ${1} sources..."
 
        cd "$(dirname "${1}")"
 
        if echo "${2}"|grep -q "\.tar\.bz2$"; then
 
                # BZip2 tarball
 
                tar xjf "${CURRENT_DIR}/${2}" || exit 1
 
        elif echo "${2}"|grep -q "\.tar\.xz$"; then
 
                # XZ tarball
 
                tar xJf "${CURRENT_DIR}/${2}" || exit 1
 
        elif echo "${2}"|grep -q "\.tar\.gz$"; then
 
                # GZipped tarball
 
                tar xzf "${CURRENT_DIR}/${2}" || exit 1
 
        else
 
                print_error_and_die "Error: unsupported file extension. Please improve the download_and_unpack_if_necessary() shell function to support it."
 
        fi
 
        # make sure the expected directory is here after extraction
 
        if [ ! -d "${1}" ]; then
 
                print_error_and_die "Error: couldn't find ${1} in extracted sources."
 
        fi
 
        # do we have a patchset to apply ?
 
        if [ -n "${4}" ]; then
 
                echo "Downloading ${1} patchset from ${4}..."
 
                wget -O "${CURRENT_DIR}/${2}.patchset" "${4}" || exit 1
 
                echo "Applying patchset..."
 
                OLDDIR="$(pwd)"
 
                cd "${1}"
 
                patch -N -Z -p1 < "${CURRENT_DIR}/${2}.patchset" || exit 1
 
                cd "${OLDDIR}"
 
                unset OLDDIR
 
        fi
 
        return 0
 
}
 
download_and_unpack_if_necessary "${LLVM_SOURCES_DIR}" "${LLVM_SOURCES_FILE}" "${LLVM_SOURCES_URL}" || exit 1
 
 
 
# create the build directory
 
echo "Wiping out build directory..."
 
test -e "${BUILD_DIR_NAME}" && rm -rf "${BUILD_DIR_NAME}"
 
mkdir "${BUILD_DIR_NAME}" || exit 1
 
cd "${BUILD_DIR_NAME}" || exit 1
 
 
 
# create the QNX CMake toolchain file
 
test -e "${TARGET_TRIPLE}.cmake" || echo '# '${TARGET_TRIPLE}' CMake toolchain file by Pierre-Marie Baty <pm@pmbaty.com>
 
 
 
SET(CMAKE_SYSTEM_NAME "QNX")
 
SET(CMAKE_SYSTEM_VERSION "'${QNXSDK_VERSION}'")
 
 
 
SET(QNX "1")
 
SET(QNXNTO "1")
 
SET(QNX_HOST "$ENV{QNX_HOST}")
 
SET(QNX_TARGET "$ENV{QNX_TARGET}")
 
SET(QNX_PROCESSOR "'${TARGET_ARCH}'")
 
 
 
SET(CMAKE_ASM_COMPILER "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-gcc")
 
SET(CMAKE_ASM_COMPILER_TARGET "gcc_nto${QNX_PROCESSOR}")
 
 
 
SET(CMAKE_C_COMPILER "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-gcc")
 
SET(CMAKE_C_COMPILER_TARGET "gcc_nto${QNX_PROCESSOR}")
 
SET(CMAKE_C_FLAGS_DEBUG "-g")
 
SET(CMAKE_C_FLAGS_MINSIZEREL "-Os -DNDEBUG")
 
SET(CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG")
 
SET(CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
 
SET(CMAKE_C_FLAGS "-D_QNX_SOURCE=1 -I${QNX_TARGET}/usr/include/devs/include_'${TARGET_ARCH}' -I${QNX_TARGET}/usr/include/devs -DDONT_DEFINE_BSD -DDONT_DEFINE___FreeBSD_kernel__ -DDONT_DEFINE_FSCALE -DDONT_DEFINE_MACHINE")
 
 
 
SET(CMAKE_CXX_COMPILER "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-g++")
 
SET(CMAKE_CXX_COMPILER_TARGET "gcc_nto${QNX_PROCESSOR}")
 
SET(CMAKE_CXX_FLAGS_DEBUG "-g")
 
SET(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG")
 
SET(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
 
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
 
SET(CMAKE_CXX_FLAGS "-D_QNX_SOURCE=1 -I${QNX_TARGET}/usr/include/devs/include_'${TARGET_ARCH}' -I${QNX_TARGET}/usr/include/devs -DDONT_DEFINE_BSD -DDONT_DEFINE___FreeBSD_kernel__ -DDONT_DEFINE_FSCALE -DDONT_DEFINE_MACHINE")
 
 
 
SET(CMAKE_LINKER "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-ld.bfd")
 
SET(CMAKE_SHARED_LINKER_FLAGS "-lsocket")
 
SET(CMAKE_EXE_LINKER_FLAGS "-lsocket")
 
 
 
SET(CMAKE_RANLIB "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-ranlib")
 
 
 
SET(CMAKE_NM "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-nm")
 
 
 
SET(CMAKE_AR "${QNX_HOST}/usr/bin/'${TARGET_TRIPLE}'-ar")
 
 
 
SET(CMAKE_FIND_ROOT_PATH "${QNX_TARGET}")
 
SET(CMAKE_FIND_ROOT_PATH_HOST_PROGRAM NEVER)
 
SET(CMAKE_FIND_ROOT_PATH_HOST_LIBRARY ONLY)
 
SET(CMAKE_FIND_ROOT_PATH_HOST_INCLUDE ONLY)
 
' > "${TARGET_TRIPLE}.cmake"
 
 
 
backup_and_patch_if_necessary()
 
{
 
        # handy function that patches a file in LLVM_SOURCES_DIR with a given sed replacement regex if necessary, creating backups
 
        # args: <file pathname> <grep_string_to_test_for_presence_of_patch> <sed regex> [<second regex> [...]]
 
        _PATCHEE_PATHNAME="${1}"
 
        _PATCHED_PATTERN="${2}"
 
        # test if already patched
 
        grep -q "${_PATCHED_PATTERN}" "../${LLVM_SOURCES_DIR}/${_PATCHEE_PATHNAME}" && return
 
        # tell what we're about to do
 
        echo "Patching ${_PATCHEE_PATHNAME}..."
 
        _DOTTED_NAME="$(echo "${_PATCHEE_PATHNAME}"|tr '/' '.')"
 
        # have a backup first
 
        test -f "${CURRENT_DIR}/${_DOTTED_NAME} [ORIGINAL]" || cp "../${LLVM_SOURCES_DIR}/${_PATCHEE_PATHNAME}" "${CURRENT_DIR}/${_DOTTED_NAME} [ORIGINAL]" || exit 1
 
        # perform the patch
 
        cp -f "${CURRENT_DIR}/${_DOTTED_NAME} [ORIGINAL]" "${CURRENT_DIR}/${_DOTTED_NAME} [PATCHED]" || exit 1
 
        while [ -n "${3}" ]; do
 
                sed -E -i "${3}" "${CURRENT_DIR}/${_DOTTED_NAME} [PATCHED]"
 
                shift
 
        done
 
        # verify that we did it successfully
 
        if ! grep -q "${_PATCHED_PATTERN}" "${CURRENT_DIR}/${_DOTTED_NAME} [PATCHED]"; then
 
                print_error_and_die "Error: the file ${_PATCHEE_PATHNAME} could not be patched. Please investigate and fix manually."
 
        fi
 
        # and put the patched file in place
 
        cp -f "${CURRENT_DIR}/${_DOTTED_NAME} [PATCHED]" "../${LLVM_SOURCES_DIR}/${_PATCHEE_PATHNAME}" || exit 1
 
}
 
 
 
# patch llvm/lib/Support/Unix/Path.inc if not done yet
 
# replace:
 
#       defined(__FreeBSD_kernel__)
 
# with:
 
#       (defined(__FreeBSD_kernel__) || defined(__QNXNTO__))
 
# RATIONALE: the concerned parts of the QNX platform SDK (/usr/include/devs/*) are actually largely based on FreeBSD code, to conveniently use the FreeBSD network stack.
 
# NONETHELESS, QNX *IS NOT* FreeBSD and "__FreeBSD_kernel__" *SHOULD NOT* be defined, else userland code may falsely assume a genuine FreeBSD include tree to be available,
 
# which leads to compilation errors caused by include files assumed to be there whereas they are in fact nowhere to be found (ex: /usr/include/sys/user.h, among others).
 
# The QNX8 platform SDK has thus been patched to NOT define __FreeBSD_kernel__ when the -DDONT_DEFINE___FreeBSD_kernel__ flag is passed, and the feature tests in Path.inc
 
# that branch into FreeBSD APIs (which ones *are* exposed in the QNX libc since QNX largely shares FreeBSD code) are about to be patched right now to accept __QNXNTO__ too.
 
# Additionally, support for statfs()/fstatfs() has been restored in the QNX8 platform SDK in /usr/include/devs/sys/mount.h where it was claimed but absent from the QNX8 libc.
 
# FIXME: these hacks should be moved elsewhere not to pollute the QNX8 platform SDK -- it *SHOULD* be possible to build without devs
 
backup_and_patch_if_necessary "llvm/lib/Support/Unix/Path.inc" __QNXNTO__ \
 
        's@defined\(__FreeBSD_kernel__\)@\(defined\(__FreeBSD_kernel__\) \|\| \defined\(__QNXNTO__\)\)@g'
 
 
 
# Clang front-end patches
 
if echo "${LLVM_PROJECTS_TO_BUILD}"|tr ';' '\n'|grep -q "clang"; then
 
 
 
        # patch clang/lib/Frontend/InitPreprocessor.cpp
 
        # replace:
 
        #         TI.getTargetDefines(LangOpts, Builder);
 
        # with:
 
        #         TI.getTargetDefines(LangOpts, Builder);
 
        #       #ifdef __QNXNTO__
 
        #         Builder.defineMacro("__QNXNTO__", "1");
 
        #         Builder.defineMacro("__QNX__", "800"); // <-- set to QNX SDK version, without the intermediary dots
 
        #         Builder.defineMacro("__X86_64__", "1"); // <-- set to either __X86_64__ or __AARCH64EL__ depending on the build target
 
        #         Builder.defineMacro("__LITTLEENDIAN__", "1");
 
        #         Builder.defineMacro("__ELF__", "1");
 
        #       #endif
 
        # RATIONALE: this adds the QNX-specific implicit preprocessor definitions. This is not the orthodox way of doing it. But we're in a hurry.
 
        test "${BUILD_TARGET_ARCH}" = "x86_64" && PLATORM_NATIVE_ARCH_DEFINE="__X86_64__" || PLATORM_NATIVE_ARCH_DEFINE="__AARCH64EL__"
 
        backup_and_patch_if_necessary "clang/lib/Frontend/InitPreprocessor.cpp" __QNXNTO__ \
 
                's@TI\.getTargetDefines\(LangOpts, Builder\);@TI\.getTargetDefines\(LangOpts, Builder\);\n#ifdef __QNXNTO__\n  Builder.defineMacro\("__QNXNTO__", "1"\);\n  Builder.defineMacro("__QNX__", "'$(echo "${QNXSDK_VERSION}"|tr -d '.')'");\n  Builder.defineMacro\("'${PLATORM_NATIVE_ARCH_DEFINE}'", "1"\);\n  Builder.defineMacro\("__LITTLEENDIAN__", "1"\);\n  Builder.defineMacro\("__ELF__", "1"\);\n#endif@'
 
fi
 
 
 
# LLDB patches
 
if echo "${LLVM_PROJECTS_TO_BUILD}"|tr ';' '\n'|grep -q "lldb"; then
 
 
 
        # patch lldb/Source/Host/common/Host.cpp if not done yet
 
        # replace:
 
        #       defined(SIGINFO)
 
        # with:
 
        #       (defined(SIGINFO) && !defined(__QNXNTO__))
 
        # RATIONALE: once upon a time (probably in the early steps of the design of their OS), the QNX people defined SIGINFO to the value of SIGUSR1 for a mysterious reason,
 
        # defeating the purpose of SIGUSR1 completely, which should be a User-Definable signal as mandated by POSIX. Consequently, any userland code that enumerates POSIX signals
 
        # hits the same value twice, and all is left to solve this problem is to filter either one out. Since SIGINFO, contrarily to SIGUSR1, is an optional signal,
 
        # this is the value that will be left out. It is not possible to correct this in the platform SDK since all the precompiled userland programs supplied by QNX
 
        # expect the value of SIGUSR1 for SIGINFO.
 
        backup_and_patch_if_necessary "lldb/source/Host/common/Host.cpp" __QNXNTO__ \
 
                's@defined\(SIGINFO\)@\(defined\(SIGINFO\) \&\& \!defined\(__QNXNTO__\)\)@g'
 
        
 
        # FIXME: another patch is needed for LLDB. Basically, the ptrace() POSIX system call doesn't exist on QNX. Instead
 
        # QNX use their own debug utility: pdebug. Note the /proc filesystem can be used to access a debuggee's virtual memory space.
 
        # in lldb/source/Host/posix/ProcessLauncherPosixFork.cpp line 196:
 
        #   if (ptrace(PT_TRACE_ME, 0, nullptr, 0) == -1) // <--- undefined: ptrace, PT_TRACE_ME
 
fi
 
 
 
# compiler-rt patches
 
if echo "${LLVM_RUNTIMES_TO_BUILD}"|tr ';' '\n'|grep -q "compiler-rt"; then
 
 
 
        # patch compiler-rt/lib/builtins/enable_execute_stack.c if not done yet
 
        # replace:
 
        #       #include "int_lib.h"
 
        # with:
 
        #       #ifdef __QNXNTO__
 
        #       #define _QNX_SOURCE 1
 
        #       #endif
 
        #       #include "int_lib.h"
 
        # RATIONALE: the QNX people decided to hide most of the UNIX APIs of their libc behind a mandatory _QNX_SOURCE definition to separate the Neutrino primitives from the rest maybe.
 
        # This name does not "enforce" any standard at all (like _POSIX_SOURCE and similar names), it's just a convenient hack for the QNX people to hide stuff.
 
        # To put things back on track and expose the POSIX interfaces of their libc to the world, _QNX_SOURCE has been added to the toolchain CMake file, but it happens that
 
        # when building compiler-rt specifically, the CMAKE_C_FLAGS directive is ignored. Patching the source file seems like the best option to fix that.
 
        backup_and_patch_if_necessary "compiler-rt/lib/builtins/enable_execute_stack.c" __QNXNTO__ \
 
                's@#include "int_lib.h"@#ifdef __QNXNTO__\n#define _QNX_SOURCE 1\n#endif\n#include "int_lib.h"@'
 
 
 
        # patch compiler-rt/lib/profile/InstrProfilingUtil.c
 
        # replace:
 
        #       #include <sys/mman.h>
 
        # with:
 
        #       #ifdef __QNXNTO__
 
        #       #include <devs/sys/mman.h>
 
        #       #endif
 
        #       #include <sys/mman.h>
 
        # RATIONALE: QNX doesn't define MADV_DONTNEED (but does so for POSIX_MADV_DONTNEED), unfortunately compiler-rt needs the former. By luck, its value is defined in
 
        # the extra platform headers they borrowed from FreeBSD, i.e. devs/sys/mman.h, and it has the same value, so include both to fix the problem.
 
        backup_and_patch_if_necessary "compiler-rt/lib/profile/InstrProfilingUtil.c" __QNXNTO__ \
 
                's@#include <sys/mman.h>@#ifdef __QNXNTO__\n#include <devs/sys/mman.h>\n#endif\n#include <sys/mman.h>@'
 
 
 
        # patch compiler-rt/lib/orc/endianness.h
 
        # replace:
 
        #       #elif defined(__MVS__)
 
        # with:
 
        #       #elif defined(__QNXNTO__)
 
        #       #define BYTE_ORDER __BYTE_ORDER__
 
        #       #elif defined(__MVS__)
 
        # RATIONALE: QNX doesn't provide a <machine/endian.h> header directly: the user must specify the machine-specific include path (e.g. -isystem ${QNX_TARGET}/usr/include/devs/include_x86_64)
 
        # Instead of going through platform detection logic, we supply the only definition this file needs, which is opportunisticly the same one that GCC and Clang provide implicitly.
 
        backup_and_patch_if_necessary "compiler-rt/lib/orc/endianness.h" __QNXNTO__ \
 
                's@#elif defined\(__MVS__\)@#elif defined\(__QNXNTO__\)\n#define BYTE_ORDER __BYTE_ORDER__\n#elif defined\(__MVS__\)@'
 
fi
 
 
 
# libunwind patches
 
if echo "${LLVM_RUNTIMES_TO_BUILD}"|tr ';' '\n'|grep -q "libunwind"; then
 
 
 
        # patch libunwind/src/libunwind.cpp
 
        # replace:
 
        #       #include <libunwind.h>:
 
        # with:
 
        #       #ifdef __QNXNTO__
 
        #       #define _QNX_SOURCE 1
 
        #       #endif
 
        #       #include <libunwind.h>
 
        # RATIONALE: the pthreads implementation in QNX 'steals' things from the POSIX.1 standard and hides them behind the __EXT_QNX macro,
 
        # which is defined when either _QNX_SOURCE or __EXT without anything else is defined. This is not correct and low-level libraries
 
        # such as libunwind that do not define either of those fail to build. Also note that a FreeBSD-compatible header was added to the QNX8
 
        # platform SDK: /usr/include/link.h, which defines Elf types as Elf64/Elf32 types depending on the architecture and adds some glue.
 
        backup_and_patch_if_necessary "libunwind/src/libunwind.cpp" __QNXNTO__ \
 
                's@#include <libunwind.h>@#ifdef __QNXNTO__\n#define _QNX_SOURCE 1\n#endif\n#include <libunwind.h>@'
 
fi
 
 
 
# libc++ patches
 
if echo "${LLVM_PROJECTS_TO_BUILD}"|tr ';' '\n'|grep -q "libcxx"; then
 
 
 
        # patch libcxx/include/__config
 
        # replace:
 
        #       #      define _LIBCPP_HAS_THREAD_API_WIN32
 
        # with:
 
        #       #      define _LIBCPP_HAS_THREAD_API_WIN32
 
        #       #    elif defined(__QNXNTO__)
 
        #       #      define _LIBCPP_HAS_THREAD_API_PTHREAD
 
        #       #      define _LIBCPP_HAS_COND_CLOCKWAIT
 
        #       #      define _LIBCPP_HAS_CLOCK_GETTIME
 
        # RATIONALE: simply bring QNX among the list of systems known by libc++ to expose a pthreads API; while we're at it inform it that pthread_cond_clockwait() is available
 
        # and that the standard POSIX clock_gettime() is available to return a realtime wall clock value in nanoseconds (this might not be the optimal way of getting it though).
 
        backup_and_patch_if_necessary "libcxx/include/__config" __QNXNTO__ \
 
                's@#      define _LIBCPP_HAS_THREAD_API_WIN32@#      define _LIBCPP_HAS_THREAD_API_WIN32\n#    elif defined(__QNXNTO__)\n#      define _LIBCPP_HAS_THREAD_API_PTHREAD\n#      define _LIBCPP_HAS_COND_CLOCKWAIT\n#      define _LIBCPP_HAS_CLOCK_GETTIME@'
 
        
 
        # patch libcxx/include/__locale
 
        # replace:
 
        #       # include <__support/openbsd/xlocale.h>
 
        # with:
 
        #       # include <__support/openbsd/xlocale.h>
 
        #       #elif defined(__QNXNTO__)
 
        #       # include <__support/qnx/xlocale.h>
 
        # and:
 
        #       #elif defined(__MVS__)
 
        # with:
 
        #       #elif defined(__QNXNTO__)
 
        #           typedef short mask;
 
        #           static const mask space  = (_CN|_SP|_XS);
 
        #           static const mask print  = (_DI|_LO|_PU|_SP|_UP|_XA);
 
        #           static const mask cntrl  = _BB;
 
        #           static const mask upper  = _UP;
 
        #           static const mask lower  = _LO;
 
        #           static const mask alpha  = (_LO|_UP|_XA);
 
        #           static const mask digit  = _DI;
 
        #           static const mask punct  = _PU;
 
        #           static const mask xdigit = _XD;
 
        #           static const mask blank  = (_SP|_XB);
 
        #           static const mask __regex_word = 0x1000;
 
        #       #elif defined(__MVS__)
 
        # RATIONALE: add QNX-specific locale C++ bindings and definitions
 
        backup_and_patch_if_necessary "libcxx/include/__locale" __QNXNTO__ \
 
                's@# include <__support/openbsd/xlocale.h>@# include <__support/openbsd/xlocale.h>\n#elif defined\(__QNXNTO__\)\n# include <__support/qnx/xlocale.h>@' \
 
                's@#elif defined\(__MVS__\)@#elif defined\(__QNXNTO__\)\n    typedef short mask;\n    static const mask space  = \(_CN\|_SP\|_XS\);\n    static const mask print  = \(_DI\|_LO\|_PU\|_SP\|_UP\|_XA\);\n    static const mask cntrl  = _BB;\n    static const mask upper  = _UP;\n    static const mask lower  = _LO;\n    static const mask alpha  = \(_LO\|_UP\|_XA\);\n    static const mask digit  = _DI;\n    static const mask punct  = _PU;\n    static const mask xdigit = _XD;\n    static const mask blank  = \(_SP\|_XB\);\n    static const mask __regex_word = 0x1000;\n#elif defined\(__MVS__\)@'
 
        
 
        # patch libcxx/include/CMakeLists.txt
 
        # replace:
 
        #         __support/openbsd/xlocale.h
 
        # with:
 
        #         __support/openbsd/xlocale.h
 
        #         __support/qnx/xlocale.h
 
        # RATIONALE: add QNX-specific locale C++ bindings and definitions
 
        backup_and_patch_if_necessary "libcxx/include/CMakeLists.txt" qnx/xlocale.h \
 
                's@  __support/openbsd/xlocale.h@  __support/openbsd/xlocale.h\n  __support/qnx/xlocale.h@'
 
        
 
        # add __support/qnx/xlocale.h to the libc++ source tree
 
        # RATIONALE: add QNX-specific locale C++ bindings and definitions
 
        test -d "../${LLVM_SOURCES_DIR}/libcxx/include/__support/qnx" || mkdir "../${LLVM_SOURCES_DIR}/libcxx/include/__support/qnx" || exit 1
 
        test -f "../${LLVM_SOURCES_DIR}/libcxx/include/__support/qnx/xlocale.h" || cp "${QNX_TARGET}/usr/include/c++/v1/__support/qnx/xlocale.h" "../${LLVM_SOURCES_DIR}/libcxx/include/__support/qnx/xlocale.h" || exit 1
 
        
 
        # patch libcxx/include/locale
 
        # replace:
 
        #       !defined(__BIONIC__) && !defined(_NEWLIB_VERSION) && !defined(__EMSCRIPTEN__)
 
        # with:
 
        #       !defined(__BIONIC__) && !defined(_NEWLIB_VERSION) && !defined(__EMSCRIPTEN__) && !defined(__QNXNTO__)
 
        # RATIONALE: QNX doesn't have catopen() to open a "message catalog"
 
        backup_and_patch_if_necessary "libcxx/include/locale" __QNXNTO__ \
 
                's@\!defined\(__BIONIC__\) \&\& \!defined\(_NEWLIB_VERSION\) \&\& \!defined\(__EMSCRIPTEN__\)@!defined\(__BIONIC__\) \&\& !defined\(_NEWLIB_VERSION\) \&\& !defined\(__EMSCRIPTEN__\) \&\& !defined\(__QNXNTO__\)@'
 
        
 
        # patch libcxx/include/setjmp.h
 
        # replace:
 
        #       #endif // __cplusplus
 
        # with:
 
        #       #ifdef __QNXNTO__
 
        #       #undef longjmp
 
        #       [[noreturn]] inline void longjmp(jmp_buf env, int val) { ::siglongjmp(env, val); }
 
        #       #endif // __QNXNTO__
 
        #       
 
        #       #endif // __cplusplus
 
        # RATIONALE: restore the thread signal mask when calling longjmp() by calling siglongjmp() instead (not sure why, but that's how they do it in the libc++ 16.0.6 they ship with their SDK)
 
        # FIXME: is this a good idea really? It looks like by calling siglongjmp() instead of longjmp() after setjmp() the QNX people did a broken implementation !?
 
        backup_and_patch_if_necessary "libcxx/include/setjmp.h" __QNXNTO__ \
 
                's@#endif // __cplusplus@#ifdef __QNXNTO__\n#undef longjmp\n\[\[noreturn\]\] inline void longjmp\(jmp_buf env, int val\) { ::siglongjmp\(env, val\); }\n#endif // __QNXNTO_\n\n#endif // __cplusplus@'
 
fi
 
 
 
# polly patches
 
if echo "${LLVM_PROJECTS_TO_BUILD}"|tr ';' '\n'|grep -q "polly"; then
 
 
 
        # patch polly/lib/External/isl/imath/imath.c
 
        # replace:
 
        #       /* Select min/max. */
 
        # with:
 
        #       #ifdef __QNXNTO__
 
        #       #undef MIN
 
        #       #undef MAX
 
        #       #endif // __QNXNTO__
 
        #       /* Select min/max. */
 
        # RATIONALE: QNX already defines MIN/MAX as macros, but polly intends to define them as inline functions. Perhaps this could be avoided by passing _POSIX_SOURCE instead of _QNX_SOURCE.
 
        backup_and_patch_if_necessary "polly/lib/External/isl/imath/imath.c" __QNXNTO__ \
 
                's@\/\* Select min\/max. \*\/@#ifdef __QNXNTO__\n#undef MIN\n#undef MAX\n#endif\n\/\* Select min\/max. \*\/@'
 
fi
 
 
 
# now configure LLVM...
 
echo "Configuring LLVM build..."
 
export CCACHE_DIR="$(realpath "../${LLVM_SOURCES_DIR}/.ccache")"
 
cmake \
 
    -D CMAKE_TOOLCHAIN_FILE="${TARGET_TRIPLE}.cmake" \
 
    -D CMAKE_BUILD_TYPE="${LLVM_BUILD_CONFIGURATION_TYPE}" \
 
    -D CMAKE_INSTALL_PREFIX="/usr/bin" \
 
    -D CMAKE_STAGING_PREFIX="${CURRENT_DIR}/llvm-build/${BUILD_TARGET_ARCH}" \
 
    -D CMAKE_C_COMPILER_LAUNCHER="ccache" \
 
    -D CMAKE_CXX_COMPILER_LAUNCHER="ccache" \
 
    -D HAVE_STEADY_CLOCK="0" \
 
    -D LLVM_HOST_TRIPLE="${TARGET_TRIPLE}" \
 
    -D LLVM_ENABLE_PROJECTS="${LLVM_PROJECTS_TO_BUILD}" \
 
    -D LLVM_ENABLE_RUNTIMES="${LLVM_RUNTIMES_TO_BUILD}" \
 
    -D LLVM_TARGETS_TO_BUILD="AArch64;X86" \
 
    -D DEFAULT_SYSROOT="../../../../../${QNXSDK_TARGETPATH}/${BUILD_TARGET_ARCH}" \
 
    -D CLANG_DEFAULT_LINKER="ld" \
 
    -D CLANG_DEFAULT_CXX_STDLIB="libc++" \
 
    -D COMPILER_RT_BUILD_SANITIZERS="OFF" \
 
    -D COMPILER_RT_BUILD_XRAY="OFF" \
 
    -D COMPILER_RT_BUILD_MEMPROF="OFF" \
 
    -D COMPILER_RT_BUILD_LIBFUZZER="OFF" \
 
    -D COMPILER_RT_BUILD_PROFILE="OFF" \
 
    -G Ninja \
 
    "../${LLVM_SOURCES_DIR}/llvm" || exit 1
 
 
 
# and do the Lord's work. https://youtu.be/jcyYmCnkbEE
 
echo "Building LLVM..."
 
cmake --build . --target install || exit 1
 
 
 
test -z "${WSL_DISTRO_NAME}" && /bin/printf "\n\xF0\x9F\x8D\xBE\x20\x43\x68\x61\x6d\x70\x61\x67\x6e\x65\x2e\n"
 
exit 0
 
 
 
# NOTE: LLD might not produce usable executables on QNX without a GNU LD-compatible linker script (-T option) that defines
 
# the *SAME* program headers as those generated by the GNU linker! (PHDRS directive). QNX is particularly picky on the layout
 
# of loadable segments (PT_LOAD): whereas GNU ld generate usually two (one for code, one for data), LLD generates a lot more,
 
# with different access permissions - and while this is technically correct ELF format (and even more secure), this unusual
 
# program header layout can be refused by QNX ("can't load xxx: exec format error"). Same if you use ld with '-z separate-code'.
 
# Also, it is likely that GCC's crti.o/crtn.o being filtered out by LLD from the output executables prevent them to run on QNX.
 
# https://stackoverflow.com/questions/18091463/why-does-an-assembly-program-only-work-when-linked-with-crt1-o-crti-o-and-crtn-o
 
# CAVEAT: well worth the read if you intend to use LLD: https://maskray.me/blog/2020-12-19-lld-and-gnu-linker-incompatibilities
 
 
 
# TODO optional: port compiler_rt sanitizer bindings and build sanitizers, xray, memprof, libfuzzer and profile
 
# TODO optional: port lldb bindings and build lldb (implement ptrace)