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