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