CheckAtomic.cmake 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # atomic builtins are required for threading support.
  2. INCLUDE(CheckCXXSourceCompiles)
  3. # Sometimes linking against libatomic is required for atomic ops, if
  4. # the platform doesn't support lock-free atomics.
  5. function(check_working_cxx_atomics varname)
  6. set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
  7. set(CMAKE_REQUIRED_FLAGS "-std=c++11")
  8. CHECK_CXX_SOURCE_COMPILES("
  9. #include <atomic>
  10. std::atomic<int> x;
  11. int main() {
  12. return x;
  13. }
  14. " ${varname})
  15. set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
  16. endfunction(check_working_cxx_atomics)
  17. # This isn't necessary on MSVC, so avoid command-line switch annoyance
  18. # by only running on GCC-like hosts.
  19. if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
  20. # First check if atomics work without the library.
  21. check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITHOUT_LIB)
  22. # If not, check if the library exists, and atomics work with it.
  23. if(NOT HAVE_CXX_ATOMICS_WITHOUT_LIB)
  24. check_library_exists(atomic __atomic_fetch_add_4 "" HAVE_LIBATOMIC)
  25. if( HAVE_LIBATOMIC )
  26. list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
  27. check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITH_LIB)
  28. if (NOT HAVE_CXX_ATOMICS_WITH_LIB)
  29. message(FATAL_ERROR "Host compiler must support std::atomic!")
  30. endif()
  31. else()
  32. message(FATAL_ERROR "Host compiler appears to require libatomic, but cannot find it.")
  33. endif()
  34. endif()
  35. endif()
  36. ## TODO: This define is only used for the legacy atomic operations in
  37. ## llvm's Atomic.h, which should be replaced. Other code simply
  38. ## assumes C++11 <atomic> works.
  39. CHECK_CXX_SOURCE_COMPILES("
  40. #ifdef _MSC_VER
  41. #include <Intrin.h> /* Workaround for PR19898. */
  42. #include <windows.h>
  43. #endif
  44. int main() {
  45. #ifdef _MSC_VER
  46. volatile LONG val = 1;
  47. MemoryBarrier();
  48. InterlockedCompareExchange(&val, 0, 1);
  49. InterlockedIncrement(&val);
  50. InterlockedDecrement(&val);
  51. #else
  52. volatile unsigned long val = 1;
  53. __sync_synchronize();
  54. __sync_val_compare_and_swap(&val, 1, 0);
  55. __sync_add_and_fetch(&val, 1);
  56. __sync_sub_and_fetch(&val, 1);
  57. #endif
  58. return 0;
  59. }
  60. " LLVM_HAS_ATOMICS)
  61. if( NOT LLVM_HAS_ATOMICS )
  62. message(STATUS "Warning: LLVM will be built thread-unsafe because atomic builtins are missing")
  63. endif()