• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  # LLVM_REQUIRES_EH is an internal flag that individual targets can use to
12  # force EH
13  if(LLVM_REQUIRES_EH OR LLVM_ENABLE_EH)
14    if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
15      message(AUTHOR_WARNING "Exception handling requires RTTI. Enabling RTTI for ${name}")
16      set(LLVM_REQUIRES_RTTI ON)
17    endif()
18    if(MSVC)
19      list(APPEND LLVM_COMPILE_FLAGS "/EHsc")
20    endif()
21  else()
22    if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
23      list(APPEND LLVM_COMPILE_FLAGS "-fno-exceptions")
24    elseif(MSVC)
25      list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0)
26      list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-")
27    endif()
28  endif()
29
30  # LLVM_REQUIRES_RTTI is an internal flag that individual
31  # targets can use to force RTTI
32  set(LLVM_CONFIG_HAS_RTTI YES CACHE INTERNAL "")
33  if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
34    set(LLVM_CONFIG_HAS_RTTI NO CACHE INTERNAL "")
35    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_RTTI=0)
36    if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
37      list(APPEND LLVM_COMPILE_FLAGS "-fno-rtti")
38    elseif (MSVC)
39      list(APPEND LLVM_COMPILE_FLAGS "/GR-")
40    endif ()
41  elseif(MSVC)
42    list(APPEND LLVM_COMPILE_FLAGS "/GR")
43  endif()
44
45  # Assume that;
46  #   - LLVM_COMPILE_FLAGS is list.
47  #   - PROPERTY COMPILE_FLAGS is string.
48  string(REPLACE ";" " " target_compile_flags " ${LLVM_COMPILE_FLAGS}")
49
50  if(update_src_props)
51    foreach(fn ${sources})
52      get_filename_component(suf ${fn} EXT)
53      if("${suf}" STREQUAL ".cpp")
54        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
55          COMPILE_FLAGS "${target_compile_flags}")
56      endif()
57    endforeach()
58  else()
59    # Update target props, since all sources are C++.
60    set_property(TARGET ${name} APPEND_STRING PROPERTY
61      COMPILE_FLAGS "${target_compile_flags}")
62  endif()
63
64  set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS ${LLVM_COMPILE_DEFINITIONS})
65endfunction()
66
67function(add_llvm_symbol_exports target_name export_file)
68  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
69    set(native_export_file "${target_name}.exports")
70    add_custom_command(OUTPUT ${native_export_file}
71      COMMAND sed -e "s/^/_/" < ${export_file} > ${native_export_file}
72      DEPENDS ${export_file}
73      VERBATIM
74      COMMENT "Creating export file for ${target_name}")
75    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
76                 LINK_FLAGS " -Wl,-exported_symbols_list,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
77  elseif(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
78    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
79                 LINK_FLAGS " -Wl,-bE:${export_file}")
80  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT)
81    # Gold and BFD ld require a version script rather than a plain list.
82    set(native_export_file "${target_name}.exports")
83    # FIXME: Don't write the "local:" line on OpenBSD.
84    # in the export file, also add a linker script to version LLVM symbols (form: LLVM_N.M)
85    add_custom_command(OUTPUT ${native_export_file}
86      COMMAND echo "LLVM_${LLVM_VERSION_MAJOR} {" > ${native_export_file}
87      COMMAND grep -q "[[:alnum:]]" ${export_file} && echo "  global:" >> ${native_export_file} || :
88      COMMAND sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
89      COMMAND echo "  local: *;" >> ${native_export_file}
90      COMMAND echo "};" >> ${native_export_file}
91      DEPENDS ${export_file}
92      VERBATIM
93      COMMENT "Creating export file for ${target_name}")
94    if (${LLVM_LINKER_IS_SOLARISLD})
95      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
96                   LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
97    else()
98      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
99                   LINK_FLAGS "  -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
100    endif()
101  else()
102    set(native_export_file "${target_name}.def")
103
104    add_custom_command(OUTPUT ${native_export_file}
105      COMMAND ${PYTHON_EXECUTABLE} -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))"
106        < ${export_file} > ${native_export_file}
107      DEPENDS ${export_file}
108      VERBATIM
109      COMMENT "Creating export file for ${target_name}")
110    set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
111    if(MSVC)
112      set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"")
113    endif()
114    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
115                 LINK_FLAGS " ${export_file_linker_flag}")
116  endif()
117
118  add_custom_target(${target_name}_exports DEPENDS ${native_export_file})
119  set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc")
120
121  get_property(srcs TARGET ${target_name} PROPERTY SOURCES)
122  foreach(src ${srcs})
123    get_filename_component(extension ${src} EXT)
124    if(extension STREQUAL ".cpp")
125      set(first_source_file ${src})
126      break()
127    endif()
128  endforeach()
129
130  # Force re-linking when the exports file changes. Actually, it
131  # forces recompilation of the source file. The LINK_DEPENDS target
132  # property only works for makefile-based generators.
133  # FIXME: This is not safe because this will create the same target
134  # ${native_export_file} in several different file:
135  # - One where we emitted ${target_name}_exports
136  # - One where we emitted the build command for the following object.
137  # set_property(SOURCE ${first_source_file} APPEND PROPERTY
138  #   OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file})
139
140  set_property(DIRECTORY APPEND
141    PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file})
142
143  add_dependencies(${target_name} ${target_name}_exports)
144
145  # Add dependency to *_exports later -- CMake issue 14747
146  list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports)
147  set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
148endfunction(add_llvm_symbol_exports)
149
150if(APPLE)
151  execute_process(
152    COMMAND "${CMAKE_LINKER}" -v
153    ERROR_VARIABLE stderr
154    )
155  set(LLVM_LINKER_DETECTED YES)
156  if("${stderr}" MATCHES "PROJECT:ld64")
157    set(LLVM_LINKER_IS_LD64 YES)
158    message(STATUS "Linker detection: ld64")
159  else()
160    set(LLVM_LINKER_DETECTED NO)
161    message(STATUS "Linker detection: unknown")
162  endif()
163elseif(NOT WIN32)
164  # Detect what linker we have here
165  if( LLVM_USE_LINKER )
166    set(command ${CMAKE_C_COMPILER} -fuse-ld=${LLVM_USE_LINKER} -Wl,--version)
167  else()
168    separate_arguments(flags UNIX_COMMAND "${CMAKE_EXE_LINKER_FLAGS}")
169    set(command ${CMAKE_C_COMPILER} ${flags} -Wl,--version)
170  endif()
171  execute_process(
172    COMMAND ${command}
173    OUTPUT_VARIABLE stdout
174    ERROR_VARIABLE stderr
175    )
176  set(LLVM_LINKER_DETECTED YES)
177  if("${stdout}" MATCHES "GNU gold")
178    set(LLVM_LINKER_IS_GOLD YES)
179    message(STATUS "Linker detection: GNU Gold")
180  elseif("${stdout}" MATCHES "^LLD")
181    set(LLVM_LINKER_IS_LLD YES)
182    message(STATUS "Linker detection: LLD")
183  elseif("${stdout}" MATCHES "GNU ld")
184    set(LLVM_LINKER_IS_GNULD YES)
185    message(STATUS "Linker detection: GNU ld")
186  elseif("${stderr}" MATCHES "Solaris Link Editors" OR
187         "${stdout}" MATCHES "Solaris Link Editors")
188    set(LLVM_LINKER_IS_SOLARISLD YES)
189    message(STATUS "Linker detection: Solaris ld")
190  else()
191    set(LLVM_LINKER_DETECTED NO)
192    message(STATUS "Linker detection: unknown")
193  endif()
194endif()
195
196function(add_link_opts target_name)
197  # Don't use linker optimizations in debug builds since it slows down the
198  # linker in a context where the optimizations are not important.
199  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
200
201    # Pass -O3 to the linker. This enabled different optimizations on different
202    # linkers.
203    if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|SunOS|AIX" OR WIN32))
204      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
205                   LINK_FLAGS " -Wl,-O3")
206    endif()
207
208    if(LLVM_LINKER_IS_GOLD)
209      # With gold gc-sections is always safe.
210      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
211                   LINK_FLAGS " -Wl,--gc-sections")
212      # Note that there is a bug with -Wl,--icf=safe so it is not safe
213      # to enable. See https://sourceware.org/bugzilla/show_bug.cgi?id=17704.
214    endif()
215
216    if(NOT LLVM_NO_DEAD_STRIP)
217      if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
218        # ld64's implementation of -dead_strip breaks tools that use plugins.
219        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
220                     LINK_FLAGS " -Wl,-dead_strip")
221      elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
222        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
223                     LINK_FLAGS " -Wl,-z -Wl,discard-unused=sections")
224      elseif(NOT WIN32 AND NOT LLVM_LINKER_IS_GOLD AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
225        # Object files are compiled with -ffunction-data-sections.
226        # Versions of bfd ld < 2.23.1 have a bug in --gc-sections that breaks
227        # tools that use plugins. Always pass --gc-sections once we require
228        # a newer linker.
229        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
230                     LINK_FLAGS " -Wl,--gc-sections")
231      endif()
232    endif()
233  endif()
234endfunction(add_link_opts)
235
236# Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}.
237# Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more,
238# or a certain builder, for eaxample, msbuild.exe, would be confused.
239function(set_output_directory target)
240  cmake_parse_arguments(ARG "" "BINARY_DIR;LIBRARY_DIR" "" ${ARGN})
241
242  # module_dir -- corresponding to LIBRARY_OUTPUT_DIRECTORY.
243  # It affects output of add_library(MODULE).
244  if(WIN32 OR CYGWIN)
245    # DLL platform
246    set(module_dir ${ARG_BINARY_DIR})
247  else()
248    set(module_dir ${ARG_LIBRARY_DIR})
249  endif()
250  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
251    foreach(build_mode ${CMAKE_CONFIGURATION_TYPES})
252      string(TOUPPER "${build_mode}" CONFIG_SUFFIX)
253      if(ARG_BINARY_DIR)
254        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${ARG_BINARY_DIR})
255        set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi})
256      endif()
257      if(ARG_LIBRARY_DIR)
258        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${ARG_LIBRARY_DIR})
259        set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li})
260      endif()
261      if(module_dir)
262        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${module_dir})
263        set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi})
264      endif()
265    endforeach()
266  else()
267    if(ARG_BINARY_DIR)
268      set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ARG_BINARY_DIR})
269    endif()
270    if(ARG_LIBRARY_DIR)
271      set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${ARG_LIBRARY_DIR})
272    endif()
273    if(module_dir)
274      set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${module_dir})
275    endif()
276  endif()
277endfunction()
278
279# If on Windows and building with MSVC, add the resource script containing the
280# VERSIONINFO data to the project.  This embeds version resource information
281# into the output .exe or .dll.
282# TODO: Enable for MinGW Windows builds too.
283#
284function(add_windows_version_resource_file OUT_VAR)
285  set(sources ${ARGN})
286  if (MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
287    set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc)
288    if(EXISTS ${resource_file})
289      set(sources ${sources} ${resource_file})
290      source_group("Resource Files" ${resource_file})
291      set(windows_resource_file ${resource_file} PARENT_SCOPE)
292    endif()
293  endif(MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
294
295  set(${OUT_VAR} ${sources} PARENT_SCOPE)
296endfunction(add_windows_version_resource_file)
297
298# set_windows_version_resource_properties(name resource_file...
299#   VERSION_MAJOR int
300#     Optional major version number (defaults to LLVM_VERSION_MAJOR)
301#   VERSION_MINOR int
302#     Optional minor version number (defaults to LLVM_VERSION_MINOR)
303#   VERSION_PATCHLEVEL int
304#     Optional patchlevel version number (defaults to LLVM_VERSION_PATCH)
305#   VERSION_STRING
306#     Optional version string (defaults to PACKAGE_VERSION)
307#   PRODUCT_NAME
308#     Optional product name string (defaults to "LLVM")
309#   )
310function(set_windows_version_resource_properties name resource_file)
311  cmake_parse_arguments(ARG
312    ""
313    "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME"
314    ""
315    ${ARGN})
316
317  if (NOT DEFINED ARG_VERSION_MAJOR)
318    set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
319  endif()
320
321  if (NOT DEFINED ARG_VERSION_MINOR)
322    set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR})
323  endif()
324
325  if (NOT DEFINED ARG_VERSION_PATCHLEVEL)
326    set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH})
327  endif()
328
329  if (NOT DEFINED ARG_VERSION_STRING)
330    set(ARG_VERSION_STRING ${PACKAGE_VERSION})
331  endif()
332
333  if (NOT DEFINED ARG_PRODUCT_NAME)
334    set(ARG_PRODUCT_NAME "LLVM")
335  endif()
336
337  set_property(SOURCE ${resource_file}
338               PROPERTY COMPILE_FLAGS /nologo)
339  set_property(SOURCE ${resource_file}
340               PROPERTY COMPILE_DEFINITIONS
341               "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}"
342               "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}"
343               "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}"
344               "RC_VERSION_FIELD_4=0"
345               "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\""
346               "RC_INTERNAL_NAME=\"${name}\""
347               "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\""
348               "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"")
349endfunction(set_windows_version_resource_properties)
350
351# llvm_add_library(name sources...
352#   SHARED;STATIC
353#     STATIC by default w/o BUILD_SHARED_LIBS.
354#     SHARED by default w/  BUILD_SHARED_LIBS.
355#   OBJECT
356#     Also create an OBJECT library target. Default if STATIC && SHARED.
357#   MODULE
358#     Target ${name} might not be created on unsupported platforms.
359#     Check with "if(TARGET ${name})".
360#   DISABLE_LLVM_LINK_LLVM_DYLIB
361#     Do not link this library to libLLVM, even if
362#     LLVM_LINK_LLVM_DYLIB is enabled.
363#   OUTPUT_NAME name
364#     Corresponds to OUTPUT_NAME in target properties.
365#   DEPENDS targets...
366#     Same semantics as add_dependencies().
367#   LINK_COMPONENTS components...
368#     Same as the variable LLVM_LINK_COMPONENTS.
369#   LINK_LIBS lib_targets...
370#     Same semantics as target_link_libraries().
371#   ADDITIONAL_HEADERS
372#     May specify header files for IDE generators.
373#   SONAME
374#     Should set SONAME link flags and create symlinks
375#   PLUGIN_TOOL
376#     The tool (i.e. cmake target) that this plugin will link against
377#   )
378function(llvm_add_library name)
379  cmake_parse_arguments(ARG
380    "MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME"
381    "OUTPUT_NAME;PLUGIN_TOOL"
382    "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
383    ${ARGN})
384  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
385  if(ARG_ADDITIONAL_HEADERS)
386    # Pass through ADDITIONAL_HEADERS.
387    set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS})
388  endif()
389  if(ARG_OBJLIBS)
390    set(ALL_FILES ${ARG_OBJLIBS})
391  else()
392    llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS})
393  endif()
394
395  if(ARG_MODULE)
396    if(ARG_SHARED OR ARG_STATIC)
397      message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
398    endif()
399    # Plugins that link against a tool are allowed even when plugins in general are not
400    if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
401      message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
402      return()
403    endif()
404  else()
405    if(ARG_PLUGIN_TOOL)
406      message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
407    endif()
408    if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
409      set(ARG_SHARED TRUE)
410    endif()
411    if(NOT ARG_SHARED)
412      set(ARG_STATIC TRUE)
413    endif()
414  endif()
415
416  # Generate objlib
417  if((ARG_SHARED AND ARG_STATIC) OR ARG_OBJECT)
418    # Generate an obj library for both targets.
419    set(obj_name "obj.${name}")
420    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
421      ${ALL_FILES}
422      )
423    llvm_update_compile_flags(${obj_name})
424    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
425
426    # Do add_dependencies(obj) later due to CMake issue 14747.
427    list(APPEND objlibs ${obj_name})
428
429    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
430  endif()
431
432  if(ARG_SHARED AND ARG_STATIC)
433    # static
434    set(name_static "${name}_static")
435    if(ARG_OUTPUT_NAME)
436      set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}")
437    endif()
438    # DEPENDS has been appended to LLVM_COMMON_LIBS.
439    llvm_add_library(${name_static} STATIC
440      ${output_name}
441      OBJLIBS ${ALL_FILES} # objlib
442      LINK_LIBS ${ARG_LINK_LIBS}
443      LINK_COMPONENTS ${ARG_LINK_COMPONENTS}
444      )
445    # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
446    set(ARG_STATIC)
447  endif()
448
449  if(ARG_MODULE)
450    add_library(${name} MODULE ${ALL_FILES})
451    llvm_setup_rpath(${name})
452  elseif(ARG_SHARED)
453    add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
454    add_library(${name} SHARED ${ALL_FILES})
455
456    llvm_setup_rpath(${name})
457
458  else()
459    add_library(${name} STATIC ${ALL_FILES})
460  endif()
461
462  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
463
464  if(DEFINED windows_resource_file)
465    set_windows_version_resource_properties(${name} ${windows_resource_file})
466    set(windows_resource_file ${windows_resource_file} PARENT_SCOPE)
467  endif()
468
469  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
470  # $<TARGET_OBJECTS> doesn't require compile flags.
471  if(NOT obj_name)
472    llvm_update_compile_flags(${name})
473  endif()
474  add_link_opts( ${name} )
475  if(ARG_OUTPUT_NAME)
476    set_target_properties(${name}
477      PROPERTIES
478      OUTPUT_NAME ${ARG_OUTPUT_NAME}
479      )
480  endif()
481
482  if(ARG_MODULE)
483    set_target_properties(${name} PROPERTIES
484      PREFIX ""
485      SUFFIX ${LLVM_PLUGIN_EXT}
486      )
487  endif()
488
489  if(ARG_SHARED)
490    if(WIN32)
491      set_target_properties(${name} PROPERTIES
492        PREFIX ""
493        )
494    endif()
495
496    # Set SOVERSION on shared libraries that lack explicit SONAME
497    # specifier, on *nix systems that are not Darwin.
498    if(UNIX AND NOT APPLE AND NOT ARG_SONAME)
499      set_target_properties(${name}
500        PROPERTIES
501        # Since 4.0.0, the ABI version is indicated by the major version
502        SOVERSION ${LLVM_VERSION_MAJOR}
503        VERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
504    endif()
505  endif()
506
507  if(ARG_MODULE OR ARG_SHARED)
508    # Do not add -Dname_EXPORTS to the command-line when building files in this
509    # target. Doing so is actively harmful for the modules build because it
510    # creates extra module variants, and not useful because we don't use these
511    # macros.
512    set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
513
514    if (LLVM_EXPORTED_SYMBOL_FILE)
515      add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
516    endif()
517  endif()
518
519  if(ARG_SHARED AND UNIX)
520    if(NOT APPLE AND ARG_SONAME)
521      get_target_property(output_name ${name} OUTPUT_NAME)
522      if(${output_name} STREQUAL "output_name-NOTFOUND")
523        set(output_name ${name})
524      endif()
525      set(library_name ${output_name}-${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
526      set(api_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
527      set_target_properties(${name} PROPERTIES OUTPUT_NAME ${library_name})
528      llvm_install_library_symlink(${api_name} ${library_name} SHARED
529        COMPONENT ${name}
530        ALWAYS_GENERATE)
531      llvm_install_library_symlink(${output_name} ${library_name} SHARED
532        COMPONENT ${name}
533        ALWAYS_GENERATE)
534    endif()
535  endif()
536
537  if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
538    # On DLL platforms symbols are imported from the tool by linking against it.
539    set(llvm_libs ${ARG_PLUGIN_TOOL})
540  elseif (DEFINED LLVM_LINK_COMPONENTS OR DEFINED ARG_LINK_COMPONENTS)
541    if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
542      set(llvm_libs LLVM)
543    else()
544      llvm_map_components_to_libnames(llvm_libs
545       ${ARG_LINK_COMPONENTS}
546       ${LLVM_LINK_COMPONENTS}
547       )
548    endif()
549  else()
550    # Components have not been defined explicitly in CMake, so add the
551    # dependency information for this library as defined by LLVMBuild.
552    #
553    # It would be nice to verify that we have the dependencies for this library
554    # name, but using get_property(... SET) doesn't suffice to determine if a
555    # property has been set to an empty value.
556    get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
557  endif()
558
559  if(ARG_STATIC)
560    set(libtype INTERFACE)
561  else()
562    # We can use PRIVATE since SO knows its dependent libs.
563    set(libtype PRIVATE)
564  endif()
565
566  target_link_libraries(${name} ${libtype}
567      ${ARG_LINK_LIBS}
568      ${lib_deps}
569      ${llvm_libs}
570      )
571
572  if(LLVM_COMMON_DEPENDS)
573    add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
574    # Add dependencies also to objlibs.
575    # CMake issue 14747 --  add_dependencies() might be ignored to objlib's user.
576    foreach(objlib ${objlibs})
577      add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS})
578    endforeach()
579  endif()
580
581  if(ARG_SHARED OR ARG_MODULE)
582    llvm_externalize_debuginfo(${name})
583    llvm_codesign(${name})
584  endif()
585endfunction()
586
587function(add_llvm_install_targets target)
588  cmake_parse_arguments(ARG "" "COMPONENT;PREFIX" "DEPENDS" ${ARGN})
589  if(ARG_COMPONENT)
590    set(component_option -DCMAKE_INSTALL_COMPONENT="${ARG_COMPONENT}")
591  endif()
592  if(ARG_PREFIX)
593    set(prefix_option -DCMAKE_INSTALL_PREFIX="${ARG_PREFIX}")
594  endif()
595
596  add_custom_target(${target}
597                    DEPENDS ${ARG_DEPENDS}
598                    COMMAND "${CMAKE_COMMAND}"
599                            ${component_option}
600                            ${prefix_option}
601                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
602                    USES_TERMINAL)
603  add_custom_target(${target}-stripped
604                    DEPENDS ${ARG_DEPENDS}
605                    COMMAND "${CMAKE_COMMAND}"
606                            ${component_option}
607                            ${prefix_option}
608                            -DCMAKE_INSTALL_DO_STRIP=1
609                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
610                    USES_TERMINAL)
611endfunction()
612
613macro(add_llvm_library name)
614  cmake_parse_arguments(ARG
615    "SHARED;BUILDTREE_ONLY"
616    ""
617    ""
618    ${ARGN})
619  if( BUILD_SHARED_LIBS OR ARG_SHARED )
620    llvm_add_library(${name} SHARED ${ARG_UNPARSED_ARGUMENTS})
621  else()
622    llvm_add_library(${name} ${ARG_UNPARSED_ARGUMENTS})
623  endif()
624
625  # Libraries that are meant to only be exposed via the build tree only are
626  # never installed and are only exported as a target in the special build tree
627  # config file.
628  if (NOT ARG_BUILDTREE_ONLY)
629    set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
630  endif()
631
632  if( EXCLUDE_FROM_ALL )
633    set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
634  elseif(ARG_BUILDTREE_ONLY)
635    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
636  else()
637    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "LTO" OR
638        (LLVM_LINK_LLVM_DYLIB AND ${name} STREQUAL "LLVM"))
639      set(install_dir lib${LLVM_LIBDIR_SUFFIX})
640      if(ARG_SHARED OR BUILD_SHARED_LIBS)
641        if(WIN32 OR CYGWIN OR MINGW)
642          set(install_type RUNTIME)
643          set(install_dir bin)
644        else()
645          set(install_type LIBRARY)
646        endif()
647      else()
648        set(install_type ARCHIVE)
649      endif()
650
651      if(${name} IN_LIST LLVM_DISTRIBUTION_COMPONENTS OR
652          NOT LLVM_DISTRIBUTION_COMPONENTS)
653        set(export_to_llvmexports EXPORT LLVMExports)
654        set_property(GLOBAL PROPERTY LLVM_HAS_EXPORTS True)
655      endif()
656
657      install(TARGETS ${name}
658              ${export_to_llvmexports}
659              ${install_type} DESTINATION ${install_dir}
660              COMPONENT ${name})
661
662      if (NOT CMAKE_CONFIGURATION_TYPES)
663        add_llvm_install_targets(install-${name}
664                                 DEPENDS ${name}
665                                 COMPONENT ${name})
666      endif()
667    endif()
668    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
669  endif()
670  set_target_properties(${name} PROPERTIES FOLDER "Libraries")
671endmacro(add_llvm_library name)
672
673macro(add_llvm_loadable_module name)
674  llvm_add_library(${name} MODULE ${ARGN})
675  if(NOT TARGET ${name})
676    # Add empty "phony" target
677    add_custom_target(${name})
678  else()
679    if( EXCLUDE_FROM_ALL )
680      set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
681    else()
682      if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
683        if(WIN32 OR CYGWIN)
684          # DLL platform
685          set(dlldir "bin")
686        else()
687          set(dlldir "lib${LLVM_LIBDIR_SUFFIX}")
688        endif()
689
690        if(${name} IN_LIST LLVM_DISTRIBUTION_COMPONENTS OR
691            NOT LLVM_DISTRIBUTION_COMPONENTS)
692          set(export_to_llvmexports EXPORT LLVMExports)
693          set_property(GLOBAL PROPERTY LLVM_HAS_EXPORTS True)
694        endif()
695
696        install(TARGETS ${name}
697                ${export_to_llvmexports}
698                LIBRARY DESTINATION ${dlldir}
699                ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
700      endif()
701      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
702    endif()
703  endif()
704
705  set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
706endmacro(add_llvm_loadable_module name)
707
708
709macro(add_llvm_executable name)
710  cmake_parse_arguments(ARG "DISABLE_LLVM_LINK_LLVM_DYLIB;IGNORE_EXTERNALIZE_DEBUGINFO;NO_INSTALL_RPATH" "" "DEPENDS" ${ARGN})
711  llvm_process_sources( ALL_FILES ${ARG_UNPARSED_ARGUMENTS} )
712
713  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
714
715  # Generate objlib
716  if(LLVM_ENABLE_OBJLIB)
717    # Generate an obj library for both targets.
718    set(obj_name "obj.${name}")
719    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
720      ${ALL_FILES}
721      )
722    llvm_update_compile_flags(${obj_name})
723    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
724
725    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
726  endif()
727
728  add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
729
730  if(XCODE)
731    # Note: the dummy.cpp source file provides no definitions. However,
732    # it forces Xcode to properly link the static library.
733    list(APPEND ALL_FILES "${LLVM_MAIN_SRC_DIR}/cmake/dummy.cpp")
734  endif()
735
736  if( EXCLUDE_FROM_ALL )
737    add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
738  else()
739    add_executable(${name} ${ALL_FILES})
740  endif()
741
742  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
743
744  if(NOT ARG_NO_INSTALL_RPATH)
745    llvm_setup_rpath(${name})
746  endif()
747
748  if(DEFINED windows_resource_file)
749    set_windows_version_resource_properties(${name} ${windows_resource_file})
750  endif()
751
752  # $<TARGET_OBJECTS> doesn't require compile flags.
753  if(NOT LLVM_ENABLE_OBJLIB)
754    llvm_update_compile_flags(${name})
755  endif()
756  add_link_opts( ${name} )
757
758  # Do not add -Dname_EXPORTS to the command-line when building files in this
759  # target. Doing so is actively harmful for the modules build because it
760  # creates extra module variants, and not useful because we don't use these
761  # macros.
762  set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
763
764  if (LLVM_EXPORTED_SYMBOL_FILE)
765    add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
766  endif(LLVM_EXPORTED_SYMBOL_FILE)
767
768  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
769    set(USE_SHARED USE_SHARED)
770  endif()
771
772  set(EXCLUDE_FROM_ALL OFF)
773  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
774  llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )
775  if( LLVM_COMMON_DEPENDS )
776    add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
777  endif( LLVM_COMMON_DEPENDS )
778
779  if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
780    llvm_externalize_debuginfo(${name})
781  endif()
782  if (LLVM_PTHREAD_LIB)
783    # libpthreads overrides some standard library symbols, so main
784    # executable must be linked with it in order to provide consistent
785    # API for all shared libaries loaded by this executable.
786    target_link_libraries(${name} PRIVATE ${LLVM_PTHREAD_LIB})
787  endif()
788
789  llvm_codesign(${name})
790endmacro(add_llvm_executable name)
791
792function(export_executable_symbols target)
793  if (LLVM_EXPORTED_SYMBOL_FILE)
794    # The symbol file should contain the symbols we want the executable to
795    # export
796    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
797  elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
798    # Extract the symbols to export from the static libraries that the
799    # executable links against.
800    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
801    set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
802    # We need to consider not just the direct link dependencies, but also the
803    # transitive link dependencies. Do this by starting with the set of direct
804    # dependencies, then the dependencies of those dependencies, and so on.
805    get_target_property(new_libs ${target} LINK_LIBRARIES)
806    set(link_libs ${new_libs})
807    while(NOT "${new_libs}" STREQUAL "")
808      foreach(lib ${new_libs})
809        if(TARGET ${lib})
810          get_target_property(lib_type ${lib} TYPE)
811          if("${lib_type}" STREQUAL "STATIC_LIBRARY")
812            list(APPEND static_libs ${lib})
813          else()
814            list(APPEND other_libs ${lib})
815          endif()
816          get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
817          foreach(transitive_lib ${transitive_libs})
818            list(FIND link_libs ${transitive_lib} idx)
819            if(TARGET ${transitive_lib} AND idx EQUAL -1)
820              list(APPEND newer_libs ${transitive_lib})
821              list(APPEND link_libs ${transitive_lib})
822            endif()
823          endforeach(transitive_lib)
824        endif()
825      endforeach(lib)
826      set(new_libs ${newer_libs})
827      set(newer_libs "")
828    endwhile()
829    if (MSVC)
830      set(mangling microsoft)
831    else()
832      set(mangling itanium)
833    endif()
834    add_custom_command(OUTPUT ${exported_symbol_file}
835                       COMMAND ${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
836                       WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
837                       DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
838                       VERBATIM
839                       COMMENT "Generating export list for ${target}")
840    add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
841    # If something links against this executable then we want a
842    # transitive link against only the libraries whose symbols
843    # we aren't exporting.
844    set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
845    # The default import library suffix that cmake uses for cygwin/mingw is
846    # ".dll.a", but for clang.exe that causes a collision with libclang.dll,
847    # where the import libraries of both get named libclang.dll.a. Use a suffix
848    # of ".exe.a" to avoid this.
849    if(CYGWIN OR MINGW)
850      set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
851    endif()
852  elseif(NOT (WIN32 OR CYGWIN))
853    # On Windows auto-exporting everything doesn't work because of the limit on
854    # the size of the exported symbol table, but on other platforms we can do
855    # it without any trouble.
856    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
857    if (APPLE)
858      set_property(TARGET ${target} APPEND_STRING PROPERTY
859        LINK_FLAGS " -rdynamic")
860    endif()
861  endif()
862endfunction()
863
864if(NOT LLVM_TOOLCHAIN_TOOLS)
865  set (LLVM_TOOLCHAIN_TOOLS
866    llvm-ar
867    llvm-ranlib
868    llvm-lib
869    llvm-objdump
870    llvm-rc
871    )
872endif()
873
874macro(add_llvm_tool name)
875  if( NOT LLVM_BUILD_TOOLS )
876    set(EXCLUDE_FROM_ALL ON)
877  endif()
878  add_llvm_executable(${name} ${ARGN})
879
880  if ( ${name} IN_LIST LLVM_TOOLCHAIN_TOOLS OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
881    if( LLVM_BUILD_TOOLS )
882      if(${name} IN_LIST LLVM_DISTRIBUTION_COMPONENTS OR
883          NOT LLVM_DISTRIBUTION_COMPONENTS)
884        set(export_to_llvmexports EXPORT LLVMExports)
885        set_property(GLOBAL PROPERTY LLVM_HAS_EXPORTS True)
886      endif()
887
888      install(TARGETS ${name}
889              ${export_to_llvmexports}
890              RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR}
891              COMPONENT ${name})
892
893      if (NOT CMAKE_CONFIGURATION_TYPES)
894        add_llvm_install_targets(install-${name}
895                                 DEPENDS ${name}
896                                 COMPONENT ${name})
897      endif()
898    endif()
899  endif()
900  if( LLVM_BUILD_TOOLS )
901    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
902  endif()
903  set_target_properties(${name} PROPERTIES FOLDER "Tools")
904endmacro(add_llvm_tool name)
905
906
907macro(add_llvm_example name)
908  if( NOT LLVM_BUILD_EXAMPLES )
909    set(EXCLUDE_FROM_ALL ON)
910  endif()
911  add_llvm_executable(${name} ${ARGN})
912  if( LLVM_BUILD_EXAMPLES )
913    install(TARGETS ${name} RUNTIME DESTINATION examples)
914  endif()
915  set_target_properties(${name} PROPERTIES FOLDER "Examples")
916endmacro(add_llvm_example name)
917
918# This is a macro that is used to create targets for executables that are needed
919# for development, but that are not intended to be installed by default.
920macro(add_llvm_utility name)
921  if ( NOT LLVM_BUILD_UTILS )
922    set(EXCLUDE_FROM_ALL ON)
923  endif()
924
925  add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
926  set_target_properties(${name} PROPERTIES FOLDER "Utils")
927  if( LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS )
928    install (TARGETS ${name}
929      RUNTIME DESTINATION ${LLVM_UTILS_INSTALL_DIR}
930      COMPONENT ${name})
931    if (NOT CMAKE_CONFIGURATION_TYPES)
932      add_llvm_install_targets(install-${name}
933                               DEPENDS ${name}
934                               COMPONENT ${name})
935    endif()
936  endif()
937endmacro(add_llvm_utility name)
938
939macro(add_llvm_fuzzer name)
940  cmake_parse_arguments(ARG "" "DUMMY_MAIN" "" ${ARGN})
941  if( LLVM_LIB_FUZZING_ENGINE )
942    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
943    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
944    target_link_libraries(${name} PRIVATE ${LLVM_LIB_FUZZING_ENGINE})
945    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
946  elseif( LLVM_USE_SANITIZE_COVERAGE )
947    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=fuzzer")
948    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
949    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
950    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
951  elseif( ARG_DUMMY_MAIN )
952    add_llvm_executable(${name} ${ARG_DUMMY_MAIN} ${ARG_UNPARSED_ARGUMENTS})
953    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
954  endif()
955endmacro()
956
957macro(add_llvm_target target_name)
958  include_directories(BEFORE
959    ${CMAKE_CURRENT_BINARY_DIR}
960    ${CMAKE_CURRENT_SOURCE_DIR})
961  add_llvm_library(LLVM${target_name} ${ARGN})
962  set( CURRENT_LLVM_TARGET LLVM${target_name} )
963endmacro(add_llvm_target)
964
965function(canonicalize_tool_name name output)
966  string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" nameStrip ${name})
967  string(REPLACE "-" "_" nameUNDERSCORE ${nameStrip})
968  string(TOUPPER ${nameUNDERSCORE} nameUPPER)
969  set(${output} "${nameUPPER}" PARENT_SCOPE)
970endfunction(canonicalize_tool_name)
971
972# Custom add_subdirectory wrapper
973# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
974# path if it differs from the name.
975macro(add_llvm_subdirectory project type name)
976  set(add_llvm_external_dir "${ARGN}")
977  if("${add_llvm_external_dir}" STREQUAL "")
978    set(add_llvm_external_dir ${name})
979  endif()
980  canonicalize_tool_name(${name} nameUPPER)
981  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}/CMakeLists.txt)
982    # Treat it as in-tree subproject.
983    option(${project}_${type}_${nameUPPER}_BUILD
984           "Whether to build ${name} as part of ${project}" On)
985    mark_as_advanced(${project}_${type}_${name}_BUILD)
986    if(${project}_${type}_${nameUPPER}_BUILD)
987      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir} ${add_llvm_external_dir})
988      # Don't process it in add_llvm_implicit_projects().
989      set(${project}_${type}_${nameUPPER}_BUILD OFF)
990    endif()
991  else()
992    set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR
993      "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}"
994      CACHE PATH "Path to ${name} source directory")
995    set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT ON)
996    if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR OR NOT EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
997      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
998    endif()
999    if("${LLVM_EXTERNAL_${nameUPPER}_BUILD}" STREQUAL "OFF")
1000      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
1001    endif()
1002    option(${project}_${type}_${nameUPPER}_BUILD
1003      "Whether to build ${name} as part of LLVM"
1004      ${${project}_${type}_${nameUPPER}_BUILD_DEFAULT})
1005    if (${project}_${type}_${nameUPPER}_BUILD)
1006      if(EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
1007        add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir})
1008      elseif(NOT "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "")
1009        message(WARNING "Nonexistent directory for ${name}: ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}")
1010      endif()
1011      # FIXME: It'd be redundant.
1012      set(${project}_${type}_${nameUPPER}_BUILD Off)
1013    endif()
1014  endif()
1015endmacro()
1016
1017# Add external project that may want to be built as part of llvm such as Clang,
1018# lld, and Polly. This adds two options. One for the source directory of the
1019# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
1020# enable or disable building it with everything else.
1021# Additional parameter can be specified as the name of directory.
1022macro(add_llvm_external_project name)
1023  add_llvm_subdirectory(LLVM TOOL ${name} ${ARGN})
1024endmacro()
1025
1026macro(add_llvm_tool_subdirectory name)
1027  add_llvm_external_project(${name})
1028endmacro(add_llvm_tool_subdirectory)
1029
1030function(get_project_name_from_src_var var output)
1031  string(REGEX MATCH "LLVM_EXTERNAL_(.*)_SOURCE_DIR"
1032         MACHED_TOOL "${var}")
1033  if(MACHED_TOOL)
1034    set(${output} ${CMAKE_MATCH_1} PARENT_SCOPE)
1035  else()
1036    set(${output} PARENT_SCOPE)
1037  endif()
1038endfunction()
1039
1040function(create_subdirectory_options project type)
1041  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1042  foreach(dir ${sub-dirs})
1043    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1044      canonicalize_tool_name(${dir} name)
1045      option(${project}_${type}_${name}_BUILD
1046           "Whether to build ${name} as part of ${project}" On)
1047      mark_as_advanced(${project}_${type}_${name}_BUILD)
1048    endif()
1049  endforeach()
1050endfunction(create_subdirectory_options)
1051
1052function(create_llvm_tool_options)
1053  create_subdirectory_options(LLVM TOOL)
1054endfunction(create_llvm_tool_options)
1055
1056function(llvm_add_implicit_projects project)
1057  set(list_of_implicit_subdirs "")
1058  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1059  foreach(dir ${sub-dirs})
1060    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1061      canonicalize_tool_name(${dir} name)
1062      if (${project}_TOOL_${name}_BUILD)
1063        get_filename_component(fn "${dir}" NAME)
1064        list(APPEND list_of_implicit_subdirs "${fn}")
1065      endif()
1066    endif()
1067  endforeach()
1068
1069  foreach(external_proj ${list_of_implicit_subdirs})
1070    add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
1071  endforeach()
1072endfunction(llvm_add_implicit_projects)
1073
1074function(add_llvm_implicit_projects)
1075  llvm_add_implicit_projects(LLVM)
1076endfunction(add_llvm_implicit_projects)
1077
1078# Generic support for adding a unittest.
1079function(add_unittest test_suite test_name)
1080  if( NOT LLVM_BUILD_TESTS )
1081    set(EXCLUDE_FROM_ALL ON)
1082  endif()
1083
1084  # Our current version of gtest does not properly recognize C++11 support
1085  # with MSVC, so it falls back to tr1 / experimental classes.  Since LLVM
1086  # itself requires C++11, we can safely force it on unconditionally so that
1087  # we don't have to fight with the buggy gtest check.
1088  add_definitions(-DGTEST_LANG_CXX11=1)
1089  add_definitions(-DGTEST_HAS_TR1_TUPLE=0)
1090
1091  include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include)
1092  include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googlemock/include)
1093  if (NOT LLVM_ENABLE_THREADS)
1094    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_PTHREAD=0)
1095  endif ()
1096
1097  if (SUPPORTS_VARIADIC_MACROS_FLAG)
1098    list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros")
1099  endif ()
1100  # Some parts of gtest rely on this GNU extension, don't warn on it.
1101  if(SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG)
1102    list(APPEND LLVM_COMPILE_FLAGS "-Wno-gnu-zero-variadic-macro-arguments")
1103  endif()
1104
1105  set(LLVM_REQUIRES_RTTI OFF)
1106
1107  list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
1108  add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO NO_INSTALL_RPATH ${ARGN})
1109  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
1110  set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
1111  # libpthreads overrides some standard library symbols, so main
1112  # executable must be linked with it in order to provide consistent
1113  # API for all shared libaries loaded by this executable.
1114  target_link_libraries(${test_name} PRIVATE gtest_main gtest ${LLVM_PTHREAD_LIB})
1115
1116  add_dependencies(${test_suite} ${test_name})
1117  get_target_property(test_suite_folder ${test_suite} FOLDER)
1118  if (NOT ${test_suite_folder} STREQUAL "NOTFOUND")
1119    set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
1120  endif ()
1121endfunction()
1122
1123function(llvm_add_go_executable binary pkgpath)
1124  cmake_parse_arguments(ARG "ALL" "" "DEPENDS;GOFLAGS" ${ARGN})
1125
1126  if(LLVM_BINDINGS MATCHES "go")
1127    # FIXME: This should depend only on the libraries Go needs.
1128    get_property(llvmlibs GLOBAL PROPERTY LLVM_LIBS)
1129    set(binpath ${CMAKE_BINARY_DIR}/bin/${binary}${CMAKE_EXECUTABLE_SUFFIX})
1130    set(cc "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1131    set(cxx "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1132    set(cppflags "")
1133    get_property(include_dirs DIRECTORY PROPERTY INCLUDE_DIRECTORIES)
1134    foreach(d ${include_dirs})
1135      set(cppflags "${cppflags} -I${d}")
1136    endforeach(d)
1137    set(ldflags "${CMAKE_EXE_LINKER_FLAGS}")
1138    add_custom_command(OUTPUT ${binpath}
1139      COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "go=${GO_EXECUTABLE}" "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}" "packages=${LLVM_GO_PACKAGES}"
1140              ${ARG_GOFLAGS} build -o ${binpath} ${pkgpath}
1141      DEPENDS llvm-config ${CMAKE_BINARY_DIR}/bin/llvm-go${CMAKE_EXECUTABLE_SUFFIX}
1142              ${llvmlibs} ${ARG_DEPENDS}
1143      COMMENT "Building Go executable ${binary}"
1144      VERBATIM)
1145    if (ARG_ALL)
1146      add_custom_target(${binary} ALL DEPENDS ${binpath})
1147    else()
1148      add_custom_target(${binary} DEPENDS ${binpath})
1149    endif()
1150  endif()
1151endfunction()
1152
1153# This function canonicalize the CMake variables passed by names
1154# from CMake boolean to 0/1 suitable for passing into Python or C++,
1155# in place.
1156function(llvm_canonicalize_cmake_booleans)
1157  foreach(var ${ARGN})
1158    if(${var})
1159      set(${var} 1 PARENT_SCOPE)
1160    else()
1161      set(${var} 0 PARENT_SCOPE)
1162    endif()
1163  endforeach()
1164endfunction(llvm_canonicalize_cmake_booleans)
1165
1166macro(set_llvm_build_mode)
1167  # Configuration-time: See Unit/lit.site.cfg.in
1168  if (CMAKE_CFG_INTDIR STREQUAL ".")
1169    set(LLVM_BUILD_MODE ".")
1170  else ()
1171    set(LLVM_BUILD_MODE "%(build_mode)s")
1172  endif ()
1173endmacro()
1174
1175# This function provides an automatic way to 'configure'-like generate a file
1176# based on a set of common and custom variables, specifically targeting the
1177# variables needed for the 'lit.site.cfg' files. This function bundles the
1178# common variables that any Lit instance is likely to need, and custom
1179# variables can be passed in.
1180function(configure_lit_site_cfg site_in site_out)
1181  cmake_parse_arguments(ARG "" "" "MAIN_CONFIG;OUTPUT_MAPPING" ${ARGN})
1182
1183  if ("${ARG_MAIN_CONFIG}" STREQUAL "")
1184    get_filename_component(INPUT_DIR ${site_in} DIRECTORY)
1185    set(ARG_MAIN_CONFIG "${INPUT_DIR}/lit.cfg")
1186  endif()
1187  if ("${ARG_OUTPUT_MAPPING}" STREQUAL "")
1188    set(ARG_OUTPUT_MAPPING "${site_out}")
1189  endif()
1190
1191  foreach(c ${LLVM_TARGETS_TO_BUILD})
1192    set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
1193  endforeach(c)
1194  set(TARGETS_TO_BUILD ${TARGETS_BUILT})
1195
1196  set(SHLIBEXT "${LTDL_SHLIB_EXT}")
1197
1198  set_llvm_build_mode()
1199
1200  # They below might not be the build tree but provided binary tree.
1201  set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
1202  set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
1203  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}")
1204  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_LIBS_DIR  "${LLVM_LIBRARY_DIR}")
1205
1206  # SHLIBDIR points the build tree.
1207  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}")
1208
1209  set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})
1210  # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for
1211  # plugins. We may rename it.
1212  if(LLVM_ENABLE_PLUGINS)
1213    set(ENABLE_SHARED "1")
1214  else()
1215    set(ENABLE_SHARED "0")
1216  endif()
1217
1218  if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE)
1219    set(ENABLE_ASSERTIONS "1")
1220  else()
1221    set(ENABLE_ASSERTIONS "0")
1222  endif()
1223
1224  set(HOST_OS ${CMAKE_SYSTEM_NAME})
1225  set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR})
1226
1227  set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1228  set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1229  set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")
1230
1231  set(LIT_SITE_CFG_IN_HEADER  "## Autogenerated from ${site_in}\n## Do not edit!")
1232
1233  # Override config_target_triple (and the env)
1234  if(LLVM_TARGET_TRIPLE_ENV)
1235    # This is expanded into the heading.
1236    string(CONCAT LIT_SITE_CFG_IN_HEADER "${LIT_SITE_CFG_IN_HEADER}\n\n"
1237      "import os\n"
1238      "target_env = \"${LLVM_TARGET_TRIPLE_ENV}\"\n"
1239      "config.target_triple = config.environment[target_env] = os.environ.get(target_env, \"${TARGET_TRIPLE}\")\n"
1240      )
1241
1242    # This is expanded to; config.target_triple = ""+config.target_triple+""
1243    set(TARGET_TRIPLE "\"+config.target_triple+\"")
1244  endif()
1245
1246  string(CONCAT LIT_SITE_CFG_IN_FOOTER
1247     "import lit.llvm\n"
1248     "lit.llvm.initialize(lit_config, config)\n")
1249
1250  configure_file(${site_in} ${site_out} @ONLY)
1251  if (EXISTS "${ARG_MAIN_CONFIG}")
1252    set(PYTHON_STATEMENT "map_config('${ARG_MAIN_CONFIG}', '${site_out}')")
1253    get_property(LLVM_LIT_CONFIG_MAP GLOBAL PROPERTY LLVM_LIT_CONFIG_MAP)
1254    set(LLVM_LIT_CONFIG_MAP "${LLVM_LIT_CONFIG_MAP}\n${PYTHON_STATEMENT}")
1255    set_property(GLOBAL PROPERTY LLVM_LIT_CONFIG_MAP ${LLVM_LIT_CONFIG_MAP})
1256  endif()
1257endfunction()
1258
1259function(dump_all_cmake_variables)
1260  get_cmake_property(_variableNames VARIABLES)
1261  foreach (_variableName ${_variableNames})
1262    message(STATUS "${_variableName}=${${_variableName}}")
1263  endforeach()
1264endfunction()
1265
1266function(get_llvm_lit_path base_dir file_name)
1267  cmake_parse_arguments(ARG "ALLOW_EXTERNAL" "" "" ${ARGN})
1268
1269  if (ARG_ALLOW_EXTERNAL)
1270    set(LLVM_DEFAULT_EXTERNAL_LIT "${LLVM_EXTERNAL_LIT}")
1271    set (LLVM_EXTERNAL_LIT "" CACHE STRING "Command used to spawn lit")
1272    if ("${LLVM_EXTERNAL_LIT}" STREQUAL "")
1273      set(LLVM_EXTERNAL_LIT "${LLVM_DEFAULT_EXTERNAL_LIT}")
1274    endif()
1275
1276    if (NOT "${LLVM_EXTERNAL_LIT}" STREQUAL "")
1277      if (EXISTS ${LLVM_EXTERNAL_LIT})
1278        get_filename_component(LIT_FILE_NAME ${LLVM_EXTERNAL_LIT} NAME)
1279        get_filename_component(LIT_BASE_DIR ${LLVM_EXTERNAL_LIT} DIRECTORY)
1280        set(${file_name} ${LIT_FILE_NAME} PARENT_SCOPE)
1281        set(${base_dir} ${LIT_BASE_DIR} PARENT_SCOPE)
1282        return()
1283      else()
1284        message(WARN "LLVM_EXTERNAL_LIT set to ${LLVM_EXTERNAL_LIT}, but the path does not exist.")
1285      endif()
1286    endif()
1287  endif()
1288
1289  set(lit_file_name "llvm-lit")
1290  if (CMAKE_HOST_WIN32 AND NOT CYGWIN)
1291    # llvm-lit needs suffix.py for multiprocess to find a main module.
1292    set(lit_file_name "${lit_file_name}.py")
1293  endif ()
1294  set(${file_name} ${lit_file_name} PARENT_SCOPE)
1295
1296  get_property(LLVM_LIT_BASE_DIR GLOBAL PROPERTY LLVM_LIT_BASE_DIR)
1297  if (NOT "${LLVM_LIT_BASE_DIR}" STREQUAL "")
1298    set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1299  endif()
1300
1301  # Allow individual projects to provide an override
1302  if (NOT "${LLVM_LIT_OUTPUT_DIR}" STREQUAL "")
1303    set(LLVM_LIT_BASE_DIR ${LLVM_LIT_OUTPUT_DIR})
1304  elseif(NOT "${LLVM_RUNTIME_OUTPUT_INTDIR}" STREQUAL "")
1305    set(LLVM_LIT_BASE_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
1306  else()
1307    set(LLVM_LIT_BASE_DIR "")
1308  endif()
1309
1310  # Cache this so we don't have to do it again and have subsequent calls
1311  # potentially disagree on the value.
1312  set_property(GLOBAL PROPERTY LLVM_LIT_BASE_DIR ${LLVM_LIT_BASE_DIR})
1313  set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1314endfunction()
1315
1316# A raw function to create a lit target. This is used to implement the testuite
1317# management functions.
1318function(add_lit_target target comment)
1319  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1320  set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
1321  separate_arguments(LIT_ARGS)
1322  if (NOT CMAKE_CFG_INTDIR STREQUAL ".")
1323    list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR})
1324  endif ()
1325
1326  # Get the path to the lit to *run* tests with.  This can be overriden by
1327  # the user by specifying -DLLVM_EXTERNAL_LIT=<path-to-lit.py>
1328  get_llvm_lit_path(
1329    lit_base_dir
1330    lit_file_name
1331    ALLOW_EXTERNAL
1332    )
1333
1334  set(LIT_COMMAND "${PYTHON_EXECUTABLE};${lit_base_dir}/${lit_file_name}")
1335  list(APPEND LIT_COMMAND ${LIT_ARGS})
1336  foreach(param ${ARG_PARAMS})
1337    list(APPEND LIT_COMMAND --param ${param})
1338  endforeach()
1339  if (ARG_UNPARSED_ARGUMENTS)
1340    add_custom_target(${target}
1341      COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
1342      COMMENT "${comment}"
1343      USES_TERMINAL
1344      )
1345  else()
1346    add_custom_target(${target}
1347      COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.")
1348    message(STATUS "${target} does nothing.")
1349  endif()
1350  if (ARG_DEPENDS)
1351    add_dependencies(${target} ${ARG_DEPENDS})
1352  endif()
1353
1354  # Tests should be excluded from "Build Solution".
1355  set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON)
1356endfunction()
1357
1358# A function to add a set of lit test suites to be driven through 'check-*' targets.
1359function(add_lit_testsuite target comment)
1360  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1361
1362  # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all.
1363  if(NOT EXCLUDE_FROM_ALL)
1364    # Register the testsuites, params and depends for the global check rule.
1365    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS})
1366    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS})
1367    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS})
1368    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS})
1369  endif()
1370
1371  # Produce a specific suffixed check rule.
1372  add_lit_target(${target} ${comment}
1373    ${ARG_UNPARSED_ARGUMENTS}
1374    PARAMS ${ARG_PARAMS}
1375    DEPENDS ${ARG_DEPENDS}
1376    ARGS ${ARG_ARGS}
1377    )
1378endfunction()
1379
1380function(add_lit_testsuites project directory)
1381  if (NOT CMAKE_CONFIGURATION_TYPES)
1382    cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1383
1384    # Search recursively for test directories by assuming anything not
1385    # in a directory called Inputs contains tests.
1386    file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*)
1387    foreach(lit_suite ${to_process})
1388      if(NOT IS_DIRECTORY ${lit_suite})
1389        continue()
1390      endif()
1391      string(FIND ${lit_suite} Inputs is_inputs)
1392      string(FIND ${lit_suite} Output is_output)
1393      if (NOT (is_inputs EQUAL -1 AND is_output EQUAL -1))
1394        continue()
1395      endif()
1396
1397      # Create a check- target for the directory.
1398      string(REPLACE ${directory} "" name_slash ${lit_suite})
1399      if (name_slash)
1400        string(REPLACE "/" "-" name_slash ${name_slash})
1401        string(REPLACE "\\" "-" name_dashes ${name_slash})
1402        string(TOLOWER "${project}${name_dashes}" name_var)
1403        add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}"
1404          ${lit_suite}
1405          PARAMS ${ARG_PARAMS}
1406          DEPENDS ${ARG_DEPENDS}
1407          ARGS ${ARG_ARGS}
1408        )
1409      endif()
1410    endforeach()
1411  endif()
1412endfunction()
1413
1414function(llvm_install_library_symlink name dest type)
1415  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1416  foreach(path ${CMAKE_MODULE_PATH})
1417    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1418      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1419      break()
1420    endif()
1421  endforeach()
1422
1423  set(component ${ARG_COMPONENT})
1424  if(NOT component)
1425    set(component ${name})
1426  endif()
1427
1428  set(full_name ${CMAKE_${type}_LIBRARY_PREFIX}${name}${CMAKE_${type}_LIBRARY_SUFFIX})
1429  set(full_dest ${CMAKE_${type}_LIBRARY_PREFIX}${dest}${CMAKE_${type}_LIBRARY_SUFFIX})
1430
1431  set(output_dir lib${LLVM_LIBDIR_SUFFIX})
1432  if(WIN32 AND "${type}" STREQUAL "SHARED")
1433    set(output_dir bin)
1434  endif()
1435
1436  install(SCRIPT ${INSTALL_SYMLINK}
1437          CODE "install_symlink(${full_name} ${full_dest} ${output_dir})"
1438          COMPONENT ${component})
1439
1440  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1441    add_llvm_install_targets(install-${name}
1442                             DEPENDS ${name} ${dest} install-${dest}
1443                             COMPONENT ${name})
1444  endif()
1445endfunction()
1446
1447function(llvm_install_symlink name dest)
1448  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1449  foreach(path ${CMAKE_MODULE_PATH})
1450    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1451      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1452      break()
1453    endif()
1454  endforeach()
1455
1456  if(ARG_COMPONENT)
1457    set(component ${ARG_COMPONENT})
1458  else()
1459    if(ARG_ALWAYS_GENERATE)
1460      set(component ${dest})
1461    else()
1462      set(component ${name})
1463    endif()
1464  endif()
1465
1466  set(full_name ${name}${CMAKE_EXECUTABLE_SUFFIX})
1467  set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})
1468
1469  install(SCRIPT ${INSTALL_SYMLINK}
1470          CODE "install_symlink(${full_name} ${full_dest} ${LLVM_TOOLS_INSTALL_DIR})"
1471          COMPONENT ${component})
1472
1473  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1474    add_llvm_install_targets(install-${name}
1475                             DEPENDS ${name} ${dest} install-${dest}
1476                             COMPONENT ${name})
1477  endif()
1478endfunction()
1479
1480function(add_llvm_tool_symlink link_name target)
1481  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "OUTPUT_DIR" "" ${ARGN})
1482  set(dest_binary "$<TARGET_FILE:${target}>")
1483
1484  # This got a bit gross... For multi-configuration generators the target
1485  # properties return the resolved value of the string, not the build system
1486  # expression. To reconstruct the platform-agnostic path we have to do some
1487  # magic. First we grab one of the types, and a type-specific path. Then from
1488  # the type-specific path we find the last occurrence of the type in the path,
1489  # and replace it with CMAKE_CFG_INTDIR. This allows the build step to be type
1490  # agnostic again.
1491  if(NOT ARG_OUTPUT_DIR)
1492    # If you're not overriding the OUTPUT_DIR, we can make the link relative in
1493    # the same directory.
1494    if(CMAKE_HOST_UNIX)
1495      set(dest_binary "$<TARGET_FILE_NAME:${target}>")
1496    endif()
1497    if(CMAKE_CONFIGURATION_TYPES)
1498      list(GET CMAKE_CONFIGURATION_TYPES 0 first_type)
1499      string(TOUPPER ${first_type} first_type_upper)
1500      set(first_type_suffix _${first_type_upper})
1501    endif()
1502    get_target_property(target_type ${target} TYPE)
1503    if(${target_type} STREQUAL "STATIC_LIBRARY")
1504      get_target_property(ARG_OUTPUT_DIR ${target} ARCHIVE_OUTPUT_DIRECTORY${first_type_suffix})
1505    elseif(UNIX AND ${target_type} STREQUAL "SHARED_LIBRARY")
1506      get_target_property(ARG_OUTPUT_DIR ${target} LIBRARY_OUTPUT_DIRECTORY${first_type_suffix})
1507    else()
1508      get_target_property(ARG_OUTPUT_DIR ${target} RUNTIME_OUTPUT_DIRECTORY${first_type_suffix})
1509    endif()
1510    if(CMAKE_CONFIGURATION_TYPES)
1511      string(FIND "${ARG_OUTPUT_DIR}" "/${first_type}/" type_start REVERSE)
1512      string(SUBSTRING "${ARG_OUTPUT_DIR}" 0 ${type_start} path_prefix)
1513      string(SUBSTRING "${ARG_OUTPUT_DIR}" ${type_start} -1 path_suffix)
1514      string(REPLACE "/${first_type}/" "/${CMAKE_CFG_INTDIR}/"
1515             path_suffix ${path_suffix})
1516      set(ARG_OUTPUT_DIR ${path_prefix}${path_suffix})
1517    endif()
1518  endif()
1519
1520  if(CMAKE_HOST_UNIX)
1521    set(LLVM_LINK_OR_COPY create_symlink)
1522  else()
1523    set(LLVM_LINK_OR_COPY copy)
1524  endif()
1525
1526  set(output_path "${ARG_OUTPUT_DIR}/${link_name}${CMAKE_EXECUTABLE_SUFFIX}")
1527
1528  set(target_name ${link_name})
1529  if(TARGET ${link_name})
1530    set(target_name ${link_name}-link)
1531  endif()
1532
1533
1534  if(ARG_ALWAYS_GENERATE)
1535    set_property(DIRECTORY APPEND PROPERTY
1536      ADDITIONAL_MAKE_CLEAN_FILES ${dest_binary})
1537    add_custom_command(TARGET ${target} POST_BUILD
1538      COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}")
1539  else()
1540    add_custom_command(OUTPUT ${output_path}
1541                     COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}"
1542                     DEPENDS ${target})
1543    add_custom_target(${target_name} ALL DEPENDS ${target} ${output_path})
1544    set_target_properties(${target_name} PROPERTIES FOLDER Tools)
1545
1546    # Make sure both the link and target are toolchain tools
1547    if (${link_name} IN_LIST LLVM_TOOLCHAIN_TOOLS AND ${target} IN_LIST LLVM_TOOLCHAIN_TOOLS)
1548      set(TOOL_IS_TOOLCHAIN ON)
1549    endif()
1550
1551    if ((TOOL_IS_TOOLCHAIN OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY) AND LLVM_BUILD_TOOLS)
1552      llvm_install_symlink(${link_name} ${target})
1553    endif()
1554  endif()
1555endfunction()
1556
1557function(llvm_externalize_debuginfo name)
1558  if(NOT LLVM_EXTERNALIZE_DEBUGINFO)
1559    return()
1560  endif()
1561
1562  if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
1563    if(APPLE)
1564      if(NOT CMAKE_STRIP)
1565        set(CMAKE_STRIP xcrun strip)
1566      endif()
1567      set(strip_command COMMAND ${CMAKE_STRIP} -Sxl $<TARGET_FILE:${name}>)
1568    else()
1569      set(strip_command COMMAND ${CMAKE_STRIP} -gx $<TARGET_FILE:${name}>)
1570    endif()
1571  endif()
1572
1573  if(APPLE)
1574    if(CMAKE_CXX_FLAGS MATCHES "-flto"
1575      OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
1576
1577      set(lto_object ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${name}-lto.o)
1578      set_property(TARGET ${name} APPEND_STRING PROPERTY
1579        LINK_FLAGS " -Wl,-object_path_lto,${lto_object}")
1580    endif()
1581    if(NOT CMAKE_DSYMUTIL)
1582      set(CMAKE_DSYMUTIL xcrun dsymutil)
1583    endif()
1584    add_custom_command(TARGET ${name} POST_BUILD
1585      COMMAND ${CMAKE_DSYMUTIL} $<TARGET_FILE:${name}>
1586      ${strip_command}
1587      )
1588  else()
1589    add_custom_command(TARGET ${name} POST_BUILD
1590      COMMAND ${CMAKE_OBJCOPY} --only-keep-debug $<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.debug
1591      ${strip_command} -R .gnu_debuglink
1592      COMMAND ${CMAKE_OBJCOPY} --add-gnu-debuglink=$<TARGET_FILE:${name}>.debug $<TARGET_FILE:${name}>
1593      )
1594  endif()
1595endfunction()
1596
1597function(llvm_codesign name)
1598  if(NOT LLVM_CODESIGNING_IDENTITY)
1599    return()
1600  endif()
1601
1602  if(APPLE)
1603    if(NOT CMAKE_CODESIGN)
1604      set(CMAKE_CODESIGN xcrun codesign)
1605    endif()
1606    if(NOT CMAKE_CODESIGN_ALLOCATE)
1607      execute_process(
1608        COMMAND xcrun -f codesign_allocate
1609        OUTPUT_STRIP_TRAILING_WHITESPACE
1610        OUTPUT_VARIABLE CMAKE_CODESIGN_ALLOCATE
1611      )
1612    endif()
1613    add_custom_command(
1614      TARGET ${name} POST_BUILD
1615      COMMAND ${CMAKE_COMMAND} -E
1616              env CODESIGN_ALLOCATE=${CMAKE_CODESIGN_ALLOCATE}
1617              ${CMAKE_CODESIGN} -s ${LLVM_CODESIGNING_IDENTITY}
1618              $<TARGET_FILE:${name}>
1619    )
1620  endif()
1621endfunction()
1622
1623function(llvm_setup_rpath name)
1624  if(CMAKE_INSTALL_RPATH)
1625    return()
1626  endif()
1627
1628  if(LLVM_INSTALL_PREFIX AND NOT (LLVM_INSTALL_PREFIX STREQUAL CMAKE_INSTALL_PREFIX))
1629    set(extra_libdir ${LLVM_LIBRARY_DIR})
1630  elseif(LLVM_BUILD_LIBRARY_DIR)
1631    set(extra_libdir ${LLVM_LIBRARY_DIR})
1632  endif()
1633
1634  if (APPLE)
1635    set(_install_name_dir INSTALL_NAME_DIR "@rpath")
1636    set(_install_rpath "@loader_path/../lib" ${extra_libdir})
1637  elseif(UNIX)
1638    set(_install_rpath "\$ORIGIN/../lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
1639    if(${CMAKE_SYSTEM_NAME} MATCHES "(FreeBSD|DragonFly)")
1640      set_property(TARGET ${name} APPEND_STRING PROPERTY
1641                   LINK_FLAGS " -Wl,-z,origin ")
1642    endif()
1643    if(LLVM_LINKER_IS_GNULD)
1644      # $ORIGIN is not interpreted at link time by ld.bfd
1645      set_property(TARGET ${name} APPEND_STRING PROPERTY
1646                   LINK_FLAGS " -Wl,-rpath-link,${LLVM_LIBRARY_OUTPUT_INTDIR} ")
1647    endif()
1648  else()
1649    return()
1650  endif()
1651
1652  set_target_properties(${name} PROPERTIES
1653                        BUILD_WITH_INSTALL_RPATH On
1654                        INSTALL_RPATH "${_install_rpath}"
1655                        ${_install_name_dir})
1656endfunction()
1657
1658function(setup_dependency_debugging name)
1659  if(NOT LLVM_DEPENDENCY_DEBUGGING)
1660    return()
1661  endif()
1662
1663  if("intrinsics_gen" IN_LIST ARGN)
1664    return()
1665  endif()
1666
1667  set(deny_attributes_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Attributes.inc\"))")
1668  set(deny_intrinsics_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Intrinsics.inc\"))")
1669
1670  set(sandbox_command "sandbox-exec -p '(version 1) (allow default) ${deny_attributes_inc} ${deny_intrinsics_inc}'")
1671  set_target_properties(${name} PROPERTIES RULE_LAUNCH_COMPILE ${sandbox_command})
1672endfunction()
1673
1674# Figure out if we can track VC revisions.
1675function(find_first_existing_file out_var)
1676  foreach(file ${ARGN})
1677    if(EXISTS "${file}")
1678      set(${out_var} "${file}" PARENT_SCOPE)
1679      return()
1680    endif()
1681  endforeach()
1682endfunction()
1683
1684macro(find_first_existing_vc_file out_var path)
1685    find_program(git_executable NAMES git git.exe git.cmd)
1686    # Run from a subdirectory to force git to print an absolute path.
1687    execute_process(COMMAND ${git_executable} rev-parse --git-dir
1688      WORKING_DIRECTORY ${path}/cmake
1689      RESULT_VARIABLE git_result
1690      OUTPUT_VARIABLE git_dir
1691      ERROR_QUIET)
1692    if(git_result EQUAL 0)
1693      string(STRIP "${git_dir}" git_dir)
1694      set(${out_var} "${git_dir}/logs/HEAD")
1695      # some branchless cases (e.g. 'repo') may not yet have .git/logs/HEAD
1696      if (NOT EXISTS "${git_dir}/logs/HEAD")
1697        file(WRITE "${git_dir}/logs/HEAD" "")
1698      endif()
1699    else()
1700      find_first_existing_file(${out_var}
1701        "${path}/.svn/wc.db"   # SVN 1.7
1702        "${path}/.svn/entries" # SVN 1.6
1703      )
1704    endif()
1705endmacro()
1706