1include(CMakePushCheckState)
2include(CheckSymbolExists)
3
4# Because compiler-rt spends a lot of time setting up custom compile flags,
5# define a handy helper function for it. The compile flags setting in CMake
6# has serious issues that make its syntax challenging at best.
7function(set_target_compile_flags target)
8  set(argstring "")
9  foreach(arg ${ARGN})
10    set(argstring "${argstring} ${arg}")
11  endforeach()
12  set_property(TARGET ${target} PROPERTY COMPILE_FLAGS "${argstring}")
13endfunction()
14
15function(set_target_link_flags target)
16  set(argstring "")
17  foreach(arg ${ARGN})
18    set(argstring "${argstring} ${arg}")
19  endforeach()
20  set_property(TARGET ${target} PROPERTY LINK_FLAGS "${argstring}")
21endfunction()
22
23# Set the variable var_PYBOOL to True if var holds a true-ish string,
24# otherwise set it to False.
25macro(pythonize_bool var)
26  if (${var})
27    set(${var}_PYBOOL True)
28  else()
29    set(${var}_PYBOOL False)
30  endif()
31endmacro()
32
33# Appends value to all lists in ARGN, if the condition is true.
34macro(append_list_if condition value)
35  if(${condition})
36    foreach(list ${ARGN})
37      list(APPEND ${list} ${value})
38    endforeach()
39  endif()
40endmacro()
41
42# Appends value to all strings in ARGN, if the condition is true.
43macro(append_string_if condition value)
44  if(${condition})
45    foreach(str ${ARGN})
46      set(${str} "${${str}} ${value}")
47    endforeach()
48  endif()
49endmacro()
50
51macro(append_rtti_flag polarity list)
52  if(${polarity})
53    append_list_if(COMPILER_RT_HAS_FRTTI_FLAG -frtti ${list})
54    append_list_if(COMPILER_RT_HAS_GR_FLAG /GR ${list})
55  else()
56    append_list_if(COMPILER_RT_HAS_FNO_RTTI_FLAG -fno-rtti ${list})
57    append_list_if(COMPILER_RT_HAS_GR_FLAG /GR- ${list})
58  endif()
59endmacro()
60
61macro(list_intersect output input1 input2)
62  set(${output})
63  foreach(it ${${input1}})
64    list(FIND ${input2} ${it} index)
65    if( NOT (index EQUAL -1))
66      list(APPEND ${output} ${it})
67    endif()
68  endforeach()
69endmacro()
70
71function(list_replace input_list old new)
72  set(replaced_list)
73  foreach(item ${${input_list}})
74    if(${item} STREQUAL ${old})
75      list(APPEND replaced_list ${new})
76    else()
77      list(APPEND replaced_list ${item})
78    endif()
79  endforeach()
80  set(${input_list} "${replaced_list}" PARENT_SCOPE)
81endfunction()
82
83# Takes ${ARGN} and puts only supported architectures in @out_var list.
84function(filter_available_targets out_var)
85  set(archs ${${out_var}})
86  foreach(arch ${ARGN})
87    list(FIND COMPILER_RT_SUPPORTED_ARCH ${arch} ARCH_INDEX)
88    if(NOT (ARCH_INDEX EQUAL -1) AND CAN_TARGET_${arch})
89      list(APPEND archs ${arch})
90    endif()
91  endforeach()
92  set(${out_var} ${archs} PARENT_SCOPE)
93endfunction()
94
95# Add $arch as supported with no additional flags.
96macro(add_default_target_arch arch)
97  set(TARGET_${arch}_CFLAGS "")
98  set(CAN_TARGET_${arch} 1)
99  list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})
100endmacro()
101
102function(check_compile_definition def argstring out_var)
103  if("${def}" STREQUAL "")
104    set(${out_var} TRUE PARENT_SCOPE)
105    return()
106  endif()
107  cmake_push_check_state()
108  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${argstring}")
109  check_symbol_exists(${def} "" ${out_var})
110  cmake_pop_check_state()
111endfunction()
112
113# test_target_arch(<arch> <def> <target flags...>)
114# Checks if architecture is supported: runs host compiler with provided
115# flags to verify that:
116#   1) <def> is defined (if non-empty)
117#   2) simple file can be successfully built.
118# If successful, saves target flags for this architecture.
119macro(test_target_arch arch def)
120  set(TARGET_${arch}_CFLAGS ${ARGN})
121  set(TARGET_${arch}_LINK_FLAGS ${ARGN})
122  set(argstring "")
123  foreach(arg ${ARGN})
124    set(argstring "${argstring} ${arg}")
125  endforeach()
126  check_compile_definition("${def}" "${argstring}" HAS_${arch}_DEF)
127  if(NOT DEFINED CAN_TARGET_${arch})
128    if(NOT HAS_${arch}_DEF)
129      set(CAN_TARGET_${arch} FALSE)
130    elseif(TEST_COMPILE_ONLY)
131      try_compile_only(CAN_TARGET_${arch}
132                       SOURCE "#include <limits.h>\nint foo(int x, int y) { return x + y; }\n"
133                       FLAGS ${TARGET_${arch}_CFLAGS})
134    else()
135      set(FLAG_NO_EXCEPTIONS "")
136      if(COMPILER_RT_HAS_FNO_EXCEPTIONS_FLAG)
137        set(FLAG_NO_EXCEPTIONS " -fno-exceptions ")
138      endif()
139      set(SAVED_CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS})
140      set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${argstring}")
141      try_compile(CAN_TARGET_${arch} ${CMAKE_BINARY_DIR} ${SIMPLE_SOURCE}
142                  COMPILE_DEFINITIONS "${TARGET_${arch}_CFLAGS} ${FLAG_NO_EXCEPTIONS}"
143                  OUTPUT_VARIABLE TARGET_${arch}_OUTPUT)
144      set(CMAKE_EXE_LINKER_FLAGS ${SAVED_CMAKE_EXE_LINKER_FLAGS})
145    endif()
146  endif()
147  if(${CAN_TARGET_${arch}})
148    list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})
149  elseif("${COMPILER_RT_DEFAULT_TARGET_ARCH}" STREQUAL "${arch}" AND
150         COMPILER_RT_HAS_EXPLICIT_DEFAULT_TARGET_TRIPLE)
151    # Bail out if we cannot target the architecture we plan to test.
152    message(FATAL_ERROR "Cannot compile for ${arch}:\n${TARGET_${arch}_OUTPUT}")
153  endif()
154endmacro()
155
156macro(detect_target_arch)
157  check_symbol_exists(__arm__ "" __ARM)
158  check_symbol_exists(__AVR__ "" __AVR)
159  check_symbol_exists(__aarch64__ "" __AARCH64)
160  check_symbol_exists(__x86_64__ "" __X86_64)
161  check_symbol_exists(__i386__ "" __I386)
162  check_symbol_exists(__mips__ "" __MIPS)
163  check_symbol_exists(__mips64__ "" __MIPS64)
164  check_symbol_exists(__powerpc__ "" __PPC)
165  check_symbol_exists(__powerpc64__ "" __PPC64)
166  check_symbol_exists(__powerpc64le__ "" __PPC64LE)
167  check_symbol_exists(__riscv "" __RISCV)
168  check_symbol_exists(__s390x__ "" __S390X)
169  check_symbol_exists(__sparc "" __SPARC)
170  check_symbol_exists(__sparcv9 "" __SPARCV9)
171  check_symbol_exists(__wasm32__ "" __WEBASSEMBLY32)
172  check_symbol_exists(__wasm64__ "" __WEBASSEMBLY64)
173  check_symbol_exists(__ve__ "" __VE)
174  if(__ARM)
175    add_default_target_arch(arm)
176  elseif(__AVR)
177    add_default_target_arch(avr)
178  elseif(__AARCH64)
179    add_default_target_arch(aarch64)
180  elseif(__X86_64)
181    if(CMAKE_SIZEOF_VOID_P EQUAL "4")
182      add_default_target_arch(x32)
183    elseif(CMAKE_SIZEOF_VOID_P EQUAL "8")
184      add_default_target_arch(x86_64)
185    else()
186      message(FATAL_ERROR "Unsupported pointer size for X86_64")
187    endif()
188  elseif(__I386)
189    add_default_target_arch(i386)
190  elseif(__MIPS64) # must be checked before __MIPS
191    add_default_target_arch(mips64)
192  elseif(__MIPS)
193    add_default_target_arch(mips)
194  elseif(__PPC64) # must be checked before __PPC
195    add_default_target_arch(powerpc64)
196  elseif(__PPC64LE)
197    add_default_target_arch(powerpc64le)
198  elseif(__PPC)
199    add_default_target_arch(powerpc)
200  elseif(__RISCV)
201    if(CMAKE_SIZEOF_VOID_P EQUAL "4")
202      add_default_target_arch(riscv32)
203    elseif(CMAKE_SIZEOF_VOID_P EQUAL "8")
204      add_default_target_arch(riscv64)
205    else()
206      message(FATAL_ERROR "Unsupport XLEN for RISC-V")
207    endif()
208  elseif(__S390X)
209    add_default_target_arch(s390x)
210  elseif(__SPARCV9)
211    add_default_target_arch(sparcv9)
212  elseif(__SPARC)
213    add_default_target_arch(sparc)
214  elseif(__WEBASSEMBLY32)
215    add_default_target_arch(wasm32)
216  elseif(__WEBASSEMBLY64)
217    add_default_target_arch(wasm64)
218  elseif(__VE)
219    add_default_target_arch(ve)
220  endif()
221endmacro()
222
223function(get_compiler_rt_root_source_dir ROOT_DIR_VAR)
224  # Compute the path to the root of the Compiler-RT source tree
225  # regardless of how the project was configured.
226  #
227  # This function is useful because using `${CMAKE_SOURCE_DIR}`
228  # is error prone due to the numerous ways Compiler-RT can be
229  # configured.
230  #
231  # `ROOT_DIR_VAR` - the name of the variable to write the result to.
232  #
233  # TODO(dliew): When CMake min version is 3.17 or newer use
234  # `CMAKE_CURRENT_FUNCTION_LIST_DIR` instead.
235  if ("${ROOT_DIR_VAR}" STREQUAL "")
236    message(FATAL_ERROR "ROOT_DIR_VAR cannot be empty")
237  endif()
238
239  # Compiler-rt supports different source root paths.
240  # Handle each case here.
241  set(PATH_TO_COMPILER_RT_SOURCE_ROOT "")
242  if (DEFINED CompilerRTBuiltins_SOURCE_DIR)
243    # Compiler-RT Builtins standalone build.
244    # `llvm-project/compiler-rt/lib/builtins`
245    set(PATH_TO_COMPILER_RT_SOURCE_ROOT "${CompilerRTBuiltins_SOURCE_DIR}/../../")
246  elseif (DEFINED CompilerRTCRT_SOURCE_DIR)
247    # Compiler-RT CRT standalone build.
248    # `llvm-project/compiler-rt/lib/crt`
249    set(PATH_TO_COMPILER_RT_SOURCE_ROOT "${CompilerRTCRT_SOURCE_DIR}/../../")
250  elseif(DEFINED CompilerRT_SOURCE_DIR)
251    # Compiler-RT standalone build.
252    # `llvm-project/compiler-rt`
253    set(PATH_TO_COMPILER_RT_SOURCE_ROOT "${CompilerRT_SOURCE_DIR}")
254  elseif (EXISTS "${CMAKE_SOURCE_DIR}/../compiler-rt")
255    # In tree build with LLVM as the root project.
256    # See `llvm-project/projects/`.
257    # Assumes monorepo layout.
258    set(PATH_TO_COMPILER_RT_SOURCE_ROOT "${CMAKE_SOURCE_DIR}/../compiler-rt")
259  else()
260    message(FATAL_ERROR "Unhandled Compiler-RT source root configuration.")
261  endif()
262
263  get_filename_component(ROOT_DIR "${PATH_TO_COMPILER_RT_SOURCE_ROOT}" ABSOLUTE)
264  if (NOT EXISTS "${ROOT_DIR}")
265    message(FATAL_ERROR "Path \"${ROOT_DIR}\" doesn't exist")
266  endif()
267
268  # Sanity check: Make sure we can locate the current source file via the
269  # computed path.
270  set(PATH_TO_CURRENT_FILE "${ROOT_DIR}/cmake/Modules/CompilerRTUtils.cmake")
271  if (NOT EXISTS "${PATH_TO_CURRENT_FILE}")
272    message(FATAL_ERROR "Could not find \"${PATH_TO_CURRENT_FILE}\"")
273  endif()
274
275  set("${ROOT_DIR_VAR}" "${ROOT_DIR}" PARENT_SCOPE)
276endfunction()
277
278macro(load_llvm_config)
279  if (NOT LLVM_CONFIG_PATH)
280    find_program(LLVM_CONFIG_PATH "llvm-config"
281                 DOC "Path to llvm-config binary")
282    if (NOT LLVM_CONFIG_PATH)
283      message(WARNING "UNSUPPORTED COMPILER-RT CONFIGURATION DETECTED: "
284                      "llvm-config not found.\n"
285                      "Reconfigure with -DLLVM_CONFIG_PATH=path/to/llvm-config.")
286    endif()
287  endif()
288
289  # Compute path to LLVM sources assuming the monorepo layout.
290  # We don't set `LLVM_MAIN_SRC_DIR` directly to avoid overriding a user provided
291  # CMake cache value.
292  get_compiler_rt_root_source_dir(COMPILER_RT_ROOT_SRC_PATH)
293  get_filename_component(LLVM_MAIN_SRC_DIR_DEFAULT "${COMPILER_RT_ROOT_SRC_PATH}/../llvm" ABSOLUTE)
294  if (NOT EXISTS "${LLVM_MAIN_SRC_DIR_DEFAULT}")
295    # TODO(dliew): Remove this legacy fallback path.
296    message(WARNING
297      "LLVM source tree not found at \"${LLVM_MAIN_SRC_DIR_DEFAULT}\". "
298      "You are not using the monorepo layout. This configuration is DEPRECATED.")
299  endif()
300
301  set(FOUND_LLVM_CMAKE_DIR FALSE)
302  if (LLVM_CONFIG_PATH)
303    execute_process(
304      COMMAND ${LLVM_CONFIG_PATH} "--obj-root" "--bindir" "--libdir" "--src-root" "--includedir"
305      RESULT_VARIABLE HAD_ERROR
306      OUTPUT_VARIABLE CONFIG_OUTPUT)
307    if (HAD_ERROR)
308      message(FATAL_ERROR "llvm-config failed with status ${HAD_ERROR}")
309    endif()
310    string(REGEX REPLACE "[ \t]*[\r\n]+[ \t]*" ";" CONFIG_OUTPUT ${CONFIG_OUTPUT})
311    list(GET CONFIG_OUTPUT 0 BINARY_DIR)
312    list(GET CONFIG_OUTPUT 1 TOOLS_BINARY_DIR)
313    list(GET CONFIG_OUTPUT 2 LIBRARY_DIR)
314    list(GET CONFIG_OUTPUT 3 MAIN_SRC_DIR)
315    list(GET CONFIG_OUTPUT 4 INCLUDE_DIR)
316
317    set(LLVM_BINARY_DIR ${BINARY_DIR} CACHE PATH "Path to LLVM build tree")
318    set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
319    set(LLVM_TOOLS_BINARY_DIR ${TOOLS_BINARY_DIR} CACHE PATH "Path to llvm/bin")
320    set(LLVM_INCLUDE_DIR ${INCLUDE_DIR} CACHE PATH "Paths to LLVM headers")
321
322    if (NOT EXISTS "${LLVM_MAIN_SRC_DIR_DEFAULT}")
323      # TODO(dliew): Remove this legacy fallback path.
324      message(WARNING
325        "Consulting llvm-config for the LLVM source path "
326        "as a fallback. This behavior will be removed in the future.")
327      # We don't set `LLVM_MAIN_SRC_DIR` directly to avoid overriding a user
328      # provided CMake cache value.
329      set(LLVM_MAIN_SRC_DIR_DEFAULT "${MAIN_SRC_DIR}")
330      message(STATUS "Using LLVM source path (${LLVM_MAIN_SRC_DIR_DEFAULT}) from llvm-config")
331    endif()
332
333    # Detect if we have the LLVMXRay and TestingSupport library installed and
334    # available from llvm-config.
335    execute_process(
336      COMMAND ${LLVM_CONFIG_PATH} "--ldflags" "--libs" "xray"
337      RESULT_VARIABLE HAD_ERROR
338      OUTPUT_VARIABLE CONFIG_OUTPUT
339      ERROR_QUIET)
340    if (HAD_ERROR)
341      message(WARNING "llvm-config finding xray failed with status ${HAD_ERROR}")
342      set(COMPILER_RT_HAS_LLVMXRAY FALSE)
343    else()
344      string(REGEX REPLACE "[ \t]*[\r\n]+[ \t]*" ";" CONFIG_OUTPUT ${CONFIG_OUTPUT})
345      list(GET CONFIG_OUTPUT 0 LDFLAGS)
346      list(GET CONFIG_OUTPUT 1 LIBLIST)
347      file(TO_CMAKE_PATH "${LDFLAGS}" LDFLAGS)
348      file(TO_CMAKE_PATH "${LIBLIST}" LIBLIST)
349      set(LLVM_XRAY_LDFLAGS ${LDFLAGS} CACHE STRING "Linker flags for LLVMXRay library")
350      set(LLVM_XRAY_LIBLIST ${LIBLIST} CACHE STRING "Library list for LLVMXRay")
351      set(COMPILER_RT_HAS_LLVMXRAY TRUE)
352    endif()
353
354    set(COMPILER_RT_HAS_LLVMTESTINGSUPPORT FALSE)
355    execute_process(
356      COMMAND ${LLVM_CONFIG_PATH} "--ldflags" "--libs" "testingsupport"
357      RESULT_VARIABLE HAD_ERROR
358      OUTPUT_VARIABLE CONFIG_OUTPUT
359      ERROR_QUIET)
360    if (HAD_ERROR)
361      message(WARNING "llvm-config finding testingsupport failed with status ${HAD_ERROR}")
362    elseif(COMPILER_RT_INCLUDE_TESTS)
363      string(REGEX REPLACE "[ \t]*[\r\n]+[ \t]*" ";" CONFIG_OUTPUT ${CONFIG_OUTPUT})
364      list(GET CONFIG_OUTPUT 0 LDFLAGS)
365      list(GET CONFIG_OUTPUT 1 LIBLIST)
366      if (LIBLIST STREQUAL "")
367        message(WARNING "testingsupport library not installed, some tests will be skipped")
368      else()
369        file(TO_CMAKE_PATH "${LDFLAGS}" LDFLAGS)
370        file(TO_CMAKE_PATH "${LIBLIST}" LIBLIST)
371        set(LLVM_TESTINGSUPPORT_LDFLAGS ${LDFLAGS} CACHE STRING "Linker flags for LLVMTestingSupport library")
372        set(LLVM_TESTINGSUPPORT_LIBLIST ${LIBLIST} CACHE STRING "Library list for LLVMTestingSupport")
373        set(COMPILER_RT_HAS_LLVMTESTINGSUPPORT TRUE)
374      endif()
375    endif()
376
377    # Make use of LLVM CMake modules.
378    # --cmakedir is supported since llvm r291218 (4.0 release)
379    execute_process(
380      COMMAND ${LLVM_CONFIG_PATH} --cmakedir
381      RESULT_VARIABLE HAD_ERROR
382      OUTPUT_VARIABLE CONFIG_OUTPUT)
383    if(NOT HAD_ERROR)
384      string(STRIP "${CONFIG_OUTPUT}" LLVM_CMAKE_DIR_FROM_LLVM_CONFIG)
385      file(TO_CMAKE_PATH ${LLVM_CMAKE_DIR_FROM_LLVM_CONFIG} LLVM_CMAKE_DIR)
386    else()
387      file(TO_CMAKE_PATH ${LLVM_BINARY_DIR} LLVM_BINARY_DIR_CMAKE_STYLE)
388      set(LLVM_CMAKE_DIR "${LLVM_BINARY_DIR_CMAKE_STYLE}/lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm")
389    endif()
390
391    set(LLVM_CMAKE_INCLUDE_FILE "${LLVM_CMAKE_DIR}/LLVMConfig.cmake")
392    if (EXISTS "${LLVM_CMAKE_INCLUDE_FILE}")
393      list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}")
394      # Get some LLVM variables from LLVMConfig.
395      include("${LLVM_CMAKE_INCLUDE_FILE}")
396      set(FOUND_LLVM_CMAKE_DIR TRUE)
397    else()
398      set(FOUND_LLVM_CMAKE_DIR FALSE)
399      message(WARNING "LLVM CMake path (${LLVM_CMAKE_INCLUDE_FILE}) reported by llvm-config does not exist")
400    endif()
401    unset(LLVM_CMAKE_INCLUDE_FILE)
402
403    set(LLVM_LIBRARY_OUTPUT_INTDIR
404      ${LLVM_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
405  endif()
406
407  # Finally set the cache variable now that `llvm-config` has also had a chance
408  # to set `LLVM_MAIN_SRC_DIR_DEFAULT`.
409  set(LLVM_MAIN_SRC_DIR "${LLVM_MAIN_SRC_DIR_DEFAULT}" CACHE PATH "Path to LLVM source tree")
410  message(STATUS "LLVM_MAIN_SRC_DIR: \"${LLVM_MAIN_SRC_DIR}\"")
411  if (NOT EXISTS "${LLVM_MAIN_SRC_DIR}")
412    # TODO(dliew): Make this a hard error
413    message(WARNING "LLVM_MAIN_SRC_DIR (${LLVM_MAIN_SRC_DIR}) does not exist. "
414                    "You can override the inferred path by adding "
415                    "`-DLLVM_MAIN_SRC_DIR=<path_to_llvm_src>` to your CMake invocation "
416                    "where `<path_to_llvm_src>` is the path to the `llvm` directory in "
417                    "the `llvm-project` repo. "
418                    "This will be treated as error in the future.")
419  endif()
420
421  if (NOT FOUND_LLVM_CMAKE_DIR)
422    # This configuration tries to configure without the prescence of `LLVMConfig.cmake`. It is
423    # intended for testing purposes (generating the lit test suites) and will likely not support
424    # a build of the runtimes in compiler-rt.
425    include(CompilerRTMockLLVMCMakeConfig)
426    compiler_rt_mock_llvm_cmake_config()
427  endif()
428
429endmacro()
430
431macro(construct_compiler_rt_default_triple)
432  if(COMPILER_RT_DEFAULT_TARGET_ONLY)
433    if(DEFINED COMPILER_RT_DEFAULT_TARGET_TRIPLE)
434      message(FATAL_ERROR "COMPILER_RT_DEFAULT_TARGET_TRIPLE isn't supported when building for default target only")
435    endif()
436    set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${CMAKE_C_COMPILER_TARGET})
437  else()
438    set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${LLVM_TARGET_TRIPLE} CACHE STRING
439          "Default triple for which compiler-rt runtimes will be built.")
440  endif()
441
442  string(REPLACE "-" ";" LLVM_TARGET_TRIPLE_LIST ${COMPILER_RT_DEFAULT_TARGET_TRIPLE})
443  list(GET LLVM_TARGET_TRIPLE_LIST 0 COMPILER_RT_DEFAULT_TARGET_ARCH)
444
445  # Map various forms of the architecture names to the canonical forms
446  # (as they are used by clang, see getArchNameForCompilerRTLib).
447  if("${COMPILER_RT_DEFAULT_TARGET_ARCH}" MATCHES "^i.86$")
448    # Android uses i686, but that's remapped at a later stage.
449    set(COMPILER_RT_DEFAULT_TARGET_ARCH "i386")
450  endif()
451
452  # Determine if test target triple is specified explicitly, and doesn't match the
453  # default.
454  if(NOT COMPILER_RT_DEFAULT_TARGET_TRIPLE STREQUAL LLVM_TARGET_TRIPLE)
455    set(COMPILER_RT_HAS_EXPLICIT_DEFAULT_TARGET_TRIPLE TRUE)
456  else()
457    set(COMPILER_RT_HAS_EXPLICIT_DEFAULT_TARGET_TRIPLE FALSE)
458  endif()
459endmacro()
460
461# Filter out generic versions of routines that are re-implemented in an
462# architecture specific manner. This prevents multiple definitions of the same
463# symbols, making the symbol selection non-deterministic.
464#
465# We follow the convention that a source file that exists in a sub-directory
466# (e.g. `ppc/divtc3.c`) is architecture-specific and that if a generic
467# implementation exists it will be a top-level source file with the same name
468# modulo the file extension (e.g. `divtc3.c`).
469function(filter_builtin_sources inout_var name)
470  set(intermediate ${${inout_var}})
471  foreach(_file ${intermediate})
472    get_filename_component(_file_dir ${_file} DIRECTORY)
473    if (NOT "${_file_dir}" STREQUAL "")
474      # Architecture specific file. If a generic version exists, print a notice
475      # and ensure that it is removed from the file list.
476      get_filename_component(_name ${_file} NAME)
477      string(REGEX REPLACE "\\.S$" ".c" _cname "${_name}")
478      if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_cname}")
479        message(STATUS "For ${name} builtins preferring ${_file} to ${_cname}")
480        list(REMOVE_ITEM intermediate ${_cname})
481      endif()
482    endif()
483  endforeach()
484  set(${inout_var} ${intermediate} PARENT_SCOPE)
485endfunction()
486
487function(get_compiler_rt_target arch variable)
488  string(FIND ${COMPILER_RT_DEFAULT_TARGET_TRIPLE} "-" dash_index)
489  string(SUBSTRING ${COMPILER_RT_DEFAULT_TARGET_TRIPLE} ${dash_index} -1 triple_suffix)
490  if(COMPILER_RT_DEFAULT_TARGET_ONLY)
491    # Use exact spelling when building only for the target specified to CMake.
492    set(target "${COMPILER_RT_DEFAULT_TARGET_TRIPLE}")
493  elseif(ANDROID AND ${arch} STREQUAL "i386")
494    set(target "i686${triple_suffix}")
495  else()
496    set(target "${arch}${triple_suffix}")
497  endif()
498  set(${variable} ${target} PARENT_SCOPE)
499endfunction()
500
501function(get_compiler_rt_install_dir arch install_dir)
502  if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
503    get_compiler_rt_target(${arch} target)
504    set(${install_dir} ${COMPILER_RT_INSTALL_LIBRARY_DIR}/${target} PARENT_SCOPE)
505  else()
506    set(${install_dir} ${COMPILER_RT_INSTALL_LIBRARY_DIR} PARENT_SCOPE)
507  endif()
508endfunction()
509
510function(get_compiler_rt_output_dir arch output_dir)
511  if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
512    get_compiler_rt_target(${arch} target)
513    set(${output_dir} ${COMPILER_RT_OUTPUT_LIBRARY_DIR}/${target} PARENT_SCOPE)
514  else()
515    set(${output_dir} ${COMPILER_RT_OUTPUT_LIBRARY_DIR} PARENT_SCOPE)
516  endif()
517endfunction()
518
519# compiler_rt_process_sources(
520#   <OUTPUT_VAR>
521#   <SOURCE_FILE> ...
522#  [ADDITIONAL_HEADERS <header> ...]
523# )
524#
525# Process the provided sources and write the list of new sources
526# into `<OUTPUT_VAR>`.
527#
528# ADDITIONAL_HEADERS     - Adds the supplied header to list of sources for IDEs.
529#
530# This function is very similar to `llvm_process_sources()` but exists here
531# because we need to support standalone builds of compiler-rt.
532function(compiler_rt_process_sources OUTPUT_VAR)
533  cmake_parse_arguments(
534    ARG
535    ""
536    ""
537    "ADDITIONAL_HEADERS"
538    ${ARGN}
539  )
540  set(sources ${ARG_UNPARSED_ARGUMENTS})
541  set(headers "")
542  if (XCODE OR MSVC_IDE OR CMAKE_EXTRA_GENERATOR)
543    # For IDEs we need to tell CMake about header files.
544    # Otherwise they won't show up in UI.
545    set(headers ${ARG_ADDITIONAL_HEADERS})
546    list(LENGTH headers headers_length)
547    if (${headers_length} GREATER 0)
548      set_source_files_properties(${headers}
549        PROPERTIES HEADER_FILE_ONLY ON)
550    endif()
551  endif()
552  set("${OUTPUT_VAR}" ${sources} ${headers} PARENT_SCOPE)
553endfunction()
554
555# Create install targets for a library and its parent component (if specified).
556function(add_compiler_rt_install_targets name)
557  cmake_parse_arguments(ARG "" "PARENT_TARGET" "" ${ARGN})
558
559  if(ARG_PARENT_TARGET AND NOT TARGET install-${ARG_PARENT_TARGET})
560    # The parent install target specifies the parent component to scrape up
561    # anything not installed by the individual install targets, and to handle
562    # installation when running the multi-configuration generators.
563    add_custom_target(install-${ARG_PARENT_TARGET}
564                      DEPENDS ${ARG_PARENT_TARGET}
565                      COMMAND "${CMAKE_COMMAND}"
566                              -DCMAKE_INSTALL_COMPONENT=${ARG_PARENT_TARGET}
567                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
568    add_custom_target(install-${ARG_PARENT_TARGET}-stripped
569                      DEPENDS ${ARG_PARENT_TARGET}
570                      COMMAND "${CMAKE_COMMAND}"
571                              -DCMAKE_INSTALL_COMPONENT=${ARG_PARENT_TARGET}
572                              -DCMAKE_INSTALL_DO_STRIP=1
573                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
574    set_target_properties(install-${ARG_PARENT_TARGET} PROPERTIES
575                          FOLDER "Compiler-RT Misc")
576    set_target_properties(install-${ARG_PARENT_TARGET}-stripped PROPERTIES
577                          FOLDER "Compiler-RT Misc")
578    add_dependencies(install-compiler-rt install-${ARG_PARENT_TARGET})
579    add_dependencies(install-compiler-rt-stripped install-${ARG_PARENT_TARGET}-stripped)
580  endif()
581
582  # We only want to generate per-library install targets if you aren't using
583  # an IDE because the extra targets get cluttered in IDEs.
584  if(NOT CMAKE_CONFIGURATION_TYPES)
585    add_custom_target(install-${name}
586                      DEPENDS ${name}
587                      COMMAND "${CMAKE_COMMAND}"
588                              -DCMAKE_INSTALL_COMPONENT=${name}
589                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
590    add_custom_target(install-${name}-stripped
591                      DEPENDS ${name}
592                      COMMAND "${CMAKE_COMMAND}"
593                              -DCMAKE_INSTALL_COMPONENT=${name}
594                              -DCMAKE_INSTALL_DO_STRIP=1
595                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
596    # If you have a parent target specified, we bind the new install target
597    # to the parent install target.
598    if(LIB_PARENT_TARGET)
599      add_dependencies(install-${LIB_PARENT_TARGET} install-${name})
600      add_dependencies(install-${LIB_PARENT_TARGET}-stripped install-${name}-stripped)
601    endif()
602  endif()
603endfunction()
604