#!/bin/sh

#
# Build GCC with support for offloading to NVIDIA GPUs.
#

# QUICK HOW TO:
# 1. Set up the following variables
#    version = This will be used as sub folder in case we want to install multiple versions
#    tag = This is equal to the tags available in the GCC repo svn://gcc.gnu.org/svn/gcc/tags/
#    install_dir = Directory where you want GCC to be installed
#    workdir = (could be left as it is) Working directory to obtain GCC relative to the current script $PWD
# 2. Remember to set your LD_LIBRARY_PATH and PATH to the right locations
#    example: export LD_LIBRARY_PATH=$install_dir/lib:$LD_LIBRARY_PATH # replace $install_dir with the right dir
#             export PATH=$install_dir/bin:$PATH # replace $install_dir with the right dir

version=7.3 
tag=gcc_7_3_0_release
install_dir=/software/apps/gcc/$version
workdir=gcc$version

# Location of the installed CUDA toolkit
cuda=/software/apps/cuda/9.2/

# Build assembler and linking tools
if [ ! -d nvptx-tools ]
then
  echo "OBTAINING NVPTX-TOOLS"
  git clone https://github.com/MentorEmbedded/nvptx-tools
fi 


echo "COMPILING AND INSTALLING NVPTX-TOOLS"
cd nvptx-tools
./configure \
    --with-cuda-driver-include=$cuda/include \
    --with-cuda-driver-lib=$cuda/lib64 \
    --prefix=$install_dir
make
make install
cd ..
rm -rf nvptx-tools

# Set up the GCC source tree
if [ ! -d nvptx-newlib ]
then 
  echo "OBTAINING NVPTX-NEWLIB"
  git clone https://github.com/MentorEmbedded/nvptx-newlib
fi

if [ ! -d $workdir ]
then
  echo "OBTAINING GCC $tag"
  svn co svn://gcc.gnu.org/svn/gcc/tags/$tag $workdir
  cd $workdir
  contrib/download_prerequisites
  ln -s ../nvptx-newlib/newlib newlib
  cd ..
fi

echo "GETTING TARGET"
target=$($workdir/config.guess)
echo "TARGET = $target"

# Build nvptx GCC
if [ ! -d build-nvptx-$workdir ]
then 
echo "BUILDING FOR THE DEVICE NVPTX"
  mkdir build-nvptx-$workdir
  cd build-nvptx-$workdir
  ../$workdir/configure \
      --target=nvptx-none --with-build-time-tools=$install_dir/nvptx-none/bin \
      --enable-as-accelerator-for=$target \
      --disable-sjlj-exceptions \
      --enable-newlib-io-long-long \
      --enable-languages="c,c++,fortran,lto" \
      --prefix=$install_dir
  
  make -j8
  make install
  cd ..
fi

# Build host GCC
if [ ! -d build-host-$workdir ]
then
echo "BUILDING FOR THE HOST"
  mkdir build-host-$workdir
  cd  build-host-$workdir
  ../$workdir/configure \
      --enable-offload-targets=nvptx-none \
      --with-cuda-driver-include=$cuda/include \
      --with-cuda-driver-lib=$cuda/lib64 \
      --disable-bootstrap \
      --disable-multilib \
      --enable-languages="c,c++,fortran,lto" \
      --prefix=$install_dir
  
  make -j8
  make install
  cd ..
fi


