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