1include(ExternalProject)
2
3# llvm_ExternalProject_BuildCmd(out_var target)
4#   Utility function for constructing command lines for external project targets
5function(llvm_ExternalProject_BuildCmd out_var target bin_dir)
6  cmake_parse_arguments(ARG "" "CONFIGURATION" "" ${ARGN})
7  if(NOT ARG_CONFIGURATION)
8    set(ARG_CONFIGURATION "$<CONFIG>")
9  endif()
10  if (CMAKE_GENERATOR MATCHES "Make")
11    # Use special command for Makefiles to support parallelism.
12    set(${out_var} "$(MAKE)" "-C" "${bin_dir}" "${target}" PARENT_SCOPE)
13  else()
14    set(${out_var} ${CMAKE_COMMAND} --build ${bin_dir} --target ${target}
15                                    --config ${ARG_CONFIGURATION} PARENT_SCOPE)
16  endif()
17endfunction()
18
19# llvm_ExternalProject_Add(name source_dir ...
20#   USE_TOOLCHAIN
21#     Use just-built tools (see TOOLCHAIN_TOOLS)
22#   EXCLUDE_FROM_ALL
23#     Exclude this project from the all target
24#   NO_INSTALL
25#     Don't generate install targets for this project
26#   ALWAYS_CLEAN
27#     Always clean the sub-project before building
28#   CMAKE_ARGS arguments...
29#     Optional cmake arguments to pass when configuring the project
30#   TOOLCHAIN_TOOLS targets...
31#     Targets for toolchain tools (defaults to clang;lld)
32#   DEPENDS targets...
33#     Targets that this project depends on
34#   EXTRA_TARGETS targets...
35#     Extra targets in the subproject to generate targets for
36#   PASSTHROUGH_PREFIXES prefix...
37#     Extra variable prefixes (name is always included) to pass down
38#   STRIP_TOOL path
39#     Use provided strip tool instead of the default one.
40#   )
41function(llvm_ExternalProject_Add name source_dir)
42  cmake_parse_arguments(ARG
43    "USE_TOOLCHAIN;EXCLUDE_FROM_ALL;NO_INSTALL;ALWAYS_CLEAN"
44    "SOURCE_DIR"
45    "CMAKE_ARGS;TOOLCHAIN_TOOLS;RUNTIME_LIBRARIES;DEPENDS;EXTRA_TARGETS;PASSTHROUGH_PREFIXES;STRIP_TOOL"
46    ${ARGN})
47  canonicalize_tool_name(${name} nameCanon)
48
49  foreach(arg ${ARG_CMAKE_ARGS})
50    if(arg MATCHES "^-DCMAKE_SYSTEM_NAME=")
51      string(REGEX REPLACE "^-DCMAKE_SYSTEM_NAME=(.*)$" "\\1" _cmake_system_name "${arg}")
52    endif()
53  endforeach()
54
55  if(NOT ARG_TOOLCHAIN_TOOLS)
56    set(ARG_TOOLCHAIN_TOOLS clang lld llvm-ar llvm-lipo llvm-ranlib llvm-nm llvm-objdump)
57    if(NOT _cmake_system_name STREQUAL Darwin)
58      # TODO: These tools don't fully support Mach-O format yet.
59      list(APPEND ARG_TOOLCHAIN_TOOLS llvm-objcopy llvm-strip)
60    endif()
61  endif()
62  foreach(tool ${ARG_TOOLCHAIN_TOOLS})
63    if(TARGET ${tool})
64      list(APPEND TOOLCHAIN_TOOLS ${tool})
65
66      # $<TARGET_FILE:tgt> only works on add_executable or add_library targets
67      # The below logic mirrors cmake's own implementation
68      get_target_property(target_type "${tool}" TYPE)
69      if(NOT target_type STREQUAL "OBJECT_LIBRARY" AND
70         NOT target_type STREQUAL "UTILITY" AND
71         NOT target_type STREQUAL "GLOBAL_TARGET" AND
72         NOT target_type STREQUAL "INTERFACE_LIBRARY")
73        list(APPEND TOOLCHAIN_BINS $<TARGET_FILE:${tool}>)
74      endif()
75
76    endif()
77  endforeach()
78
79  if(NOT ARG_RUNTIME_LIBRARIES)
80    set(ARG_RUNTIME_LIBRARIES compiler-rt libcxx)
81  endif()
82  foreach(lib ${ARG_RUNTIME_LIBRARIES})
83    if(TARGET ${lib})
84      list(APPEND RUNTIME_LIBRARIES ${lib})
85    endif()
86  endforeach()
87
88  if(ARG_ALWAYS_CLEAN)
89    set(always_clean clean)
90  endif()
91
92  list(FIND TOOLCHAIN_TOOLS clang FOUND_CLANG)
93  if(FOUND_CLANG GREATER -1)
94    set(CLANG_IN_TOOLCHAIN On)
95  endif()
96
97  if(RUNTIME_LIBRARIES AND CLANG_IN_TOOLCHAIN)
98    list(APPEND TOOLCHAIN_BINS ${RUNTIME_LIBRARIES})
99  endif()
100
101  set(STAMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/${name}-stamps/)
102  set(BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/${name}-bins/)
103
104  add_custom_target(${name}-clear
105    COMMAND ${CMAKE_COMMAND} -E remove_directory ${BINARY_DIR}
106    COMMAND ${CMAKE_COMMAND} -E remove_directory ${STAMP_DIR}
107    COMMENT "Clobbering ${name} build and stamp directories"
108    USES_TERMINAL
109    )
110
111  # Find all variables that start with a prefix and propagate them through
112  get_cmake_property(variableNames VARIABLES)
113
114  list(APPEND ARG_PASSTHROUGH_PREFIXES ${nameCanon})
115  foreach(prefix ${ARG_PASSTHROUGH_PREFIXES})
116    foreach(variableName ${variableNames})
117      if(variableName MATCHES "^${prefix}")
118        string(REPLACE ";" "|" value "${${variableName}}")
119        list(APPEND PASSTHROUGH_VARIABLES
120          -D${variableName}=${value})
121      endif()
122    endforeach()
123  endforeach()
124
125  if(ARG_USE_TOOLCHAIN AND NOT CMAKE_CROSSCOMPILING)
126    if(CLANG_IN_TOOLCHAIN)
127      if(_cmake_system_name STREQUAL Windows)
128        set(compiler_args -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}
129                          -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}
130                          -DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX})
131      else()
132        set(compiler_args -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang${CMAKE_EXECUTABLE_SUFFIX}
133                          -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang++${CMAKE_EXECUTABLE_SUFFIX}
134                          -DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang${CMAKE_EXECUTABLE_SUFFIX})
135      endif()
136    endif()
137    if(lld IN_LIST TOOLCHAIN_TOOLS)
138      if(_cmake_system_name STREQUAL Windows)
139        list(APPEND compiler_args -DCMAKE_LINKER=${LLVM_RUNTIME_OUTPUT_INTDIR}/lld-link${CMAKE_EXECUTABLE_SUFFIX})
140      else()
141        list(APPEND compiler_args -DCMAKE_LINKER=${LLVM_RUNTIME_OUTPUT_INTDIR}/ld.lld${CMAKE_EXECUTABLE_SUFFIX})
142      endif()
143    endif()
144    if(llvm-ar IN_LIST TOOLCHAIN_TOOLS)
145      list(APPEND compiler_args -DCMAKE_AR=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-ar${CMAKE_EXECUTABLE_SUFFIX})
146    endif()
147    if(llvm-lipo IN_LIST TOOLCHAIN_TOOLS)
148      list(APPEND compiler_args -DCMAKE_LIPO=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-lipo${CMAKE_EXECUTABLE_SUFFIX})
149    endif()
150    if(llvm-ranlib IN_LIST TOOLCHAIN_TOOLS)
151      list(APPEND compiler_args -DCMAKE_RANLIB=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-ranlib${CMAKE_EXECUTABLE_SUFFIX})
152    endif()
153    if(llvm-nm IN_LIST TOOLCHAIN_TOOLS)
154      list(APPEND compiler_args -DCMAKE_NM=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-nm${CMAKE_EXECUTABLE_SUFFIX})
155    endif()
156    if(llvm-objdump IN_LIST TOOLCHAIN_TOOLS)
157      list(APPEND compiler_args -DCMAKE_OBJDUMP=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-objdump${CMAKE_EXECUTABLE_SUFFIX})
158    endif()
159    if(llvm-objcopy IN_LIST TOOLCHAIN_TOOLS)
160      list(APPEND compiler_args -DCMAKE_OBJCOPY=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-objcopy${CMAKE_EXECUTABLE_SUFFIX})
161    endif()
162    if(llvm-strip IN_LIST TOOLCHAIN_TOOLS AND NOT ARG_STRIP_TOOL)
163      list(APPEND compiler_args -DCMAKE_STRIP=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-strip${CMAKE_EXECUTABLE_SUFFIX})
164    endif()
165    list(APPEND ARG_DEPENDS ${TOOLCHAIN_TOOLS})
166  endif()
167
168  if(ARG_STRIP_TOOL)
169    list(APPEND compiler_args -DCMAKE_STRIP=${ARG_STRIP_TOOL})
170  endif()
171
172  add_custom_command(
173    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp
174    DEPENDS ${ARG_DEPENDS}
175    COMMAND ${CMAKE_COMMAND} -E touch ${BINARY_DIR}/CMakeCache.txt
176    COMMAND ${CMAKE_COMMAND} -E touch ${STAMP_DIR}/${name}-mkdir
177    COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp
178    COMMENT "Clobbering bootstrap build and stamp directories"
179    )
180
181  add_custom_target(${name}-clobber
182    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp)
183
184  if(ARG_EXCLUDE_FROM_ALL)
185    set(exclude EXCLUDE_FROM_ALL 1)
186  endif()
187
188  if(CMAKE_SYSROOT)
189    set(sysroot_arg -DCMAKE_SYSROOT=${CMAKE_SYSROOT})
190  endif()
191
192  if(CMAKE_CROSSCOMPILING)
193    set(compiler_args -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
194                      -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
195                      -DCMAKE_LINKER=${CMAKE_LINKER}
196                      -DCMAKE_AR=${CMAKE_AR}
197                      -DCMAKE_RANLIB=${CMAKE_RANLIB}
198                      -DCMAKE_NM=${CMAKE_NM}
199                      -DCMAKE_OBJCOPY=${CMAKE_OBJCOPY}
200                      -DCMAKE_OBJDUMP=${CMAKE_OBJDUMP}
201                      -DCMAKE_STRIP=${CMAKE_STRIP})
202    set(llvm_config_path ${LLVM_CONFIG_PATH})
203
204    if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
205      string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION
206             ${PACKAGE_VERSION})
207      set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION}")
208      set(flag_types ASM C CXX MODULE_LINKER SHARED_LINKER EXE_LINKER)
209      foreach(type ${flag_types})
210        set(${type}_flag -DCMAKE_${type}_FLAGS=-resource-dir=${resource_dir})
211      endforeach()
212      string(REPLACE ";" "|" flag_string "${flag_types}")
213      foreach(arg ${ARG_CMAKE_ARGS})
214        if(arg MATCHES "^-DCMAKE_(${flag_string})_FLAGS")
215          foreach(type ${flag_types})
216            if(arg MATCHES "^-DCMAKE_${type}_FLAGS")
217              string(REGEX REPLACE "^-DCMAKE_${type}_FLAGS=(.*)$" "\\1" flag_value "${arg}")
218              set(${type}_flag "${${type}_flag} ${flag_value}")
219            endif()
220          endforeach()
221        else()
222          list(APPEND cmake_args ${arg})
223        endif()
224      endforeach()
225      foreach(type ${flag_types})
226        list(APPEND cmake_args ${${type}_flag})
227      endforeach()
228    endif()
229  else()
230    set(llvm_config_path "$<TARGET_FILE:llvm-config>")
231    set(cmake_args ${ARG_CMAKE_ARGS})
232  endif()
233
234  ExternalProject_Add(${name}
235    DEPENDS ${ARG_DEPENDS} llvm-config
236    ${name}-clobber
237    PREFIX ${CMAKE_BINARY_DIR}/projects/${name}
238    SOURCE_DIR ${source_dir}
239    STAMP_DIR ${STAMP_DIR}
240    BINARY_DIR ${BINARY_DIR}
241    ${exclude}
242    CMAKE_ARGS ${${nameCanon}_CMAKE_ARGS}
243               ${compiler_args}
244               -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
245               ${sysroot_arg}
246               -DLLVM_BINARY_DIR=${PROJECT_BINARY_DIR}
247               -DLLVM_CONFIG_PATH=${llvm_config_path}
248               -DLLVM_ENABLE_WERROR=${LLVM_ENABLE_WERROR}
249               -DLLVM_HOST_TRIPLE=${LLVM_HOST_TRIPLE}
250               -DLLVM_HAVE_LINK_VERSION_SCRIPT=${LLVM_HAVE_LINK_VERSION_SCRIPT}
251               -DLLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO=${LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO}
252               -DLLVM_USE_RELATIVE_PATHS_IN_FILES=${LLVM_USE_RELATIVE_PATHS_IN_FILES}
253               -DLLVM_LIT_ARGS=${LLVM_LIT_ARGS}
254               -DLLVM_SOURCE_PREFIX=${LLVM_SOURCE_PREFIX}
255               -DPACKAGE_VERSION=${PACKAGE_VERSION}
256               -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
257               -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
258               -DCMAKE_EXPORT_COMPILE_COMMANDS=1
259               ${cmake_args}
260               ${PASSTHROUGH_VARIABLES}
261    INSTALL_COMMAND ""
262    STEP_TARGETS configure build
263    BUILD_ALWAYS 1
264    USES_TERMINAL_CONFIGURE 1
265    USES_TERMINAL_BUILD 1
266    USES_TERMINAL_INSTALL 1
267    LIST_SEPARATOR |
268    )
269
270  if(ARG_USE_TOOLCHAIN)
271    set(force_deps DEPENDS ${TOOLCHAIN_BINS})
272  endif()
273
274  llvm_ExternalProject_BuildCmd(run_clean clean ${BINARY_DIR})
275  ExternalProject_Add_Step(${name} clean
276    COMMAND ${run_clean}
277    COMMENT "Cleaning ${name}..."
278    DEPENDEES configure
279    ${force_deps}
280    WORKING_DIRECTORY ${BINARY_DIR}
281    EXCLUDE_FROM_MAIN 1
282    USES_TERMINAL 1
283    )
284  ExternalProject_Add_StepTargets(${name} clean)
285
286  if(ARG_USE_TOOLCHAIN)
287    add_dependencies(${name}-clean ${name}-clobber)
288    set_target_properties(${name}-clean PROPERTIES
289      SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp)
290  endif()
291
292  if(NOT ARG_NO_INSTALL)
293    install(CODE "execute_process\(COMMAND \${CMAKE_COMMAND} -DCMAKE_INSTALL_PREFIX=\${CMAKE_INSTALL_PREFIX} -DCMAKE_INSTALL_DO_STRIP=\${CMAKE_INSTALL_DO_STRIP} -P ${BINARY_DIR}/cmake_install.cmake\)"
294      COMPONENT ${name})
295
296    add_llvm_install_targets(install-${name}
297                             DEPENDS ${name}
298                             COMPONENT ${name})
299  endif()
300
301  # Add top-level targets
302  foreach(target ${ARG_EXTRA_TARGETS})
303    if(DEFINED ${target})
304      set(external_target "${${target}}")
305    else()
306      set(external_target "${target}")
307    endif()
308    llvm_ExternalProject_BuildCmd(build_runtime_cmd ${external_target} ${BINARY_DIR})
309    add_custom_target(${target}
310      COMMAND ${build_runtime_cmd}
311      DEPENDS ${name}-configure
312      WORKING_DIRECTORY ${BINARY_DIR}
313      VERBATIM
314      USES_TERMINAL)
315  endforeach()
316endfunction()
317