###########################################################
# Authors :
#   - Máté Ferenc Nagy-Egri - 2021
#   - Sébastien Valat (ISTerre/CNRS) - 2026
###########################################################

###########################################################
# min:
#  - 3.8  : CUDA LANGUAGE SUPPORT
#  - 3.12 : CMP0074
cmake_minimum_required(VERSION 3.12)

# handle policies
cmake_policy(SET CMP0074 NEW)

###########################################################
project(SHTns VERSION 3.8 LANGUAGES C)

###########################################################
# set default build type to release
if (CMAKE_BUILD_TYPE STREQUAL "")
	set(CMAKE_BUILD_TYPE "Release")
endif()

###########################################################
# configure options
option(BUILD_TESTING "Build unit tests" ON)
option(BUILD_EXAMPLES "Build examples" OFF)
option(BUILD_DOCUMENTATION "Build docs" OFF)
option(BUILD_FORTRAN "Build the Fortran77 API" ON)
option(BUILD_FOR_PYTHON "Build the library as python module." OFF)
set(USE_HIP "AUTO" CACHE STRING "Enable HIP support (ON/OFF/AUTO) or directly a hip architecture (eg. mi100, mi250, gfx908...), implying USE_HIP=ON. Only used when CUDA is not enabled, as CUDA has precedence (both cannot be built simultaneously).")
option(USE_HIP_CMAKE "Enable HIP support via CMake native HIP support (instead of the SHTns manual HIP binding)." OFF)
option(USE_MAGIC "I need the transforms compatible with the MagIC code, to speed it up!" OFF)
option(USE_ISHIOKA "Enable the new recurrence proposed by Ishioka (2018) see https://doi.org/10.2151/jmsj.2018-019 (faster)" ON)
option(USE_SHARED "Enable building shared libraries" OFF)
option(USE_MKL "Enable usage of the MKL library" OFF)
option(USE_SIMD "Enable explicit SIMD support" ON)
# options with values
set(USE_OPENMP "AUTO" CACHE STRING "Enable OpenMP support (ON, OFF or AUTO)")
set(USE_HIP_ARCH "AUTO" CACHE STRING "Select the architecture to build for (mi100, mi200, mi250, gfx908, gfx90a...). Implies USE_HIP=ON (when CUDA is not enabled).")
set(USE_CUDA "AUTO" CACHE STRING "Enable CUDA support (ON/OFF/AUTO) or directly a cuda architecture (eg. ampere, hopper, 80, ...), implying USE_CUDA=ON.")
set(USE_MARCH "AUTO" CACHE STRING "Select the -march value to apply, can use AUTO to autoselect depending on ARM or x86 familly.")
set(USE_GPU_MARCH "AUTO" CACHE STRING "Select the -march value to apply on GPU binary, can use AUTO to autoselect depending on ARM or x86 familly.")
set(USE_CUDA_ARCH "AUTO" CACHE STRING "Select the architecture to build for (nativ, all, all-major, kepler, pascal, volta, ampere, 70, 80, ...). Implies USE_CUDA=ON.")
set(SHT_VERBOSE 1 CACHE STRING "0:no output, 1:output info to stdout, 2:more output (debug info), 3:also print fftw plans.")
set(MKL_ROOT "" CACHE PATH "Path to search the MKL library.")

###########################################################
# dependency
# shortcuts: setting the GPU architecture directly (e.g. -DUSE_CUDA=ampere) implies enabling it,
# and is equivalent to USE_CUDA=ON + USE_CUDA_ARCH=ampere. Same for USE_HIP.
# Must be done before shtns_config_gpu_cuda_arch() and shtns_config_gpu_hip_arch() are called,
# and before USE_HIP is normalized to ON by USE_HIP_CMAKE below (so that the arch value is not lost).
if(USE_CUDA AND NOT USE_CUDA STREQUAL "AUTO" AND NOT USE_CUDA STREQUAL "ON")
	if(USE_CUDA_ARCH STREQUAL "AUTO")
		set(USE_CUDA_ARCH "${USE_CUDA}")
	endif()
	set(USE_CUDA ON)
endif()
if(USE_HIP AND NOT USE_HIP STREQUAL "AUTO" AND NOT USE_HIP STREQUAL "ON")
	if(USE_HIP_ARCH STREQUAL "AUTO")
		set(USE_HIP_ARCH "${USE_HIP}")
	endif()
	set(USE_HIP ON)
endif()
# setting USE_CUDA_ARCH (or USE_HIP_ARCH) to an explicit architecture also enables the corresponding GPU support
if(USE_CUDA STREQUAL "AUTO" AND NOT USE_CUDA_ARCH STREQUAL "AUTO")
	set(USE_CUDA ON)
endif()
if(USE_HIP STREQUAL "AUTO" AND NOT USE_HIP_ARCH STREQUAL "AUTO")
	set(USE_HIP ON)
endif()

if (USE_HIP_CMAKE)
	set(USE_HIP ON)
endif()

###########################################################
# Dependencies
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake)
if (USE_MKL)
	find_package(MKL REQUIRED)
else()
	find_package(FFTW REQUIRED)
endif()

###########################################################
# include some custom scripts
include(cmake/SHTnsConfigHeader.cmake)
include(cmake/SHTnsBuildLib.cmake)
include(cmake/SHTnsBuildTimeSht.cmake)
include(cmake/SHTnsBuildInfos.cmake)
include(cmake/SHTnsCpuGpuArch.cmake)
include(cmake/SHTnsCheckFlags.cmake)
# Initializes ${CMAKE_INSTALL_*DIR} variables
include(GNUInstallDirs)

###########################################################
add_definitions(-DSHTNS_VER="${PROJECT_VERSION}")
# check for flags
shtns_check_all_compiler_flags(VAR SHT_C_FLAGS FLAGS
	-std=gnu99
	-Wno-declared_but_not_referenced
	-Wno-mixed_enum_type
	-fno-tree-loop-distribute-patterns
	-mno-vzeroupper
	-fopenmp-simd
	-qopenmp-simd
	-mtune=skylake
)
set(CMAKE_C_FLAGS "${SHT_C_FLAGS} ${CMAKE_C_FLAGS}")
# check for specific ffast match related flags
shtns_check_all_compiler_flags(VAR SHT_SEMI_FASTMATH_C_FLAGS FLAGS
	-fno-math-errno -fno-trapping-math -ffinite-math-only -fcx-limited-range
)
# Check for ffast-math used on some files
shtns_check_all_compiler_flags(VAR SHT_FASTMATH_C_FLAGS FLAGS
	-ffast-math
)

###########################################################
# GPU support detection: CUDA has precedence over HIP.
# Both cannot be built simultaneously (they produce the same library, shtns_cuda),
# so HIP is only enabled when CUDA is not.
if(USE_CUDA STREQUAL "AUTO")
	find_package(CUDAToolkit QUIET)
	if (CUDAToolkit_FOUND)
		set(USE_CUDA ON)
	else()
		set(USE_CUDA OFF)
	endif()
endif()
if(USE_CUDA)
	if(USE_HIP STREQUAL "ON")
		message(STATUS "HIP disabled: CUDA is enabled and has precedence over HIP (they cannot be built simultaneously).")
	endif()
	set(USE_HIP OFF)
elseif(USE_HIP STREQUAL "AUTO")
	if (USE_HIP_CMAKE)
		find_package(hip QUIET)
		find_package(hipfft QUIET)
		find_package(hiprtc QUIET)
		if (hip_FOUND AND hipfft_FOUND AND hiprtc_FOUND)
			set(USE_HIP ON)
		else()
			set(USE_HIP OFF)
		endif()
	else()
		find_package(SHTnsHIP QUIET)
		if (SHTnsHIP_FOUND)
			set(USE_HIP ON)
		else()
			set(USE_HIP OFF)
		endif()
	endif()
endif()

###########################################################
# configure march for cpu & gpu
shtns_config_cpu_gpu_march()
shtns_config_gpu_cuda_arch()
shtns_config_gpu_hip_arch()

###########################################################
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/sht_config.h)
	message(FATAL_ERROR "Caution, you have previously run SHTNS 'configure' script in the sources, this is not compatible with cmake. Please run 'make clean' in the sources.")
endif()

###########################################################
# standards to use
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 11)

###########################################################
# search deps
# SHTNS_OPENMP environment variable overrides auto-detection (used eg. by pip install)
if(DEFINED ENV{SHTNS_OPENMP} AND NOT USE_OPENMP STREQUAL "ON" AND NOT USE_OPENMP STREQUAL "OFF")
	if("$ENV{SHTNS_OPENMP}" STREQUAL "0" OR "$ENV{SHTNS_OPENMP}" STREQUAL "OFF")
		set(USE_OPENMP OFF)
		message(STATUS "OpenMP disabled by SHTNS_OPENMP=$ENV{SHTNS_OPENMP}")
	elseif("$ENV{SHTNS_OPENMP}" STREQUAL "1" OR "$ENV{SHTNS_OPENMP}" STREQUAL "ON")
		set(USE_OPENMP ON)
	endif()
endif()
if(USE_OPENMP STREQUAL "AUTO")
	find_package(OpenMP COMPONENTS C)
	if(OpenMP_FOUND)
		set(USE_OPENMP ON)
	else()
		set(USE_OPENMP OFF)
	endif()
elseif(USE_OPENMP)
	find_package(OpenMP REQUIRED COMPONENTS C)
endif()

if(USE_CUDA)
	enable_language(CUDA)
	find_package(CUDAToolkit REQUIRED)
endif()

if(USE_HIP)
	if (USE_HIP_CMAKE)
		cmake_minimum_required(
			VERSION 3.21 # HIP LANGUAGE SUPPORT
		)
		# Enabling CXX (and searching for a C++ compiler) is a workaround for a bug in ROCm 4.3, where hipfft pulls in
		# /opt/rocm/lib/cmake/hip/hip-config.cmake:273 which still expects CMAKE_CXX_COMPILER_ID to exist (as previous) HIP support
		# in CMake required overriding the C++ compiler with hipcc. Once this is changed to CMAKE_HIP_COMPILER_ID, this can be removed.
		enable_language(CXX) # Workaround
		enable_language(HIP)

		# search hip libs
		find_package(hip REQUIRED)
		find_package(hipfft REQUIRED)
		find_package(hiprtc REQUIRED)
	else()
		# use SHTns manual HIP binding
		find_package(SHTnsHIP REQUIRED)
		include(cmake/SHTnsHIP.cmake)
	endif()
endif()

# Find the Python development files
if (BUILD_FOR_PYTHON)
	find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module)
	find_package(Numpy REQUIRED)
endif()

###########################################################
# tricks to get the version file generated all the time
# but the file being touch only if it changes by using the cmake
# internals (configure_file)
# from : https://www.marcusfolkesson.se/blog/git-version-in-cmake/
add_custom_target(sht_version ALL
	${CMAKE_COMMAND}
		-D SRC=${CMAKE_CURRENT_SOURCE_DIR}/sht_version.h.in
		-D DST=${CMAKE_CURRENT_BINARY_DIR}/sht_version.h
		-P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/GenerateVersion.cmake
)
add_definitions(-DSHTNS_CMAKE=1)
include_directories(${CMAKE_CURRENT_BINARY_DIR})

###########################################################
# build libraries variants
shtns_build_library(LIBNAME shtns MARCH ${SHTNS_CPU_MARCH})
if (USE_OPENMP)
	shtns_build_library(LIBNAME shtns_omp OPENMP MARCH ${SHTNS_CPU_MARCH})
endif()
if (USE_CUDA AND CUDAToolkit_FOUND)
	shtns_build_library(LIBNAME shtns_cuda CUDA MARCH ${SHTNS_GPU_MARCH})
endif()
if (USE_CUDA AND CUDAToolkit_FOUND AND USE_OPENMP)
	shtns_build_library(LIBNAME shtns_cuda_omp CUDA OPENMP MARCH ${SHTNS_GPU_MARCH})
endif()
if (USE_HIP)
	shtns_build_library(LIBNAME shtns_cuda HIP MARCH ${SHTNS_GPU_MARCH})
endif()
if (USE_HIP AND USE_OPENMP)
	shtns_build_library(LIBNAME shtns_cuda_omp HIP OPENMP MARCH ${SHTNS_GPU_MARCH})
endif()

###########################################################
# enable testing
if(BUILD_TESTING)
	enable_testing()
endif()

###########################################################
# build and run time_SHT tests for all variants
if(BUILD_TESTING)
	shtns_build_exe_shtns_variants(EXENAME time_SHT SRCS time_SHT.c)
endif()

###########################################################
# install
if(USE_CUDA OR USE_HIP)
	install(FILES shtns_cuda.h TYPE INCLUDE)
endif()
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/sht_config.h shtns.h TYPE INCLUDE)

###########################################################
if (BUILD_FOR_PYTHON)
	# set or unset _omp in name
	if (USE_OPENMP)
		set(omp_name "_omp")
	else()
		set(omp_name "")
	endif()

	# Python wrapper for shtns
	Python3_add_library(_shtns MODULE "shtns_numpy_wrap.c" WITH_SOABI)
	target_link_libraries(_shtns PRIVATE shtns${omp_name})
	target_include_directories(_shtns PRIVATE ${NUMPY_INCLUDE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
	install(TARGETS _shtns COMPONENT SHTnsPy DESTINATION .)

	# Python wrapper for shtns cuda
	if ((USE_CUDA AND CUDAToolkit_FOUND) OR USE_HIP)
		Python3_add_library(_shtns_cuda MODULE "shtns_cuda_wrap.c" WITH_SOABI)
		target_link_libraries(_shtns_cuda PRIVATE shtns_cuda${omp_name})
		target_include_directories(_shtns_cuda PRIVATE ${NUMPY_INCLUDE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
		install(TARGETS _shtns_cuda COMPONENT SHTnsPy DESTINATION .)
	endif()
endif()

###########################################################
# subdirs
add_subdirectory(SHT)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/examples)
    add_subdirectory(examples)
endif()

###########################################################
shtns_print_status()
