1include(GNUInstallDirs)
2include(LLVMDistributionSupport)
3include(LLVMProcessSources)
4include(LLVM-Config)
5include(DetermineGCCCompatible)
6
7function(llvm_update_compile_flags name)
8  get_property(sources TARGET ${name} PROPERTY SOURCES)
9  if("${sources}" MATCHES "\\.c(;|$)")
10    set(update_src_props ON)
11  endif()
12
13  list(APPEND LLVM_COMPILE_CFLAGS " ${LLVM_COMPILE_FLAGS}")
14
15  # LLVM_REQUIRES_EH is an internal flag that individual targets can use to
16  # force EH
17  if(LLVM_REQUIRES_EH OR LLVM_ENABLE_EH)
18    if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
19      message(AUTHOR_WARNING "Exception handling requires RTTI. Enabling RTTI for ${name}")
20      set(LLVM_REQUIRES_RTTI ON)
21    endif()
22    if(MSVC)
23      list(APPEND LLVM_COMPILE_FLAGS "/EHsc")
24    endif()
25  else()
26    if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
27      list(APPEND LLVM_COMPILE_FLAGS "-fno-exceptions")
28      if(NOT LLVM_ENABLE_UNWIND_TABLES)
29        list(APPEND LLVM_COMPILE_FLAGS "-fno-unwind-tables")
30        list(APPEND LLVM_COMPILE_FLAGS "-fno-asynchronous-unwind-tables")
31      endif()
32    elseif(MSVC)
33      list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0)
34      list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-")
35    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
36      list(APPEND LLVM_COMPILE_FLAGS "-qnoeh")
37    endif()
38  endif()
39
40  # LLVM_REQUIRES_RTTI is an internal flag that individual
41  # targets can use to force RTTI
42  set(LLVM_CONFIG_HAS_RTTI YES CACHE INTERNAL "")
43  if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
44    set(LLVM_CONFIG_HAS_RTTI NO CACHE INTERNAL "")
45    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_RTTI=0)
46    if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
47      list(APPEND LLVM_COMPILE_FLAGS "-fno-rtti")
48    elseif (MSVC)
49      list(APPEND LLVM_COMPILE_FLAGS "/GR-")
50    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
51      list(APPEND LLVM_COMPILE_FLAGS "-qnortti")
52    endif ()
53  elseif(MSVC)
54    list(APPEND LLVM_COMPILE_FLAGS "/GR")
55  endif()
56
57  # Assume that;
58  #   - LLVM_COMPILE_FLAGS is list.
59  #   - PROPERTY COMPILE_FLAGS is string.
60  string(REPLACE ";" " " target_compile_flags " ${LLVM_COMPILE_FLAGS}")
61  string(REPLACE ";" " " target_compile_cflags " ${LLVM_COMPILE_CFLAGS}")
62
63  if(update_src_props)
64    foreach(fn ${sources})
65      get_filename_component(suf ${fn} EXT)
66      if("${suf}" STREQUAL ".cpp")
67        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
68          COMPILE_FLAGS "${target_compile_flags}")
69      endif()
70      if("${suf}" STREQUAL ".c")
71        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
72          COMPILE_FLAGS "${target_compile_cflags}")
73      endif()
74    endforeach()
75  else()
76    # Update target props, since all sources are C++.
77    set_property(TARGET ${name} APPEND_STRING PROPERTY
78      COMPILE_FLAGS "${target_compile_flags}")
79  endif()
80
81  set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS ${LLVM_COMPILE_DEFINITIONS})
82endfunction()
83
84function(add_llvm_symbol_exports target_name export_file)
85  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
86    set(native_export_file "${target_name}.exports")
87    add_custom_command(OUTPUT ${native_export_file}
88      COMMAND sed -e "s/^/_/" < ${export_file} > ${native_export_file}
89      DEPENDS ${export_file}
90      VERBATIM
91      COMMENT "Creating export file for ${target_name}")
92    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
93                 LINK_FLAGS " -Wl,-exported_symbols_list,\"${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}\"")
94  elseif(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
95    # FIXME: `-Wl,-bE:` bypasses whatever handling there is in the build
96    # compiler driver to defer to the specified export list.
97    set(native_export_file "${export_file}")
98    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
99                 LINK_FLAGS " -Wl,-bE:${export_file}")
100  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT)
101    # Gold and BFD ld require a version script rather than a plain list.
102    set(native_export_file "${target_name}.exports")
103    # FIXME: Don't write the "local:" line on OpenBSD.
104    # in the export file, also add a linker script to version LLVM symbols (form: LLVM_N.M)
105    add_custom_command(OUTPUT ${native_export_file}
106      COMMAND echo "LLVM_${LLVM_VERSION_MAJOR} {" > ${native_export_file}
107      COMMAND grep -q "[[:alnum:]]" ${export_file} && echo "  global:" >> ${native_export_file} || :
108      COMMAND sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
109      COMMAND echo "  local: *;" >> ${native_export_file}
110      COMMAND echo "};" >> ${native_export_file}
111      DEPENDS ${export_file}
112      VERBATIM
113      COMMENT "Creating export file for ${target_name}")
114    if (${LLVM_LINKER_IS_SOLARISLD})
115      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
116                   LINK_FLAGS "  -Wl,-M,\"${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}\"")
117    else()
118      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
119                   LINK_FLAGS "  -Wl,--version-script,\"${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}\"")
120    endif()
121  else()
122    set(native_export_file "${target_name}.def")
123
124    add_custom_command(OUTPUT ${native_export_file}
125      COMMAND "${Python3_EXECUTABLE}" -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))"
126        < ${export_file} > ${native_export_file}
127      DEPENDS ${export_file}
128      VERBATIM
129      COMMENT "Creating export file for ${target_name}")
130    set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
131    if(MSVC)
132      set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"")
133    endif()
134    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
135                 LINK_FLAGS " ${export_file_linker_flag}")
136  endif()
137
138  add_custom_target(${target_name}_exports DEPENDS ${native_export_file})
139  set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc")
140
141  get_property(srcs TARGET ${target_name} PROPERTY SOURCES)
142  foreach(src ${srcs})
143    get_filename_component(extension ${src} EXT)
144    if(extension STREQUAL ".cpp")
145      set(first_source_file ${src})
146      break()
147    endif()
148  endforeach()
149
150  # Force re-linking when the exports file changes. Actually, it
151  # forces recompilation of the source file. The LINK_DEPENDS target
152  # property only works for makefile-based generators.
153  # FIXME: This is not safe because this will create the same target
154  # ${native_export_file} in several different file:
155  # - One where we emitted ${target_name}_exports
156  # - One where we emitted the build command for the following object.
157  # set_property(SOURCE ${first_source_file} APPEND PROPERTY
158  #   OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file})
159
160  set_property(DIRECTORY APPEND
161    PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file})
162
163  add_dependencies(${target_name} ${target_name}_exports)
164
165  # Add dependency to *_exports later -- CMake issue 14747
166  list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports)
167  set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
168endfunction(add_llvm_symbol_exports)
169
170if (NOT DEFINED LLVM_LINKER_DETECTED AND NOT WIN32)
171  # Detect what linker we have here.
172  if(APPLE)
173    # Linkers with ld64-compatible flags.
174    set(version_flag "-Wl,-v")
175  else()
176    # Linkers with BFD ld-compatible flags.
177    set(version_flag "-Wl,--version")
178  endif()
179
180  if(LLVM_USE_LINKER)
181    set(command ${CMAKE_C_COMPILER} -fuse-ld=${LLVM_USE_LINKER} ${version_flag})
182  else()
183    separate_arguments(flags UNIX_COMMAND "${CMAKE_EXE_LINKER_FLAGS}")
184    set(command ${CMAKE_C_COMPILER} ${flags} ${version_flag})
185  endif()
186  execute_process(
187    COMMAND ${command}
188    OUTPUT_VARIABLE stdout
189    ERROR_VARIABLE stderr
190    )
191
192  if(APPLE)
193    if("${stderr}" MATCHES "PROJECT:ld64")
194      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
195      set(LLVM_LINKER_IS_LD64 YES CACHE INTERNAL "")
196      message(STATUS "Linker detection: ld64")
197    elseif("${stderr}" MATCHES "^LLD" OR
198           "${stdout}" MATCHES "^LLD")
199      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
200      set(LLVM_LINKER_IS_LLD YES CACHE INTERNAL "")
201      message(STATUS "Linker detection: lld")
202    else()
203      set(LLVM_LINKER_DETECTED NO CACHE INTERNAL "")
204      message(STATUS "Linker detection: unknown")
205    endif()
206  else()
207    if("${stdout}" MATCHES "^mold")
208      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
209      message(STATUS "Linker detection: mold")
210    elseif("${stdout}" MATCHES "GNU gold")
211      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
212      set(LLVM_LINKER_IS_GOLD YES CACHE INTERNAL "")
213      message(STATUS "Linker detection: GNU Gold")
214    elseif("${stdout}" MATCHES "^LLD")
215      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
216      set(LLVM_LINKER_IS_LLD YES CACHE INTERNAL "")
217      message(STATUS "Linker detection: LLD")
218    elseif("${stdout}" MATCHES "GNU ld")
219      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
220      set(LLVM_LINKER_IS_GNULD YES CACHE INTERNAL "")
221      message(STATUS "Linker detection: GNU ld")
222    elseif("${stderr}" MATCHES "Solaris Link Editors" OR
223           "${stdout}" MATCHES "Solaris Link Editors")
224      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
225      set(LLVM_LINKER_IS_SOLARISLD YES CACHE INTERNAL "")
226      message(STATUS "Linker detection: Solaris ld")
227    else()
228      set(LLVM_LINKER_DETECTED NO CACHE INTERNAL "")
229      message(STATUS "Linker detection: unknown")
230    endif()
231  endif()
232endif()
233
234function(add_link_opts target_name)
235  get_llvm_distribution(${target_name} in_distribution in_distribution_var)
236  if(NOT in_distribution)
237    # Don't LTO optimize targets that aren't part of any distribution.
238    if (LLVM_ENABLE_LTO)
239      # We may consider avoiding LTO altogether by using -fembed-bitcode
240      # and teaching the linker to select machine code from .o files, see
241      # https://lists.llvm.org/pipermail/llvm-dev/2021-April/149843.html
242      if((UNIX OR MINGW) AND LINKER_IS_LLD)
243        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
244                      LINK_FLAGS " -Wl,--lto-O0")
245      elseif(LINKER_IS_LLD_LINK)
246        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
247                      LINK_FLAGS " /opt:lldlto=0")
248      elseif(APPLE AND NOT uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
249        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
250                      LINK_FLAGS " -Wl,-mllvm,-O0")
251      endif()
252    endif()
253  endif()
254
255  # Don't use linker optimizations in debug builds since it slows down the
256  # linker in a context where the optimizations are not important.
257  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
258    if(NOT LLVM_NO_DEAD_STRIP)
259      if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
260        # ld64's implementation of -dead_strip breaks tools that use plugins.
261        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
262                     LINK_FLAGS " -Wl,-dead_strip")
263      elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
264        # Support for ld -z discard-unused=sections was only added in
265        # Solaris 11.4.
266        include(LLVMCheckLinkerFlag)
267        llvm_check_linker_flag(CXX "-Wl,-z,discard-unused=sections" LINKER_SUPPORTS_Z_DISCARD_UNUSED)
268        if (LINKER_SUPPORTS_Z_DISCARD_UNUSED)
269          set_property(TARGET ${target_name} APPEND_STRING PROPERTY
270                       LINK_FLAGS " -Wl,-z,discard-unused=sections")
271        endif()
272      elseif(NOT MSVC AND NOT CMAKE_SYSTEM_NAME MATCHES "AIX|OS390")
273        # TODO Revisit this later on z/OS.
274        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
275                     LINK_FLAGS " -Wl,--gc-sections")
276      endif()
277    else() #LLVM_NO_DEAD_STRIP
278      if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
279        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
280                     LINK_FLAGS " -Wl,-bnogc")
281      endif()
282    endif()
283  endif()
284
285  if(ARG_SUPPORT_PLUGINS AND ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
286    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
287                 LINK_FLAGS " -Wl,-brtl")
288  endif()
289endfunction(add_link_opts)
290
291# Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}.
292# Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more,
293# or a certain builder, for eaxample, msbuild.exe, would be confused.
294function(set_output_directory target)
295  cmake_parse_arguments(ARG "" "BINARY_DIR;LIBRARY_DIR" "" ${ARGN})
296
297  # module_dir -- corresponding to LIBRARY_OUTPUT_DIRECTORY.
298  # It affects output of add_library(MODULE).
299  if(WIN32 OR CYGWIN)
300    # DLL platform
301    set(module_dir ${ARG_BINARY_DIR})
302  else()
303    set(module_dir ${ARG_LIBRARY_DIR})
304  endif()
305  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
306    foreach(build_mode ${CMAKE_CONFIGURATION_TYPES})
307      string(TOUPPER "${build_mode}" CONFIG_SUFFIX)
308      if(ARG_BINARY_DIR)
309        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${ARG_BINARY_DIR})
310        set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi})
311      endif()
312      if(ARG_LIBRARY_DIR)
313        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${ARG_LIBRARY_DIR})
314        set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li})
315      endif()
316      if(module_dir)
317        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${module_dir})
318        set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi})
319      endif()
320    endforeach()
321  else()
322    if(ARG_BINARY_DIR)
323      set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ARG_BINARY_DIR})
324    endif()
325    if(ARG_LIBRARY_DIR)
326      set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${ARG_LIBRARY_DIR})
327    endif()
328    if(module_dir)
329      set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${module_dir})
330    endif()
331  endif()
332endfunction()
333
334# If on Windows and building with MSVC, add the resource script containing the
335# VERSIONINFO data to the project.  This embeds version resource information
336# into the output .exe or .dll.
337# TODO: Enable for MinGW Windows builds too.
338#
339function(add_windows_version_resource_file OUT_VAR)
340  set(sources ${ARGN})
341  if (MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
342    set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc)
343    if(EXISTS ${resource_file})
344      set(sources ${sources} ${resource_file})
345      source_group("Resource Files" ${resource_file})
346      set(windows_resource_file ${resource_file} PARENT_SCOPE)
347    endif()
348  endif(MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
349
350  set(${OUT_VAR} ${sources} PARENT_SCOPE)
351endfunction(add_windows_version_resource_file)
352
353# set_windows_version_resource_properties(name resource_file...
354#   VERSION_MAJOR int
355#     Optional major version number (defaults to LLVM_VERSION_MAJOR)
356#   VERSION_MINOR int
357#     Optional minor version number (defaults to LLVM_VERSION_MINOR)
358#   VERSION_PATCHLEVEL int
359#     Optional patchlevel version number (defaults to LLVM_VERSION_PATCH)
360#   VERSION_STRING
361#     Optional version string (defaults to PACKAGE_VERSION)
362#   PRODUCT_NAME
363#     Optional product name string (defaults to "LLVM")
364#   )
365function(set_windows_version_resource_properties name resource_file)
366  cmake_parse_arguments(ARG
367    ""
368    "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME"
369    ""
370    ${ARGN})
371
372  if (NOT DEFINED ARG_VERSION_MAJOR)
373    set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
374  endif()
375
376  if (NOT DEFINED ARG_VERSION_MINOR)
377    set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR})
378  endif()
379
380  if (NOT DEFINED ARG_VERSION_PATCHLEVEL)
381    set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH})
382  endif()
383
384  if (NOT DEFINED ARG_VERSION_STRING)
385    set(ARG_VERSION_STRING ${PACKAGE_VERSION})
386  endif()
387
388  if (NOT DEFINED ARG_PRODUCT_NAME)
389    set(ARG_PRODUCT_NAME "LLVM")
390  endif()
391
392  set_property(SOURCE ${resource_file}
393               PROPERTY COMPILE_FLAGS /nologo)
394  set_property(SOURCE ${resource_file}
395               PROPERTY COMPILE_DEFINITIONS
396               "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}"
397               "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}"
398               "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}"
399               "RC_VERSION_FIELD_4=0"
400               "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\""
401               "RC_INTERNAL_NAME=\"${name}\""
402               "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\""
403               "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"")
404endfunction(set_windows_version_resource_properties)
405
406# llvm_add_library(name sources...
407#   SHARED;STATIC
408#     STATIC by default w/o BUILD_SHARED_LIBS.
409#     SHARED by default w/  BUILD_SHARED_LIBS.
410#   OBJECT
411#     Also create an OBJECT library target. Default if STATIC && SHARED.
412#   MODULE
413#     Target ${name} might not be created on unsupported platforms.
414#     Check with "if(TARGET ${name})".
415#   DISABLE_LLVM_LINK_LLVM_DYLIB
416#     Do not link this library to libLLVM, even if
417#     LLVM_LINK_LLVM_DYLIB is enabled.
418#   OUTPUT_NAME name
419#     Corresponds to OUTPUT_NAME in target properties.
420#   DEPENDS targets...
421#     Same semantics as add_dependencies().
422#   LINK_COMPONENTS components...
423#     Same as the variable LLVM_LINK_COMPONENTS.
424#   LINK_LIBS lib_targets...
425#     Same semantics as target_link_libraries().
426#   ADDITIONAL_HEADERS
427#     May specify header files for IDE generators.
428#   SONAME
429#     Should set SONAME link flags and create symlinks
430#   NO_INSTALL_RPATH
431#     Suppress default RPATH settings in shared libraries.
432#   PLUGIN_TOOL
433#     The tool (i.e. cmake target) that this plugin will link against
434#   COMPONENT_LIB
435#      This is used to specify that this is a component library of
436#      LLVM which means that the source resides in llvm/lib/ and it is a
437#      candidate for inclusion into libLLVM.so.
438#   )
439function(llvm_add_library name)
440  cmake_parse_arguments(ARG
441    "MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME;NO_INSTALL_RPATH;COMPONENT_LIB"
442    "OUTPUT_NAME;PLUGIN_TOOL;ENTITLEMENTS;BUNDLE_PATH"
443    "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
444    ${ARGN})
445  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
446  if(ARG_ADDITIONAL_HEADERS)
447    # Pass through ADDITIONAL_HEADERS.
448    set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS})
449  endif()
450  if(ARG_OBJLIBS)
451    set(ALL_FILES ${ARG_OBJLIBS})
452  else()
453    llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS})
454  endif()
455
456  if(ARG_MODULE)
457    if(ARG_SHARED OR ARG_STATIC)
458      message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
459    endif()
460    # Plugins that link against a tool are allowed even when plugins in general are not
461    if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
462      message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
463      return()
464    endif()
465  else()
466    if(ARG_PLUGIN_TOOL)
467      message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
468    endif()
469    if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
470      set(ARG_SHARED TRUE)
471    endif()
472    if(NOT ARG_SHARED)
473      set(ARG_STATIC TRUE)
474    endif()
475  endif()
476
477  # Generate objlib
478  if((ARG_SHARED AND ARG_STATIC) OR ARG_OBJECT)
479    # Generate an obj library for both targets.
480    set(obj_name "obj.${name}")
481    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
482      ${ALL_FILES}
483      )
484    llvm_update_compile_flags(${obj_name})
485    if(CMAKE_GENERATOR STREQUAL "Xcode")
486      set(DUMMY_FILE ${CMAKE_CURRENT_BINARY_DIR}/Dummy.c)
487      file(WRITE ${DUMMY_FILE} "// This file intentionally empty\n")
488      set_property(SOURCE ${DUMMY_FILE} APPEND_STRING PROPERTY COMPILE_FLAGS "-Wno-empty-translation-unit")
489    endif()
490    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>" ${DUMMY_FILE})
491
492    # Do add_dependencies(obj) later due to CMake issue 14747.
493    list(APPEND objlibs ${obj_name})
494
495    # Bring in the target include directories from our original target.
496    target_include_directories(${obj_name} PRIVATE $<TARGET_PROPERTY:${name},INCLUDE_DIRECTORIES>)
497
498    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
499    if(ARG_DEPENDS)
500      add_dependencies(${obj_name} ${ARG_DEPENDS})
501    endif()
502    # Treat link libraries like PUBLIC dependencies.  LINK_LIBS might
503    # result in generating header files.  Add a dependendency so that
504    # the generated header is created before this object library.
505    if(ARG_LINK_LIBS)
506      cmake_parse_arguments(LINK_LIBS_ARG
507        ""
508        ""
509        "PUBLIC;PRIVATE"
510        ${ARG_LINK_LIBS})
511      foreach(link_lib ${LINK_LIBS_ARG_PUBLIC})
512        if(LLVM_PTHREAD_LIB)
513          # Can't specify a dependence on -lpthread
514          if(NOT ${link_lib} STREQUAL ${LLVM_PTHREAD_LIB})
515            add_dependencies(${obj_name} ${link_lib})
516          endif()
517        else()
518          add_dependencies(${obj_name} ${link_lib})
519        endif()
520      endforeach()
521    endif()
522  endif()
523
524  if(ARG_SHARED AND ARG_STATIC)
525    # static
526    set(name_static "${name}_static")
527    if(ARG_OUTPUT_NAME)
528      set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}")
529    endif()
530    # DEPENDS has been appended to LLVM_COMMON_LIBS.
531    llvm_add_library(${name_static} STATIC
532      ${output_name}
533      OBJLIBS ${ALL_FILES} # objlib
534      LINK_LIBS ${ARG_LINK_LIBS}
535      LINK_COMPONENTS ${ARG_LINK_COMPONENTS}
536      )
537
538    # Bring in the target link info from our original target.
539    target_link_directories(${name_static} PRIVATE $<TARGET_PROPERTY:${name},LINK_DIRECTORIES>)
540    target_link_libraries(${name_static} PRIVATE $<TARGET_PROPERTY:${name},LINK_LIBRARIES>)
541
542    # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
543    set(ARG_STATIC)
544  endif()
545
546  if(ARG_MODULE)
547    add_library(${name} MODULE ${ALL_FILES})
548  elseif(ARG_SHARED)
549    add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
550    add_library(${name} SHARED ${ALL_FILES})
551  else()
552    add_library(${name} STATIC ${ALL_FILES})
553  endif()
554
555  if(ARG_COMPONENT_LIB)
556    set_target_properties(${name} PROPERTIES LLVM_COMPONENT TRUE)
557    set_property(GLOBAL APPEND PROPERTY LLVM_COMPONENT_LIBS ${name})
558  endif()
559
560  if(NOT ARG_NO_INSTALL_RPATH)
561    if(ARG_MODULE OR ARG_SHARED)
562      llvm_setup_rpath(${name})
563    endif()
564  endif()
565
566  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
567
568  if(DEFINED windows_resource_file)
569    set_windows_version_resource_properties(${name} ${windows_resource_file})
570    set(windows_resource_file ${windows_resource_file} PARENT_SCOPE)
571  endif()
572
573  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
574  # $<TARGET_OBJECTS> doesn't require compile flags.
575  if(NOT obj_name)
576    llvm_update_compile_flags(${name})
577  endif()
578  add_link_opts( ${name} )
579  if(ARG_OUTPUT_NAME)
580    set_target_properties(${name}
581      PROPERTIES
582      OUTPUT_NAME ${ARG_OUTPUT_NAME}
583      )
584  endif()
585
586  if(ARG_MODULE)
587    set_target_properties(${name} PROPERTIES
588      PREFIX ""
589      SUFFIX ${LLVM_PLUGIN_EXT}
590      )
591  endif()
592
593  if(ARG_SHARED)
594    if(MSVC)
595      set_target_properties(${name} PROPERTIES
596        PREFIX ""
597        )
598    endif()
599
600    # Set SOVERSION on shared libraries that lack explicit SONAME
601    # specifier, on *nix systems that are not Darwin.
602    if(UNIX AND NOT APPLE AND NOT ARG_SONAME)
603      set_target_properties(${name}
604        PROPERTIES
605        # Since 4.0.0, the ABI version is indicated by the major version
606        SOVERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX}
607        VERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
608    endif()
609  endif()
610
611  if(ARG_MODULE OR ARG_SHARED)
612    # Do not add -Dname_EXPORTS to the command-line when building files in this
613    # target. Doing so is actively harmful for the modules build because it
614    # creates extra module variants, and not useful because we don't use these
615    # macros.
616    set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
617
618    if (LLVM_EXPORTED_SYMBOL_FILE)
619      add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
620    endif()
621  endif()
622
623  if(ARG_SHARED)
624    if(NOT APPLE AND ARG_SONAME)
625      get_target_property(output_name ${name} OUTPUT_NAME)
626      if(${output_name} STREQUAL "output_name-NOTFOUND")
627        set(output_name ${name})
628      endif()
629      set(library_name ${output_name}-${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
630      set(api_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
631      set_target_properties(${name} PROPERTIES OUTPUT_NAME ${library_name})
632      if(UNIX)
633        llvm_install_library_symlink(${api_name} ${library_name} SHARED
634          COMPONENT ${name})
635        llvm_install_library_symlink(${output_name} ${library_name} SHARED
636          COMPONENT ${name})
637      endif()
638    endif()
639  endif()
640
641  if(ARG_STATIC)
642    set(libtype PUBLIC)
643  else()
644    # We can use PRIVATE since SO knows its dependent libs.
645    set(libtype PRIVATE)
646  endif()
647
648  if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
649    # On DLL platforms symbols are imported from the tool by linking against it.
650    set(llvm_libs ${ARG_PLUGIN_TOOL})
651  elseif (NOT ARG_COMPONENT_LIB)
652    if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
653      set(llvm_libs LLVM)
654    else()
655      llvm_map_components_to_libnames(llvm_libs
656       ${ARG_LINK_COMPONENTS}
657       ${LLVM_LINK_COMPONENTS}
658       )
659    endif()
660  else()
661    # Components have not been defined explicitly in CMake, so add the
662    # dependency information for this library through their name, and let
663    # LLVMBuildResolveComponentsLink resolve the mapping.
664    #
665    # It would be nice to verify that we have the dependencies for this library
666    # name, but using get_property(... SET) doesn't suffice to determine if a
667    # property has been set to an empty value.
668    set_property(TARGET ${name} PROPERTY LLVM_LINK_COMPONENTS ${ARG_LINK_COMPONENTS} ${LLVM_LINK_COMPONENTS})
669
670    # This property is an internal property only used to make sure the
671    # link step applied in LLVMBuildResolveComponentsLink uses the same
672    # property as the target_link_libraries call below.
673    set_property(TARGET ${name} PROPERTY LLVM_LIBTYPE ${libtype})
674  endif()
675
676  target_link_libraries(${name} ${libtype}
677      ${ARG_LINK_LIBS}
678      ${lib_deps}
679      ${llvm_libs}
680      )
681
682  if(LLVM_COMMON_DEPENDS)
683    add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
684    # Add dependencies also to objlibs.
685    # CMake issue 14747 --  add_dependencies() might be ignored to objlib's user.
686    foreach(objlib ${objlibs})
687      add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS})
688    endforeach()
689  endif()
690
691  if(ARG_SHARED OR ARG_MODULE)
692    llvm_externalize_debuginfo(${name})
693    llvm_codesign(${name} ENTITLEMENTS ${ARG_ENTITLEMENTS} BUNDLE_PATH ${ARG_BUNDLE_PATH})
694  endif()
695  # clang and newer versions of ninja use high-resolutions timestamps,
696  # but older versions of libtool on Darwin don't, so the archive will
697  # often get an older timestamp than the last object that was added
698  # or updated.  To fix this, we add a custom command to touch archive
699  # after it's been built so that ninja won't rebuild it unnecessarily
700  # the next time it's run.
701  if(ARG_STATIC AND LLVM_TOUCH_STATIC_LIBRARIES)
702    add_custom_command(TARGET ${name}
703      POST_BUILD
704      COMMAND touch ${LLVM_LIBRARY_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}${name}${CMAKE_STATIC_LIBRARY_SUFFIX}
705      )
706  endif()
707endfunction()
708
709function(add_llvm_install_targets target)
710  cmake_parse_arguments(ARG "" "COMPONENT;PREFIX;SYMLINK" "DEPENDS" ${ARGN})
711  if(ARG_COMPONENT)
712    set(component_option -DCMAKE_INSTALL_COMPONENT="${ARG_COMPONENT}")
713  endif()
714  if(ARG_PREFIX)
715    set(prefix_option -DCMAKE_INSTALL_PREFIX="${ARG_PREFIX}")
716  endif()
717
718  set(file_dependencies)
719  set(target_dependencies)
720  foreach(dependency ${ARG_DEPENDS})
721    if(TARGET ${dependency})
722      list(APPEND target_dependencies ${dependency})
723    else()
724      list(APPEND file_dependencies ${dependency})
725    endif()
726  endforeach()
727
728  add_custom_target(${target}
729                    DEPENDS ${file_dependencies}
730                    COMMAND "${CMAKE_COMMAND}"
731                            ${component_option}
732                            ${prefix_option}
733                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
734                    USES_TERMINAL)
735  set_target_properties(${target} PROPERTIES FOLDER "Component Install Targets")
736  add_custom_target(${target}-stripped
737                    DEPENDS ${file_dependencies}
738                    COMMAND "${CMAKE_COMMAND}"
739                            ${component_option}
740                            ${prefix_option}
741                            -DCMAKE_INSTALL_DO_STRIP=1
742                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
743                    USES_TERMINAL)
744  set_target_properties(${target}-stripped PROPERTIES FOLDER "Component Install Targets (Stripped)")
745  if(target_dependencies)
746    add_dependencies(${target} ${target_dependencies})
747    add_dependencies(${target}-stripped ${target_dependencies})
748  endif()
749
750  if(ARG_SYMLINK)
751    add_dependencies(${target} install-${ARG_SYMLINK})
752    add_dependencies(${target}-stripped install-${ARG_SYMLINK}-stripped)
753  endif()
754endfunction()
755
756# Define special targets that behave like a component group. They don't have any
757# source attached but other components can add themselves to them. If the
758# component supports is a Target and it supports JIT compilation, HAS_JIT must
759# be passed. One can use ADD_TO_COMPONENT option from add_llvm_component_library
760# to link extra component into an existing group.
761function(add_llvm_component_group name)
762  cmake_parse_arguments(ARG "HAS_JIT" "" "LINK_COMPONENTS" ${ARGN})
763  add_custom_target(${name})
764  if(ARG_HAS_JIT)
765    set_property(TARGET ${name} PROPERTY COMPONENT_HAS_JIT ON)
766  endif()
767  if(ARG_LINK_COMPONENTS)
768    set_property(TARGET ${name} PROPERTY LLVM_LINK_COMPONENTS ${ARG_LINK_COMPONENTS})
769  endif()
770endfunction()
771
772# An LLVM component is a cmake target with the following cmake properties
773# eventually set:
774#   - LLVM_COMPONENT_NAME: the name of the component, which can be the name of
775#     the associated library or the one specified through COMPONENT_NAME
776#   - LLVM_LINK_COMPONENTS: a list of component this component depends on
777#   - COMPONENT_HAS_JIT: (only for group component) whether this target group
778#     supports JIT compilation
779# Additionnaly, the ADD_TO_COMPONENT <component> option make it possible to add this
780# component to the LLVM_LINK_COMPONENTS of <component>.
781function(add_llvm_component_library name)
782  cmake_parse_arguments(ARG
783    ""
784    "COMPONENT_NAME;ADD_TO_COMPONENT"
785    ""
786    ${ARGN})
787  add_llvm_library(${name} COMPONENT_LIB ${ARG_UNPARSED_ARGUMENTS})
788  string(REGEX REPLACE "^LLVM" "" component_name ${name})
789  set_property(TARGET ${name} PROPERTY LLVM_COMPONENT_NAME ${component_name})
790
791  if(ARG_COMPONENT_NAME)
792    set_property(GLOBAL PROPERTY LLVM_COMPONENT_NAME_${ARG_COMPONENT_NAME} ${component_name})
793  endif()
794
795  if(ARG_ADD_TO_COMPONENT)
796    set_property(TARGET ${ARG_ADD_TO_COMPONENT} APPEND PROPERTY LLVM_LINK_COMPONENTS ${component_name})
797  endif()
798
799endfunction()
800
801macro(add_llvm_library name)
802  cmake_parse_arguments(ARG
803    "SHARED;BUILDTREE_ONLY;MODULE;INSTALL_WITH_TOOLCHAIN"
804    ""
805    ""
806    ${ARGN})
807  if(ARG_MODULE)
808    llvm_add_library(${name} MODULE ${ARG_UNPARSED_ARGUMENTS})
809  elseif( BUILD_SHARED_LIBS OR ARG_SHARED )
810    llvm_add_library(${name} SHARED ${ARG_UNPARSED_ARGUMENTS})
811  else()
812    llvm_add_library(${name} ${ARG_UNPARSED_ARGUMENTS})
813  endif()
814
815  # Libraries that are meant to only be exposed via the build tree only are
816  # never installed and are only exported as a target in the special build tree
817  # config file.
818  if (NOT ARG_BUILDTREE_ONLY AND NOT ARG_MODULE)
819    set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
820    set(in_llvm_libs YES)
821  endif()
822
823  if (ARG_MODULE AND NOT TARGET ${name})
824    # Add empty "phony" target
825    add_custom_target(${name})
826  elseif( EXCLUDE_FROM_ALL )
827    set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
828  elseif(ARG_BUILDTREE_ONLY)
829    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
830  else()
831    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ARG_INSTALL_WITH_TOOLCHAIN)
832      if(in_llvm_libs)
833        set(umbrella UMBRELLA llvm-libraries)
834      else()
835        set(umbrella)
836      endif()
837
838      get_target_export_arg(${name} LLVM export_to_llvmexports ${umbrella})
839      install(TARGETS ${name}
840              ${export_to_llvmexports}
841              LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX} COMPONENT ${name}
842              ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX} COMPONENT ${name}
843              RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" COMPONENT ${name})
844
845      if (NOT LLVM_ENABLE_IDE)
846        add_llvm_install_targets(install-${name}
847                                 DEPENDS ${name}
848                                 COMPONENT ${name})
849      endif()
850    endif()
851    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
852  endif()
853  if (ARG_MODULE)
854    set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
855  else()
856    set_target_properties(${name} PROPERTIES FOLDER "Libraries")
857  endif()
858endmacro(add_llvm_library name)
859
860macro(add_llvm_executable name)
861  cmake_parse_arguments(ARG
862    "DISABLE_LLVM_LINK_LLVM_DYLIB;IGNORE_EXTERNALIZE_DEBUGINFO;NO_INSTALL_RPATH;SUPPORT_PLUGINS"
863    "ENTITLEMENTS;BUNDLE_PATH"
864    "DEPENDS"
865    ${ARGN})
866
867  llvm_process_sources( ALL_FILES ${ARG_UNPARSED_ARGUMENTS} )
868
869  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
870
871  # Generate objlib
872  if(LLVM_ENABLE_OBJLIB)
873    # Generate an obj library for both targets.
874    set(obj_name "obj.${name}")
875    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
876      ${ALL_FILES}
877      )
878    llvm_update_compile_flags(${obj_name})
879    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
880    if(ARG_DEPENDS)
881      add_dependencies(${obj_name} ${ARG_DEPENDS})
882    endif()
883
884    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
885  endif()
886
887  add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
888
889  if(XCODE)
890    # Note: the dummy.cpp source file provides no definitions. However,
891    # it forces Xcode to properly link the static library.
892    list(APPEND ALL_FILES "${LLVM_MAIN_SRC_DIR}/cmake/dummy.cpp")
893  endif()
894
895  if( EXCLUDE_FROM_ALL )
896    add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
897  else()
898    add_executable(${name} ${ALL_FILES})
899  endif()
900
901  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
902
903  if(NOT ARG_NO_INSTALL_RPATH)
904    llvm_setup_rpath(${name})
905  elseif(NOT "${LLVM_LOCAL_RPATH}" STREQUAL "")
906    # Enable BUILD_WITH_INSTALL_RPATH unless CMAKE_BUILD_RPATH is set.
907    if("${CMAKE_BUILD_RPATH}" STREQUAL "")
908      set_property(TARGET ${name} PROPERTY BUILD_WITH_INSTALL_RPATH ON)
909    endif()
910
911    set_property(TARGET ${name} PROPERTY INSTALL_RPATH "${LLVM_LOCAL_RPATH}")
912  endif()
913
914  if(DEFINED windows_resource_file)
915    set_windows_version_resource_properties(${name} ${windows_resource_file})
916  endif()
917
918  # $<TARGET_OBJECTS> doesn't require compile flags.
919  if(NOT LLVM_ENABLE_OBJLIB)
920    llvm_update_compile_flags(${name})
921  endif()
922
923  if (ARG_SUPPORT_PLUGINS AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
924    set(LLVM_NO_DEAD_STRIP On)
925  endif()
926
927  add_link_opts( ${name} )
928
929  # Do not add -Dname_EXPORTS to the command-line when building files in this
930  # target. Doing so is actively harmful for the modules build because it
931  # creates extra module variants, and not useful because we don't use these
932  # macros.
933  set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
934
935  if (LLVM_EXPORTED_SYMBOL_FILE)
936    add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
937  endif(LLVM_EXPORTED_SYMBOL_FILE)
938
939  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
940    set(USE_SHARED USE_SHARED)
941  endif()
942
943  set(EXCLUDE_FROM_ALL OFF)
944  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
945  llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )
946  if( LLVM_COMMON_DEPENDS )
947    add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
948  endif( LLVM_COMMON_DEPENDS )
949
950  if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
951    llvm_externalize_debuginfo(${name})
952  endif()
953  if (LLVM_PTHREAD_LIB)
954    # libpthreads overrides some standard library symbols, so main
955    # executable must be linked with it in order to provide consistent
956    # API for all shared libaries loaded by this executable.
957    target_link_libraries(${name} PRIVATE ${LLVM_PTHREAD_LIB})
958  endif()
959
960  llvm_codesign(${name} ENTITLEMENTS ${ARG_ENTITLEMENTS} BUNDLE_PATH ${ARG_BUNDLE_PATH})
961endmacro(add_llvm_executable name)
962
963# add_llvm_pass_plugin(name [NO_MODULE] ...)
964#   Add ${name} as an llvm plugin.
965#   If option LLVM_${name_upper}_LINK_INTO_TOOLS is set to ON, the plugin is registered statically.
966#   Otherwise a pluggable shared library is registered.
967#
968#   If NO_MODULE is specified, when option LLVM_${name_upper}_LINK_INTO_TOOLS is set to OFF,
969#   only an object library is built, and no module is built. This is specific to the Polly use case.
970#
971#   The SUBPROJECT argument contains the LLVM project the plugin belongs
972#   to. If set, the plugin will link statically by default it if the
973#   project was enabled.
974function(add_llvm_pass_plugin name)
975  cmake_parse_arguments(ARG
976    "NO_MODULE" "SUBPROJECT" ""
977    ${ARGN})
978
979  string(TOUPPER ${name} name_upper)
980
981  # Enable the plugin by default if it was explicitly enabled by the user.
982  # Note: If was set to "all", LLVM's CMakeLists.txt replaces it with a
983  # list of all projects, counting as explicitly enabled.
984  set(link_into_tools_default OFF)
985  if (ARG_SUBPROJECT AND LLVM_TOOL_${name_upper}_BUILD)
986    set(link_into_tools_default ON)
987  endif()
988  option(LLVM_${name_upper}_LINK_INTO_TOOLS "Statically link ${name} into tools (if available)" ${link_into_tools_default})
989
990  # If we statically link the plugin, don't use llvm dylib because we're going
991  # to be part of it.
992  if(LLVM_${name_upper}_LINK_INTO_TOOLS)
993      list(APPEND ARG_UNPARSED_ARGUMENTS DISABLE_LLVM_LINK_LLVM_DYLIB)
994  endif()
995
996  if(LLVM_${name_upper}_LINK_INTO_TOOLS)
997    list(REMOVE_ITEM ARG_UNPARSED_ARGUMENTS BUILDTREE_ONLY)
998    # process_llvm_pass_plugins takes care of the actual linking, just create an
999    # object library as of now
1000    add_llvm_library(${name} OBJECT ${ARG_UNPARSED_ARGUMENTS})
1001    target_compile_definitions(${name} PRIVATE LLVM_${name_upper}_LINK_INTO_TOOLS)
1002    set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS LLVM_LINK_INTO_TOOLS)
1003    if (TARGET intrinsics_gen)
1004      add_dependencies(obj.${name} intrinsics_gen)
1005    endif()
1006    if (TARGET omp_gen)
1007      add_dependencies(obj.${name} omp_gen)
1008    endif()
1009    if (TARGET acc_gen)
1010      add_dependencies(obj.${name} acc_gen)
1011    endif()
1012    set_property(GLOBAL APPEND PROPERTY LLVM_STATIC_EXTENSIONS ${name})
1013  elseif(NOT ARG_NO_MODULE)
1014    add_llvm_library(${name} MODULE ${ARG_UNPARSED_ARGUMENTS})
1015  else()
1016    add_llvm_library(${name} OBJECT ${ARG_UNPARSED_ARGUMENTS})
1017  endif()
1018  message(STATUS "Registering ${name} as a pass plugin (static build: ${LLVM_${name_upper}_LINK_INTO_TOOLS})")
1019
1020endfunction(add_llvm_pass_plugin)
1021
1022# process_llvm_pass_plugins([GEN_CONFIG])
1023#
1024# Correctly set lib dependencies between plugins and tools, based on tools
1025# registered with the ENABLE_PLUGINS option.
1026#
1027# if GEN_CONFIG option is set, also generate X Macro file for extension
1028# handling. It provides a HANDLE_EXTENSION(extension_namespace, ExtensionProject)
1029# call for each extension allowing client code to define
1030# HANDLE_EXTENSION to have a specific code be run for each extension.
1031#
1032function(process_llvm_pass_plugins)
1033  cmake_parse_arguments(ARG
1034      "GEN_CONFIG" "" ""
1035    ${ARGN})
1036
1037  if(ARG_GEN_CONFIG)
1038      get_property(LLVM_STATIC_EXTENSIONS GLOBAL PROPERTY LLVM_STATIC_EXTENSIONS)
1039  else()
1040      include(LLVMConfigExtensions)
1041  endif()
1042
1043  # Add static plugins to the Extension component
1044  foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1045      set_property(TARGET LLVMExtensions APPEND PROPERTY LINK_LIBRARIES ${llvm_extension})
1046      set_property(TARGET LLVMExtensions APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${llvm_extension})
1047  endforeach()
1048
1049  # Eventually generate the extension headers, and store config to a cmake file
1050  # for usage in third-party configuration.
1051  if(ARG_GEN_CONFIG)
1052
1053      ## Part 1: Extension header to be included whenever we need extension
1054      #  processing.
1055      set(LLVM_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm)
1056      set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/${LLVM_INSTALL_PACKAGE_DIR}")
1057      file(WRITE
1058          "${llvm_cmake_builddir}/LLVMConfigExtensions.cmake"
1059          "set(LLVM_STATIC_EXTENSIONS ${LLVM_STATIC_EXTENSIONS})")
1060      install(FILES
1061          ${llvm_cmake_builddir}/LLVMConfigExtensions.cmake
1062          DESTINATION ${LLVM_INSTALL_PACKAGE_DIR}
1063          COMPONENT cmake-exports)
1064
1065      set(ExtensionDef "${LLVM_BINARY_DIR}/include/llvm/Support/Extension.def")
1066      file(WRITE "${ExtensionDef}.tmp" "//extension handlers\n")
1067      foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1068          file(APPEND "${ExtensionDef}.tmp" "HANDLE_EXTENSION(${llvm_extension})\n")
1069      endforeach()
1070      file(APPEND "${ExtensionDef}.tmp" "#undef HANDLE_EXTENSION\n")
1071
1072      # only replace if there's an actual change
1073      execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
1074          "${ExtensionDef}.tmp"
1075          "${ExtensionDef}")
1076      file(REMOVE "${ExtensionDef}.tmp")
1077
1078      ## Part 2: Extension header that captures each extension dependency, to be
1079      #  used by llvm-config.
1080      set(ExtensionDeps "${LLVM_BINARY_DIR}/tools/llvm-config/ExtensionDependencies.inc")
1081
1082      # Max needed to correctly size the required library array.
1083      set(llvm_plugin_max_deps_length 0)
1084      foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1085        get_property(llvm_plugin_deps TARGET ${llvm_extension} PROPERTY LINK_LIBRARIES)
1086        list(LENGTH llvm_plugin_deps llvm_plugin_deps_length)
1087        if(llvm_plugin_deps_length GREATER llvm_plugin_max_deps_length)
1088            set(llvm_plugin_max_deps_length ${llvm_plugin_deps_length})
1089        endif()
1090      endforeach()
1091
1092      list(LENGTH LLVM_STATIC_EXTENSIONS llvm_static_extension_count)
1093      file(WRITE
1094          "${ExtensionDeps}.tmp"
1095          "#include <array>\n\
1096           struct ExtensionDescriptor {\n\
1097              const char* Name;\n\
1098              const char* RequiredLibraries[1 + 1 + ${llvm_plugin_max_deps_length}];\n\
1099           };\n\
1100           std::array<ExtensionDescriptor, ${llvm_static_extension_count}> AvailableExtensions{\n")
1101
1102      foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1103        get_property(llvm_plugin_deps TARGET ${llvm_extension} PROPERTY LINK_LIBRARIES)
1104
1105        file(APPEND "${ExtensionDeps}.tmp" "ExtensionDescriptor{\"${llvm_extension}\", {")
1106        foreach(llvm_plugin_dep ${llvm_plugin_deps})
1107            # Turn library dependency back to component name, if possible.
1108            # That way llvm-config can avoid redundant dependencies.
1109            STRING(REGEX REPLACE "^-l" ""  plugin_dep_name ${llvm_plugin_dep})
1110            STRING(REGEX MATCH "^LLVM" is_llvm_library ${plugin_dep_name})
1111            if(is_llvm_library)
1112                STRING(REGEX REPLACE "^LLVM" ""  plugin_dep_name ${plugin_dep_name})
1113                STRING(TOLOWER ${plugin_dep_name} plugin_dep_name)
1114            endif()
1115            file(APPEND "${ExtensionDeps}.tmp" "\"${plugin_dep_name}\", ")
1116        endforeach()
1117
1118        # Self + mandatory trailing null, because the number of RequiredLibraries differs between extensions.
1119        file(APPEND "${ExtensionDeps}.tmp" \"${llvm_extension}\", "nullptr}},\n")
1120      endforeach()
1121      file(APPEND "${ExtensionDeps}.tmp" "};\n")
1122
1123      # only replace if there's an actual change
1124      execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
1125          "${ExtensionDeps}.tmp"
1126          "${ExtensionDeps}")
1127      file(REMOVE "${ExtensionDeps}.tmp")
1128  endif()
1129endfunction()
1130
1131function(export_executable_symbols target)
1132  if (LLVM_EXPORTED_SYMBOL_FILE)
1133    # The symbol file should contain the symbols we want the executable to
1134    # export
1135    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
1136  elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1137    # Extract the symbols to export from the static libraries that the
1138    # executable links against.
1139    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
1140    set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
1141    # We need to consider not just the direct link dependencies, but also the
1142    # transitive link dependencies. Do this by starting with the set of direct
1143    # dependencies, then the dependencies of those dependencies, and so on.
1144    get_target_property(new_libs ${target} LINK_LIBRARIES)
1145    set(link_libs ${new_libs})
1146    while(NOT "${new_libs}" STREQUAL "")
1147      foreach(lib ${new_libs})
1148        if(TARGET ${lib})
1149          get_target_property(lib_type ${lib} TYPE)
1150          if("${lib_type}" STREQUAL "STATIC_LIBRARY")
1151            list(APPEND static_libs ${lib})
1152          else()
1153            list(APPEND other_libs ${lib})
1154          endif()
1155          get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
1156          foreach(transitive_lib ${transitive_libs})
1157            list(FIND link_libs ${transitive_lib} idx)
1158            if(TARGET ${transitive_lib} AND idx EQUAL -1)
1159              list(APPEND newer_libs ${transitive_lib})
1160              list(APPEND link_libs ${transitive_lib})
1161            endif()
1162          endforeach(transitive_lib)
1163        endif()
1164      endforeach(lib)
1165      set(new_libs ${newer_libs})
1166      set(newer_libs "")
1167    endwhile()
1168    list(REMOVE_DUPLICATES static_libs)
1169    if (MSVC)
1170      set(mangling microsoft)
1171    else()
1172      set(mangling itanium)
1173    endif()
1174    add_custom_command(OUTPUT ${exported_symbol_file}
1175                       COMMAND "${Python3_EXECUTABLE}" ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${LLVM_EXTRACT_SYMBOLS_FLAGS} --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
1176                       WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
1177                       DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
1178                       VERBATIM
1179                       COMMENT "Generating export list for ${target}")
1180    add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
1181    # If something links against this executable then we want a
1182    # transitive link against only the libraries whose symbols
1183    # we aren't exporting.
1184    set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
1185    # The default import library suffix that cmake uses for cygwin/mingw is
1186    # ".dll.a", but for clang.exe that causes a collision with libclang.dll,
1187    # where the import libraries of both get named libclang.dll.a. Use a suffix
1188    # of ".exe.a" to avoid this.
1189    if(CYGWIN OR MINGW)
1190      set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
1191    endif()
1192  elseif(NOT (WIN32 OR CYGWIN))
1193    # On Windows auto-exporting everything doesn't work because of the limit on
1194    # the size of the exported symbol table, but on other platforms we can do
1195    # it without any trouble.
1196    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
1197    if (APPLE)
1198      set_property(TARGET ${target} APPEND_STRING PROPERTY
1199        LINK_FLAGS " -rdynamic")
1200    endif()
1201  endif()
1202endfunction()
1203
1204# Export symbols if LLVM plugins are enabled.
1205function(export_executable_symbols_for_plugins target)
1206  if(LLVM_ENABLE_PLUGINS OR LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1207    export_executable_symbols(${target})
1208  endif()
1209endfunction()
1210
1211if(NOT LLVM_TOOLCHAIN_TOOLS)
1212  set (LLVM_TOOLCHAIN_TOOLS
1213    llvm-ar
1214    llvm-cov
1215    llvm-cxxfilt
1216    llvm-dwp
1217    llvm-ranlib
1218    llvm-lib
1219    llvm-ml
1220    llvm-nm
1221    llvm-objcopy
1222    llvm-objdump
1223    llvm-pdbutil
1224    llvm-rc
1225    llvm-readobj
1226    llvm-size
1227    llvm-strings
1228    llvm-strip
1229    llvm-profdata
1230    llvm-symbolizer
1231    # symlink version of some of above tools that are enabled by
1232    # LLVM_INSTALL_BINUTILS_SYMLINKS.
1233    addr2line
1234    ar
1235    c++filt
1236    ranlib
1237    nm
1238    objcopy
1239    objdump
1240    readelf
1241    size
1242    strings
1243    strip
1244    )
1245endif()
1246
1247macro(add_llvm_tool name)
1248  if( NOT LLVM_BUILD_TOOLS )
1249    set(EXCLUDE_FROM_ALL ON)
1250  endif()
1251  add_llvm_executable(${name} ${ARGN})
1252
1253  if ( ${name} IN_LIST LLVM_TOOLCHAIN_TOOLS OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
1254    if( LLVM_BUILD_TOOLS )
1255      get_target_export_arg(${name} LLVM export_to_llvmexports)
1256      install(TARGETS ${name}
1257              ${export_to_llvmexports}
1258              RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR}
1259              COMPONENT ${name})
1260
1261      if (NOT LLVM_ENABLE_IDE)
1262        add_llvm_install_targets(install-${name}
1263                                 DEPENDS ${name}
1264                                 COMPONENT ${name})
1265      endif()
1266    endif()
1267  endif()
1268  if( LLVM_BUILD_TOOLS )
1269    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
1270  endif()
1271  set_target_properties(${name} PROPERTIES FOLDER "Tools")
1272endmacro(add_llvm_tool name)
1273
1274
1275macro(add_llvm_example name)
1276  if( NOT LLVM_BUILD_EXAMPLES )
1277    set(EXCLUDE_FROM_ALL ON)
1278  endif()
1279  add_llvm_executable(${name} ${ARGN})
1280  if( LLVM_BUILD_EXAMPLES )
1281    install(TARGETS ${name} RUNTIME DESTINATION "${LLVM_EXAMPLES_INSTALL_DIR}")
1282  endif()
1283  set_target_properties(${name} PROPERTIES FOLDER "Examples")
1284endmacro(add_llvm_example name)
1285
1286macro(add_llvm_example_library name)
1287  if( NOT LLVM_BUILD_EXAMPLES )
1288    set(EXCLUDE_FROM_ALL ON)
1289    add_llvm_library(${name} BUILDTREE_ONLY ${ARGN})
1290  else()
1291    add_llvm_library(${name} ${ARGN})
1292  endif()
1293
1294  set_target_properties(${name} PROPERTIES FOLDER "Examples")
1295endmacro(add_llvm_example_library name)
1296
1297# This is a macro that is used to create targets for executables that are needed
1298# for development, but that are not intended to be installed by default.
1299macro(add_llvm_utility name)
1300  if ( NOT LLVM_BUILD_UTILS )
1301    set(EXCLUDE_FROM_ALL ON)
1302  endif()
1303
1304  add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
1305  set_target_properties(${name} PROPERTIES FOLDER "Utils")
1306  if ( ${name} IN_LIST LLVM_TOOLCHAIN_UTILITIES OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
1307    if (LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS)
1308      get_target_export_arg(${name} LLVM export_to_llvmexports)
1309      install(TARGETS ${name}
1310              ${export_to_llvmexports}
1311              RUNTIME DESTINATION ${LLVM_UTILS_INSTALL_DIR}
1312              COMPONENT ${name})
1313
1314      if (NOT LLVM_ENABLE_IDE)
1315        add_llvm_install_targets(install-${name}
1316                                 DEPENDS ${name}
1317                                 COMPONENT ${name})
1318      endif()
1319      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
1320    elseif(LLVM_BUILD_UTILS)
1321      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
1322    endif()
1323  endif()
1324endmacro(add_llvm_utility name)
1325
1326macro(add_llvm_fuzzer name)
1327  cmake_parse_arguments(ARG "" "DUMMY_MAIN" "" ${ARGN})
1328  if( LLVM_LIB_FUZZING_ENGINE )
1329    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
1330    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
1331    target_link_libraries(${name} PRIVATE ${LLVM_LIB_FUZZING_ENGINE})
1332    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
1333  elseif( LLVM_USE_SANITIZE_COVERAGE )
1334    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=fuzzer")
1335    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
1336    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
1337    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
1338  elseif( ARG_DUMMY_MAIN )
1339    add_llvm_executable(${name} ${ARG_DUMMY_MAIN} ${ARG_UNPARSED_ARGUMENTS})
1340    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
1341  endif()
1342endmacro()
1343
1344macro(add_llvm_target target_name)
1345  include_directories(BEFORE
1346    ${CMAKE_CURRENT_BINARY_DIR}
1347    ${CMAKE_CURRENT_SOURCE_DIR})
1348  add_llvm_component_library(LLVM${target_name} ${ARGN})
1349  set( CURRENT_LLVM_TARGET LLVM${target_name} )
1350endmacro(add_llvm_target)
1351
1352function(canonicalize_tool_name name output)
1353  string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" nameStrip ${name})
1354  string(REPLACE "-" "_" nameUNDERSCORE ${nameStrip})
1355  string(TOUPPER ${nameUNDERSCORE} nameUPPER)
1356  set(${output} "${nameUPPER}" PARENT_SCOPE)
1357endfunction(canonicalize_tool_name)
1358
1359# Custom add_subdirectory wrapper
1360# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
1361# path if it differs from the name.
1362function(add_llvm_subdirectory project type name)
1363  set(add_llvm_external_dir "${ARGN}")
1364  if("${add_llvm_external_dir}" STREQUAL "")
1365    set(add_llvm_external_dir ${name})
1366  endif()
1367  canonicalize_tool_name(${name} nameUPPER)
1368  set(canonical_full_name ${project}_${type}_${nameUPPER})
1369  get_property(already_processed GLOBAL PROPERTY ${canonical_full_name}_PROCESSED)
1370  if(already_processed)
1371    return()
1372  endif()
1373  set_property(GLOBAL PROPERTY ${canonical_full_name}_PROCESSED YES)
1374
1375  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}/CMakeLists.txt)
1376    # Treat it as in-tree subproject.
1377    option(${canonical_full_name}_BUILD
1378           "Whether to build ${name} as part of ${project}" On)
1379    mark_as_advanced(${project}_${type}_${name}_BUILD)
1380    if(${canonical_full_name}_BUILD)
1381      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir} ${add_llvm_external_dir})
1382    endif()
1383  else()
1384    set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR
1385      "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}"
1386      CACHE PATH "Path to ${name} source directory")
1387    set(${canonical_full_name}_BUILD_DEFAULT ON)
1388    if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR OR NOT EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
1389      set(${canonical_full_name}_BUILD_DEFAULT OFF)
1390    endif()
1391    if("${LLVM_EXTERNAL_${nameUPPER}_BUILD}" STREQUAL "OFF")
1392      set(${canonical_full_name}_BUILD_DEFAULT OFF)
1393    endif()
1394    option(${canonical_full_name}_BUILD
1395      "Whether to build ${name} as part of LLVM"
1396      ${${canonical_full_name}_BUILD_DEFAULT})
1397    if (${canonical_full_name}_BUILD)
1398      if(EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
1399        add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir})
1400      elseif(NOT "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "")
1401        message(WARNING "Nonexistent directory for ${name}: ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}")
1402      endif()
1403    endif()
1404  endif()
1405endfunction()
1406
1407# Add external project that may want to be built as part of llvm such as Clang,
1408# lld, and Polly. This adds two options. One for the source directory of the
1409# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
1410# enable or disable building it with everything else.
1411# Additional parameter can be specified as the name of directory.
1412macro(add_llvm_external_project name)
1413  add_llvm_subdirectory(LLVM TOOL ${name} ${ARGN})
1414endmacro()
1415
1416macro(add_llvm_tool_subdirectory name)
1417  add_llvm_external_project(${name})
1418endmacro(add_llvm_tool_subdirectory)
1419
1420function(get_project_name_from_src_var var output)
1421  string(REGEX MATCH "LLVM_EXTERNAL_(.*)_SOURCE_DIR"
1422         MACHED_TOOL "${var}")
1423  if(MACHED_TOOL)
1424    set(${output} ${CMAKE_MATCH_1} PARENT_SCOPE)
1425  else()
1426    set(${output} PARENT_SCOPE)
1427  endif()
1428endfunction()
1429
1430function(create_subdirectory_options project type)
1431  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1432  foreach(dir ${sub-dirs})
1433    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1434      canonicalize_tool_name(${dir} name)
1435      option(${project}_${type}_${name}_BUILD
1436           "Whether to build ${name} as part of ${project}" On)
1437      mark_as_advanced(${project}_${type}_${name}_BUILD)
1438    endif()
1439  endforeach()
1440endfunction(create_subdirectory_options)
1441
1442function(create_llvm_tool_options)
1443  create_subdirectory_options(LLVM TOOL)
1444endfunction(create_llvm_tool_options)
1445
1446function(llvm_add_implicit_projects project)
1447  set(list_of_implicit_subdirs "")
1448  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1449  foreach(dir ${sub-dirs})
1450    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1451      canonicalize_tool_name(${dir} name)
1452      if (${project}_TOOL_${name}_BUILD)
1453        get_filename_component(fn "${dir}" NAME)
1454        list(APPEND list_of_implicit_subdirs "${fn}")
1455      endif()
1456    endif()
1457  endforeach()
1458
1459  foreach(external_proj ${list_of_implicit_subdirs})
1460    add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
1461  endforeach()
1462endfunction(llvm_add_implicit_projects)
1463
1464function(add_llvm_implicit_projects)
1465  llvm_add_implicit_projects(LLVM)
1466endfunction(add_llvm_implicit_projects)
1467
1468# Generic support for adding a unittest.
1469function(add_unittest test_suite test_name)
1470  if( NOT LLVM_BUILD_TESTS )
1471    set(EXCLUDE_FROM_ALL ON)
1472  endif()
1473
1474  if (SUPPORTS_VARIADIC_MACROS_FLAG)
1475    list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros")
1476  endif ()
1477  # Some parts of gtest rely on this GNU extension, don't warn on it.
1478  if(SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG)
1479    list(APPEND LLVM_COMPILE_FLAGS "-Wno-gnu-zero-variadic-macro-arguments")
1480  endif()
1481
1482  if (NOT DEFINED LLVM_REQUIRES_RTTI)
1483    set(LLVM_REQUIRES_RTTI OFF)
1484  endif()
1485
1486  list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
1487  add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO NO_INSTALL_RPATH ${ARGN})
1488
1489  # The runtime benefits of LTO don't outweight the compile time costs for tests.
1490  if(LLVM_ENABLE_LTO)
1491    if((UNIX OR MINGW) AND LINKER_IS_LLD)
1492      set_property(TARGET ${test_name} APPEND_STRING PROPERTY
1493                    LINK_FLAGS " -Wl,--lto-O0")
1494    elseif(LINKER_IS_LLD_LINK)
1495      set_property(TARGET ${test_name} APPEND_STRING PROPERTY
1496                    LINK_FLAGS " /opt:lldlto=0")
1497    elseif(APPLE AND NOT uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
1498      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
1499                    LINK_FLAGS " -Wl,-mllvm,-O0")
1500    endif()
1501  endif()
1502
1503  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
1504  set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
1505  # libpthreads overrides some standard library symbols, so main
1506  # executable must be linked with it in order to provide consistent
1507  # API for all shared libaries loaded by this executable.
1508  target_link_libraries(${test_name} PRIVATE llvm_gtest_main llvm_gtest ${LLVM_PTHREAD_LIB})
1509
1510  add_dependencies(${test_suite} ${test_name})
1511  get_target_property(test_suite_folder ${test_suite} FOLDER)
1512  if (test_suite_folder)
1513    set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
1514  endif ()
1515endfunction()
1516
1517# Use for test binaries that call llvm::getInputFileDirectory(). Use of this
1518# is discouraged.
1519function(add_unittest_with_input_files test_suite test_name)
1520  set(LLVM_UNITTEST_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
1521  configure_file(
1522    ${LLVM_MAIN_SRC_DIR}/unittests/unittest.cfg.in
1523    ${CMAKE_CURRENT_BINARY_DIR}/llvm.srcdir.txt)
1524
1525  add_unittest(${test_suite} ${test_name} ${ARGN})
1526endfunction()
1527
1528# Generic support for adding a benchmark.
1529function(add_benchmark benchmark_name)
1530  if( NOT LLVM_BUILD_BENCHMARKS )
1531    set(EXCLUDE_FROM_ALL ON)
1532  endif()
1533
1534  add_llvm_executable(${benchmark_name} IGNORE_EXTERNALIZE_DEBUGINFO NO_INSTALL_RPATH ${ARGN})
1535  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
1536  set_output_directory(${benchmark_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
1537  set_property(TARGET ${benchmark_name} PROPERTY FOLDER "Utils")
1538  target_link_libraries(${benchmark_name} PRIVATE benchmark)
1539endfunction()
1540
1541# This function canonicalize the CMake variables passed by names
1542# from CMake boolean to 0/1 suitable for passing into Python or C++,
1543# in place.
1544function(llvm_canonicalize_cmake_booleans)
1545  foreach(var ${ARGN})
1546    if(${var})
1547      set(${var} 1 PARENT_SCOPE)
1548    else()
1549      set(${var} 0 PARENT_SCOPE)
1550    endif()
1551  endforeach()
1552endfunction(llvm_canonicalize_cmake_booleans)
1553
1554macro(set_llvm_build_mode)
1555  # Configuration-time: See Unit/lit.site.cfg.in
1556  if (CMAKE_CFG_INTDIR STREQUAL ".")
1557    set(LLVM_BUILD_MODE ".")
1558  else ()
1559    set(LLVM_BUILD_MODE "%(build_mode)s")
1560  endif ()
1561endmacro()
1562
1563# Takes a list of path names in pathlist and a base directory, and returns
1564# a list of paths relative to the base directory in out_pathlist.
1565# Paths that are on a different drive than the basedir (on Windows) or that
1566# contain symlinks are returned absolute.
1567# Use with LLVM_LIT_PATH_FUNCTION below.
1568function(make_paths_relative out_pathlist basedir pathlist)
1569  # Passing ARG_PATH_VALUES as-is to execute_process() makes cmake strip
1570  # empty list entries. So escape the ;s in the list and do the splitting
1571  # ourselves. cmake has no relpath function, so use Python for that.
1572  string(REPLACE ";" "\\;" pathlist_escaped "${pathlist}")
1573  execute_process(COMMAND "${Python3_EXECUTABLE}" "-c" "\n
1574import os, sys\n
1575base = sys.argv[1]
1576def haslink(p):\n
1577    if not p or p == os.path.dirname(p): return False\n
1578    return os.path.islink(p) or haslink(os.path.dirname(p))\n
1579def relpath(p):\n
1580    if not p: return ''\n
1581    if os.path.splitdrive(p)[0] != os.path.splitdrive(base)[0]: return p\n
1582    if haslink(p) or haslink(base): return p\n
1583    return os.path.relpath(p, base)\n
1584if len(sys.argv) < 3: sys.exit(0)\n
1585sys.stdout.write(';'.join(relpath(p) for p in sys.argv[2].split(';')))"
1586    ${basedir}
1587    ${pathlist_escaped}
1588    OUTPUT_VARIABLE pathlist_relative
1589    ERROR_VARIABLE error
1590    RESULT_VARIABLE result)
1591  if (NOT result EQUAL 0)
1592    message(FATAL_ERROR "make_paths_relative() failed due to error '${result}', with stderr\n${error}")
1593  endif()
1594  set(${out_pathlist} "${pathlist_relative}" PARENT_SCOPE)
1595endfunction()
1596
1597# Converts a file that's relative to the current python file to an absolute
1598# path. Since this uses __file__, it has to be emitted into python files that
1599# use it and can't be in a lit module. Use with make_paths_relative().
1600string(CONCAT LLVM_LIT_PATH_FUNCTION
1601  "# Allow generated file to be relocatable.\n"
1602  "from pathlib import Path\n"
1603  "def path(p):\n"
1604  "    if not p: return ''\n"
1605  "    return str((Path(__file__).parent / p).resolve())\n"
1606  )
1607
1608# This function provides an automatic way to 'configure'-like generate a file
1609# based on a set of common and custom variables, specifically targeting the
1610# variables needed for the 'lit.site.cfg' files. This function bundles the
1611# common variables that any Lit instance is likely to need, and custom
1612# variables can be passed in.
1613# The keyword PATHS is followed by a list of cmake variable names that are
1614# mentioned as `path("@varname@")` in the lit.cfg.py.in file. Variables in that
1615# list are treated as paths that are relative to the directory the generated
1616# lit.cfg.py file is in, and the `path()` function converts the relative
1617# path back to absolute form. This makes it possible to move a build directory
1618# containing lit.cfg.py files from one machine to another.
1619function(configure_lit_site_cfg site_in site_out)
1620  cmake_parse_arguments(ARG "" "" "MAIN_CONFIG;PATHS" ${ARGN})
1621
1622  if ("${ARG_MAIN_CONFIG}" STREQUAL "")
1623    get_filename_component(INPUT_DIR ${site_in} DIRECTORY)
1624    set(ARG_MAIN_CONFIG "${INPUT_DIR}/lit.cfg")
1625  endif()
1626
1627  foreach(c ${LLVM_TARGETS_TO_BUILD})
1628    set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
1629  endforeach(c)
1630  set(TARGETS_TO_BUILD ${TARGETS_BUILT})
1631
1632  set(SHLIBEXT "${LTDL_SHLIB_EXT}")
1633
1634  set_llvm_build_mode()
1635
1636  # For standalone builds of subprojects, these might not be the build tree but
1637  # a provided binary tree.
1638  set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
1639  set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
1640  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}")
1641  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_LIBS_DIR  "${LLVM_LIBRARY_DIR}")
1642  # Like LLVM_{TOOLS,LIBS}_DIR, but pointing at the build tree.
1643  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" CURRENT_TOOLS_DIR "${LLVM_RUNTIME_OUTPUT_INTDIR}")
1644  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" CURRENT_LIBS_DIR  "${LLVM_LIBRARY_OUTPUT_INTDIR}")
1645  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}")
1646
1647  # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for
1648  # plugins. We may rename it.
1649  if(LLVM_ENABLE_PLUGINS)
1650    set(ENABLE_SHARED "1")
1651  else()
1652    set(ENABLE_SHARED "0")
1653  endif()
1654
1655  if(LLVM_ENABLE_ASSERTIONS)
1656    set(ENABLE_ASSERTIONS "1")
1657  else()
1658    set(ENABLE_ASSERTIONS "0")
1659  endif()
1660
1661  set(HOST_OS ${CMAKE_SYSTEM_NAME})
1662  set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR})
1663
1664  set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1665  set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1666  set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")
1667
1668  string(CONCAT LIT_SITE_CFG_IN_HEADER
1669    "# Autogenerated from ${site_in}\n# Do not edit!\n\n"
1670    "${LLVM_LIT_PATH_FUNCTION}"
1671    )
1672
1673  # Override config_target_triple (and the env)
1674  if(LLVM_TARGET_TRIPLE_ENV)
1675    # This is expanded into the heading.
1676    string(CONCAT LIT_SITE_CFG_IN_HEADER "${LIT_SITE_CFG_IN_HEADER}"
1677      "import os\n"
1678      "target_env = \"${LLVM_TARGET_TRIPLE_ENV}\"\n"
1679      "config.target_triple = config.environment[target_env] = os.environ.get(target_env, \"${LLVM_TARGET_TRIPLE}\")\n"
1680      )
1681
1682    # This is expanded to; config.target_triple = ""+config.target_triple+""
1683    set(LLVM_TARGET_TRIPLE "\"+config.target_triple+\"")
1684  endif()
1685
1686  if (ARG_PATHS)
1687    # Walk ARG_PATHS and collect the current value of the variables in there.
1688    # list(APPEND) ignores empty elements exactly if the list is empty,
1689    # so start the list with a dummy element and drop it, to make sure that
1690    # even empty values make it into the values list.
1691    set(ARG_PATH_VALUES "dummy")
1692    foreach(path ${ARG_PATHS})
1693      list(APPEND ARG_PATH_VALUES "${${path}}")
1694    endforeach()
1695    list(REMOVE_AT ARG_PATH_VALUES 0)
1696
1697    get_filename_component(OUTPUT_DIR ${site_out} DIRECTORY)
1698    make_paths_relative(
1699        ARG_PATH_VALUES_RELATIVE "${OUTPUT_DIR}" "${ARG_PATH_VALUES}")
1700
1701    list(LENGTH ARG_PATHS len_paths)
1702    list(LENGTH ARG_PATH_VALUES len_path_values)
1703    list(LENGTH ARG_PATH_VALUES_RELATIVE len_path_value_rels)
1704    if ((NOT ${len_paths} EQUAL ${len_path_values}) OR
1705        (NOT ${len_paths} EQUAL ${len_path_value_rels}))
1706      message(SEND_ERROR "PATHS lengths got confused")
1707    endif()
1708
1709    # Transform variables mentioned in ARG_PATHS to relative paths for
1710    # the configure_file() call. Variables are copied to subscopeds by cmake,
1711    # so this only modifies the local copy of the variables.
1712    math(EXPR arg_path_limit "${len_paths} - 1")
1713    foreach(i RANGE ${arg_path_limit})
1714      list(GET ARG_PATHS ${i} val1)
1715      list(GET ARG_PATH_VALUES_RELATIVE ${i} val2)
1716      set(${val1} ${val2})
1717    endforeach()
1718  endif()
1719
1720  configure_file(${site_in} ${site_out} @ONLY)
1721
1722  if (EXISTS "${ARG_MAIN_CONFIG}")
1723    # Remember main config / generated site config for llvm-lit.in.
1724    get_property(LLVM_LIT_CONFIG_FILES GLOBAL PROPERTY LLVM_LIT_CONFIG_FILES)
1725    list(APPEND LLVM_LIT_CONFIG_FILES "${ARG_MAIN_CONFIG}" "${site_out}")
1726    set_property(GLOBAL PROPERTY LLVM_LIT_CONFIG_FILES ${LLVM_LIT_CONFIG_FILES})
1727  endif()
1728endfunction()
1729
1730function(dump_all_cmake_variables)
1731  get_cmake_property(_variableNames VARIABLES)
1732  foreach (_variableName ${_variableNames})
1733    message(STATUS "${_variableName}=${${_variableName}}")
1734  endforeach()
1735endfunction()
1736
1737function(get_llvm_lit_path base_dir file_name)
1738  cmake_parse_arguments(ARG "ALLOW_EXTERNAL" "" "" ${ARGN})
1739
1740  if (ARG_ALLOW_EXTERNAL)
1741    set (LLVM_EXTERNAL_LIT "" CACHE STRING "Command used to spawn lit")
1742    if ("${LLVM_EXTERNAL_LIT}" STREQUAL "")
1743      set(LLVM_EXTERNAL_LIT "${LLVM_DEFAULT_EXTERNAL_LIT}")
1744    endif()
1745
1746    if (NOT "${LLVM_EXTERNAL_LIT}" STREQUAL "")
1747      if (EXISTS ${LLVM_EXTERNAL_LIT})
1748        get_filename_component(LIT_FILE_NAME ${LLVM_EXTERNAL_LIT} NAME)
1749        get_filename_component(LIT_BASE_DIR ${LLVM_EXTERNAL_LIT} DIRECTORY)
1750        set(${file_name} ${LIT_FILE_NAME} PARENT_SCOPE)
1751        set(${base_dir} ${LIT_BASE_DIR} PARENT_SCOPE)
1752        return()
1753      elseif (NOT DEFINED CACHE{LLVM_EXTERNAL_LIT_MISSING_WARNED_ONCE})
1754        message(WARNING "LLVM_EXTERNAL_LIT set to ${LLVM_EXTERNAL_LIT}, but the path does not exist.")
1755        set(LLVM_EXTERNAL_LIT_MISSING_WARNED_ONCE YES CACHE INTERNAL "")
1756      endif()
1757    endif()
1758  endif()
1759
1760  set(lit_file_name "llvm-lit")
1761  if (CMAKE_HOST_WIN32 AND NOT CYGWIN)
1762    # llvm-lit needs suffix.py for multiprocess to find a main module.
1763    set(lit_file_name "${lit_file_name}.py")
1764  endif ()
1765  set(${file_name} ${lit_file_name} PARENT_SCOPE)
1766
1767  get_property(LLVM_LIT_BASE_DIR GLOBAL PROPERTY LLVM_LIT_BASE_DIR)
1768  if (NOT "${LLVM_LIT_BASE_DIR}" STREQUAL "")
1769    set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1770  endif()
1771
1772  # Allow individual projects to provide an override
1773  if (NOT "${LLVM_LIT_OUTPUT_DIR}" STREQUAL "")
1774    set(LLVM_LIT_BASE_DIR ${LLVM_LIT_OUTPUT_DIR})
1775  elseif(NOT "${LLVM_RUNTIME_OUTPUT_INTDIR}" STREQUAL "")
1776    set(LLVM_LIT_BASE_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
1777  else()
1778    set(LLVM_LIT_BASE_DIR "")
1779  endif()
1780
1781  # Cache this so we don't have to do it again and have subsequent calls
1782  # potentially disagree on the value.
1783  set_property(GLOBAL PROPERTY LLVM_LIT_BASE_DIR ${LLVM_LIT_BASE_DIR})
1784  set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1785endfunction()
1786
1787# A raw function to create a lit target. This is used to implement the testuite
1788# management functions.
1789function(add_lit_target target comment)
1790  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1791  set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
1792  separate_arguments(LIT_ARGS)
1793  if (NOT CMAKE_CFG_INTDIR STREQUAL ".")
1794    list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR})
1795  endif ()
1796
1797  # Get the path to the lit to *run* tests with.  This can be overriden by
1798  # the user by specifying -DLLVM_EXTERNAL_LIT=<path-to-lit.py>
1799  get_llvm_lit_path(
1800    lit_base_dir
1801    lit_file_name
1802    ALLOW_EXTERNAL
1803    )
1804
1805  set(LIT_COMMAND "${Python3_EXECUTABLE};${lit_base_dir}/${lit_file_name}")
1806  list(APPEND LIT_COMMAND ${LIT_ARGS})
1807  foreach(param ${ARG_PARAMS})
1808    list(APPEND LIT_COMMAND --param ${param})
1809  endforeach()
1810  if (ARG_UNPARSED_ARGUMENTS)
1811    add_custom_target(${target}
1812      COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
1813      COMMENT "${comment}"
1814      USES_TERMINAL
1815      )
1816  else()
1817    add_custom_target(${target}
1818      COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.")
1819    message(STATUS "${target} does nothing.")
1820  endif()
1821
1822  if (ARG_DEPENDS)
1823    add_dependencies(${target} ${ARG_DEPENDS})
1824  endif()
1825
1826  # Tests should be excluded from "Build Solution".
1827  set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON)
1828endfunction()
1829
1830# Convert a target name like check-clang to a variable name like CLANG.
1831function(umbrella_lit_testsuite_var target outvar)
1832  if (NOT target MATCHES "^check-")
1833    message(FATAL_ERROR "umbrella lit suites must be check-*, not '${target}'")
1834  endif()
1835  string(SUBSTRING "${target}" 6 -1 var)
1836  string(REPLACE "-" "_" var ${var})
1837  string(TOUPPER "${var}" var)
1838  set(${outvar} "${var}" PARENT_SCOPE)
1839endfunction()
1840
1841# Start recording all lit test suites for a combined 'check-foo' target.
1842# The recording continues until umbrella_lit_testsuite_end() creates the target.
1843function(umbrella_lit_testsuite_begin target)
1844  umbrella_lit_testsuite_var(${target} name)
1845  set_property(GLOBAL APPEND PROPERTY LLVM_LIT_UMBRELLAS ${name})
1846endfunction()
1847
1848# Create a combined 'check-foo' target for a set of related test suites.
1849# It runs all suites added since the matching umbrella_lit_testsuite_end() call.
1850# Tests marked EXCLUDE_FROM_CHECK_ALL are not gathered.
1851function(umbrella_lit_testsuite_end target)
1852  umbrella_lit_testsuite_var(${target} name)
1853
1854  get_property(testsuites GLOBAL PROPERTY LLVM_${name}_LIT_TESTSUITES)
1855  get_property(params GLOBAL PROPERTY LLVM_${name}_LIT_PARAMS)
1856  get_property(depends GLOBAL PROPERTY LLVM_${name}_LIT_DEPENDS)
1857  get_property(extra_args GLOBAL PROPERTY LLVM_${name}_LIT_EXTRA_ARGS)
1858  # Additional test targets are not gathered, but may be set externally.
1859  get_property(additional_test_targets
1860               GLOBAL PROPERTY LLVM_${name}_ADDITIONAL_TEST_TARGETS)
1861
1862  string(TOLOWER ${name} name)
1863  add_lit_target(${target}
1864    "Running ${name} regression tests"
1865    ${testsuites}
1866    PARAMS ${params}
1867    DEPENDS ${depends} ${additional_test_targets}
1868    ARGS ${extra_args}
1869    )
1870endfunction()
1871
1872# A function to add a set of lit test suites to be driven through 'check-*' targets.
1873function(add_lit_testsuite target comment)
1874  cmake_parse_arguments(ARG "EXCLUDE_FROM_CHECK_ALL" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1875
1876  # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all.
1877  if(NOT ARG_EXCLUDE_FROM_CHECK_ALL)
1878    get_property(gather_names GLOBAL PROPERTY LLVM_LIT_UMBRELLAS)
1879    foreach(name ${gather_names})
1880    # Register the testsuites, params and depends for the umbrella check rule.
1881      set_property(GLOBAL APPEND PROPERTY LLVM_${name}_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS})
1882      set_property(GLOBAL APPEND PROPERTY LLVM_${name}_LIT_PARAMS ${ARG_PARAMS})
1883      set_property(GLOBAL APPEND PROPERTY LLVM_${name}_LIT_DEPENDS ${ARG_DEPENDS})
1884      set_property(GLOBAL APPEND PROPERTY LLVM_${name}_LIT_EXTRA_ARGS ${ARG_ARGS})
1885    endforeach()
1886  endif()
1887
1888  # Produce a specific suffixed check rule.
1889  add_lit_target(${target} ${comment}
1890    ${ARG_UNPARSED_ARGUMENTS}
1891    PARAMS ${ARG_PARAMS}
1892    DEPENDS ${ARG_DEPENDS}
1893    ARGS ${ARG_ARGS}
1894    )
1895endfunction()
1896
1897function(add_lit_testsuites project directory)
1898  if (NOT LLVM_ENABLE_IDE)
1899    cmake_parse_arguments(ARG "EXCLUDE_FROM_CHECK_ALL" "FOLDER" "PARAMS;DEPENDS;ARGS" ${ARGN})
1900
1901    if (NOT ARG_FOLDER)
1902      set(ARG_FOLDER "Test Subdirectories")
1903    endif()
1904
1905    # Search recursively for test directories by assuming anything not
1906    # in a directory called Inputs contains tests.
1907    file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*)
1908    foreach(lit_suite ${to_process})
1909      if(NOT IS_DIRECTORY ${lit_suite})
1910        continue()
1911      endif()
1912      string(FIND ${lit_suite} Inputs is_inputs)
1913      string(FIND ${lit_suite} Output is_output)
1914      if (NOT (is_inputs EQUAL -1 AND is_output EQUAL -1))
1915        continue()
1916      endif()
1917
1918      # Create a check- target for the directory.
1919      string(REPLACE ${directory} "" name_slash ${lit_suite})
1920      if (name_slash)
1921        string(REPLACE "/" "-" name_slash ${name_slash})
1922        string(REPLACE "\\" "-" name_dashes ${name_slash})
1923        string(TOLOWER "${project}${name_dashes}" name_var)
1924        add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}"
1925          ${lit_suite}
1926          ${EXCLUDE_FROM_CHECK_ALL}
1927          PARAMS ${ARG_PARAMS}
1928          DEPENDS ${ARG_DEPENDS}
1929          ARGS ${ARG_ARGS}
1930        )
1931        set_target_properties(check-${name_var} PROPERTIES FOLDER ${ARG_FOLDER})
1932      endif()
1933    endforeach()
1934  endif()
1935endfunction()
1936
1937function(llvm_install_library_symlink name dest type)
1938  cmake_parse_arguments(ARG "" "COMPONENT" "" ${ARGN})
1939  foreach(path ${CMAKE_MODULE_PATH})
1940    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1941      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1942      break()
1943    endif()
1944  endforeach()
1945
1946  set(component ${ARG_COMPONENT})
1947  if(NOT component)
1948    set(component ${name})
1949  endif()
1950
1951  set(full_name ${CMAKE_${type}_LIBRARY_PREFIX}${name}${CMAKE_${type}_LIBRARY_SUFFIX})
1952  set(full_dest ${CMAKE_${type}_LIBRARY_PREFIX}${dest}${CMAKE_${type}_LIBRARY_SUFFIX})
1953
1954  set(output_dir lib${LLVM_LIBDIR_SUFFIX})
1955  if(WIN32 AND "${type}" STREQUAL "SHARED")
1956    set(output_dir bin)
1957  endif()
1958
1959  install(SCRIPT ${INSTALL_SYMLINK}
1960          CODE "install_symlink(${full_name} ${full_dest} ${output_dir})"
1961          COMPONENT ${component})
1962
1963endfunction()
1964
1965function(llvm_install_symlink name dest)
1966  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1967  foreach(path ${CMAKE_MODULE_PATH})
1968    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1969      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1970      break()
1971    endif()
1972  endforeach()
1973
1974  if(ARG_COMPONENT)
1975    set(component ${ARG_COMPONENT})
1976  else()
1977    if(ARG_ALWAYS_GENERATE)
1978      set(component ${dest})
1979    else()
1980      set(component ${name})
1981    endif()
1982  endif()
1983
1984  set(full_name ${name}${CMAKE_EXECUTABLE_SUFFIX})
1985  set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})
1986
1987  install(SCRIPT ${INSTALL_SYMLINK}
1988          CODE "install_symlink(${full_name} ${full_dest} ${LLVM_TOOLS_INSTALL_DIR})"
1989          COMPONENT ${component})
1990
1991  if (NOT LLVM_ENABLE_IDE AND NOT ARG_ALWAYS_GENERATE)
1992    add_llvm_install_targets(install-${name}
1993                             DEPENDS ${name} ${dest}
1994                             COMPONENT ${name}
1995                             SYMLINK ${dest})
1996  endif()
1997endfunction()
1998
1999function(add_llvm_tool_symlink link_name target)
2000  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "OUTPUT_DIR" "" ${ARGN})
2001  set(dest_binary "$<TARGET_FILE:${target}>")
2002
2003  # This got a bit gross... For multi-configuration generators the target
2004  # properties return the resolved value of the string, not the build system
2005  # expression. To reconstruct the platform-agnostic path we have to do some
2006  # magic. First we grab one of the types, and a type-specific path. Then from
2007  # the type-specific path we find the last occurrence of the type in the path,
2008  # and replace it with CMAKE_CFG_INTDIR. This allows the build step to be type
2009  # agnostic again.
2010  if(NOT ARG_OUTPUT_DIR)
2011    # If you're not overriding the OUTPUT_DIR, we can make the link relative in
2012    # the same directory.
2013    if(CMAKE_HOST_UNIX)
2014      set(dest_binary "$<TARGET_FILE_NAME:${target}>")
2015    endif()
2016    if(CMAKE_CONFIGURATION_TYPES)
2017      list(GET CMAKE_CONFIGURATION_TYPES 0 first_type)
2018      string(TOUPPER ${first_type} first_type_upper)
2019      set(first_type_suffix _${first_type_upper})
2020    endif()
2021    get_target_property(target_type ${target} TYPE)
2022    if(${target_type} STREQUAL "STATIC_LIBRARY")
2023      get_target_property(ARG_OUTPUT_DIR ${target} ARCHIVE_OUTPUT_DIRECTORY${first_type_suffix})
2024    elseif(UNIX AND ${target_type} STREQUAL "SHARED_LIBRARY")
2025      get_target_property(ARG_OUTPUT_DIR ${target} LIBRARY_OUTPUT_DIRECTORY${first_type_suffix})
2026    else()
2027      get_target_property(ARG_OUTPUT_DIR ${target} RUNTIME_OUTPUT_DIRECTORY${first_type_suffix})
2028    endif()
2029    if(CMAKE_CONFIGURATION_TYPES)
2030      string(FIND "${ARG_OUTPUT_DIR}" "/${first_type}/" type_start REVERSE)
2031      string(SUBSTRING "${ARG_OUTPUT_DIR}" 0 ${type_start} path_prefix)
2032      string(SUBSTRING "${ARG_OUTPUT_DIR}" ${type_start} -1 path_suffix)
2033      string(REPLACE "/${first_type}/" "/${CMAKE_CFG_INTDIR}/"
2034             path_suffix ${path_suffix})
2035      set(ARG_OUTPUT_DIR ${path_prefix}${path_suffix})
2036    endif()
2037  endif()
2038
2039  if(CMAKE_HOST_UNIX)
2040    set(LLVM_LINK_OR_COPY create_symlink)
2041  else()
2042    set(LLVM_LINK_OR_COPY copy)
2043  endif()
2044
2045  set(output_path "${ARG_OUTPUT_DIR}/${link_name}${CMAKE_EXECUTABLE_SUFFIX}")
2046
2047  set(target_name ${link_name})
2048  if(TARGET ${link_name})
2049    set(target_name ${link_name}-link)
2050  endif()
2051
2052
2053  if(ARG_ALWAYS_GENERATE)
2054    set_property(DIRECTORY APPEND PROPERTY
2055      ADDITIONAL_MAKE_CLEAN_FILES ${dest_binary})
2056    add_custom_command(TARGET ${target} POST_BUILD
2057      COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}")
2058  else()
2059    add_custom_command(OUTPUT ${output_path}
2060                     COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}"
2061                     DEPENDS ${target})
2062    add_custom_target(${target_name} ALL DEPENDS ${target} ${output_path})
2063    set_target_properties(${target_name} PROPERTIES FOLDER Tools)
2064
2065    # Make sure both the link and target are toolchain tools
2066    if (${link_name} IN_LIST LLVM_TOOLCHAIN_TOOLS AND ${target} IN_LIST LLVM_TOOLCHAIN_TOOLS)
2067      set(TOOL_IS_TOOLCHAIN ON)
2068    endif()
2069
2070    if ((TOOL_IS_TOOLCHAIN OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY) AND LLVM_BUILD_TOOLS)
2071      llvm_install_symlink(${link_name} ${target})
2072    endif()
2073  endif()
2074endfunction()
2075
2076function(llvm_externalize_debuginfo name)
2077  if(NOT LLVM_EXTERNALIZE_DEBUGINFO)
2078    return()
2079  endif()
2080
2081  if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
2082    if(APPLE)
2083      if(NOT CMAKE_STRIP)
2084        set(CMAKE_STRIP xcrun strip)
2085      endif()
2086      set(strip_command COMMAND ${CMAKE_STRIP} -S -x $<TARGET_FILE:${name}>)
2087    else()
2088      set(strip_command COMMAND ${CMAKE_STRIP} -g -x $<TARGET_FILE:${name}>)
2089    endif()
2090  endif()
2091
2092  if(APPLE)
2093    if(LLVM_EXTERNALIZE_DEBUGINFO_EXTENSION)
2094      set(file_ext ${LLVM_EXTERNALIZE_DEBUGINFO_EXTENSION})
2095    else()
2096      set(file_ext dSYM)
2097    endif()
2098
2099    set(output_name "$<TARGET_FILE_NAME:${name}>.${file_ext}")
2100
2101    if(LLVM_EXTERNALIZE_DEBUGINFO_OUTPUT_DIR)
2102      set(output_path "-o=${LLVM_EXTERNALIZE_DEBUGINFO_OUTPUT_DIR}/${output_name}")
2103    else()
2104      set(output_path "-o=${output_name}")
2105    endif()
2106
2107    if(CMAKE_CXX_FLAGS MATCHES "-flto"
2108      OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
2109
2110      set(lto_object ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${name}-lto.o)
2111      set_property(TARGET ${name} APPEND_STRING PROPERTY
2112        LINK_FLAGS " -Wl,-object_path_lto,${lto_object}")
2113    endif()
2114    if(NOT CMAKE_DSYMUTIL)
2115      set(CMAKE_DSYMUTIL xcrun dsymutil)
2116    endif()
2117    add_custom_command(TARGET ${name} POST_BUILD
2118      COMMAND ${CMAKE_DSYMUTIL} ${output_path} $<TARGET_FILE:${name}>
2119      ${strip_command}
2120      )
2121  else()
2122    add_custom_command(TARGET ${name} POST_BUILD
2123      COMMAND ${CMAKE_OBJCOPY} --only-keep-debug $<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.debug
2124      ${strip_command} -R .gnu_debuglink
2125      COMMAND ${CMAKE_OBJCOPY} --add-gnu-debuglink=$<TARGET_FILE:${name}>.debug $<TARGET_FILE:${name}>
2126      )
2127  endif()
2128endfunction()
2129
2130# Usage: llvm_codesign(name [FORCE] [ENTITLEMENTS file] [BUNDLE_PATH path])
2131function(llvm_codesign name)
2132  cmake_parse_arguments(ARG "FORCE" "ENTITLEMENTS;BUNDLE_PATH" "" ${ARGN})
2133
2134  if(NOT LLVM_CODESIGNING_IDENTITY)
2135    return()
2136  endif()
2137
2138  if(CMAKE_GENERATOR STREQUAL "Xcode")
2139    set_target_properties(${name} PROPERTIES
2140      XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${LLVM_CODESIGNING_IDENTITY}
2141    )
2142    if(DEFINED ARG_ENTITLEMENTS)
2143      set_target_properties(${name} PROPERTIES
2144        XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS ${ARG_ENTITLEMENTS}
2145      )
2146    endif()
2147  elseif(APPLE AND CMAKE_HOST_SYSTEM_NAME MATCHES Darwin)
2148    if(NOT CMAKE_CODESIGN)
2149      set(CMAKE_CODESIGN xcrun codesign)
2150    endif()
2151    if(NOT CMAKE_CODESIGN_ALLOCATE)
2152      execute_process(
2153        COMMAND xcrun -f codesign_allocate
2154        OUTPUT_STRIP_TRAILING_WHITESPACE
2155        OUTPUT_VARIABLE CMAKE_CODESIGN_ALLOCATE
2156      )
2157    endif()
2158    if(DEFINED ARG_ENTITLEMENTS)
2159      set(pass_entitlements --entitlements ${ARG_ENTITLEMENTS})
2160    endif()
2161
2162    if (NOT ARG_BUNDLE_PATH)
2163      set(ARG_BUNDLE_PATH $<TARGET_FILE:${name}>)
2164    endif()
2165
2166    # ld64 now always codesigns the binaries it creates. Apply the force arg
2167    # unconditionally so that we can - for example - add entitlements to the
2168    # targets that need it.
2169    set(force_flag "-f")
2170
2171    add_custom_command(
2172      TARGET ${name} POST_BUILD
2173      COMMAND ${CMAKE_COMMAND} -E
2174              env CODESIGN_ALLOCATE=${CMAKE_CODESIGN_ALLOCATE}
2175              ${CMAKE_CODESIGN} -s ${LLVM_CODESIGNING_IDENTITY}
2176              ${pass_entitlements} ${force_flag} ${ARG_BUNDLE_PATH}
2177    )
2178  endif()
2179endfunction()
2180
2181function(llvm_setup_rpath name)
2182  if(CMAKE_INSTALL_RPATH)
2183    return()
2184  endif()
2185
2186  if(LLVM_INSTALL_PREFIX AND NOT (LLVM_INSTALL_PREFIX STREQUAL CMAKE_INSTALL_PREFIX))
2187    set(extra_libdir ${LLVM_LIBRARY_DIR})
2188  elseif(LLVM_BUILD_LIBRARY_DIR)
2189    set(extra_libdir ${LLVM_LIBRARY_DIR})
2190  endif()
2191
2192  if (APPLE)
2193    set(_install_name_dir INSTALL_NAME_DIR "@rpath")
2194    set(_install_rpath "@loader_path/../lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
2195  elseif(${CMAKE_SYSTEM_NAME} MATCHES "AIX" AND BUILD_SHARED_LIBS)
2196    # $ORIGIN is not interpreted at link time by aix ld.
2197    # Since BUILD_SHARED_LIBS is only recommended for use by developers,
2198    # hardcode the rpath to build/install lib dir first in this mode.
2199    # FIXME: update this when there is better solution.
2200    set(_install_rpath "${LLVM_LIBRARY_OUTPUT_INTDIR}" "${CMAKE_INSTALL_PREFIX}/lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
2201  elseif(UNIX)
2202    set(_install_rpath "\$ORIGIN/../lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
2203    if(${CMAKE_SYSTEM_NAME} MATCHES "(FreeBSD|DragonFly)")
2204      set_property(TARGET ${name} APPEND_STRING PROPERTY
2205                   LINK_FLAGS " -Wl,-z,origin ")
2206    endif()
2207    if(LLVM_LINKER_IS_GNULD)
2208      # $ORIGIN is not interpreted at link time by ld.bfd
2209      set_property(TARGET ${name} APPEND_STRING PROPERTY
2210                   LINK_FLAGS " -Wl,-rpath-link,${LLVM_LIBRARY_OUTPUT_INTDIR} ")
2211    endif()
2212  else()
2213    return()
2214  endif()
2215
2216  # Enable BUILD_WITH_INSTALL_RPATH unless CMAKE_BUILD_RPATH is set.
2217  if("${CMAKE_BUILD_RPATH}" STREQUAL "")
2218    set_property(TARGET ${name} PROPERTY BUILD_WITH_INSTALL_RPATH ON)
2219  endif()
2220
2221  set_target_properties(${name} PROPERTIES
2222                        INSTALL_RPATH "${_install_rpath}"
2223                        ${_install_name_dir})
2224endfunction()
2225
2226function(setup_dependency_debugging name)
2227  if(NOT LLVM_DEPENDENCY_DEBUGGING)
2228    return()
2229  endif()
2230
2231  if("intrinsics_gen" IN_LIST ARGN)
2232    return()
2233  endif()
2234
2235  set(deny_attributes_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Attributes.inc\"))")
2236  set(deny_intrinsics_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Intrinsics.inc\"))")
2237
2238  set(sandbox_command "sandbox-exec -p '(version 1) (allow default) ${deny_attributes_inc} ${deny_intrinsics_inc}'")
2239  set_target_properties(${name} PROPERTIES RULE_LAUNCH_COMPILE ${sandbox_command})
2240endfunction()
2241
2242# If the sources at the given `path` are under version control, set `out_var`
2243# to the the path of a file which will be modified when the VCS revision
2244# changes, attempting to create that file if it does not exist; if no such
2245# file exists and one cannot be created, instead set `out_var` to the
2246# empty string.
2247#
2248# If the sources are not under version control, do not define `out_var`.
2249function(find_first_existing_vc_file path out_var)
2250  if(NOT EXISTS "${path}")
2251    return()
2252  endif()
2253  find_package(Git)
2254  if(GIT_FOUND)
2255    execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir
2256      WORKING_DIRECTORY ${path}
2257      RESULT_VARIABLE git_result
2258      OUTPUT_VARIABLE git_output
2259      ERROR_QUIET)
2260    if(git_result EQUAL 0)
2261      string(STRIP "${git_output}" git_output)
2262      get_filename_component(git_dir ${git_output} ABSOLUTE BASE_DIR ${path})
2263      # Some branchless cases (e.g. 'repo') may not yet have .git/logs/HEAD
2264      if (NOT EXISTS "${git_dir}/logs/HEAD")
2265        execute_process(COMMAND ${CMAKE_COMMAND} -E touch HEAD
2266          WORKING_DIRECTORY "${git_dir}/logs"
2267          RESULT_VARIABLE touch_head_result
2268          ERROR_QUIET)
2269        if (NOT touch_head_result EQUAL 0)
2270          set(${out_var} "" PARENT_SCOPE)
2271          return()
2272        endif()
2273      endif()
2274      set(${out_var} "${git_dir}/logs/HEAD" PARENT_SCOPE)
2275    endif()
2276  endif()
2277endfunction()
2278