# Helper macros for packages built against nvidia-cuda-toolkit
#
# Usage in spec:
#   BuildRequires(pre): rpm-macros-cuda-toolkit
#   %set_gcc_version %cuda_gcc_version   # gcc/g++ become the nvcc-supported version
#   BuildRequires: %cuda_buildreq
#   %cmake %cuda_cmake_flags ...         # cmake projects
#   nvcc %cuda_nvcc_flags ...            # plain nvcc
#   %cuda_export                         # env for setup.py/meson/autotools

# CUDA version shipped in the branch: the only per-branch value
%cuda_version %(if [ %_priority_distbranch = p11 ]; then echo 12.9; else echo 13.2; fi)
%cuda_major %(echo %cuda_version | cut -d. -f1)

# host compiler: newest gcc nvcc accepts, but never newer than the system one
%cuda_gcc_max 14
%cuda_gcc_version %(g=%__gcc_version_major; [ $g -lt %cuda_gcc_max ] && echo $g || echo %cuda_gcc_max)
%cuda_host_cc %_bindir/gcc-%cuda_gcc_version
%cuda_host_cxx %_bindir/g++-%cuda_gcc_version

%cuda_buildreq nvidia-cuda-devel gcc%cuda_gcc_version gcc%cuda_gcc_version-c++

# supported GPU architectures (compute capability, sm_XX), ascending
# 87 = Jetson Orin, aarch64 only
%cuda_archs_x86_64 75 80 86 89 90 100 103 120 121
%cuda_archs_aarch64 75 80 86 87 89 90 100 103 120 121
# Maxwell/Pascal/Volta (53/62/72 = Jetson Nano/TX2/Xavier): CUDA 12 only, dropped in 13
%cuda_archs_12_x86_64 50 60 61 70
%cuda_archs_12_aarch64 53 62 72
%cuda_archs %(echo %{expand:%%{?cuda_archs_%{cuda_major}_%_arch}} %{expand:%%{cuda_archs_%_arch}})

%cuda_arch_min %(echo %cuda_archs | awk '{print $1}')
%cuda_arch_max %(echo %cuda_archs | awk '{print $NF}')

# cmake: CMAKE_CUDA_ARCHITECTURES="75-real;80-real;...;120" (SASS for all, PTX only for the newest)
%cuda_archs_cmake %(echo %cuda_archs | sed 's/ /-real;/g')
# torch/pytorch: TORCH_CUDA_ARCH_LIST="7.5 8.0 ... 12.0+PTX"
%cuda_archs_torch %(echo %cuda_archs | sed 's/[0-9]$/.&+PTX/;s/[0-9] /.&/g')

# -gencode arch=compute_XX,code=sm_XX for every arch, plus PTX for the newest
%cuda_gencode %(for c in %cuda_archs; do echo -n "-gencode arch=compute_$c,code=sm_$c "; done; echo -n "-gencode arch=compute_%cuda_arch_max,code=compute_%cuda_arch_max")
%cuda_nvcc_flags -ccbin %cuda_host_cxx %cuda_gencode

%cuda_cmake_flags -DCMAKE_CUDA_HOST_COMPILER=%cuda_host_cxx -DCMAKE_CUDA_ARCHITECTURES="%cuda_archs_cmake" -DCUDAToolkit_ROOT=%_prefix

# env for autotools/meson/setup.py: host compiler for every nvcc call
%cuda_export export CUDAHOSTCXX=%cuda_host_cxx NVCC_PREPEND_FLAGS="-ccbin %cuda_host_cxx" TORCH_CUDA_ARCH_LIST="%cuda_archs_torch" CUDA_HOME=%_prefix
