Large diffs are not rendered by default.

Oops, something went wrong.
@@ -8,9 +8,9 @@ function(llvm_update_compile_flags name)
set(update_src_props ON)
endif()

# LLVM_REQUIRES_EH is an internal flag that individual
# targets can use to force EH
if((LLVM_REQUIRES_EH OR LLVM_ENABLE_EH) AND NOT CLANG_CL)
# LLVM_REQUIRES_EH is an internal flag that individual targets can use to
# force EH
if(LLVM_REQUIRES_EH OR LLVM_ENABLE_EH)
if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
message(AUTHOR_WARNING "Exception handling requires RTTI. Enabling RTTI for ${name}")
set(LLVM_REQUIRES_RTTI ON)
@@ -328,11 +328,13 @@ endfunction(set_windows_version_resource_properties)
# May specify header files for IDE generators.
# SONAME
# Should set SONAME link flags and create symlinks
# PLUGIN_TOOL
# The tool (i.e. cmake target) that this plugin will link against
# )
function(llvm_add_library name)
cmake_parse_arguments(ARG
"MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME"
"OUTPUT_NAME"
"OUTPUT_NAME;PLUGIN_TOOL"
"ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
${ARGN})
list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
@@ -350,11 +352,15 @@ function(llvm_add_library name)
if(ARG_SHARED OR ARG_STATIC)
message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
endif()
if(NOT LLVM_ENABLE_PLUGINS)
# Plugins that link against a tool are allowed even when plugins in general are not
if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
return()
endif()
else()
if(ARG_PLUGIN_TOOL)
message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
endif()
if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
set(ARG_SHARED TRUE)
endif()
@@ -468,43 +474,40 @@ function(llvm_add_library name)
endif()
endif()

# Add the explicit dependency information for this library.
#
# It would be nice to verify that we have the dependencies for this library
# name, but using get_property(... SET) doesn't suffice to determine if a
# property has been set to an empty value.
get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})

if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_STATIC AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
set(llvm_libs LLVM)
if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
# On DLL platforms symbols are imported from the tool by linking against it.
set(llvm_libs ${ARG_PLUGIN_TOOL})
elseif (DEFINED LLVM_LINK_COMPONENTS OR DEFINED ARG_LINK_COMPONENTS)
if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
set(llvm_libs LLVM)
else()
llvm_map_components_to_libnames(llvm_libs
${ARG_LINK_COMPONENTS}
${LLVM_LINK_COMPONENTS}
)
endif()
else()
llvm_map_components_to_libnames(llvm_libs
${ARG_LINK_COMPONENTS}
${LLVM_LINK_COMPONENTS}
)
# Components have not been defined explicitly in CMake, so add the
# dependency information for this library as defined by LLVMBuild.
#
# It would be nice to verify that we have the dependencies for this library
# name, but using get_property(... SET) doesn't suffice to determine if a
# property has been set to an empty value.
get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
endif()

if(CMAKE_VERSION VERSION_LESS 2.8.12)
# Link libs w/o keywords, assuming PUBLIC.
target_link_libraries(${name}
${ARG_LINK_LIBS}
${lib_deps}
${llvm_libs}
)
elseif(ARG_STATIC)
target_link_libraries(${name} INTERFACE
${ARG_LINK_LIBS}
${lib_deps}
${llvm_libs}
)
if(ARG_STATIC)
set(libtype INTERFACE)
else()
# We can use PRIVATE since SO knows its dependent libs.
target_link_libraries(${name} PRIVATE
set(libtype PRIVATE)
endif()

target_link_libraries(${name} ${libtype}
${ARG_LINK_LIBS}
${lib_deps}
${llvm_libs}
)
endif()

if(LLVM_COMMON_DEPENDS)
add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
@@ -667,10 +670,78 @@ macro(add_llvm_executable name)
if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
llvm_externalize_debuginfo(${name})
endif()
if (PTHREAD_LIB)
# libpthreads overrides some standard library symbols, so main
# executable must be linked with it in order to provide consistent
# API for all shared libaries loaded by this executable.
target_link_libraries(${name} ${PTHREAD_LIB})
endif()
endmacro(add_llvm_executable name)

function(export_executable_symbols target)
if (NOT MSVC) # MSVC's linker doesn't support exporting all symbols.
if (LLVM_EXPORTED_SYMBOL_FILE)
# The symbol file should contain the symbols we want the executable to
# export
set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
# Extract the symbols to export from the static libraries that the
# executable links against.
set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
# We need to consider not just the direct link dependencies, but also the
# transitive link dependencies. Do this by starting with the set of direct
# dependencies, then the dependencies of those dependencies, and so on.
get_target_property(new_libs ${target} LINK_LIBRARIES)
set(link_libs ${new_libs})
while(NOT "${new_libs}" STREQUAL "")
foreach(lib ${new_libs})
if(TARGET ${lib})
get_target_property(lib_type ${lib} TYPE)
if("${lib_type}" STREQUAL "STATIC_LIBRARY")
list(APPEND static_libs ${lib})
else()
list(APPEND other_libs ${lib})
endif()
get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
foreach(transitive_lib ${transitive_libs})
list(FIND link_libs ${transitive_lib} idx)
if(TARGET ${transitive_lib} AND idx EQUAL -1)
list(APPEND newer_libs ${transitive_lib})
list(APPEND link_libs ${transitive_lib})
endif()
endforeach(transitive_lib)
endif()
endforeach(lib)
set(new_libs ${newer_libs})
set(newer_libs "")
endwhile()
if (MSVC)
set(mangling microsoft)
else()
set(mangling itanium)
endif()
add_custom_command(OUTPUT ${exported_symbol_file}
COMMAND ${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
VERBATIM
COMMENT "Generating export list for ${target}")
add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
# If something links against this executable then we want a
# transitive link against only the libraries whose symbols
# we aren't exporting.
set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
# The default import library suffix that cmake uses for cygwin/mingw is
# ".dll.a", but for clang.exe that causes a collision with libclang.dll,
# where the import libraries of both get named libclang.dll.a. Use a suffix
# of ".exe.a" to avoid this.
if(CYGWIN OR MINGW)
set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
endif()
elseif(NOT (WIN32 OR CYGWIN))
# On Windows auto-exporting everything doesn't work because of the limit on
# the size of the exported symbol table, but on other platforms we can do
# it without any trouble.
set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
if (APPLE)
set_property(TARGET ${target} APPEND_STRING PROPERTY
@@ -699,7 +770,7 @@ macro(add_llvm_tool name)
if( LLVM_BUILD_TOOLS )
install(TARGETS ${name}
EXPORT LLVMExports
RUNTIME DESTINATION bin
RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR}
COMPONENT ${name})

if (NOT CMAKE_CONFIGURATION_TYPES)
@@ -729,11 +800,16 @@ macro(add_llvm_example name)
set_target_properties(${name} PROPERTIES FOLDER "Examples")
endmacro(add_llvm_example name)


# This is a macro that is used to create targets for executables that are needed
# for development, but that are not intended to be installed by default.
macro(add_llvm_utility name)
if ( NOT LLVM_BUILD_UTILS )
set(EXCLUDE_FROM_ALL ON)
endif()

add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
set_target_properties(${name} PROPERTIES FOLDER "Utils")
if( LLVM_INSTALL_UTILS )
if( LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS )
install (TARGETS ${name}
RUNTIME DESTINATION bin
COMPONENT ${name})
@@ -764,8 +840,8 @@ function(canonicalize_tool_name name output)
endfunction(canonicalize_tool_name)

# Custom add_subdirectory wrapper
# Takes in a project name (i.e. LLVM), the the subdirectory name, and an
# and an optional path if it differs from the name.
# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
# path if it differs from the name.
macro(add_llvm_subdirectory project type name)
set(add_llvm_external_dir "${ARGN}")
if("${add_llvm_external_dir}" STREQUAL "")
@@ -847,22 +923,26 @@ function(create_llvm_tool_options)
create_subdirectory_options(LLVM TOOL)
endfunction(create_llvm_tool_options)

function(add_llvm_implicit_projects)
function(llvm_add_implicit_projects project)
set(list_of_implicit_subdirs "")
file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
foreach(dir ${sub-dirs})
if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
canonicalize_tool_name(${dir} name)
if (LLVM_TOOL_${name}_BUILD)
if (${project}_TOOL_${name}_BUILD)
get_filename_component(fn "${dir}" NAME)
list(APPEND list_of_implicit_subdirs "${fn}")
endif()
endif()
endforeach()

foreach(external_proj ${list_of_implicit_subdirs})
add_llvm_external_project("${external_proj}")
add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
endforeach()
endfunction(llvm_add_implicit_projects)

function(add_llvm_implicit_projects)
llvm_add_implicit_projects(LLVM)
endfunction(add_llvm_implicit_projects)

# Generic support for adding a unittest.
@@ -882,14 +962,14 @@ function(add_unittest test_suite test_name)

set(LLVM_REQUIRES_RTTI OFF)

list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO ${ARGN})
set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
target_link_libraries(${test_name}
gtest
gtest_main
LLVMSupport # gtest needs it for raw_ostream.
)
# libpthreads overrides some standard library symbols, so main
# executable must be linked with it in order to provide consistent
# API for all shared libaries loaded by this executable.
target_link_libraries(${test_name} gtest_main gtest ${PTHREAD_LIB})

add_dependencies(${test_suite} ${test_name})
get_target_property(test_suite_folder ${test_suite} FOLDER)
@@ -913,13 +993,8 @@ function(llvm_add_go_executable binary pkgpath)
set(cppflags "${cppflags} -I${d}")
endforeach(d)
set(ldflags "${CMAKE_EXE_LINKER_FLAGS}")
if (LLVM_LINK_LLVM_DYLIB)
set(linkmode "dylib")
else()
set(linkmode "component-libs")
endif()
add_custom_command(OUTPUT ${binpath}
COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "go=${GO_EXECUTABLE}" "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}" "linkmode=${linkmode}"
COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "go=${GO_EXECUTABLE}" "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}"
${ARG_GOFLAGS} build -o ${binpath} ${pkgpath}
DEPENDS llvm-config ${CMAKE_BINARY_DIR}/bin/llvm-go${CMAKE_EXECUTABLE_SUFFIX}
${llvmlibs} ${ARG_DEPENDS}
@@ -984,6 +1059,8 @@ function(configure_lit_site_cfg input output)
set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")

set(LIT_SITE_CFG_IN_HEADER "## Autogenerated from ${input}\n## Do not edit!")

configure_file(${input} ${output} @ONLY)
endfunction()

@@ -1009,7 +1086,7 @@ function(add_lit_target target comment)
add_custom_target(${target}
COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
COMMENT "${comment}"
${cmake_3_2_USES_TERMINAL}
USES_TERMINAL
)
else()
add_custom_target(${target}
@@ -1049,21 +1126,27 @@ endfunction()
function(add_lit_testsuites project directory)
if (NOT CMAKE_CONFIGURATION_TYPES)
cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
file(GLOB_RECURSE litCfg ${directory}/lit*.cfg)
set(lit_suites)
foreach(f ${litCfg})
get_filename_component(dir ${f} DIRECTORY)
set(lit_suites ${lit_suites} ${dir})
endforeach()
list(REMOVE_DUPLICATES lit_suites)
foreach(dir ${lit_suites})
string(REPLACE ${directory} "" name_slash ${dir})

# Search recursively for test directories by assuming anything not
# in a directory called Inputs contains tests.
file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*)
foreach(lit_suite ${to_process})
if(NOT IS_DIRECTORY ${lit_suite})
continue()
endif()
string(FIND ${lit_suite} Inputs is_inputs)
if (NOT is_inputs EQUAL -1)
continue()
endif()

# Create a check- target for the directory.
string(REPLACE ${directory} "" name_slash ${lit_suite})
if (name_slash)
string(REPLACE "/" "-" name_slash ${name_slash})
string(REPLACE "\\" "-" name_dashes ${name_slash})
string(TOLOWER "${project}${name_dashes}" name_var)
add_lit_target("check-${name_var}" "Running lit suite ${dir}"
${dir}
add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}"
${lit_suite}
PARAMS ${ARG_PARAMS}
DEPENDS ${ARG_DEPENDS}
ARGS ${ARG_ARGS}
@@ -1127,7 +1210,7 @@ function(llvm_install_symlink name dest)
set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})

install(SCRIPT ${INSTALL_SYMLINK}
CODE "install_symlink(${full_name} ${full_dest} bin)"
CODE "install_symlink(${full_name} ${full_dest} ${LLVM_TOOLS_INSTALL_DIR})"
COMPONENT ${component})

if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
@@ -1186,6 +1269,10 @@ function(llvm_externalize_debuginfo name)
return()
endif()

if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
set(strip_command COMMAND xcrun strip -Sxl $<TARGET_FILE:${name}>)
endif()

if(APPLE)
if(CMAKE_CXX_FLAGS MATCHES "-flto"
OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
@@ -1196,7 +1283,8 @@ function(llvm_externalize_debuginfo name)
endif()
add_custom_command(TARGET ${name} POST_BUILD
COMMAND xcrun dsymutil $<TARGET_FILE:${name}>
COMMAND xcrun strip -Sl $<TARGET_FILE:${name}>)
${strip_command}
)
else()
message(FATAL_ERROR "LLVM_EXTERNALIZE_DEBUGINFO isn't implemented for non-darwin platforms!")
endif()
@@ -73,7 +73,13 @@ function(add_ocaml_library name)

get_property(system_libs TARGET LLVMSupport PROPERTY LLVM_SYSTEM_LIBS)
foreach(system_lib ${system_libs})
list(APPEND ocaml_flags "-l${system_lib}" )
if (system_lib MATCHES "^-")
# If it's an option, pass it without changes.
list(APPEND ocaml_flags "${system_lib}" )
else()
# Otherwise assume it's a library name we need to link with.
list(APPEND ocaml_flags "-l${system_lib}" )
endif()
endforeach()

string(REPLACE ";" " " ARG_CFLAGS "${ARG_CFLAGS}")
@@ -1,4 +1,4 @@
set(LLVM_INSTALL_PACKAGE_DIR share/llvm/cmake)
set(LLVM_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm)
set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/${LLVM_INSTALL_PACKAGE_DIR}")

get_property(LLVM_EXPORTS GLOBAL PROPERTY LLVM_EXPORTS)
@@ -29,6 +29,7 @@ set(LLVM_CONFIG_LIBRARY_DIRS
"${LLVM_LIBRARY_DIR}"
)
set(LLVM_CONFIG_CMAKE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(LLVM_CONFIG_BINARY_DIR "${LLVM_BINARY_DIR}")
set(LLVM_CONFIG_TOOLS_BINARY_DIR "${LLVM_TOOLS_BINARY_DIR}")
set(LLVM_CONFIG_EXPORTS_FILE "${llvm_cmake_builddir}/LLVMExports.cmake")
configure_file(
@@ -60,6 +61,7 @@ endforeach(p)
set(LLVM_CONFIG_INCLUDE_DIRS "\${LLVM_INSTALL_PREFIX}/include")
set(LLVM_CONFIG_LIBRARY_DIRS "\${LLVM_INSTALL_PREFIX}/lib\${LLVM_LIBDIR_SUFFIX}")
set(LLVM_CONFIG_CMAKE_DIR "\${LLVM_INSTALL_PREFIX}/${LLVM_INSTALL_PACKAGE_DIR}")
set(LLVM_CONFIG_BINARY_DIR "\${LLVM_INSTALL_PREFIX}")
set(LLVM_CONFIG_TOOLS_BINARY_DIR "\${LLVM_INSTALL_PREFIX}/bin")
set(LLVM_CONFIG_EXPORTS_FILE "\${LLVM_CMAKE_DIR}/LLVMExports.cmake")
configure_file(
@@ -90,6 +92,5 @@ if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
PATTERN LLVMConfigVersion.cmake EXCLUDE
PATTERN LLVM-Config.cmake EXCLUDE
PATTERN GetHostTriple.cmake EXCLUDE
PATTERN VersionFromVCS.cmake EXCLUDE
PATTERN CheckAtomic.cmake EXCLUDE)
endif()
@@ -18,6 +18,22 @@ int main() {
set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
endfunction(check_working_cxx_atomics)

function(check_working_cxx_atomics64 varname)
set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_FLAGS "-std=c++11 ${CMAKE_REQUIRED_FLAGS}")
CHECK_CXX_SOURCE_COMPILES("
#include <atomic>
#include <cstdint>
std::atomic<uint64_t> x (0);
int main() {
uint64_t i = x.load(std::memory_order_relaxed);
return 0;
}
" ${varname})
set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
endfunction(check_working_cxx_atomics64)


# This isn't necessary on MSVC, so avoid command-line switch annoyance
# by only running on GCC-like hosts.
if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
@@ -38,6 +54,27 @@ if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
endif()
endif()

# Check for 64 bit atomic operations.
if(MSVC)
set(HAVE_CXX_ATOMICS64_WITHOUT_LIB True)
else()
check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITHOUT_LIB)
endif()

# If not, check if the library exists, and atomics work with it.
if(NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB)
check_library_exists(atomic __atomic_load_8 "" HAVE_CXX_LIBATOMICS64)
if(HAVE_CXX_LIBATOMICS64)
list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITH_LIB)
if (NOT HAVE_CXX_ATOMICS64_WITH_LIB)
message(FATAL_ERROR "Host compiler must support std::atomic!")
endif()
else()
message(FATAL_ERROR "Host compiler appears to require libatomic, but cannot find it.")
endif()
endif()

## TODO: This define is only used for the legacy atomic operations in
## llvm's Atomic.h, which should be replaced. Other code simply
## assumes C++11 <atomic> works.
@@ -0,0 +1,52 @@
# Check if the host compiler is new enough. LLVM requires at least GCC 4.7,
# MSVC 2013, or Clang 3.1.

include(CheckCXXSourceCompiles)

if(NOT DEFINED LLVM_COMPILER_CHECKED)
set(LLVM_COMPILER_CHECKED ON)

if(NOT LLVM_FORCE_USE_OLD_TOOLCHAIN)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7)
message(FATAL_ERROR "Host GCC version must be at least 4.7!")
endif()
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
message(FATAL_ERROR "Host Clang version must be at least 3.1!")
endif()

if (CMAKE_CXX_SIMULATE_ID MATCHES "MSVC")
if (CMAKE_CXX_SIMULATE_VERSION VERSION_LESS 18.0)
message(FATAL_ERROR "Host Clang must have at least -fms-compatibility-version=18.0")
endif()
set(CLANG_CL 1)
elseif(NOT LLVM_ENABLE_LIBCXX)
# Otherwise, test that we aren't using too old of a version of libstdc++
# with the Clang compiler. This is tricky as there is no real way to
# check the version of libstdc++ directly. Instead we test for a known
# bug in libstdc++4.6 that is fixed in libstdc++4.7.
set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
set(OLD_CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
set(CMAKE_REQUIRED_FLAGS "-std=c++0x")
check_cxx_source_compiles("
#include <atomic>
std::atomic<float> x(0.0f);
int main() { return (float)x; }"
LLVM_NO_OLD_LIBSTDCXX)
if(NOT LLVM_NO_OLD_LIBSTDCXX)
message(FATAL_ERROR "Host Clang must be able to find libstdc++4.7 or newer!")
endif()
set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_LIBRARIES ${OLD_CMAKE_REQUIRED_LIBRARIES})
endif()
elseif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0)
message(FATAL_ERROR "Host Visual Studio must be at least 2013")
elseif(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0.31101)
message(WARNING "Host Visual Studio should at least be 2013 Update 4 (MSVC 18.0.31101)"
" due to miscompiles from earlier versions")
endif()
endif()
endif()
endif()
@@ -1,4 +1,4 @@
function(llvm_create_cross_target_internal target_name toochain buildtype)
function(llvm_create_cross_target_internal target_name toolchain buildtype)

if(NOT DEFINED LLVM_${target_name}_BUILD)
set(LLVM_${target_name}_BUILD "${CMAKE_BINARY_DIR}/${target_name}")
@@ -0,0 +1,39 @@
# CMake project that writes Subversion revision information to a header.
#
# Input variables:
# SRC - Source directory
# HEADER_FILE - The header file to write
#
# The output header will contain macros FIRST_REPOSITORY and FIRST_REVISION,
# and SECOND_REPOSITORY and SECOND_REVISION if requested, where "FIRST" and
# "SECOND" are substituted with the names specified in the input variables.



# Chop off cmake/modules/GetSVN.cmake
get_filename_component(LLVM_DIR "${CMAKE_SCRIPT_MODE_FILE}" PATH)
get_filename_component(LLVM_DIR "${LLVM_DIR}" PATH)
get_filename_component(LLVM_DIR "${LLVM_DIR}" PATH)

set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
"${LLVM_DIR}/cmake/modules")
include(VersionFromVCS)

# Handle strange terminals
set(ENV{TERM} "dumb")

function(append_info name path)
add_version_info_from_vcs(REVISION ${path})
string(STRIP "${REVISION}" REVISION)
file(APPEND "${HEADER_FILE}.txt"
"#define ${name} \"${REVISION}\"\n")
endfunction()

append_info(${NAME} "${SOURCE_DIR}")

# Copy the file only if it has changed.
execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${HEADER_FILE}.txt" "${HEADER_FILE}")
file(REMOVE "${HEADER_FILE}.txt")

@@ -15,7 +15,7 @@ function( get_host_triple var )
set( value "i686-pc-mingw32" )
endif()
else( MSVC )
set(config_guess ${LLVM_MAIN_SRC_DIR}/autoconf/config.guess)
set(config_guess ${LLVM_MAIN_SRC_DIR}/cmake/config.guess)
execute_process(COMMAND sh ${config_guess}
RESULT_VARIABLE TT_RV
OUTPUT_VARIABLE TT_OUT
@@ -6,53 +6,19 @@
# else.
string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE)

include(CheckCompilerVersion)
include(HandleLLVMStdlib)
include(AddLLVMDefinitions)
include(CheckCCompilerFlag)
include(CheckCXXCompilerFlag)

if(NOT LLVM_FORCE_USE_OLD_TOOLCHAIN)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7)
message(FATAL_ERROR "Host GCC version must be at least 4.7!")
endif()
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
message(FATAL_ERROR "Host Clang version must be at least 3.1!")
endif()

if (CMAKE_CXX_SIMULATE_ID MATCHES "MSVC")
if (CMAKE_CXX_SIMULATE_VERSION VERSION_LESS 18.0)
message(FATAL_ERROR "Host Clang must have at least -fms-compatibility-version=18.0")
endif()
set(CLANG_CL 1)
elseif(NOT LLVM_ENABLE_LIBCXX)
# Otherwise, test that we aren't using too old of a version of libstdc++
# with the Clang compiler. This is tricky as there is no real way to
# check the version of libstdc++ directly. Instead we test for a known
# bug in libstdc++4.6 that is fixed in libstdc++4.7.
set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
set(OLD_CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
set(CMAKE_REQUIRED_FLAGS "-std=c++0x")
check_cxx_source_compiles("
#include <atomic>
std::atomic<float> x(0.0f);
int main() { return (float)x; }"
LLVM_NO_OLD_LIBSTDCXX)
if(NOT LLVM_NO_OLD_LIBSTDCXX)
message(FATAL_ERROR "Host Clang must be able to find libstdc++4.7 or newer!")
endif()
set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_LIBRARIES ${OLD_CMAKE_REQUIRED_LIBRARIES})
endif()
elseif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0)
message(FATAL_ERROR "Host Visual Studio must be at least 2013")
elseif(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0.31101)
message(WARNING "Host Visual Studio should at least be 2013 Update 4 (MSVC 18.0.31101)"
" due to miscompiles from earlier versions")
endif()
endif()
if (CMAKE_LINKER MATCHES "lld-link.exe")
# Pass /MANIFEST:NO so that CMake doesn't run mt.exe on our binaries. Adding
# manifests with mt.exe breaks LLD's symbol tables and takes as much time as
# the link. See PR24476.
append("/MANIFEST:NO"
CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
endif()

if( LLVM_ENABLE_ASSERTIONS )
@@ -78,6 +44,11 @@ if( LLVM_ENABLE_ASSERTIONS )
endif()
endif()

if(LLVM_ENABLE_EXPENSIVE_CHECKS)
add_definitions(-DEXPENSIVE_CHECKS)
add_definitions(-D_GLIBCXX_DEBUG)
endif()

string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS)

if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" )
@@ -195,7 +166,8 @@ if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
# TODO: support other platforms and toolchains.
if( LLVM_BUILD_32_BITS )
message(STATUS "Building 32 bits executables and libraries.")
add_llvm_definitions( -m32 )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32")
@@ -255,14 +227,12 @@ if( MSVC )

include(ChooseMSVCCRT)

if( NOT (${CMAKE_VERSION} VERSION_LESS 2.8.11) )
# set stack reserved size to ~10MB
# CMake previously automatically set this value for MSVC builds, but the
# behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default
# value (1 MB) which is not enough for us in tasks such as parsing recursive
# C++ templates in Clang.
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000")
endif()
# set stack reserved size to ~10MB
# CMake previously automatically set this value for MSVC builds, but the
# behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default
# value (1 MB) which is not enough for us in tasks such as parsing recursive
# C++ templates in Clang.
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000")

if( MSVC11 )
add_llvm_definitions(-D_VARIADIC_MAX=10)
@@ -279,6 +249,12 @@ if( MSVC )
-D_SCL_SECURE_NO_WARNINGS
)

# Tell MSVC to use the Unicode version of the Win32 APIs instead of ANSI.
add_llvm_definitions(
-DUNICODE
-D_UNICODE
)

set(msvc_warning_flags
# Disabled warnings.
-wd4141 # Suppress ''modifier' : used more than once' (because of __forceinline combined with inline)
@@ -320,6 +296,7 @@ if( MSVC )
# C4592 is disabled because of false positives in Visual Studio 2015
# Update 1. Re-evaluate the usefulness of this diagnostic with Update 2.
-wd4592 # Suppress ''var': symbol will be dynamically initialized (implementation limitation)
-wd4319 # Suppress ''operator' : zero extending 'type' to 'type' of greater size'

# Ideally, we'd like this warning to be enabled, but MSVC 2013 doesn't
# support the 'aligned' attribute in the way that clang sources requires (for
@@ -328,7 +305,7 @@ if( MSVC )
# When we switch to requiring a version of MSVC that supports the 'alignas'
# specifier (MSVC 2015?) this warning can be re-enabled.
-wd4324 # Suppress 'structure was padded due to __declspec(align())'

# Promoted warnings.
-w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.

@@ -363,32 +340,46 @@ if( MSVC )

append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)

if (NOT LLVM_ENABLE_TIMESTAMPS AND CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# /Zc:strictStrings is incompatible with VS12's (Visual Studio 2013's)
# debug mode headers. Instead of only enabling them in VS2013's debug mode,
# we'll just enable them for Visual Studio 2015 (VS 14, MSVC_VERSION 1900)
# and up.
if (NOT (MSVC_VERSION LESS 1900))
# Disable string literal const->non-const type conversion.
# "When specified, the compiler requires strict const-qualification
# conformance for pointers initialized by using string literals."
append("/Zc:strictStrings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
endif(NOT (MSVC_VERSION LESS 1900))

# "Generate Intrinsic Functions".
append("/Oi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)

# "Enforce type conversion rules".
append("/Zc:rvalueCast" CMAKE_CXX_FLAGS)

if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# clang-cl and cl by default produce non-deterministic binaries because
# link.exe /incremental requires a timestamp in the .obj file. clang-cl
# has the flag /Brepro to force deterministic binaries, so pass that when
# LLVM_ENABLE_TIMESTAMPS is turned off.
# has the flag /Brepro to force deterministic binaries. We want to pass that
# whenever you're building with clang unless you're passing /incremental.
# This checks CMAKE_CXX_COMPILER_ID in addition to check_cxx_compiler_flag()
# because cl.exe does not emit an error on flags it doesn't understand,
# letting check_cxx_compiler_flag() claim it understands all flags.
check_cxx_compiler_flag("/Brepro" SUPPORTS_BREPRO)
append_if(SUPPORTS_BREPRO "/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)

if (SUPPORTS_BREPRO)
# Check if /INCREMENTAL is passed to the linker and complain that it
# won't work with /Brepro.
string(TOUPPER "${CMAKE_EXE_LINKER_FLAGS}" upper_exe_flags)
string(TOUPPER "${CMAKE_MODULE_LINKER_FLAGS}" upper_module_flags)
string(TOUPPER "${CMAKE_SHARED_LINKER_FLAGS}" upper_shared_flags)

string(FIND "${upper_exe_flags}" "/INCREMENTAL" exe_index)
string(FIND "${upper_module_flags}" "/INCREMENTAL" module_index)
string(FIND "${upper_shared_flags}" "/INCREMENTAL" shared_index)
string(FIND "${upper_exe_flags} ${upper_module_flags} ${upper_shared_flags}"
"/INCREMENTAL" linker_flag_idx)

if (${exe_index} GREATER -1 OR
${module_index} GREATER -1 OR
${shared_index} GREATER -1)
message(FATAL_ERROR "LLVM_ENABLE_TIMESTAMPS not compatible with /INCREMENTAL linking")
if (${linker_flag_idx} GREATER -1)
message(WARNING "/Brepro not compatible with /INCREMENTAL linking - builds will be non-deterministic")
else()
append("/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
endif()
endif()
endif()
@@ -454,9 +445,7 @@ elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
endif()
endif (LLVM_ENABLE_WARNINGS)
append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
if (NOT LLVM_ENABLE_TIMESTAMPS)
add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
endif ()
add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
if (LLVM_ENABLE_CXX1Y)
check_cxx_compiler_flag("-std=c++1y" CXX_SUPPORTS_CXX1Y)
append_if(CXX_SUPPORTS_CXX1Y "-std=c++1y" CMAKE_CXX_FLAGS)
@@ -476,7 +465,21 @@ elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
endif()
if (LLVM_ENABLE_MODULES)
set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fmodules")
set(module_flags "-fmodules -fmodules-cache-path=module.cache")
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
# On Darwin -fmodules does not imply -fcxx-modules.
set(module_flags "${module_flags} -fcxx-modules")
endif()
if (LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY)
set(module_flags "${module_flags} -Xclang -fmodules-local-submodule-visibility")
endif()
if (LLVM_ENABLE_MODULE_DEBUGGING AND
((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
(uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
set(module_flags "${module_flags} -gmodules")
endif()
set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${module_flags}")

# Check that we can build code with modules enabled, and that repeatedly
# including <cassert> still manages to respect NDEBUG properly.
CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG
@@ -487,8 +490,7 @@ elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
CXX_SUPPORTS_MODULES)
set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
if (CXX_SUPPORTS_MODULES)
append_if(CXX_SUPPORTS_MODULES "-fmodules" CMAKE_C_FLAGS)
append_if(CXX_SUPPORTS_MODULES "-fmodules -fcxx-modules" CMAKE_CXX_FLAGS)
append("${module_flags}" CMAKE_CXX_FLAGS)
else()
message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
endif()
@@ -514,10 +516,6 @@ macro(append_common_sanitizer_flags)
if (CMAKE_LINKER MATCHES "lld-link.exe")
# Use DWARF debug info with LLD.
append("-gdwarf" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
# Pass /MANIFEST:NO so that CMake doesn't run mt.exe on our binaries.
# Adding manifests with mt.exe breaks LLD's symbol tables. See PR24476.
append("/MANIFEST:NO"
CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
else()
# Enable codeview otherwise.
append("/Z7" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
@@ -580,7 +578,7 @@ add_llvm_definitions( -D__STDC_LIMIT_MACROS )

# clang doesn't print colored diagnostics when invoked from Ninja
if (UNIX AND
CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND
CMAKE_GENERATOR STREQUAL "Ninja")
append("-fcolor-diagnostics" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
endif()
@@ -602,15 +600,6 @@ if(NOT CYGWIN AND NOT WIN32)
endif()
endif()

if(CYGWIN OR MINGW)
# Prune --out-implib from executables. It doesn't make sense even
# with --export-all-symbols.
string(REGEX REPLACE "-Wl,--out-implib,[^ ]+ " " "
CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE}")
string(REGEX REPLACE "-Wl,--out-implib,[^ ]+ " " "
CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE}")
endif()

if(MSVC)
# Remove flags here, for exceptions and RTTI.
# Each target property or source property should be responsible to control
@@ -629,12 +618,46 @@ endif()

option(LLVM_BUILD_INSTRUMENTED "Build LLVM and tools with PGO instrumentation (experimental)" Off)
mark_as_advanced(LLVM_BUILD_INSTRUMENTED)
append_if(LLVM_BUILD_INSTRUMENTED "-fprofile-instr-generate"
append_if(LLVM_BUILD_INSTRUMENTED "-fprofile-instr-generate='${LLVM_PROFILE_FILE_PATTERN}'"
CMAKE_CXX_FLAGS
CMAKE_C_FLAGS
CMAKE_EXE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS)

option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation (experimental)" Off)
mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE)
append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate='${LLVM_PROFILE_FILE_PATTERN}' -fcoverage-mapping"
CMAKE_CXX_FLAGS
CMAKE_C_FLAGS
CMAKE_EXE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS)

set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as Thin or Full to use a particular kind of LTO")
string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
if(uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
append("-flto=thin" CMAKE_CXX_FLAGS CMAKE_C_FLAGS
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
elseif(uppercase_LLVM_ENABLE_LTO STREQUAL "FULL")
append("-flto=full" CMAKE_CXX_FLAGS CMAKE_C_FLAGS
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
elseif(LLVM_ENABLE_LTO)
append("-flto" CMAKE_CXX_FLAGS CMAKE_C_FLAGS
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
endif()

# This option makes utils/extract_symbols.py be used to determine the list of
# symbols to export from LLVM tools. This is necessary when using MSVC if you
# want to allow plugins, though note that the plugin has to explicitly link
# against (exactly one) tool so we can't unilaterally turn on
# LLVM_ENABLE_PLUGINS when it's enabled.
option(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS "Export symbols from LLVM tools so that plugins can import them" OFF)
if(BUILD_SHARED_LIBS AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
message(FATAL_ERROR "BUILD_SHARED_LIBS not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
endif()
if(LLVM_LINK_LLVM_DYLIB AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
message(FATAL_ERROR "LLVM_LINK_LLVM_DYLIB not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
endif()

# Plugin support
# FIXME: Make this configurable.
if(WIN32 OR CYGWIN)
@@ -40,10 +40,19 @@ macro(llvm_config executable)
# done in case libLLVM does not contain all of the components
# the target requires.
#
# TODO strip LLVM_DYLIB_COMPONENTS out of link_components.
# Strip LLVM_DYLIB_COMPONENTS out of link_components.
# To do this, we need special handling for "all", since that
# may imply linking to libraries that are not included in
# libLLVM.

if (DEFINED link_components AND DEFINED LLVM_DYLIB_COMPONENTS)
if("${LLVM_DYLIB_COMPONENTS}" STREQUAL "all")
set(link_components "")
else()
list(REMOVE_ITEM link_components ${LLVM_DYLIB_COMPONENTS})
endif()
endif()

target_link_libraries(${executable} LLVM)
endif()

@@ -7,6 +7,8 @@ set(LLVM_VERSION_MINOR @LLVM_VERSION_MINOR@)
set(LLVM_VERSION_PATCH @LLVM_VERSION_PATCH@)
set(LLVM_PACKAGE_VERSION @PACKAGE_VERSION@)

set(LLVM_BUILD_TYPE @CMAKE_BUILD_TYPE@)

set(LLVM_COMMON_DEPENDS @LLVM_COMMON_DEPENDS@)

set(LLVM_AVAILABLE_LIBS @LLVM_AVAILABLE_LIBS@)
@@ -39,7 +41,10 @@ set(LLVM_NATIVE_ARCH @LLVM_NATIVE_ARCH@)

set(LLVM_ENABLE_PIC @LLVM_ENABLE_PIC@)

set(LLVM_BUILD_32_BITS @LLVM_BUILD_32_BITS@)

set(LLVM_ENABLE_PLUGINS @LLVM_ENABLE_PLUGINS@)
set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS @LLVM_EXPORT_SYMBOLS_FOR_PLUGINS@)
set(LLVM_PLUGIN_EXT @LLVM_PLUGIN_EXT@)

set(LLVM_ON_UNIX @LLVM_ON_UNIX@)
@@ -49,11 +54,15 @@ set(LLVM_LIBDIR_SUFFIX @LLVM_LIBDIR_SUFFIX@)

set(LLVM_INCLUDE_DIRS "@LLVM_CONFIG_INCLUDE_DIRS@")
set(LLVM_LIBRARY_DIRS "@LLVM_CONFIG_LIBRARY_DIRS@")
set(LLVM_LIBRARY_DIR "@LLVM_CONFIG_LIBRARY_DIRS@")
set(LLVM_DEFINITIONS "@LLVM_DEFINITIONS@")
set(LLVM_CMAKE_DIR "@LLVM_CONFIG_CMAKE_DIR@")
set(LLVM_BINARY_DIR "@LLVM_CONFIG_BINARY_DIR@")
set(LLVM_TOOLS_BINARY_DIR "@LLVM_CONFIG_TOOLS_BINARY_DIR@")
set(LLVM_TOOLS_INSTALL_DIR "@LLVM_TOOLS_INSTALL_DIR@")

if(NOT TARGET LLVMSupport)
set(LLVM_EXPORTED_TARGETS "@LLVM_EXPORTS@")
include("@LLVM_CONFIG_EXPORTS_FILE@")
endif()

@@ -2,12 +2,12 @@ include(ExternalProject)

# llvm_ExternalProject_BuildCmd(out_var target)
# Utility function for constructing command lines for external project targets
function(llvm_ExternalProject_BuildCmd out_var target)
function(llvm_ExternalProject_BuildCmd out_var target bin_dir)
if (CMAKE_GENERATOR MATCHES "Make")
# Use special command for Makefiles to support parallelism.
set(${out_var} "$(MAKE)" "${target}" PARENT_SCOPE)
set(${out_var} "$(MAKE)" "-C" "${BINARY_DIR}" "${target}" PARENT_SCOPE)
else()
set(${out_var} ${CMAKE_COMMAND} --build . --target ${target}
set(${out_var} ${CMAKE_COMMAND} --build ${bin_dir} --target ${target}
--config $<CONFIGURATION> PARENT_SCOPE)
endif()
endfunction()
@@ -19,6 +19,8 @@ endfunction()
# Exclude this project from the all target
# NO_INSTALL
# Don't generate install targets for this project
# ALWAYS_CLEAN
# Always clean the sub-project before building
# CMAKE_ARGS arguments...
# Optional cmake arguments to pass when configuring the project
# TOOLCHAIN_TOOLS targets...
@@ -27,11 +29,15 @@ endfunction()
# Targets that this project depends on
# EXTRA_TARGETS targets...
# Extra targets in the subproject to generate targets for
# PASSTHROUGH_PREFIXES prefix...
# Extra variable prefixes (name is always included) to pass down
# )
function(llvm_ExternalProject_Add name source_dir)
cmake_parse_arguments(ARG "USE_TOOLCHAIN;EXCLUDE_FROM_ALL;NO_INSTALL"
cmake_parse_arguments(ARG
"USE_TOOLCHAIN;EXCLUDE_FROM_ALL;NO_INSTALL;ALWAYS_CLEAN"
"SOURCE_DIR"
"CMAKE_ARGS;TOOLCHAIN_TOOLS;RUNTIME_LIBRARIES;DEPENDS;EXTRA_TARGETS" ${ARGN})
"CMAKE_ARGS;TOOLCHAIN_TOOLS;RUNTIME_LIBRARIES;DEPENDS;EXTRA_TARGETS;PASSTHROUGH_PREFIXES"
${ARGN})
canonicalize_tool_name(${name} nameCanon)
if(NOT ARG_TOOLCHAIN_TOOLS)
set(ARG_TOOLCHAIN_TOOLS clang lld)
@@ -52,6 +58,10 @@ function(llvm_ExternalProject_Add name source_dir)
endif()
endforeach()

if(ARG_ALWAYS_CLEAN)
set(always_clean clean)
endif()

list(FIND TOOLCHAIN_TOOLS clang FOUND_CLANG)
if(FOUND_CLANG GREATER -1)
set(CLANG_IN_TOOLCHAIN On)
@@ -61,42 +71,28 @@ function(llvm_ExternalProject_Add name source_dir)
list(APPEND TOOLCHAIN_BINS ${RUNTIME_LIBRARIES})
endif()

if(CMAKE_VERSION VERSION_GREATER 3.1.0)
set(cmake_3_1_EXCLUDE_FROM_ALL EXCLUDE_FROM_ALL 1)
endif()

if(CMAKE_VERSION VERSION_GREATER 3.3.20150708)
set(cmake_3_4_USES_TERMINAL_OPTIONS
USES_TERMINAL_CONFIGURE 1
USES_TERMINAL_BUILD 1
USES_TERMINAL_INSTALL 1
)
set(cmake_3_4_USES_TERMINAL USES_TERMINAL 1)
endif()

if(CMAKE_VERSION VERSION_GREATER 3.1.20141116)
set(cmake_3_2_USES_TERMINAL USES_TERMINAL)
endif()

set(STAMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/${name}-stamps/)
set(BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/${name}-bins/)

add_custom_target(${name}-clear
COMMAND ${CMAKE_COMMAND} -E remove_directory ${BINARY_DIR}
COMMAND ${CMAKE_COMMAND} -E remove_directory ${STAMP_DIR}
COMMENT "Clobbering ${name} build and stamp directories"
${cmake_3_2_USES_TERMINAL}
USES_TERMINAL
)

# Find all variables that start with COMPILER_RT and populate a variable with
# them.
# Find all variables that start with a prefix and propagate them through
get_cmake_property(variableNames VARIABLES)
foreach(variableName ${variableNames})
if(variableName MATCHES "^${nameCanon}")
string(REPLACE ";" "\;" value "${${variableName}}")
list(APPEND PASSTHROUGH_VARIABLES
-D${variableName}=${value})
endif()

list(APPEND ARG_PASSTHROUGH_PREFIXES ${nameCanon})
foreach(prefix ${ARG_PASSTHROUGH_PREFIXES})
foreach(variableName ${variableNames})
if(variableName MATCHES "^${prefix}")
string(REPLACE ";" "\;" value "${${variableName}}")
list(APPEND PASSTHROUGH_VARIABLES
-D${variableName}=${value})
endif()
endforeach()
endforeach()

if(ARG_USE_TOOLCHAIN)
@@ -120,7 +116,7 @@ function(llvm_ExternalProject_Add name source_dir)
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp)

if(ARG_EXCLUDE_FROM_ALL)
set(exclude ${cmake_3_1_EXCLUDE_FROM_ALL})
set(exclude EXCLUDE_FROM_ALL 1)
endif()

ExternalProject_Add(${name}
@@ -134,33 +130,35 @@ function(llvm_ExternalProject_Add name source_dir)
CMAKE_ARGS ${${nameCanon}_CMAKE_ARGS}
${compiler_args}
-DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
-DLLVM_BINARY_DIR=${PROJECT_BINARY_DIR}
-DLLVM_CONFIG_PATH=$<TARGET_FILE:llvm-config>
-DLLVM_ENABLE_WERROR=${LLVM_ENABLE_WERROR}
-DPACKAGE_VERSION=${PACKAGE_VERSION}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
${ARG_CMAKE_ARGS}
${PASSTHROUGH_VARIABLES}
INSTALL_COMMAND ""
STEP_TARGETS configure build
${cmake_3_4_USES_TERMINAL_OPTIONS}
BUILD_ALWAYS 1
USES_TERMINAL_CONFIGURE 1
USES_TERMINAL_BUILD 1
USES_TERMINAL_INSTALL 1
)

if(ARG_USE_TOOLCHAIN)
ExternalProject_Add_Step(${name} force-rebuild
COMMENT "Forcing rebuild becaues tools have changed"
DEPENDERS configure
DEPENDS ${TOOLCHAIN_BINS}
${cmake_3_4_USES_TERMINAL} )
endif()

if(ARG_USE_TOOLCHAIN)
set(force_deps DEPENDS ${TOOLCHAIN_BINS})
endif()

llvm_ExternalProject_BuildCmd(run_clean clean)
llvm_ExternalProject_BuildCmd(run_clean clean ${BINARY_DIR})
ExternalProject_Add_Step(${name} clean
COMMAND ${run_clean}
COMMENT "Cleaning ${name}..."
DEPENDEES configure
${force_deps}
WORKING_DIRECTORY ${BINARY_DIR}
${cmake_3_4_USES_TERMINAL}
EXCLUDE_FROM_MAIN 1
USES_TERMINAL 1
)
ExternalProject_Add_StepTargets(${name} clean)

@@ -179,17 +177,17 @@ function(llvm_ExternalProject_Add name source_dir)
COMMAND "${CMAKE_COMMAND}"
-DCMAKE_INSTALL_COMPONENT=${name}
-P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
${cmake_3_2_USES_TERMINAL})
USES_TERMINAL)
endif()

# Add top-level targets
foreach(target ${ARG_EXTRA_TARGETS})
llvm_ExternalProject_BuildCmd(build_runtime_cmd ${target})
llvm_ExternalProject_BuildCmd(build_runtime_cmd ${target} ${BINARY_DIR})
add_custom_target(${target}
COMMAND ${build_runtime_cmd}
DEPENDS ${name}-configure
WORKING_DIRECTORY ${BINARY_DIR}
VERBATIM
${cmake_3_2_USES_TERMINAL})
USES_TERMINAL)
endforeach()
endfunction()

This file was deleted.

Oops, something went wrong.
@@ -141,7 +141,7 @@ macro(add_tablegen target project)
if (${project} STREQUAL LLVM AND NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
install(TARGETS ${target}
EXPORT LLVMExports
RUNTIME DESTINATION bin)
RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR})
endif()
set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${target})
endmacro()
@@ -1,45 +1,57 @@
# Adds version control information to the variable VERS. For
# determining the Version Control System used (if any) it inspects the
# existence of certain subdirectories under CMAKE_CURRENT_SOURCE_DIR.
# existence of certain subdirectories under SOURCE_DIR (if provided as an
# extra argument, otherwise uses CMAKE_CURRENT_SOURCE_DIR).

function(add_version_info_from_vcs VERS)
SET(SOURCE_DIR ${ARGV1})
if("${SOURCE_DIR}" STREQUAL "")
SET(SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
endif()
string(REPLACE "svn" "" result "${${VERS}}")
if( EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.svn" )
if( EXISTS "${SOURCE_DIR}/.svn" )
set(result "${result}svn")
# FindSubversion does not work with symlinks. See PR 8437
if( NOT IS_SYMLINK "${CMAKE_CURRENT_SOURCE_DIR}" )
if( NOT IS_SYMLINK "${SOURCE_DIR}" )
find_package(Subversion)
endif()
if( Subversion_FOUND )
subversion_wc_info( ${CMAKE_CURRENT_SOURCE_DIR} Project )
subversion_wc_info( ${SOURCE_DIR} Project )
if( Project_WC_REVISION )
set(SVN_REVISION ${Project_WC_REVISION} PARENT_SCOPE)
set(result "${result}-r${Project_WC_REVISION}")
endif()
if( Project_WC_URL )
set(LLVM_REPOSITORY ${Project_WC_URL} PARENT_SCOPE)
endif()
endif()
elseif( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git )
elseif( EXISTS ${SOURCE_DIR}/.git )
set(result "${result}git")
# Try to get a ref-id
if( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git/svn )
if( EXISTS ${SOURCE_DIR}/.git/svn )
find_program(git_executable NAMES git git.exe git.cmd)
if( git_executable )
set(is_git_svn_rev_exact false)
execute_process(COMMAND ${git_executable} svn log --limit=1 --oneline
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
execute_process(COMMAND
${git_executable} svn info
WORKING_DIRECTORY ${SOURCE_DIR}
TIMEOUT 5
RESULT_VARIABLE git_result
OUTPUT_VARIABLE git_output)
if( git_result EQUAL 0 )
string(REGEX MATCH r[0-9]+ git_svn_rev ${git_output})
string(LENGTH "${git_svn_rev}" rev_length)
math(EXPR rev_length "${rev_length}-1")
string(SUBSTRING "${git_svn_rev}" 1 ${rev_length} git_svn_rev_number)
string(REGEX MATCH "URL: ([^ \n]*)" svn_url ${git_output})
if(svn_url)
set(LLVM_REPOSITORY ${CMAKE_MATCH_1} PARENT_SCOPE)
endif()

string(REGEX REPLACE "^(.*\n)?Revision: ([^\n]+).*"
"\\2" git_svn_rev_number "${git_output}")
set(SVN_REVISION ${git_svn_rev_number} PARENT_SCOPE)
set(git_svn_rev "-svn-${git_svn_rev}")

# Determine if the HEAD points directly at a subversion revision.
execute_process(COMMAND ${git_executable} svn find-rev HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
WORKING_DIRECTORY ${SOURCE_DIR}
TIMEOUT 5
RESULT_VARIABLE git_result
OUTPUT_VARIABLE git_output)
@@ -54,17 +66,19 @@ function(add_version_info_from_vcs VERS)
endif()
execute_process(COMMAND
${git_executable} rev-parse --short HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
WORKING_DIRECTORY ${SOURCE_DIR}
TIMEOUT 5
RESULT_VARIABLE git_result
OUTPUT_VARIABLE git_output)

if( git_result EQUAL 0 AND NOT is_git_svn_rev_exact )
string(STRIP "${git_output}" git_ref_id)
set(GIT_COMMIT ${git_ref_id} PARENT_SCOPE)
set(result "${result}${git_svn_rev}-${git_ref_id}")
else()
set(result "${result}${git_svn_rev}")
endif()

endif()
endif()
endif()
@@ -1,55 +1,42 @@
# Toolchain config for iOS.
#
# Usage:
# mkdir build; cd build
# cmake ..; make
# mkdir ios; cd ios
# cmake -DLLVM_IOS_TOOLCHAIN_DIR=/path/to/ios/ndk \
# -DCMAKE_TOOLCHAIN_FILE=../../cmake/platforms/iOS.cmake ../..
# make <target>

SET(CMAKE_SYSTEM_NAME Darwin)
SET(CMAKE_SYSTEM_VERSION 13)
SET(CMAKE_CXX_COMPILER_WORKS True)
SET(CMAKE_C_COMPILER_WORKS True)
SET(DARWIN_TARGET_OS_NAME ios)

IF(NOT DEFINED ENV{SDKROOT})
execute_process(COMMAND xcodebuild -version -sdk iphoneos Path
OUTPUT_VARIABLE SDKROOT
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
ELSE()
execute_process(COMMAND xcodebuild -version -sdk $ENV{SDKROOT} Path
OUTPUT_VARIABLE SDKROOT
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
ENDIF()
if(NOT CMAKE_OSX_SYSROOT)
execute_process(COMMAND xcodebuild -version -sdk iphoneos Path
OUTPUT_VARIABLE SDKROOT
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)

IF(NOT EXISTS ${SDKROOT})
MESSAGE(FATAL_ERROR "SDKROOT could not be detected!")
ENDIF()
IF(NOT EXISTS ${SDKROOT})
MESSAGE(FATAL_ERROR "SDKROOT could not be detected!")
ENDIF()

set(CMAKE_OSX_SYSROOT ${SDKROOT})
message(STATUS "Using SDKROOT ${SDKROOT}")
set(CMAKE_OSX_SYSROOT ${SDKROOT})
endif()

IF(NOT CMAKE_C_COMPILER)
execute_process(COMMAND xcrun -sdk ${SDKROOT} -find clang
execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find clang
OUTPUT_VARIABLE CMAKE_C_COMPILER
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "Using c compiler ${CMAKE_C_COMPILER}")
ENDIF()

IF(NOT CMAKE_CXX_COMPILER)
execute_process(COMMAND xcrun -sdk ${SDKROOT} -find clang++
execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find clang++
OUTPUT_VARIABLE CMAKE_CXX_COMPILER
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "Using c compiler ${CMAKE_CXX_COMPILER}")
ENDIF()

IF(NOT CMAKE_AR)
execute_process(COMMAND xcrun -sdk ${SDKROOT} -find ar
execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find ar
OUTPUT_VARIABLE CMAKE_AR_val
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
@@ -58,22 +45,10 @@ IF(NOT CMAKE_AR)
ENDIF()

IF(NOT CMAKE_RANLIB)
execute_process(COMMAND xcrun -sdk ${SDKROOT} -find ranlib
execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find ranlib
OUTPUT_VARIABLE CMAKE_RANLIB_val
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
SET(CMAKE_RANLIB ${CMAKE_RANLIB_val} CACHE FILEPATH "Ranlib")
message(STATUS "Using ranlib ${CMAKE_RANLIB}")
ENDIF()

IF (NOT DEFINED IOS_MIN_TARGET)
execute_process(COMMAND xcodebuild -sdk ${SDKROOT} -version SDKVersion
OUTPUT_VARIABLE IOS_MIN_TARGET
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
ENDIF()

SET(IOS_COMMON_FLAGS "-mios-version-min=${IOS_MIN_TARGET}")
SET(CMAKE_C_FLAGS "${IOS_COMMON_FLAGS}" CACHE STRING "toolchain_cflags" FORCE)
SET(CMAKE_CXX_FLAGS "${IOS_COMMON_FLAGS}" CACHE STRING "toolchain_cxxflags" FORCE)
SET(CMAKE_LINK_FLAGS "${IOS_COMMON_FLAGS}" CACHE STRING "toolchain_linkflags" FORCE)
19,472 configure

Large diffs are not rendered by default.

Oops, something went wrong.
@@ -9,6 +9,29 @@ The AMDGPU back-end provides ISA code generation for AMD GPUs, starting with
the R600 family up until the current Volcanic Islands (GCN Gen 3).


Conventions
===========

Address Spaces
--------------

The AMDGPU back-end uses the following address space mapping:

============= ============================================
Address Space Memory Space
============= ============================================
0 Private
1 Global
2 Constant
3 Local
4 Generic (Flat)
5 Region
============= ============================================

The terminology in the table, aside from the region memory space, is from the
OpenCL standard.


Assembler
=========

@@ -65,14 +88,14 @@ wait for.

.. code-block:: nasm

// Wait for all counters to be 0
; Wait for all counters to be 0
s_waitcnt 0

// Equivalent to s_waitcnt 0. Counter names can also be delimited by
// '&' or ','.
; Equivalent to s_waitcnt 0. Counter names can also be delimited by
; '&' or ','.
s_waitcnt vmcnt(0) expcnt(0) lgkcmt(0)

// Wait for vmcnt counter to be 1.
; Wait for vmcnt counter to be 1.
s_waitcnt vmcnt(1)

VOP1, VOP2, VOP3, VOPC Instructions
@@ -153,7 +176,10 @@ Here is an example of a minimal amd_kernel_code_t specification:
.hsa_code_object_version 1,0
.hsa_code_object_isa

.text
.hsatext
.globl hello_world
.p2align 8
.amdgpu_hsa_kernel hello_world

hello_world:

@@ -173,5 +199,7 @@ Here is an example of a minimal amd_kernel_code_t specification:
s_waitcnt lgkmcnt(0)
v_mov_b32 v1, s0
v_mov_b32 v2, s1
flat_store_dword v0, v[1:2]
flat_store_dword v[1:2], v0
s_endpgm
.Lfunc_end0:
.size hello_world, .Lfunc_end0-hello_world
@@ -0,0 +1,174 @@
=============================
Advanced Build Configurations
=============================

.. contents::
:local:

Introduction
============

`CMake <http://www.cmake.org/>`_ is a cross-platform build-generator tool. CMake
does not build the project, it generates the files needed by your build tool
(GNU make, Visual Studio, etc.) for building LLVM.

If **you are a new contributor**, please start with the :doc:`GettingStarted` or
:doc:`CMake` pages. This page is intended for users doing more complex builds.

Many of the examples below are written assuming specific CMake Generators.
Unless otherwise explicitly called out these commands should work with any CMake
generator.

Bootstrap Builds
================

The Clang CMake build system supports bootstrap (aka multi-stage) builds. At a
high level a multi-stage build is a chain of builds that pass data from one
stage into the next. The most common and simple version of this is a traditional
bootstrap build.

In a simple two-stage bootstrap build, we build clang using the system compiler,
then use that just-built clang to build clang again. In CMake this simplest form
of a bootstrap build can be configured with a single option,
CLANG_ENABLE_BOOTSTRAP.

.. code-block:: console

$ cmake -G Ninja -DCLANG_ENABLE_BOOTSTRAP=On <path to source>
$ ninja stage2

This command itself isn't terribly useful because it assumes default
configurations for each stage. The next series of examples utilize CMake cache
scripts to provide more complex options.

The clang build system refers to builds as stages. A stage1 build is a standard
build using the compiler installed on the host, and a stage2 build is built
using the stage1 compiler. This nomenclature holds up to more stages too. In
general a stage*n* build is built using the output from stage*n-1*.

Apple Clang Builds (A More Complex Bootstrap)
=============================================

Apple's Clang builds are a slightly more complicated example of the simple
bootstrapping scenario. Apple Clang is built using a 2-stage build.

The stage1 compiler is a host-only compiler with some options set. The stage1
compiler is a balance of optimization vs build time because it is a throwaway.
The stage2 compiler is the fully optimized compiler intended to ship to users.

Setting up these compilers requires a lot of options. To simplify the
configuration the Apple Clang build settings are contained in CMake Cache files.
You can build an Apple Clang compiler using the following commands:

.. code-block:: console

$ cmake -G Ninja -C <path to clang>/cmake/caches/Apple-stage1.cmake <path to source>
$ ninja stage2-distribution

This CMake invocation configures the stage1 host compiler, and sets
CLANG_BOOTSTRAP_CMAKE_ARGS to pass the Apple-stage2.cmake cache script to the
stage2 configuration step.

When you build the stage2-distribution target it builds the minimal stage1
compiler and required tools, then configures and builds the stage2 compiler
based on the settings in Apple-stage2.cmake.

This pattern of using cache scripts to set complex settings, and specifically to
make later stage builds include cache scripts is common in our more advanced
build configurations.

Multi-stage PGO
===============

Profile-Guided Optimizations (PGO) is a really great way to optimize the code
clang generates. Our multi-stage PGO builds are a workflow for generating PGO
profiles that can be used to optimize clang.

At a high level, the way PGO works is that you build an instrumented compiler,
then you run the instrumented compiler against sample source files. While the
instrumented compiler runs it will output a bunch of files containing
performance counters (.profraw files). After generating all the profraw files
you use llvm-profdata to merge the files into a single profdata file that you
can feed into the LLVM_PROFDATA_FILE option.

Our PGO.cmake cache script automates that whole process. You can use it by
running:

.. code-block:: console

$ cmake -G Ninja -C <path_to_clang>/cmake/caches/PGO.cmake <source dir>
$ ninja stage2-instrumented-generate-profdata

If you let that run for a few hours or so, it will place a profdata file in your
build directory. This takes a really long time because it builds clang twice,
and you *must* have compiler-rt in your build tree.

This process uses any source files under the perf-training directory as training
data as long as the source files are marked up with LIT-style RUN lines.

After it finishes you can use “find . -name clang.profdata” to find it, but it
should be at a path something like:

.. code-block:: console

<build dir>/tools/clang/stage2-instrumented-bins/utils/perf-training/clang.profdata

You can feed that file into the LLVM_PROFDATA_FILE option when you build your
optimized compiler.

The PGO came cache has a slightly different stage naming scheme than other
multi-stage builds. It generates three stages; stage1, stage2-instrumented, and
stage2. Both of the stage2 builds are built using the stage1 compiler.

The PGO came cache generates the following additional targets:

**stage2-instrumented**
Builds a stage1 x86 compiler, runtime, and required tools (llvm-config,
llvm-profdata) then uses that compiler to build an instrumented stage2 compiler.

**stage2-instrumented-generate-profdata**
Depends on "stage2-instrumented" and will use the instrumented compiler to
generate profdata based on the training files in <clang>/utils/perf-training

**stage2**
Depends of "stage2-instrumented-generate-profdata" and will use the stage1
compiler with the stage2 profdata to build a PGO-optimized compiler.

**stage2-check-llvm**
Depends on stage2 and runs check-llvm using the stage2 compiler.

**stage2-check-clang**
Depends on stage2 and runs check-clang using the stage2 compiler.

**stage2-check-all**
Depends on stage2 and runs check-all using the stage2 compiler.

**stage2-test-suite**
Depends on stage2 and runs the test-suite using the stage3 compiler (requires
in-tree test-suite).

3-Stage Non-Determinism
=======================

In the ancient lore of compilers non-determinism is like the multi-headed hydra.
Whenever it's head pops up, terror and chaos ensue.

Historically one of the tests to verify that a compiler was deterministic would
be a three stage build. The idea of a three stage build is you take your sources
and build a compiler (stage1), then use that compiler to rebuild the sources
(stage2), then you use that compiler to rebuild the sources a third time
(stage3) with an identical configuration to the stage2 build. At the end of
this, you have a stage2 and stage3 compiler that should be bit-for-bit
identical.

You can perform one of these 3-stage builds with LLVM & clang using the
following commands:

.. code-block:: console

$ cmake -G Ninja -C <path_to_clang>/cmake/caches/3-stage.cmake <source dir>
$ ninja stage3

After the build you can compare the stage2 & stage3 compilers. We have a bot
setup `here <http://lab.llvm.org:8011/builders/clang-3stage-ubuntu>`_ that runs
this build and compare configuration.
@@ -31,8 +31,7 @@ well together.

This document contains information necessary to successfully implement this
interface, use it, and to test both sides. It also explains some of the finer
points about what exactly results mean. If you feel that something is unclear
or should be added, please `let me know <mailto:sabre@nondot.org>`_.
points about what exactly results mean.

``AliasAnalysis`` Class Overview
================================
@@ -8,17 +8,13 @@ LLVM Atomic Instructions and Concurrency Guide
Introduction
============

Historically, LLVM has not had very strong support for concurrency; some minimal
intrinsics were provided, and ``volatile`` was used in some cases to achieve
rough semantics in the presence of concurrency. However, this is changing;
there are now new instructions which are well-defined in the presence of threads
and asynchronous signals, and the model for existing instructions has been
clarified in the IR.
LLVM supports instructions which are well-defined in the presence of threads and
asynchronous signals.

The atomic instructions are designed specifically to provide readable IR and
optimized code generation for the following:

* The new C++11 ``<atomic>`` header. (`C++11 draft available here
* The C++11 ``<atomic>`` header. (`C++11 draft available here
<http://www.open-std.org/jtc1/sc22/wg21/>`_.) (`C11 draft available here
<http://www.open-std.org/jtc1/sc22/wg14/>`_.)

@@ -371,7 +367,7 @@ Predicates for optimizer writers to query:
that they return true for any operation which is volatile or at least
Monotonic.

* ``isAtLeastAcquire()``/``isAtLeastRelease()``: These are predicates on
* ``isStrongerThan`` / ``isAtLeastOrStrongerThan``: These are predicates on
orderings. They can be useful for passes that are aware of atomics, for
example to do DSE across a single atomic access, but not across a
release-acquire pair (see MemoryDependencyAnalysis for an example of this)
@@ -402,7 +398,7 @@ operations:
MemoryDependencyAnalysis (which is also used by other passes like GVN).

* Folding a load: Any atomic load from a constant global can be constant-folded,
because it cannot be observed. Similar reasoning allows scalarrepl with
because it cannot be observed. Similar reasoning allows sroa with
atomic loads and stores.

Atomics and Codegen
@@ -417,19 +413,28 @@ The MachineMemOperand for all atomic operations is currently marked as volatile;
this is not correct in the IR sense of volatile, but CodeGen handles anything
marked volatile very conservatively. This should get fixed at some point.

Common architectures have some way of representing at least a pointer-sized
lock-free ``cmpxchg``; such an operation can be used to implement all the other
atomic operations which can be represented in IR up to that size. Backends are
expected to implement all those operations, but not operations which cannot be
implemented in a lock-free manner. It is expected that backends will give an
error when given an operation which cannot be implemented. (The LLVM code
generator is not very helpful here at the moment, but hopefully that will
change.)
One very important property of the atomic operations is that if your backend
supports any inline lock-free atomic operations of a given size, you should
support *ALL* operations of that size in a lock-free manner.

When the target implements atomic ``cmpxchg`` or LL/SC instructions (as most do)
this is trivial: all the other operations can be implemented on top of those
primitives. However, on many older CPUs (e.g. ARMv5, SparcV8, Intel 80386) there
are atomic load and store instructions, but no ``cmpxchg`` or LL/SC. As it is
invalid to implement ``atomic load`` using the native instruction, but
``cmpxchg`` using a library call to a function that uses a mutex, ``atomic
load`` must *also* expand to a library call on such architectures, so that it
can remain atomic with regards to a simultaneous ``cmpxchg``, by using the same
mutex.

AtomicExpandPass can help with that: it will expand all atomic operations to the
proper ``__atomic_*`` libcalls for any size above the maximum set by
``setMaxAtomicSizeInBitsSupported`` (which defaults to 0).

On x86, all atomic loads generate a ``MOV``. SequentiallyConsistent stores
generate an ``XCHG``, other stores generate a ``MOV``. SequentiallyConsistent
fences generate an ``MFENCE``, other fences do not cause any code to be
generated. cmpxchg uses the ``LOCK CMPXCHG`` instruction. ``atomicrmw xchg``
generated. ``cmpxchg`` uses the ``LOCK CMPXCHG`` instruction. ``atomicrmw xchg``
uses ``XCHG``, ``atomicrmw add`` and ``atomicrmw sub`` use ``XADD``, and all
other ``atomicrmw`` operations generate a loop with ``LOCK CMPXCHG``. Depending
on the users of the result, some ``atomicrmw`` operations can be translated into
@@ -450,10 +455,151 @@ atomic constructs. Here are some lowerings it can do:
``emitStoreConditional()``
* large loads/stores -> ll-sc/cmpxchg
by overriding ``shouldExpandAtomicStoreInIR()``/``shouldExpandAtomicLoadInIR()``
* strong atomic accesses -> monotonic accesses + fences
by using ``setInsertFencesForAtomic()`` and overriding ``emitLeadingFence()``
and ``emitTrailingFence()``
* strong atomic accesses -> monotonic accesses + fences by overriding
``shouldInsertFencesForAtomic()``, ``emitLeadingFence()``, and
``emitTrailingFence()``
* atomic rmw -> loop with cmpxchg or load-linked/store-conditional
by overriding ``expandAtomicRMWInIR()``
* expansion to __atomic_* libcalls for unsupported sizes.

For an example of all of these, look at the ARM backend.

Libcalls: __atomic_*
====================

There are two kinds of atomic library calls that are generated by LLVM. Please
note that both sets of library functions somewhat confusingly share the names of
builtin functions defined by clang. Despite this, the library functions are
not directly related to the builtins: it is *not* the case that ``__atomic_*``
builtins lower to ``__atomic_*`` library calls and ``__sync_*`` builtins lower
to ``__sync_*`` library calls.

The first set of library functions are named ``__atomic_*``. This set has been
"standardized" by GCC, and is described below. (See also `GCC's documentation
<https://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary>`_)

LLVM's AtomicExpandPass will translate atomic operations on data sizes above
``MaxAtomicSizeInBitsSupported`` into calls to these functions.

There are four generic functions, which can be called with data of any size or
alignment::

void __atomic_load(size_t size, void *ptr, void *ret, int ordering)
void __atomic_store(size_t size, void *ptr, void *val, int ordering)
void __atomic_exchange(size_t size, void *ptr, void *val, void *ret, int ordering)
bool __atomic_compare_exchange(size_t size, void *ptr, void *expected, void *desired, int success_order, int failure_order)

There are also size-specialized versions of the above functions, which can only
be used with *naturally-aligned* pointers of the appropriate size. In the
signatures below, "N" is one of 1, 2, 4, 8, and 16, and "iN" is the appropriate
integer type of that size; if no such integer type exists, the specialization
cannot be used::

iN __atomic_load_N(iN *ptr, iN val, int ordering)
void __atomic_store_N(iN *ptr, iN val, int ordering)
iN __atomic_exchange_N(iN *ptr, iN val, int ordering)
bool __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired, int success_order, int failure_order)

Finally there are some read-modify-write functions, which are only available in
the size-specific variants (any other sizes use a ``__atomic_compare_exchange``
loop)::

iN __atomic_fetch_add_N(iN *ptr, iN val, int ordering)
iN __atomic_fetch_sub_N(iN *ptr, iN val, int ordering)
iN __atomic_fetch_and_N(iN *ptr, iN val, int ordering)
iN __atomic_fetch_or_N(iN *ptr, iN val, int ordering)
iN __atomic_fetch_xor_N(iN *ptr, iN val, int ordering)
iN __atomic_fetch_nand_N(iN *ptr, iN val, int ordering)

This set of library functions have some interesting implementation requirements
to take note of:

- They support all sizes and alignments -- including those which cannot be
implemented natively on any existing hardware. Therefore, they will certainly
use mutexes in for some sizes/alignments.

- As a consequence, they cannot be shipped in a statically linked
compiler-support library, as they have state which must be shared amongst all
DSOs loaded in the program. They must be provided in a shared library used by
all objects.

- The set of atomic sizes supported lock-free must be a superset of the sizes
any compiler can emit. That is: if a new compiler introduces support for
inline-lock-free atomics of size N, the ``__atomic_*`` functions must also have a
lock-free implementation for size N. This is a requirement so that code
produced by an old compiler (which will have called the ``__atomic_*`` function)
interoperates with code produced by the new compiler (which will use native
the atomic instruction).

Note that it's possible to write an entirely target-independent implementation
of these library functions by using the compiler atomic builtins themselves to
implement the operations on naturally-aligned pointers of supported sizes, and a
generic mutex implementation otherwise.

Libcalls: __sync_*
==================

Some targets or OS/target combinations can support lock-free atomics, but for
various reasons, it is not practical to emit the instructions inline.

There's two typical examples of this.

Some CPUs support multiple instruction sets which can be swiched back and forth
on function-call boundaries. For example, MIPS supports the MIPS16 ISA, which
has a smaller instruction encoding than the usual MIPS32 ISA. ARM, similarly,
has the Thumb ISA. In MIPS16 and earlier versions of Thumb, the atomic
instructions are not encodable. However, those instructions are available via a
function call to a function with the longer encoding.

Additionally, a few OS/target pairs provide kernel-supported lock-free
atomics. ARM/Linux is an example of this: the kernel `provides
<https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt>`_ a
function which on older CPUs contains a "magically-restartable" atomic sequence
(which looks atomic so long as there's only one CPU), and contains actual atomic
instructions on newer multicore models. This sort of functionality can typically
be provided on any architecture, if all CPUs which are missing atomic
compare-and-swap support are uniprocessor (no SMP). This is almost always the
case. The only common architecture without that property is SPARC -- SPARCV8 SMP
systems were common, yet it doesn't support any sort of compare-and-swap
operation.

In either of these cases, the Target in LLVM can claim support for atomics of an
appropriate size, and then implement some subset of the operations via libcalls
to a ``__sync_*`` function. Such functions *must* not use locks in their
implementation, because unlike the ``__atomic_*`` routines used by
AtomicExpandPass, these may be mixed-and-matched with native instructions by the
target lowering.

Further, these routines do not need to be shared, as they are stateless. So,
there is no issue with having multiple copies included in one binary. Thus,
typically these routines are implemented by the statically-linked compiler
runtime support library.

LLVM will emit a call to an appropriate ``__sync_*`` routine if the target
ISelLowering code has set the corresponding ``ATOMIC_CMPXCHG``, ``ATOMIC_SWAP``,
or ``ATOMIC_LOAD_*`` operation to "Expand", and if it has opted-into the
availability of those library functions via a call to ``initSyncLibcalls()``.

The full set of functions that may be called by LLVM is (for ``N`` being 1, 2,
4, 8, or 16)::

iN __sync_val_compare_and_swap_N(iN *ptr, iN expected, iN desired)
iN __sync_lock_test_and_set_N(iN *ptr, iN val)
iN __sync_fetch_and_add_N(iN *ptr, iN val)
iN __sync_fetch_and_sub_N(iN *ptr, iN val)
iN __sync_fetch_and_and_N(iN *ptr, iN val)
iN __sync_fetch_and_or_N(iN *ptr, iN val)
iN __sync_fetch_and_xor_N(iN *ptr, iN val)
iN __sync_fetch_and_nand_N(iN *ptr, iN val)
iN __sync_fetch_and_max_N(iN *ptr, iN val)
iN __sync_fetch_and_umax_N(iN *ptr, iN val)
iN __sync_fetch_and_min_N(iN *ptr, iN val)
iN __sync_fetch_and_umin_N(iN *ptr, iN val)

This list doesn't include any function for atomic load or store; all known
architectures support atomic loads and stores directly (possibly by emitting a
fence on either side of a normal load or store.)

There's also, somewhat separately, the possibility to lower ``ATOMIC_FENCE`` to
``__sync_synchronize()``. This may happen or not happen independent of all the
above, controlled purely by ``setOperationAction(ISD::ATOMIC_FENCE, ...)``.
@@ -467,10 +467,11 @@ Native Object File Wrapper Format
=================================

Bitcode files for LLVM IR may also be wrapped in a native object file
(i.e. ELF, COFF, Mach-O). The bitcode must be stored in a section of the
object file named ``.llvmbc``. This wrapper format is useful for accommodating
LTO in compilation pipelines where intermediate objects must be native object
files which contain metadata in other sections.
(i.e. ELF, COFF, Mach-O). The bitcode must be stored in a section of the object
file named ``__LLVM,__bitcode`` for MachO and ``.llvmbc`` for the other object
formats. This wrapper format is useful for accommodating LTO in compilation
pipelines where intermediate objects must be native object files which contain
metadata in other sections.

Not all tools support this format.

@@ -689,6 +690,7 @@ global variable. The operand fields are:
.. _linkage type:

* *linkage*: An encoding of the linkage type for this variable:

* ``external``: code 0
* ``weak``: code 1
* ``appending``: code 2
@@ -713,20 +715,30 @@ global variable. The operand fields are:
.. _visibility:

* *visibility*: If present, an encoding of the visibility of this variable:

* ``default``: code 0
* ``hidden``: code 1
* ``protected``: code 2

.. _bcthreadlocal:

* *threadlocal*: If present, an encoding of the thread local storage mode of the
variable:

* ``not thread local``: code 0
* ``thread local; default TLS model``: code 1
* ``localdynamic``: code 2
* ``initialexec``: code 3
* ``localexec``: code 4

* *unnamed_addr*: If present and non-zero, indicates that the variable has
``unnamed_addr``
.. _bcunnamedaddr:

* *unnamed_addr*: If present, an encoding of the ``unnamed_addr`` attribute of this
variable:

* not ``unnamed_addr``: code 0
* ``unnamed_addr``: code 1
* ``local_unnamed_addr``: code 2

.. _bcdllstorageclass:

@@ -736,6 +748,8 @@ global variable. The operand fields are:
* ``dllimport``: code 1
* ``dllexport``: code 2

* *comdat*: An encoding of the COMDAT of this function

.. _FUNCTION:

MODULE_CODE_FUNCTION Record
@@ -756,6 +770,7 @@ function. The operand fields are:
* ``anyregcc``: code 13
* ``preserve_mostcc``: code 14
* ``preserve_allcc``: code 15
* ``swiftcc`` : code 16
* ``cxx_fast_tlscc``: code 17
* ``x86_stdcallcc``: code 64
* ``x86_fastcallcc``: code 65
@@ -782,8 +797,8 @@ function. The operand fields are:
* *gc*: If present and nonzero, the 1-based garbage collector index in the table
of `MODULE_CODE_GCNAME`_ entries.

* *unnamed_addr*: If present and non-zero, indicates that the function has
``unnamed_addr``
* *unnamed_addr*: If present, an encoding of the
:ref:`unnamed_addr<bcunnamedaddr>` attribute of this function

* *prologuedata*: If non-zero, the value index of the prologue data for this function,
plus 1.
@@ -802,7 +817,7 @@ function. The operand fields are:
MODULE_CODE_ALIAS Record
^^^^^^^^^^^^^^^^^^^^^^^^

``[ALIAS, alias type, aliasee val#, linkage, visibility, dllstorageclass]``
``[ALIAS, alias type, aliasee val#, linkage, visibility, dllstorageclass, threadlocal, unnamed_addr]``

The ``ALIAS`` record (code 9) marks the definition of an alias. The operand
fields are
@@ -818,6 +833,12 @@ fields are
* *dllstorageclass*: If present, an encoding of the
:ref:`dllstorageclass<bcdllstorageclass>` of the alias

* *threadlocal*: If present, an encoding of the
:ref:`thread local property<bcthreadlocal>` of the alias

* *unnamed_addr*: If present, an encoding of the
:ref:`unnamed_addr<bcunnamedaddr>` attribute of this alias

MODULE_CODE_PURGEVALS Record
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This file was deleted.

Oops, something went wrong.
Oops, something went wrong.