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