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    add_custom_command(OUTPUT ${native_export_file}
85      COMMAND echo "{" > ${native_export_file}
86      COMMAND grep -q "[[:alnum:]]" ${export_file} && echo "  global:" >> ${native_export_file} || :
87      COMMAND sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
88      COMMAND echo "  local: *;" >> ${native_export_file}
89      COMMAND echo "};" >> ${native_export_file}
90      DEPENDS ${export_file}
91      VERBATIM
92      COMMENT "Creating export file for ${target_name}")
93    if (${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
94      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
95                   LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
96    else()
97      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
98                   LINK_FLAGS "  -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
99    endif()
100  else()
101    set(native_export_file "${target_name}.def")
102
103    add_custom_command(OUTPUT ${native_export_file}
104      COMMAND ${PYTHON_EXECUTABLE} -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))"
105        < ${export_file} > ${native_export_file}
106      DEPENDS ${export_file}
107      VERBATIM
108      COMMENT "Creating export file for ${target_name}")
109    set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
110    if(MSVC)
111      set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"")
112    endif()
113    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
114                 LINK_FLAGS " ${export_file_linker_flag}")
115  endif()
116
117  add_custom_target(${target_name}_exports DEPENDS ${native_export_file})
118  set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc")
119
120  get_property(srcs TARGET ${target_name} PROPERTY SOURCES)
121  foreach(src ${srcs})
122    get_filename_component(extension ${src} EXT)
123    if(extension STREQUAL ".cpp")
124      set(first_source_file ${src})
125      break()
126    endif()
127  endforeach()
128
129  # Force re-linking when the exports file changes. Actually, it
130  # forces recompilation of the source file. The LINK_DEPENDS target
131  # property only works for makefile-based generators.
132  # FIXME: This is not safe because this will create the same target
133  # ${native_export_file} in several different file:
134  # - One where we emitted ${target_name}_exports
135  # - One where we emitted the build command for the following object.
136  # set_property(SOURCE ${first_source_file} APPEND PROPERTY
137  #   OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file})
138
139  set_property(DIRECTORY APPEND
140    PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file})
141
142  add_dependencies(${target_name} ${target_name}_exports)
143
144  # Add dependency to *_exports later -- CMake issue 14747
145  list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports)
146  set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
147endfunction(add_llvm_symbol_exports)
148
149if(NOT WIN32 AND NOT APPLE)
150  execute_process(
151    COMMAND ${CMAKE_C_COMPILER} -Wl,--version
152    OUTPUT_VARIABLE stdout
153    ERROR_QUIET
154    )
155  if("${stdout}" MATCHES "GNU gold")
156    set(LLVM_LINKER_IS_GOLD ON)
157  endif()
158endif()
159
160function(add_link_opts target_name)
161  # Don't use linker optimizations in debug builds since it slows down the
162  # linker in a context where the optimizations are not important.
163  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
164
165    # Pass -O3 to the linker. This enabled different optimizations on different
166    # linkers.
167    if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|SunOS|AIX" OR WIN32))
168      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
169                   LINK_FLAGS " -Wl,-O3")
170    endif()
171
172    if(LLVM_LINKER_IS_GOLD)
173      # With gold gc-sections is always safe.
174      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
175                   LINK_FLAGS " -Wl,--gc-sections")
176      # Note that there is a bug with -Wl,--icf=safe so it is not safe
177      # to enable. See https://sourceware.org/bugzilla/show_bug.cgi?id=17704.
178    endif()
179
180    if(NOT LLVM_NO_DEAD_STRIP)
181      if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
182        # ld64's implementation of -dead_strip breaks tools that use plugins.
183        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
184                     LINK_FLAGS " -Wl,-dead_strip")
185      elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
186        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
187                     LINK_FLAGS " -Wl,-z -Wl,discard-unused=sections")
188      elseif(NOT WIN32 AND NOT LLVM_LINKER_IS_GOLD)
189        # Object files are compiled with -ffunction-data-sections.
190        # Versions of bfd ld < 2.23.1 have a bug in --gc-sections that breaks
191        # tools that use plugins. Always pass --gc-sections once we require
192        # a newer linker.
193        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
194                     LINK_FLAGS " -Wl,--gc-sections")
195      endif()
196    endif()
197  endif()
198endfunction(add_link_opts)
199
200# Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}.
201# Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more,
202# or a certain builder, for eaxample, msbuild.exe, would be confused.
203function(set_output_directory target)
204  cmake_parse_arguments(ARG "" "BINARY_DIR;LIBRARY_DIR" "" ${ARGN})
205
206  # module_dir -- corresponding to LIBRARY_OUTPUT_DIRECTORY.
207  # It affects output of add_library(MODULE).
208  if(WIN32 OR CYGWIN)
209    # DLL platform
210    set(module_dir ${ARG_BINARY_DIR})
211  else()
212    set(module_dir ${ARG_LIBRARY_DIR})
213  endif()
214  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
215    foreach(build_mode ${CMAKE_CONFIGURATION_TYPES})
216      string(TOUPPER "${build_mode}" CONFIG_SUFFIX)
217      if(ARG_BINARY_DIR)
218        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${ARG_BINARY_DIR})
219        set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi})
220      endif()
221      if(ARG_LIBRARY_DIR)
222        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${ARG_LIBRARY_DIR})
223        set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li})
224      endif()
225      if(module_dir)
226        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${module_dir})
227        set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi})
228      endif()
229    endforeach()
230  else()
231    if(ARG_BINARY_DIR)
232      set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ARG_BINARY_DIR})
233    endif()
234    if(ARG_LIBRARY_DIR)
235      set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${ARG_LIBRARY_DIR})
236    endif()
237    if(module_dir)
238      set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${module_dir})
239    endif()
240  endif()
241endfunction()
242
243# If on Windows and building with MSVC, add the resource script containing the
244# VERSIONINFO data to the project.  This embeds version resource information
245# into the output .exe or .dll.
246# TODO: Enable for MinGW Windows builds too.
247#
248function(add_windows_version_resource_file OUT_VAR)
249  set(sources ${ARGN})
250  if (MSVC)
251    set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc)
252    if(EXISTS ${resource_file})
253      set(sources ${sources} ${resource_file})
254      source_group("Resource Files" ${resource_file})
255      set(windows_resource_file ${resource_file} PARENT_SCOPE)
256    endif()
257  endif(MSVC)
258
259  set(${OUT_VAR} ${sources} PARENT_SCOPE)
260endfunction(add_windows_version_resource_file)
261
262# set_windows_version_resource_properties(name resource_file...
263#   VERSION_MAJOR int
264#     Optional major version number (defaults to LLVM_VERSION_MAJOR)
265#   VERSION_MINOR int
266#     Optional minor version number (defaults to LLVM_VERSION_MINOR)
267#   VERSION_PATCHLEVEL int
268#     Optional patchlevel version number (defaults to LLVM_VERSION_PATCH)
269#   VERSION_STRING
270#     Optional version string (defaults to PACKAGE_VERSION)
271#   PRODUCT_NAME
272#     Optional product name string (defaults to "LLVM")
273#   )
274function(set_windows_version_resource_properties name resource_file)
275  cmake_parse_arguments(ARG
276    ""
277    "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME"
278    ""
279    ${ARGN})
280
281  if (NOT DEFINED ARG_VERSION_MAJOR)
282    set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
283  endif()
284
285  if (NOT DEFINED ARG_VERSION_MINOR)
286    set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR})
287  endif()
288
289  if (NOT DEFINED ARG_VERSION_PATCHLEVEL)
290    set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH})
291  endif()
292
293  if (NOT DEFINED ARG_VERSION_STRING)
294    set(ARG_VERSION_STRING ${PACKAGE_VERSION})
295  endif()
296
297  if (NOT DEFINED ARG_PRODUCT_NAME)
298    set(ARG_PRODUCT_NAME "LLVM")
299  endif()
300
301  set_property(SOURCE ${resource_file}
302               PROPERTY COMPILE_FLAGS /nologo)
303  set_property(SOURCE ${resource_file}
304               PROPERTY COMPILE_DEFINITIONS
305               "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}"
306               "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}"
307               "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}"
308               "RC_VERSION_FIELD_4=0"
309               "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\""
310               "RC_INTERNAL_NAME=\"${name}\""
311               "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\""
312               "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"")
313endfunction(set_windows_version_resource_properties)
314
315# llvm_add_library(name sources...
316#   SHARED;STATIC
317#     STATIC by default w/o BUILD_SHARED_LIBS.
318#     SHARED by default w/  BUILD_SHARED_LIBS.
319#   OBJECT
320#     Also create an OBJECT library target. Default if STATIC && SHARED.
321#   MODULE
322#     Target ${name} might not be created on unsupported platforms.
323#     Check with "if(TARGET ${name})".
324#   DISABLE_LLVM_LINK_LLVM_DYLIB
325#     Do not link this library to libLLVM, even if
326#     LLVM_LINK_LLVM_DYLIB is enabled.
327#   OUTPUT_NAME name
328#     Corresponds to OUTPUT_NAME in target properties.
329#   DEPENDS targets...
330#     Same semantics as add_dependencies().
331#   LINK_COMPONENTS components...
332#     Same as the variable LLVM_LINK_COMPONENTS.
333#   LINK_LIBS lib_targets...
334#     Same semantics as target_link_libraries().
335#   ADDITIONAL_HEADERS
336#     May specify header files for IDE generators.
337#   SONAME
338#     Should set SONAME link flags and create symlinks
339#   PLUGIN_TOOL
340#     The tool (i.e. cmake target) that this plugin will link against
341#   )
342function(llvm_add_library name)
343  cmake_parse_arguments(ARG
344    "MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME"
345    "OUTPUT_NAME;PLUGIN_TOOL"
346    "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
347    ${ARGN})
348  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
349  if(ARG_ADDITIONAL_HEADERS)
350    # Pass through ADDITIONAL_HEADERS.
351    set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS})
352  endif()
353  if(ARG_OBJLIBS)
354    set(ALL_FILES ${ARG_OBJLIBS})
355  else()
356    llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS})
357  endif()
358
359  if(ARG_MODULE)
360    if(ARG_SHARED OR ARG_STATIC)
361      message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
362    endif()
363    # Plugins that link against a tool are allowed even when plugins in general are not
364    if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
365      message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
366      return()
367    endif()
368  else()
369    if(ARG_PLUGIN_TOOL)
370      message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
371    endif()
372    if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
373      set(ARG_SHARED TRUE)
374    endif()
375    if(NOT ARG_SHARED)
376      set(ARG_STATIC TRUE)
377    endif()
378  endif()
379
380  # Generate objlib
381  if((ARG_SHARED AND ARG_STATIC) OR ARG_OBJECT)
382    # Generate an obj library for both targets.
383    set(obj_name "obj.${name}")
384    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
385      ${ALL_FILES}
386      )
387    llvm_update_compile_flags(${obj_name})
388    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
389
390    # Do add_dependencies(obj) later due to CMake issue 14747.
391    list(APPEND objlibs ${obj_name})
392
393    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
394  endif()
395
396  if(ARG_SHARED AND ARG_STATIC)
397    # static
398    set(name_static "${name}_static")
399    if(ARG_OUTPUT_NAME)
400      set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}")
401    endif()
402    # DEPENDS has been appended to LLVM_COMMON_LIBS.
403    llvm_add_library(${name_static} STATIC
404      ${output_name}
405      OBJLIBS ${ALL_FILES} # objlib
406      LINK_LIBS ${ARG_LINK_LIBS}
407      LINK_COMPONENTS ${ARG_LINK_COMPONENTS}
408      )
409    # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
410    set(ARG_STATIC)
411  endif()
412
413  if(ARG_MODULE)
414    add_library(${name} MODULE ${ALL_FILES})
415  elseif(ARG_SHARED)
416    add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
417    add_library(${name} SHARED ${ALL_FILES})
418  else()
419    add_library(${name} STATIC ${ALL_FILES})
420  endif()
421
422  if(DEFINED windows_resource_file)
423    set_windows_version_resource_properties(${name} ${windows_resource_file})
424    set(windows_resource_file ${windows_resource_file} PARENT_SCOPE)
425  endif()
426
427  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
428  # $<TARGET_OBJECTS> doesn't require compile flags.
429  if(NOT obj_name)
430    llvm_update_compile_flags(${name})
431  endif()
432  add_link_opts( ${name} )
433  if(ARG_OUTPUT_NAME)
434    set_target_properties(${name}
435      PROPERTIES
436      OUTPUT_NAME ${ARG_OUTPUT_NAME}
437      )
438  endif()
439
440  if(ARG_MODULE)
441    set_target_properties(${name} PROPERTIES
442      PREFIX ""
443      SUFFIX ${LLVM_PLUGIN_EXT}
444      )
445  endif()
446
447  if(ARG_SHARED)
448    if(WIN32)
449      set_target_properties(${name} PROPERTIES
450        PREFIX ""
451        )
452    endif()
453
454    # Set SOVERSION on shared libraries that lack explicit SONAME
455    # specifier, on *nix systems that are not Darwin.
456    if(UNIX AND NOT APPLE AND NOT ARG_SONAME)
457      set_target_properties(${name}
458        PROPERTIES
459		# Concatenate the version numbers since ldconfig expects exactly
460		# one component indicating the ABI version, while LLVM uses
461		# major+minor for that.
462        SOVERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_MINOR}
463        VERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
464    endif()
465  endif()
466
467  if(ARG_MODULE OR ARG_SHARED)
468    # Do not add -Dname_EXPORTS to the command-line when building files in this
469    # target. Doing so is actively harmful for the modules build because it
470    # creates extra module variants, and not useful because we don't use these
471    # macros.
472    set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
473
474    if (LLVM_EXPORTED_SYMBOL_FILE)
475      add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
476    endif()
477  endif()
478
479  if(ARG_SHARED AND UNIX)
480    if(NOT APPLE AND ARG_SONAME)
481      get_target_property(output_name ${name} OUTPUT_NAME)
482      if(${output_name} STREQUAL "output_name-NOTFOUND")
483        set(output_name ${name})
484      endif()
485      set(library_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}${LLVM_VERSION_SUFFIX})
486      set(api_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
487      set_target_properties(${name} PROPERTIES OUTPUT_NAME ${library_name})
488      llvm_install_library_symlink(${api_name} ${library_name} SHARED
489        COMPONENT ${name}
490        ALWAYS_GENERATE)
491      llvm_install_library_symlink(${output_name} ${library_name} SHARED
492        COMPONENT ${name}
493        ALWAYS_GENERATE)
494    endif()
495  endif()
496
497  if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
498    # On DLL platforms symbols are imported from the tool by linking against it.
499    set(llvm_libs ${ARG_PLUGIN_TOOL})
500  elseif (DEFINED LLVM_LINK_COMPONENTS OR DEFINED ARG_LINK_COMPONENTS)
501    if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
502      set(llvm_libs LLVM)
503    else()
504      llvm_map_components_to_libnames(llvm_libs
505       ${ARG_LINK_COMPONENTS}
506       ${LLVM_LINK_COMPONENTS}
507       )
508    endif()
509  else()
510    # Components have not been defined explicitly in CMake, so add the
511    # dependency information for this library as defined by LLVMBuild.
512    #
513    # It would be nice to verify that we have the dependencies for this library
514    # name, but using get_property(... SET) doesn't suffice to determine if a
515    # property has been set to an empty value.
516    get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
517  endif()
518
519  if(ARG_STATIC)
520    set(libtype INTERFACE)
521  else()
522    # We can use PRIVATE since SO knows its dependent libs.
523    set(libtype PRIVATE)
524  endif()
525
526  target_link_libraries(${name} ${libtype}
527      ${ARG_LINK_LIBS}
528      ${lib_deps}
529      ${llvm_libs}
530      )
531
532  if(LLVM_COMMON_DEPENDS)
533    add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
534    # Add dependencies also to objlibs.
535    # CMake issue 14747 --  add_dependencies() might be ignored to objlib's user.
536    foreach(objlib ${objlibs})
537      add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS})
538    endforeach()
539  endif()
540
541  if(ARG_SHARED OR ARG_MODULE)
542    llvm_externalize_debuginfo(${name})
543  endif()
544endfunction()
545
546macro(add_llvm_library name)
547  cmake_parse_arguments(ARG
548    "SHARED;BUILDTREE_ONLY"
549    ""
550    ""
551    ${ARGN})
552  if( BUILD_SHARED_LIBS OR ARG_SHARED )
553    llvm_add_library(${name} SHARED ${ARG_UNPARSED_ARGUMENTS})
554  else()
555    llvm_add_library(${name} ${ARG_UNPARSED_ARGUMENTS})
556  endif()
557
558  # Libraries that are meant to only be exposed via the build tree only are
559  # never installed and are only exported as a target in the special build tree
560  # config file.
561  if (NOT ARG_BUILDTREE_ONLY)
562    set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
563  endif()
564
565  if( EXCLUDE_FROM_ALL )
566    set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
567  elseif(ARG_BUILDTREE_ONLY)
568    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
569  else()
570    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "LTO" OR
571        (LLVM_LINK_LLVM_DYLIB AND ${name} STREQUAL "LLVM"))
572      set(install_dir lib${LLVM_LIBDIR_SUFFIX})
573      if(ARG_SHARED OR BUILD_SHARED_LIBS)
574        if(WIN32 OR CYGWIN OR MINGW)
575          set(install_type RUNTIME)
576          set(install_dir bin)
577        else()
578          set(install_type LIBRARY)
579        endif()
580      else()
581        set(install_type ARCHIVE)
582      endif()
583
584      install(TARGETS ${name}
585            EXPORT LLVMExports
586            ${install_type} DESTINATION ${install_dir}
587            COMPONENT ${name})
588
589      if (NOT CMAKE_CONFIGURATION_TYPES)
590        add_custom_target(install-${name}
591                          DEPENDS ${name}
592                          COMMAND "${CMAKE_COMMAND}"
593                                  -DCMAKE_INSTALL_COMPONENT=${name}
594                                  -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
595      endif()
596    endif()
597    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
598  endif()
599  set_target_properties(${name} PROPERTIES FOLDER "Libraries")
600endmacro(add_llvm_library name)
601
602macro(add_llvm_loadable_module name)
603  llvm_add_library(${name} MODULE ${ARGN})
604  if(NOT TARGET ${name})
605    # Add empty "phony" target
606    add_custom_target(${name})
607  else()
608    if( EXCLUDE_FROM_ALL )
609      set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
610    else()
611      if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
612        if(WIN32 OR CYGWIN)
613          # DLL platform
614          set(dlldir "bin")
615        else()
616          set(dlldir "lib${LLVM_LIBDIR_SUFFIX}")
617        endif()
618        install(TARGETS ${name}
619          EXPORT LLVMExports
620          LIBRARY DESTINATION ${dlldir}
621          ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
622      endif()
623      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
624    endif()
625  endif()
626
627  set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
628endmacro(add_llvm_loadable_module name)
629
630
631macro(add_llvm_executable name)
632  cmake_parse_arguments(ARG "DISABLE_LLVM_LINK_LLVM_DYLIB;IGNORE_EXTERNALIZE_DEBUGINFO" "" "" ${ARGN})
633  llvm_process_sources( ALL_FILES ${ARG_UNPARSED_ARGUMENTS} )
634
635  # Generate objlib
636  if(LLVM_ENABLE_OBJLIB)
637    # Generate an obj library for both targets.
638    set(obj_name "obj.${name}")
639    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
640      ${ALL_FILES}
641      )
642    llvm_update_compile_flags(${obj_name})
643    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
644
645    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
646  endif()
647
648  add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
649
650  if(XCODE)
651    # Note: the dummy.cpp source file provides no definitions. However,
652    # it forces Xcode to properly link the static library.
653    list(APPEND ALL_FILES "${LLVM_MAIN_SRC_DIR}/cmake/dummy.cpp")
654  endif()
655
656  if( EXCLUDE_FROM_ALL )
657    add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
658  else()
659    add_executable(${name} ${ALL_FILES})
660  endif()
661
662  if(DEFINED windows_resource_file)
663    set_windows_version_resource_properties(${name} ${windows_resource_file})
664  endif()
665
666  # $<TARGET_OBJECTS> doesn't require compile flags.
667  if(NOT LLVM_ENABLE_OBJLIB)
668    llvm_update_compile_flags(${name})
669  endif()
670  add_link_opts( ${name} )
671
672  # Do not add -Dname_EXPORTS to the command-line when building files in this
673  # target. Doing so is actively harmful for the modules build because it
674  # creates extra module variants, and not useful because we don't use these
675  # macros.
676  set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
677
678  if (LLVM_EXPORTED_SYMBOL_FILE)
679    add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
680  endif(LLVM_EXPORTED_SYMBOL_FILE)
681
682  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
683    set(USE_SHARED USE_SHARED)
684  endif()
685
686  set(EXCLUDE_FROM_ALL OFF)
687  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
688  llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )
689  if( LLVM_COMMON_DEPENDS )
690    add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
691  endif( LLVM_COMMON_DEPENDS )
692
693  if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
694    llvm_externalize_debuginfo(${name})
695  endif()
696  if (PTHREAD_LIB)
697    # libpthreads overrides some standard library symbols, so main
698    # executable must be linked with it in order to provide consistent
699    # API for all shared libaries loaded by this executable.
700    target_link_libraries(${name} ${PTHREAD_LIB})
701  endif()
702endmacro(add_llvm_executable name)
703
704function(export_executable_symbols target)
705  if (LLVM_EXPORTED_SYMBOL_FILE)
706    # The symbol file should contain the symbols we want the executable to
707    # export
708    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
709  elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
710    # Extract the symbols to export from the static libraries that the
711    # executable links against.
712    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
713    set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
714    # We need to consider not just the direct link dependencies, but also the
715    # transitive link dependencies. Do this by starting with the set of direct
716    # dependencies, then the dependencies of those dependencies, and so on.
717    get_target_property(new_libs ${target} LINK_LIBRARIES)
718    set(link_libs ${new_libs})
719    while(NOT "${new_libs}" STREQUAL "")
720      foreach(lib ${new_libs})
721        if(TARGET ${lib})
722          get_target_property(lib_type ${lib} TYPE)
723          if("${lib_type}" STREQUAL "STATIC_LIBRARY")
724            list(APPEND static_libs ${lib})
725          else()
726            list(APPEND other_libs ${lib})
727          endif()
728          get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
729          foreach(transitive_lib ${transitive_libs})
730            list(FIND link_libs ${transitive_lib} idx)
731            if(TARGET ${transitive_lib} AND idx EQUAL -1)
732              list(APPEND newer_libs ${transitive_lib})
733              list(APPEND link_libs ${transitive_lib})
734            endif()
735          endforeach(transitive_lib)
736        endif()
737      endforeach(lib)
738      set(new_libs ${newer_libs})
739      set(newer_libs "")
740    endwhile()
741    if (MSVC)
742      set(mangling microsoft)
743    else()
744      set(mangling itanium)
745    endif()
746    add_custom_command(OUTPUT ${exported_symbol_file}
747                       COMMAND ${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
748                       WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
749                       DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
750                       VERBATIM
751                       COMMENT "Generating export list for ${target}")
752    add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
753    # If something links against this executable then we want a
754    # transitive link against only the libraries whose symbols
755    # we aren't exporting.
756    set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
757    # The default import library suffix that cmake uses for cygwin/mingw is
758    # ".dll.a", but for clang.exe that causes a collision with libclang.dll,
759    # where the import libraries of both get named libclang.dll.a. Use a suffix
760    # of ".exe.a" to avoid this.
761    if(CYGWIN OR MINGW)
762      set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
763    endif()
764  elseif(NOT (WIN32 OR CYGWIN))
765    # On Windows auto-exporting everything doesn't work because of the limit on
766    # the size of the exported symbol table, but on other platforms we can do
767    # it without any trouble.
768    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
769    if (APPLE)
770      set_property(TARGET ${target} APPEND_STRING PROPERTY
771        LINK_FLAGS " -rdynamic")
772    endif()
773  endif()
774endfunction()
775
776if(NOT LLVM_TOOLCHAIN_TOOLS)
777  set (LLVM_TOOLCHAIN_TOOLS
778    llvm-ar
779    llvm-ranlib
780    llvm-lib
781    llvm-objdump
782    )
783endif()
784
785macro(add_llvm_tool name)
786  if( NOT LLVM_BUILD_TOOLS )
787    set(EXCLUDE_FROM_ALL ON)
788  endif()
789  add_llvm_executable(${name} ${ARGN})
790
791  if ( ${name} IN_LIST LLVM_TOOLCHAIN_TOOLS OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
792    if( LLVM_BUILD_TOOLS )
793      install(TARGETS ${name}
794              EXPORT LLVMExports
795              RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR}
796              COMPONENT ${name})
797
798      if (NOT CMAKE_CONFIGURATION_TYPES)
799        add_custom_target(install-${name}
800                          DEPENDS ${name}
801                          COMMAND "${CMAKE_COMMAND}"
802                                  -DCMAKE_INSTALL_COMPONENT=${name}
803                                  -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
804      endif()
805    endif()
806  endif()
807  if( LLVM_BUILD_TOOLS )
808    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
809  endif()
810  set_target_properties(${name} PROPERTIES FOLDER "Tools")
811endmacro(add_llvm_tool name)
812
813
814macro(add_llvm_example name)
815  if( NOT LLVM_BUILD_EXAMPLES )
816    set(EXCLUDE_FROM_ALL ON)
817  endif()
818  add_llvm_executable(${name} ${ARGN})
819  if( LLVM_BUILD_EXAMPLES )
820    install(TARGETS ${name} RUNTIME DESTINATION examples)
821  endif()
822  set_target_properties(${name} PROPERTIES FOLDER "Examples")
823endmacro(add_llvm_example name)
824
825# This is a macro that is used to create targets for executables that are needed
826# for development, but that are not intended to be installed by default.
827macro(add_llvm_utility name)
828  if ( NOT LLVM_BUILD_UTILS )
829    set(EXCLUDE_FROM_ALL ON)
830  endif()
831
832  add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
833  set_target_properties(${name} PROPERTIES FOLDER "Utils")
834  if( LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS )
835    install (TARGETS ${name}
836      RUNTIME DESTINATION bin
837      COMPONENT ${name})
838    if (NOT CMAKE_CONFIGURATION_TYPES)
839      add_custom_target(install-${name}
840                        DEPENDS ${name}
841                        COMMAND "${CMAKE_COMMAND}"
842                                -DCMAKE_INSTALL_COMPONENT=${name}
843                                -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
844    endif()
845  endif()
846endmacro(add_llvm_utility name)
847
848
849macro(add_llvm_target target_name)
850  include_directories(BEFORE
851    ${CMAKE_CURRENT_BINARY_DIR}
852    ${CMAKE_CURRENT_SOURCE_DIR})
853  add_llvm_library(LLVM${target_name} ${ARGN})
854  set( CURRENT_LLVM_TARGET LLVM${target_name} )
855endmacro(add_llvm_target)
856
857function(canonicalize_tool_name name output)
858  string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" nameStrip ${name})
859  string(REPLACE "-" "_" nameUNDERSCORE ${nameStrip})
860  string(TOUPPER ${nameUNDERSCORE} nameUPPER)
861  set(${output} "${nameUPPER}" PARENT_SCOPE)
862endfunction(canonicalize_tool_name)
863
864# Custom add_subdirectory wrapper
865# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
866# path if it differs from the name.
867macro(add_llvm_subdirectory project type name)
868  set(add_llvm_external_dir "${ARGN}")
869  if("${add_llvm_external_dir}" STREQUAL "")
870    set(add_llvm_external_dir ${name})
871  endif()
872  canonicalize_tool_name(${name} nameUPPER)
873  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}/CMakeLists.txt)
874    # Treat it as in-tree subproject.
875    option(${project}_${type}_${nameUPPER}_BUILD
876           "Whether to build ${name} as part of ${project}" On)
877    mark_as_advanced(${project}_${type}_${name}_BUILD)
878    if(${project}_${type}_${nameUPPER}_BUILD)
879      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir} ${add_llvm_external_dir})
880      # Don't process it in add_llvm_implicit_projects().
881      set(${project}_${type}_${nameUPPER}_BUILD OFF)
882    endif()
883  else()
884    set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR
885      "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}"
886      CACHE PATH "Path to ${name} source directory")
887    set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT ON)
888    if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR OR NOT EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
889      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
890    endif()
891    if("${LLVM_EXTERNAL_${nameUPPER}_BUILD}" STREQUAL "OFF")
892      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
893    endif()
894    option(${project}_${type}_${nameUPPER}_BUILD
895      "Whether to build ${name} as part of LLVM"
896      ${${project}_${type}_${nameUPPER}_BUILD_DEFAULT})
897    if (${project}_${type}_${nameUPPER}_BUILD)
898      if(EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
899        add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir})
900      elseif(NOT "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "")
901        message(WARNING "Nonexistent directory for ${name}: ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}")
902      endif()
903      # FIXME: It'd be redundant.
904      set(${project}_${type}_${nameUPPER}_BUILD Off)
905    endif()
906  endif()
907endmacro()
908
909# Add external project that may want to be built as part of llvm such as Clang,
910# lld, and Polly. This adds two options. One for the source directory of the
911# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
912# enable or disable building it with everything else.
913# Additional parameter can be specified as the name of directory.
914macro(add_llvm_external_project name)
915  add_llvm_subdirectory(LLVM TOOL ${name} ${ARGN})
916endmacro()
917
918macro(add_llvm_tool_subdirectory name)
919  add_llvm_external_project(${name})
920endmacro(add_llvm_tool_subdirectory)
921
922function(get_project_name_from_src_var var output)
923  string(REGEX MATCH "LLVM_EXTERNAL_(.*)_SOURCE_DIR"
924         MACHED_TOOL "${var}")
925  if(MACHED_TOOL)
926    set(${output} ${CMAKE_MATCH_1} PARENT_SCOPE)
927  else()
928    set(${output} PARENT_SCOPE)
929  endif()
930endfunction()
931
932function(create_subdirectory_options project type)
933  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
934  foreach(dir ${sub-dirs})
935    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
936      canonicalize_tool_name(${dir} name)
937      option(${project}_${type}_${name}_BUILD
938           "Whether to build ${name} as part of ${project}" On)
939      mark_as_advanced(${project}_${type}_${name}_BUILD)
940    endif()
941  endforeach()
942endfunction(create_subdirectory_options)
943
944function(create_llvm_tool_options)
945  create_subdirectory_options(LLVM TOOL)
946endfunction(create_llvm_tool_options)
947
948function(llvm_add_implicit_projects project)
949  set(list_of_implicit_subdirs "")
950  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
951  foreach(dir ${sub-dirs})
952    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
953      canonicalize_tool_name(${dir} name)
954      if (${project}_TOOL_${name}_BUILD)
955        get_filename_component(fn "${dir}" NAME)
956        list(APPEND list_of_implicit_subdirs "${fn}")
957      endif()
958    endif()
959  endforeach()
960
961  foreach(external_proj ${list_of_implicit_subdirs})
962    add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
963  endforeach()
964endfunction(llvm_add_implicit_projects)
965
966function(add_llvm_implicit_projects)
967  llvm_add_implicit_projects(LLVM)
968endfunction(add_llvm_implicit_projects)
969
970# Generic support for adding a unittest.
971function(add_unittest test_suite test_name)
972  if( NOT LLVM_BUILD_TESTS )
973    set(EXCLUDE_FROM_ALL ON)
974  endif()
975
976  include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include)
977  if (NOT LLVM_ENABLE_THREADS)
978    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_PTHREAD=0)
979  endif ()
980
981  if (SUPPORTS_NO_VARIADIC_MACROS_FLAG)
982    list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros")
983  endif ()
984
985  set(LLVM_REQUIRES_RTTI OFF)
986
987  list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
988  add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO ${ARGN})
989  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
990  set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
991  # libpthreads overrides some standard library symbols, so main
992  # executable must be linked with it in order to provide consistent
993  # API for all shared libaries loaded by this executable.
994  target_link_libraries(${test_name} gtest_main gtest ${PTHREAD_LIB})
995
996  add_dependencies(${test_suite} ${test_name})
997  get_target_property(test_suite_folder ${test_suite} FOLDER)
998  if (NOT ${test_suite_folder} STREQUAL "NOTFOUND")
999    set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
1000  endif ()
1001endfunction()
1002
1003function(llvm_add_go_executable binary pkgpath)
1004  cmake_parse_arguments(ARG "ALL" "" "DEPENDS;GOFLAGS" ${ARGN})
1005
1006  if(LLVM_BINDINGS MATCHES "go")
1007    # FIXME: This should depend only on the libraries Go needs.
1008    get_property(llvmlibs GLOBAL PROPERTY LLVM_LIBS)
1009    set(binpath ${CMAKE_BINARY_DIR}/bin/${binary}${CMAKE_EXECUTABLE_SUFFIX})
1010    set(cc "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1011    set(cxx "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1012    set(cppflags "")
1013    get_property(include_dirs DIRECTORY PROPERTY INCLUDE_DIRECTORIES)
1014    foreach(d ${include_dirs})
1015      set(cppflags "${cppflags} -I${d}")
1016    endforeach(d)
1017    set(ldflags "${CMAKE_EXE_LINKER_FLAGS}")
1018    add_custom_command(OUTPUT ${binpath}
1019      COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "go=${GO_EXECUTABLE}" "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}" "packages=${LLVM_GO_PACKAGES}"
1020              ${ARG_GOFLAGS} build -o ${binpath} ${pkgpath}
1021      DEPENDS llvm-config ${CMAKE_BINARY_DIR}/bin/llvm-go${CMAKE_EXECUTABLE_SUFFIX}
1022              ${llvmlibs} ${ARG_DEPENDS}
1023      COMMENT "Building Go executable ${binary}"
1024      VERBATIM)
1025    if (ARG_ALL)
1026      add_custom_target(${binary} ALL DEPENDS ${binpath})
1027    else()
1028      add_custom_target(${binary} DEPENDS ${binpath})
1029    endif()
1030  endif()
1031endfunction()
1032
1033# This function provides an automatic way to 'configure'-like generate a file
1034# based on a set of common and custom variables, specifically targeting the
1035# variables needed for the 'lit.site.cfg' files. This function bundles the
1036# common variables that any Lit instance is likely to need, and custom
1037# variables can be passed in.
1038function(configure_lit_site_cfg input output)
1039  foreach(c ${LLVM_TARGETS_TO_BUILD})
1040    set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
1041  endforeach(c)
1042  set(TARGETS_TO_BUILD ${TARGETS_BUILT})
1043
1044  set(SHLIBEXT "${LTDL_SHLIB_EXT}")
1045
1046  # Configuration-time: See Unit/lit.site.cfg.in
1047  if (CMAKE_CFG_INTDIR STREQUAL ".")
1048    set(LLVM_BUILD_MODE ".")
1049  else ()
1050    set(LLVM_BUILD_MODE "%(build_mode)s")
1051  endif ()
1052
1053  # They below might not be the build tree but provided binary tree.
1054  set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
1055  set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
1056  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_TOOLS_DIR ${LLVM_TOOLS_BINARY_DIR})
1057  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_LIBS_DIR  ${LLVM_LIBRARY_DIR})
1058
1059  # SHLIBDIR points the build tree.
1060  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}")
1061
1062  set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})
1063  # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for
1064  # plugins. We may rename it.
1065  if(LLVM_ENABLE_PLUGINS)
1066    set(ENABLE_SHARED "1")
1067  else()
1068    set(ENABLE_SHARED "0")
1069  endif()
1070
1071  if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE)
1072    set(ENABLE_ASSERTIONS "1")
1073  else()
1074    set(ENABLE_ASSERTIONS "0")
1075  endif()
1076
1077  set(HOST_OS ${CMAKE_SYSTEM_NAME})
1078  set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR})
1079
1080  set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1081  set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1082  set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")
1083
1084  set(LIT_SITE_CFG_IN_HEADER  "## Autogenerated from ${input}\n## Do not edit!")
1085
1086  configure_file(${input} ${output} @ONLY)
1087endfunction()
1088
1089# A raw function to create a lit target. This is used to implement the testuite
1090# management functions.
1091function(add_lit_target target comment)
1092  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1093  set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
1094  separate_arguments(LIT_ARGS)
1095  if (NOT CMAKE_CFG_INTDIR STREQUAL ".")
1096    list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR})
1097  endif ()
1098  if (EXISTS ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py)
1099    # reset cache after erraneous r283029
1100    # TODO: remove this once all buildbots run
1101    if (LIT_COMMAND STREQUAL "${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py")
1102      unset(LIT_COMMAND CACHE)
1103    endif()
1104    set (LIT_COMMAND "${PYTHON_EXECUTABLE};${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py"
1105         CACHE STRING "Command used to spawn llvm-lit")
1106  else()
1107    find_program(LIT_COMMAND NAMES llvm-lit lit.py lit)
1108  endif ()
1109  list(APPEND LIT_COMMAND ${LIT_ARGS})
1110  foreach(param ${ARG_PARAMS})
1111    list(APPEND LIT_COMMAND --param ${param})
1112  endforeach()
1113  if (ARG_UNPARSED_ARGUMENTS)
1114    add_custom_target(${target}
1115      COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
1116      COMMENT "${comment}"
1117      USES_TERMINAL
1118      )
1119  else()
1120    add_custom_target(${target}
1121      COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.")
1122    message(STATUS "${target} does nothing.")
1123  endif()
1124  if (ARG_DEPENDS)
1125    add_dependencies(${target} ${ARG_DEPENDS})
1126  endif()
1127
1128  # Tests should be excluded from "Build Solution".
1129  set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON)
1130endfunction()
1131
1132# A function to add a set of lit test suites to be driven through 'check-*' targets.
1133function(add_lit_testsuite target comment)
1134  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1135
1136  # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all.
1137  if(NOT EXCLUDE_FROM_ALL)
1138    # Register the testsuites, params and depends for the global check rule.
1139    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS})
1140    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS})
1141    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS})
1142    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS})
1143  endif()
1144
1145  # Produce a specific suffixed check rule.
1146  add_lit_target(${target} ${comment}
1147    ${ARG_UNPARSED_ARGUMENTS}
1148    PARAMS ${ARG_PARAMS}
1149    DEPENDS ${ARG_DEPENDS}
1150    ARGS ${ARG_ARGS}
1151    )
1152endfunction()
1153
1154function(add_lit_testsuites project directory)
1155  if (NOT CMAKE_CONFIGURATION_TYPES)
1156    cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1157
1158    # Search recursively for test directories by assuming anything not
1159    # in a directory called Inputs contains tests.
1160    file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*)
1161    foreach(lit_suite ${to_process})
1162      if(NOT IS_DIRECTORY ${lit_suite})
1163        continue()
1164      endif()
1165      string(FIND ${lit_suite} Inputs is_inputs)
1166      string(FIND ${lit_suite} Output is_output)
1167      if (NOT (is_inputs EQUAL -1 AND is_output EQUAL -1))
1168        continue()
1169      endif()
1170
1171      # Create a check- target for the directory.
1172      string(REPLACE ${directory} "" name_slash ${lit_suite})
1173      if (name_slash)
1174        string(REPLACE "/" "-" name_slash ${name_slash})
1175        string(REPLACE "\\" "-" name_dashes ${name_slash})
1176        string(TOLOWER "${project}${name_dashes}" name_var)
1177        add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}"
1178          ${lit_suite}
1179          PARAMS ${ARG_PARAMS}
1180          DEPENDS ${ARG_DEPENDS}
1181          ARGS ${ARG_ARGS}
1182        )
1183      endif()
1184    endforeach()
1185  endif()
1186endfunction()
1187
1188function(llvm_install_library_symlink name dest type)
1189  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1190  foreach(path ${CMAKE_MODULE_PATH})
1191    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1192      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1193      break()
1194    endif()
1195  endforeach()
1196
1197  set(component ${ARG_COMPONENT})
1198  if(NOT component)
1199    set(component ${name})
1200  endif()
1201
1202  set(full_name ${CMAKE_${type}_LIBRARY_PREFIX}${name}${CMAKE_${type}_LIBRARY_SUFFIX})
1203  set(full_dest ${CMAKE_${type}_LIBRARY_PREFIX}${dest}${CMAKE_${type}_LIBRARY_SUFFIX})
1204
1205  set(output_dir lib${LLVM_LIBDIR_SUFFIX})
1206  if(WIN32 AND "${type}" STREQUAL "SHARED")
1207    set(output_dir bin)
1208  endif()
1209
1210  install(SCRIPT ${INSTALL_SYMLINK}
1211          CODE "install_symlink(${full_name} ${full_dest} ${output_dir})"
1212          COMPONENT ${component})
1213
1214  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1215    add_custom_target(install-${name}
1216                      DEPENDS ${name} ${dest} install-${dest}
1217                      COMMAND "${CMAKE_COMMAND}"
1218                              -DCMAKE_INSTALL_COMPONENT=${name}
1219                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
1220  endif()
1221endfunction()
1222
1223function(llvm_install_symlink name dest)
1224  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "" "" ${ARGN})
1225  foreach(path ${CMAKE_MODULE_PATH})
1226    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1227      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1228      break()
1229    endif()
1230  endforeach()
1231
1232  if(ARG_ALWAYS_GENERATE)
1233    set(component ${dest})
1234  else()
1235    set(component ${name})
1236  endif()
1237
1238  set(full_name ${name}${CMAKE_EXECUTABLE_SUFFIX})
1239  set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})
1240
1241  install(SCRIPT ${INSTALL_SYMLINK}
1242          CODE "install_symlink(${full_name} ${full_dest} ${LLVM_TOOLS_INSTALL_DIR})"
1243          COMPONENT ${component})
1244
1245  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1246    add_custom_target(install-${name}
1247                      DEPENDS ${name} ${dest} install-${dest}
1248                      COMMAND "${CMAKE_COMMAND}"
1249                              -DCMAKE_INSTALL_COMPONENT=${name}
1250                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
1251  endif()
1252endfunction()
1253
1254function(add_llvm_tool_symlink name dest)
1255  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "" "" ${ARGN})
1256  if(UNIX)
1257    set(LLVM_LINK_OR_COPY create_symlink)
1258    set(dest_binary "${dest}${CMAKE_EXECUTABLE_SUFFIX}")
1259  else()
1260    set(LLVM_LINK_OR_COPY copy)
1261    set(dest_binary "${LLVM_RUNTIME_OUTPUT_INTDIR}/${dest}${CMAKE_EXECUTABLE_SUFFIX}")
1262  endif()
1263
1264  set(output_path "${LLVM_RUNTIME_OUTPUT_INTDIR}/${name}${CMAKE_EXECUTABLE_SUFFIX}")
1265
1266  set(target_name ${name})
1267  if(TARGET ${name})
1268    set(target_name ${name}-link)
1269  endif()
1270
1271
1272  if(ARG_ALWAYS_GENERATE)
1273    set_property(DIRECTORY APPEND PROPERTY
1274      ADDITIONAL_MAKE_CLEAN_FILES ${dest_binary})
1275    add_custom_command(TARGET ${dest} POST_BUILD
1276      COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}")
1277  else()
1278    add_custom_command(OUTPUT ${output_path}
1279                     COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}"
1280                     DEPENDS ${dest})
1281    add_custom_target(${target_name} ALL DEPENDS ${output_path})
1282    set_target_properties(${target_name} PROPERTIES FOLDER Tools)
1283
1284    # Make sure both the link and target are toolchain tools
1285    if (${name} IN_LIST LLVM_TOOLCHAIN_TOOLS AND ${dest} IN_LIST LLVM_TOOLCHAIN_TOOLS)
1286      set(TOOL_IS_TOOLCHAIN ON)
1287    endif()
1288
1289    if ((TOOL_IS_TOOLCHAIN OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY) AND LLVM_BUILD_TOOLS)
1290      llvm_install_symlink(${name} ${dest})
1291    endif()
1292  endif()
1293endfunction()
1294
1295function(llvm_externalize_debuginfo name)
1296  if(NOT LLVM_EXTERNALIZE_DEBUGINFO)
1297    return()
1298  endif()
1299
1300  if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
1301    set(strip_command COMMAND xcrun strip -Sxl $<TARGET_FILE:${name}>)
1302  endif()
1303
1304  if(APPLE)
1305    if(CMAKE_CXX_FLAGS MATCHES "-flto"
1306      OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
1307
1308      set(lto_object ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${name}-lto.o)
1309      set_property(TARGET ${name} APPEND_STRING PROPERTY
1310        LINK_FLAGS " -Wl,-object_path_lto,${lto_object}")
1311    endif()
1312    add_custom_command(TARGET ${name} POST_BUILD
1313      COMMAND xcrun dsymutil $<TARGET_FILE:${name}>
1314      ${strip_command}
1315      )
1316  else()
1317    message(FATAL_ERROR "LLVM_EXTERNALIZE_DEBUGINFO isn't implemented for non-darwin platforms!")
1318  endif()
1319endfunction()
1320