#!/bin/bash

set -ex

export ARCH=powerpc
export CROSS_COMPILE=powerpc-linux-gnu-
FILE=arch/powerpc/mm/mem.o
TMP_DIR=$(mktemp -d -p "${HOME}/cbl/tmp")

# https://raw.githubusercontent.com/nathanchance/scripts/master/funcs/bldgcc
source "${HOME}"/github/scripts/funcs/bldgcc

cd "${HOME}"/cbl/linux-next

CBL_BIN=${HOME}/cbl/usr/bin

# Clang without patch
git reset -q --hard
git checkout -q next-20190809
curl -LSs 'https://git.kernel.org/pub/scm/linux/kernel/git/powerpc/linux.git/patch/?id=ed4289e8b48845888ee46377bd2b55884a55e60b' | git ap
PATH=${CBL_BIN}:${PATH} make -s -j$(nproc) CC=clang O=out distclean ppc44x_defconfig "${FILE}"
"${CBL_BIN}"/${CROSS_COMPILE}objdump -dr out/"${FILE}" > "${TMP_DIR}"/clang-without-6c5875843b87-mem.o.txt

# Clang with Nick's patch
git reset -q --hard
curl -LSs https://raw.githubusercontent.com/ClangBuiltLinux/continuous-integration/ppc32/patches/llvm-all/linux/ppc32/0001-powerpc-fix-inline-asm-constraints-for-dcbz.patch | git ap
PATH=${CBL_BIN}:${PATH} make -s -j$(nproc) CC=clang O=out distclean ppc44x_defconfig "${FILE}"
"${CBL_BIN}"/${CROSS_COMPILE}objdump -dr out/"${FILE}" > "${TMP_DIR}"/clang-with-equal-Z-mem.o.txt

export CROSS_COMPILE=powerpc-linux-
for GCC_VERSION in 9.1.0 8.3.0 7.4.0 6.5.0 5.5.0; do
    GCC_TC_FOLDER=${HOME}/toolchains/gcc/${GCC_VERSION}/bin

    # Make sure GCC is built and installed
    [[ -f ${GCC_TC_FOLDER}/${CROSS_COMPILE}gcc ]] || GCC_VERSION=${GCC_VERSION} GCC_TC_FOLDER=${HOME}/toolchains/gcc bldgcc powerpc
    "${GCC_TC_FOLDER}"/${CROSS_COMPILE}gcc --version

    # GCC without patch
    git reset -q --hard
    curl -LSs 'https://git.kernel.org/pub/scm/linux/kernel/git/powerpc/linux.git/patch/?id=ed4289e8b48845888ee46377bd2b55884a55e60b' | git ap
    PATH=${GCC_TC_FOLDER}:${PATH} make -s -j$(nproc) O=out distclean ppc44x_defconfig "${FILE}"
    "${GCC_TC_FOLDER}"/${CROSS_COMPILE}objdump -dr out/"${FILE}" > "${TMP_DIR}"/gcc-${GCC_VERSION}-without-6c5875843b87-mem.o.txt

    # GCC with Nick's patch
    git reset -q --hard
    curl -LSs https://raw.githubusercontent.com/ClangBuiltLinux/continuous-integration/ppc32/patches/llvm-all/linux/ppc32/0001-powerpc-fix-inline-asm-constraints-for-dcbz.patch | git ap
    PATH=${GCC_TC_FOLDER}:${PATH} make -s -j$(nproc) O=out distclean ppc44x_defconfig "${FILE}"
    "${GCC_TC_FOLDER}"/${CROSS_COMPILE}objdump -dr out/"${FILE}" > "${TMP_DIR}"/gcc-${GCC_VERSION}-with-equal-Z-mem.o.txt

    diff -uprN "${TMP_DIR}"/gcc-${GCC_VERSION}-without-6c5875843b87-mem.o.txt "${TMP_DIR}"/gcc-${GCC_VERSION}-with-equal-Z-mem.o.txt > "${TMP_DIR}"/gcc-${GCC_VERSION}-mem.o.diff
done

echo
echo "Files are available at: ${TMP_DIR}"
