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