2 # This was originally part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 # See (https://llvm.org/)LICENSE.txt for license information.
4 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 # Modifications have been made to suit building OpenTTD.
9 # atomic builtins are required for threading support.
11 INCLUDE(CheckCXXSourceCompiles)
12 INCLUDE(CheckLibraryExists)
14 # Sometimes linking against libatomic is required for atomic ops, if
15 # the platform doesn't support lock-free atomics.
17 function(check_working_cxx_atomics varname)
18 set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
19 set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++17")
20 check_cxx_source_compiles("
31 set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
32 endfunction(check_working_cxx_atomics)
34 function(check_working_cxx_atomics64 varname)
35 set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
36 set(CMAKE_REQUIRED_FLAGS "-std=c++17 ${CMAKE_REQUIRED_FLAGS}")
37 check_cxx_source_compiles("
40 std::atomic<uint64_t> x (0);
42 uint64_t i = x.load(std::memory_order_relaxed);
47 set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
48 endfunction(check_working_cxx_atomics64)
51 # Check for (non-64-bit) atomic operations.
53 set(HAVE_CXX_ATOMICS_WITHOUT_LIB True)
55 # First check if atomics work without the library.
56 check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITHOUT_LIB)
57 # If not, check if the library exists, and atomics work with it.
58 if(NOT HAVE_CXX_ATOMICS_WITHOUT_LIB)
59 # check_library_exists requires the C-compiler as the atomic functions are built-in declared.
61 check_library_exists(atomic __atomic_fetch_add_4 "" HAVE_LIBATOMIC)
63 list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
64 check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITH_LIB)
65 if (NOT HAVE_CXX_ATOMICS_WITH_LIB)
66 message(FATAL_ERROR "Host compiler must support std::atomic!")
69 message(FATAL_ERROR "Host compiler appears to require libatomic, but cannot find it.")
74 # Check for 64 bit atomic operations.
76 set(HAVE_CXX_ATOMICS64_WITHOUT_LIB True)
78 # First check if atomics work without the library.
79 check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITHOUT_LIB)
80 # If not, check if the library exists, and atomics work with it.
81 if(NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB)
82 # check_library_exists requires the C-compiler as the atomic functions are built-in declared.
84 check_library_exists(atomic __atomic_load_8 "" HAVE_CXX_LIBATOMICS64)
85 if(HAVE_CXX_LIBATOMICS64)
86 list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
87 check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITH_LIB)
88 if (NOT HAVE_CXX_ATOMICS64_WITH_LIB)
89 message(FATAL_ERROR "Host compiler must support 64-bit std::atomic!")
92 message(FATAL_ERROR "Host compiler appears to require libatomic for 64-bit operations, but cannot find it.")
97 if(HAVE_CXX_ATOMICS_WITH_LIB OR HAVE_CXX_ATOMICS64_WITH_LIB)
98 target_link_libraries(openttd_lib atomic)