# Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
cmake_minimum_required(VERSION 3.3)


####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
####### Any changes to this file will be overwritten by the next CMake run ####
####### The input file was hip-config.cmake.in                            ########

get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)

macro(set_and_check _var _file)
  set(${_var} "${_file}")
  if(NOT EXISTS "${_file}")
    message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
  endif()
endmacro()

macro(check_required_components _NAME)
  foreach(comp ${${_NAME}_FIND_COMPONENTS})
    if(NOT ${_NAME}_${comp}_FOUND)
      if(${_NAME}_FIND_REQUIRED_${comp})
        set(${_NAME}_FOUND FALSE)
      endif()
    endif()
  endforeach()
endmacro()

####################################################################################
include(CheckCXXCompilerFlag)
include(CMakeFindDependencyMacro OPTIONAL RESULT_VARIABLE _CMakeFindDependencyMacro_FOUND)
if (NOT _CMakeFindDependencyMacro_FOUND)
  macro(find_dependency dep)
    if (NOT ${dep}_FOUND)
      set(cmake_fd_version)
      if (${ARGC} GREATER 1)
        set(cmake_fd_version ${ARGV1})
      endif()
      set(cmake_fd_exact_arg)
      if(${CMAKE_FIND_PACKAGE_NAME}_FIND_VERSION_EXACT)
        set(cmake_fd_exact_arg EXACT)
      endif()
      set(cmake_fd_quiet_arg)
      if(${CMAKE_FIND_PACKAGE_NAME}_FIND_QUIETLY)
        set(cmake_fd_quiet_arg QUIET)
      endif()
      set(cmake_fd_required_arg)
      if(${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED)
        set(cmake_fd_required_arg REQUIRED)
      endif()
      find_package(${dep} ${cmake_fd_version}
          ${cmake_fd_exact_arg}
          ${cmake_fd_quiet_arg}
          ${cmake_fd_required_arg}
      )
      string(TOUPPER ${dep} cmake_dep_upper)
      if (NOT ${dep}_FOUND AND NOT ${cmake_dep_upper}_FOUND)
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "${CMAKE_FIND_PACKAGE_NAME} could not be found because dependency ${dep} could not be found.")
        set(${CMAKE_FIND_PACKAGE_NAME}_FOUND False)
        return()
      endif()
      set(cmake_fd_version)
      set(cmake_fd_required_arg)
      set(cmake_fd_quiet_arg)
      set(cmake_fd_exact_arg)
    endif()
  endmacro()
endif()

set(_HIP_SHELL "SHELL:")
if(CMAKE_VERSION VERSION_LESS 3.12)
  set(_HIP_SHELL "")
endif()

function(hip_add_interface_compile_flags TARGET)
  set_property(TARGET ${TARGET} APPEND PROPERTY
    INTERFACE_COMPILE_OPTIONS "$<$<COMPILE_LANGUAGE:CXX>:${_HIP_SHELL}${ARGN}>"
  )
endfunction()

function(hip_add_interface_link_flags TARGET)
  if(CMAKE_VERSION VERSION_LESS 3.20)
    set_property(TARGET ${TARGET} APPEND PROPERTY
      INTERFACE_LINK_LIBRARIES "${ARGN}"
    )
  else()
    set_property(TARGET ${TARGET} APPEND PROPERTY
      INTERFACE_LINK_LIBRARIES "$<$<LINK_LANGUAGE:CXX>:${ARGN}>"
    )
  endif()
endfunction()

#Number of parallel jobs by default is 1
if(NOT DEFINED HIP_CLANG_NUM_PARALLEL_JOBS)
  set(HIP_CLANG_NUM_PARALLEL_JOBS 1)
endif()
set(HIP_COMPILER "clang")
set(HIP_RUNTIME "rocclr")

set_and_check( hip_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/include" )
set_and_check( hip_INCLUDE_DIRS "${hip_INCLUDE_DIR}" )
set_and_check( hip_LIB_INSTALL_DIR "${PACKAGE_PREFIX_DIR}/lib" )
set_and_check( hip_BIN_INSTALL_DIR "${PACKAGE_PREFIX_DIR}/bin" )
if(WIN32)
  set_and_check(hip_HIPCC_EXECUTABLE "${hip_BIN_INSTALL_DIR}/hipcc.bat")
  set_and_check(hip_HIPCONFIG_EXECUTABLE "${hip_BIN_INSTALL_DIR}/hipconfig.bat")
else()
  set_and_check(hip_HIPCC_EXECUTABLE "${hip_BIN_INSTALL_DIR}/hipcc")
  set_and_check(hip_HIPCONFIG_EXECUTABLE "${hip_BIN_INSTALL_DIR}/hipconfig")
endif()
# Windows Specific Definition here:
if(WIN32)
  if(DEFINED ENV{HIP_PATH})
    file(TO_CMAKE_PATH "$ENV{HIP_PATH}" HIP_PATH)
  elseif(DEFINED ENV{HIP_DIR})
    file(TO_CMAKE_PATH "$ENV{HIP_DIR}" HIP_DIR)
  else()
    set(HIP_PATH "C:/Program Files/AMD HIP SDK/hip")
  endif()
else()
  # Linux - set a default path for ROCM_PATH
  if(NOT DEFINED ROCM_PATH)
    set(ROCM_PATH /opt/rocm)
  endif()

  #If HIP is not installed under ROCm, need this to find HSA assuming HSA is under ROCm
  if(DEFINED ENV{ROCM_PATH})
    set(ROCM_PATH "$ENV{ROCM_PATH}")
  endif()
endif()

if(HIP_COMPILER STREQUAL "clang")
  if(WIN32)
    file(TO_CMAKE_PATH "$ENV{HIP_PATH}" HIP_CLANG_ROOT)
  else()
    set(HIP_CLANG_ROOT "${ROCM_PATH}/llvm")
  endif()
  if(NOT HIP_CXX_COMPILER)
    set(HIP_CXX_COMPILER ${CMAKE_CXX_COMPILER})
  endif()
  if(HIP_CXX_COMPILER MATCHES ".*hipcc" OR HIP_CXX_COMPILER MATCHES ".*clang\\+\\+")
    execute_process(COMMAND ${HIP_CXX_COMPILER} --version
                    OUTPUT_STRIP_TRAILING_WHITESPACE
                    OUTPUT_VARIABLE HIP_CXX_COMPILER_VERSION_OUTPUT)
    # Capture the repo, branch and patch level details of the HIP CXX Compiler.
    # Ex. clang version 13.0.0 (https://github.com/ROCm-Developer-Tools/HIP main 12345 COMMIT_HASH)
    # HIP_CLANG_REPO: https://github.com/ROCm-Developer-Tools/HIP
    # HIP_CLANG_BRANCH: main
    # HIP_CLANG_PATCH_LEVEL: 12345
    if(${HIP_CXX_COMPILER_VERSION_OUTPUT} MATCHES "clang version [0-9]+\\.[0-9]+\\.[0-9]+ \\(([^ \n]*) ([^ \n]*) ([^ \n]*)")
      set(HIP_CLANG_REPO ${CMAKE_MATCH_1})
      set(HIP_CLANG_BRANCH ${CMAKE_MATCH_2})
      set(HIP_CLANG_PATCH_LEVEL ${CMAKE_MATCH_3})
    endif()
  endif()
  if(HIP_CXX_COMPILER MATCHES ".*hipcc")
    if(HIP_CXX_COMPILER_VERSION_OUTPUT MATCHES "InstalledDir:[ \t]*([^\n]*)")
      get_filename_component(HIP_CLANG_ROOT "${CMAKE_MATCH_1}" DIRECTORY)
    endif()
  elseif (HIP_CXX_COMPILER MATCHES ".*clang\\+\\+")
    get_filename_component(HIP_CLANG_ROOT "${HIP_CXX_COMPILER}" DIRECTORY)
    get_filename_component(HIP_CLANG_ROOT "${HIP_CLANG_ROOT}" DIRECTORY)
  endif()
  file(GLOB HIP_CLANG_INCLUDE_SEARCH_PATHS ${HIP_CLANG_ROOT}/lib/clang/*/include)
  find_path(HIP_CLANG_INCLUDE_PATH stddef.h
      HINTS
          ${HIP_CLANG_INCLUDE_SEARCH_PATHS}
      NO_DEFAULT_PATH)
  if(NOT WIN32)
    find_dependency(AMDDeviceLibs)
  endif()
  set(AMDGPU_TARGETS "gfx900;gfx906;gfx908;gfx90a;gfx1030" CACHE STRING "AMD GPU targets to compile for")
  set(GPU_TARGETS "${AMDGPU_TARGETS}" CACHE STRING "GPU targets to compile for")
endif()

if(NOT WIN32)
  find_dependency(amd_comgr)
endif()

include( "${CMAKE_CURRENT_LIST_DIR}/hip-targets.cmake" )

#Using find_dependency to locate the dependency for the packages
#This makes the cmake generated file xxxx-targets to supply the linker libraries
# without worrying other transitive dependencies
if(NOT WIN32)
  find_dependency(hsa-runtime64)
  find_dependency(Threads)
endif()

#get_filename_component cannot resolve the symlinks if called from /opt/rocm/lib/hip
#and do three level up again
get_filename_component(_DIR "${CMAKE_CURRENT_LIST_DIR}" REALPATH)
get_filename_component(_IMPORT_PREFIX "${_DIR}/../../../" REALPATH)

# Windows doesn't need HSA
if(NOT WIN32)
  #if HSA is not under ROCm then provide CMAKE_PREFIX_PATH=<HSA_PATH>
  find_path(HSA_HEADER hsa/hsa.h
    PATHS
      "${_IMPORT_PREFIX}/../include"
      ${ROCM_PATH}/include
  )

  if (HSA_HEADER-NOTFOUND)
    message (FATAL_ERROR "HSA header not found! ROCM_PATH environment not set")
  endif()
endif()

# Right now this is only supported for amd platforms
set_target_properties(hip::host PROPERTIES
  INTERFACE_COMPILE_DEFINITIONS "__HIP_PLATFORM_HCC__=1;__HIP_PLATFORM_AMD__=1"
)

if(HIP_RUNTIME MATCHES "rocclr")
  set_target_properties(hip::amdhip64 PROPERTIES
    INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;${HSA_HEADER}"
    INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;${HSA_HEADER}"
  )

  get_target_property(amdhip64_type hip::amdhip64 TYPE)
  message(STATUS "hip::amdhip64 is ${amdhip64_type}")

  if(NOT WIN32)
    set_target_properties(hip::device PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include"
      INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include"
    )
  endif()
endif()

if(HIP_COMPILER STREQUAL "clang")
  get_property(compilePropIsSet TARGET hip::device PROPERTY INTERFACE_COMPILE_OPTIONS SET)

  if (NOT compilePropIsSet AND HIP_CXX_COMPILER MATCHES ".*clang\\+\\+")
    hip_add_interface_compile_flags(hip::device -mllvm -amdgpu-early-inline-all=true -mllvm -amdgpu-function-calls=false)
  endif()

  if (NOT compilePropIsSet)
    hip_add_interface_compile_flags(hip::device -x hip)
    if (NOT EXISTS ${AMD_DEVICE_LIBS_PREFIX}/amdgcn/bitcode)
      # This path is to support an older build of the device library
      # TODO: To be removed in the future.
      if(WIN32)
        hip_add_interface_compile_flags(hip::device -fms-extensions -fms-compatibility)
        hip_add_interface_compile_flags(hip::device --hip-device-lib-path=\"${HIP_PATH}/lib/bitcode\")
      else()
        hip_add_interface_compile_flags(hip::device --hip-device-lib-path=\"${AMD_DEVICE_LIBS_PREFIX}/lib\")
      endif()
    endif()
  endif()

  hip_add_interface_link_flags(hip::device --hip-link)

  set_property(TARGET hip::device APPEND PROPERTY
    INTERFACE_INCLUDE_DIRECTORIES "${HIP_CLANG_INCLUDE_PATH}/.."
  )

  set_property(TARGET hip::device APPEND PROPERTY
    INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${HIP_CLANG_INCLUDE_PATH}/.."
  )

  foreach(GPU_TARGET ${GPU_TARGETS})
      if (NOT compilePropIsSet)
        hip_add_interface_compile_flags(hip::device --offload-arch=${GPU_TARGET})
      endif()
      hip_add_interface_link_flags(hip::device --offload-arch=${GPU_TARGET})
  endforeach()
  #Add support for parallel build and link
  if(${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")
    check_cxx_compiler_flag("-parallel-jobs=1" HIP_CLANG_SUPPORTS_PARALLEL_JOBS)
  endif()
  if(HIP_CLANG_NUM_PARALLEL_JOBS GREATER 1)
    if(${HIP_CLANG_SUPPORTS_PARALLEL_JOBS} )
      if (NOT compilePropIsSet)
        hip_add_interface_compile_flags(hip::device -parallel-jobs=${HIP_CLANG_NUM_PARALLEL_JOBS} -Wno-format-nonliteral)
      endif()
      hip_add_interface_link_flags(hip::device -parallel-jobs=${HIP_CLANG_NUM_PARALLEL_JOBS})
    else()
      message("clang compiler doesn't support parallel jobs")
    endif()
  endif()

  file(GLOB HIP_CLANGRT_LIB_SEARCH_PATHS "${HIP_CLANG_ROOT}/lib/clang/*/lib/*")
  find_library(CLANGRT_BUILTINS
    NAMES
      clang_rt.builtins
      clang_rt.builtins-x86_64
    PATHS
      ${HIP_CLANGRT_LIB_SEARCH_PATHS}
      ${HIP_CLANG_INCLUDE_PATH}/../lib/linux)

  # Add support for __fp16 and _Float16, explicitly link with compiler-rt
  if(CLANGRT_BUILTINS-NOTFOUND)
    message(FATAL_ERROR "clangrt builtins lib not found")
  else()
    set_property(TARGET hip::host APPEND PROPERTY INTERFACE_LINK_LIBRARIES "${CLANGRT_BUILTINS}")
    set_property(TARGET hip::device APPEND PROPERTY INTERFACE_LINK_LIBRARIES "${CLANGRT_BUILTINS}")
  endif()
endif()

set( hip_LIBRARIES hip::host hip::device)
set( hip_LIBRARY ${hip_LIBRARIES})

set(HIP_INCLUDE_DIR ${hip_INCLUDE_DIR})
set(HIP_INCLUDE_DIRS ${hip_INCLUDE_DIRS})
set(HIP_LIB_INSTALL_DIR ${hip_LIB_INSTALL_DIR})
set(HIP_BIN_INSTALL_DIR ${hip_BIN_INSTALL_DIR})
set(HIP_LIBRARIES ${hip_LIBRARIES})
set(HIP_LIBRARY ${hip_LIBRARY})
set(HIP_HIPCC_EXECUTABLE ${hip_HIPCC_EXECUTABLE})
set(HIP_HIPCONFIG_EXECUTABLE ${hip_HIPCONFIG_EXECUTABLE})

