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