set(BUILTINS_LIT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})

# If COMPILER_RT_TEST_EXTERNAL_BUILTINS is set, the builtins
# were already built and we are just going to test them.
# NOTE: This is currently an LLVM-internal option which should
# only be used by the LLVM_ENABLE_RUNTIMES build configured
# in llvm/runtimes/CMakeLists.txt
if(COMPILER_RT_TEST_EXTERNAL_BUILTINS)
  set(BUILTINS_TEST_DEPS ${SANITIZER_COMMON_LIT_TEST_DEPS})
else()
  set(BUILTINS_TEST_DEPS ${SANITIZER_COMMON_LIT_TEST_DEPS} builtins)
endif()

set(BUILTINS_TESTSUITES ${CMAKE_CURRENT_BINARY_DIR}/TestCases)

# Test cases.
configure_lit_site_cfg(
  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.py.in
  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg.py
)

#Unit tests.

include(builtin-config-ix)

if (COMPILER_RT_BUILD_CRT AND COMPILER_RT_HAS_CRT)
  if (TARGET crt)
    list(APPEND BUILTINS_TEST_DEPS crt)
  endif()
  set(COMPILER_RT_TEST_CRT ON)
endif()
pythonize_bool(COMPILER_RT_TEST_CRT)

# Indicate if this is an MSVC environment.
pythonize_bool(MSVC)

# Indicate if the compiler for the builtins library was MSVC. If the builtins
# compiler was clang-cl, we will enable some features that the host compiler
# will not, like C99 _Complex and int128.
set(BUILTINS_IS_MSVC OFF)
if (MSVC AND NOT "${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
  set(BUILTINS_IS_MSVC ON)
endif()
pythonize_bool(BUILTINS_IS_MSVC)

set(BUILTIN_TEST_ARCH ${BUILTIN_SUPPORTED_ARCH})
if(APPLE)
  darwin_filter_host_archs(BUILTIN_SUPPORTED_ARCH BUILTIN_TEST_ARCH)
endif()

foreach(arch ${BUILTIN_TEST_ARCH})
  set(BUILTINS_TEST_TARGET_ARCH ${arch})
  string(TOLOWER "-${arch}-${OS_NAME}" BUILTINS_TEST_CONFIG_SUFFIX)
  get_test_cc_for_arch(${arch} BUILTINS_TEST_TARGET_CC BUILTINS_TEST_TARGET_CFLAGS)

  if(COMPILER_RT_GPU_BUILD)
    if("${arch}" MATCHES "amdgcn")
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS
           -Wno-multi-gpu -flto -mcpu=native -nogpulib -startfiles -stdlib)
    elseif("${arch}" MATCHES "nvptx")
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS
           -Wno-multi-gpu -flto -march=native -nogpulib -startfiles -stdlib)
    endif()
    list(APPEND BUILTINS_TEST_TARGET_CFLAGS --target=${COMPILER_RT_DEFAULT_TARGET_TRIPLE})
    string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
  endif()

  if (${arch} STREQUAL "armhf")
    list(APPEND BUILTINS_TEST_TARGET_CFLAGS -fomit-frame-pointer -DCOMPILER_RT_ARMHF_TARGET)
    string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
  endif()

  if (COMPILER_RT_ENABLE_SOFTWARE_INT128 OR ("${arch}" MATCHES "riscv32|sparc$"
    AND NOT CMAKE_COMPILER_IS_GNUCC))
    list(APPEND BUILTINS_TEST_TARGET_CFLAGS -fforce-enable-int128)
    string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
  endif()

  if(APPLE)
    # TODO: Support the new ABI on Apple platforms.
    if (${arch} MATCHES "arm|armhf|aarch64|arm64" AND COMPILER_RT_HAS_${arch}_FLOAT16)
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS -DCOMPILER_RT_HAS_FLOAT16)
      string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
    endif()
  else()
    if (${arch} MATCHES "arm|armhf|aarch64|arm64|i?86|x86_64|AMD64|riscv32|riscv64|s390x" AND COMPILER_RT_HAS_${arch}_FLOAT16)
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS -DCOMPILER_RT_HAS_FLOAT16)
      string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
    endif()
  endif()

  if(COMPILER_RT_ARM_OPTIMIZED_FP AND arch MATCHES "arm")
    if(arch MATCHES "armv6m|armv8m\.base")
      # Set a compile-time definition promising that the Thumb-1 optimized FP
      # implementations are present in this library, and therefore, can be
      # expected to behave in the way expected by the extra-strict tests of NaN
      # and error handling.
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS
        -DCOMPILER_RT_ARM_OPTIMIZED_FP_THUMB1)
    elseif(NOT arch MATCHES "armv[456]")
      # For AArch32 targets that are not just Thumb-1, set a more general flag
      # _and_ the previous one too, so that tests can check
      # COMPILER_RT_ARM_OPTIMIZED_FP_THUMB1 by itself to test for an optimized
      # function available on all AArch32 platforms.
      #
      # We exclude armv[456] because those architecture versions are too old
      # for the optimized functions to support them at all. (And we test
      # against the fixed set of too-old versions rather than the open-ended
      # set of newer ones, for future-proofing.)
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS
        -DCOMPILER_RT_ARM_OPTIMIZED_FP
        -DCOMPILER_RT_ARM_OPTIMIZED_FP_THUMB1)
    endif()
    string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
  endif()

  if(COMPILER_RT_ENABLE_CET)
    if(NOT arch MATCHES "i?86|x86_64|AMD64")
      message(SEND_ERROR "${arch} does not support CET")
    endif()
    if(COMPILER_RT_HAS_FCF_PROTECTION_FLAG)
      list(APPEND BUILTINS_TEST_TARGET_CFLAGS -fcf-protection=full)
      string(REPLACE ";" " " BUILTINS_TEST_TARGET_CFLAGS "${BUILTINS_TEST_TARGET_CFLAGS}")
    endif()
  endif()

  # Compute builtins available in library and add them as lit features.
  if(APPLE)
    # TODO: Support other Apple platforms.
    set(BUILTIN_LIB_TARGET_NAME "clang_rt.builtins_${arch}_osx")
    set(BUILTIN_LIB_OUTPUT_NAME "clang_rt.builtins_${arch}_osx")
  else()
    set(BUILTIN_LIB_TARGET_NAME "clang_rt.builtins-${arch}")
    set_output_name(BUILTIN_LIB_OUTPUT_NAME clang_rt.builtins ${arch})
  endif()
  # Normally, we can just inspect the target directly to get the sources, but if
  # we are testing an externally-built builtins library, we expect a file named
  # ${BUILTIN_LIB_OUTPUT_NAME}.sources.txt in the compiler-rt output directory.
  # This file is created by compiler-rt/lib/builtins/CMakeLists.txt
  if(NOT COMPILER_RT_TEST_EXTERNAL_BUILTINS)
    if (NOT TARGET "${BUILTIN_LIB_TARGET_NAME}")
      message(FATAL_ERROR "Target ${BUILTIN_LIB_TARGET_NAME} does not exist")
    endif()
    get_target_property(BUILTIN_LIB_SOURCES "${BUILTIN_LIB_TARGET_NAME}" SOURCES)
  else()
    get_compiler_rt_output_dir(${arch} BUILTIN_LIB_OUTPUT_DIR)
    file(READ "${BUILTIN_LIB_OUTPUT_DIR}/${BUILTIN_LIB_OUTPUT_NAME}.sources.txt" BUILTIN_LIB_SOURCES)
  endif()
  list(LENGTH BUILTIN_LIB_SOURCES BUILTIN_LIB_SOURCES_LENGTH)
  if (BUILTIN_LIB_SOURCES_LENGTH EQUAL 0)
    message(FATAL_ERROR "Failed to find source files for ${arch} builtin library")
  endif()
  set(BUILTINS_LIT_SOURCE_FEATURES "")
  foreach (file_name ${BUILTIN_LIB_SOURCES})
    # Strip off any directories and file extensions. This approach means we add
    # add a single feature if there is a C source file or assembly override
    # present in the builtin library.
    # E.g.
    # "hexagon/udivsi3.S" => "udivsi3"
    # "udivsi3.c" => "udivsi3"
    get_filename_component(FILE_NAME_FILTERED "${file_name}" NAME_WE)
    get_property(_also_provided SOURCE "${COMPILER_RT_SOURCE_DIR}/lib/builtins/${file_name}" DIRECTORY ${COMPILER_RT_SOURCE_DIR} PROPERTY crt_provides)
    foreach(_function "${FILE_NAME_FILTERED}" ${_also_provided})
      list(APPEND BUILTINS_LIT_SOURCE_FEATURES "librt_has_${_function}")
    endforeach()
  endforeach()

  string(TOUPPER ${arch} ARCH_UPPER_CASE)
  set(CONFIG_NAME ${ARCH_UPPER_CASE}${OS_NAME}Config)
  configure_lit_site_cfg(
    ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.py.in
    ${CMAKE_CURRENT_BINARY_DIR}/Unit/${CONFIG_NAME}/lit.site.cfg.py
    )
  list(APPEND BUILTINS_TESTSUITES ${CMAKE_CURRENT_BINARY_DIR}/Unit/${CONFIG_NAME})
endforeach()

# TODO: Add support for running tests on iOS and iOS simulator.

add_lit_testsuite(check-builtins "Running the Builtins tests"
  ${BUILTINS_TESTSUITES}
  DEPENDS ${BUILTINS_TEST_DEPS})
