1# This CMake module is responsible for interpreting the user defined LLVM_
2# options and executing the appropriate CMake commands to realize the users'
3# selections.
4
5# This is commonly needed so make sure it's defined before we include anything
6# else.
7string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE)
8
9include(CheckCompilerVersion)
10include(HandleLLVMStdlib)
11include(CheckCCompilerFlag)
12include(CheckCXXCompilerFlag)
13include(CheckSymbolExists)
14include(CMakeDependentOption)
15include(LLVMProcessSources)
16
17if(CMAKE_LINKER MATCHES ".*lld" OR (LLVM_USE_LINKER STREQUAL "lld" OR LLVM_ENABLE_LLD))
18  set(LINKER_IS_LLD TRUE)
19else()
20  set(LINKER_IS_LLD FALSE)
21endif()
22
23if(CMAKE_LINKER MATCHES "lld-link" OR (MSVC AND (LLVM_USE_LINKER STREQUAL "lld" OR LLVM_ENABLE_LLD)))
24  set(LINKER_IS_LLD_LINK TRUE)
25else()
26  set(LINKER_IS_LLD_LINK FALSE)
27endif()
28
29set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as Thin or Full to use a particular kind of LTO")
30string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
31
32# Ninja Job Pool support
33# The following only works with the Ninja generator in CMake >= 3.0.
34set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
35  "Define the maximum number of concurrent compilation jobs (Ninja only).")
36if(LLVM_PARALLEL_COMPILE_JOBS)
37  if(NOT CMAKE_GENERATOR STREQUAL "Ninja")
38    message(WARNING "Job pooling is only available with Ninja generators.")
39  else()
40    set_property(GLOBAL APPEND PROPERTY JOB_POOLS compile_job_pool=${LLVM_PARALLEL_COMPILE_JOBS})
41    set(CMAKE_JOB_POOL_COMPILE compile_job_pool)
42  endif()
43endif()
44
45set(LLVM_PARALLEL_LINK_JOBS "" CACHE STRING
46  "Define the maximum number of concurrent link jobs (Ninja only).")
47if(CMAKE_GENERATOR STREQUAL "Ninja")
48  if(NOT LLVM_PARALLEL_LINK_JOBS AND uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
49    message(STATUS "ThinLTO provides its own parallel linking - limiting parallel link jobs to 2.")
50    set(LLVM_PARALLEL_LINK_JOBS "2")
51  endif()
52  if(LLVM_PARALLEL_LINK_JOBS)
53    set_property(GLOBAL APPEND PROPERTY JOB_POOLS link_job_pool=${LLVM_PARALLEL_LINK_JOBS})
54    set(CMAKE_JOB_POOL_LINK link_job_pool)
55  endif()
56elseif(LLVM_PARALLEL_LINK_JOBS)
57  message(WARNING "Job pooling is only available with Ninja generators.")
58endif()
59
60if( LLVM_ENABLE_ASSERTIONS )
61  # MSVC doesn't like _DEBUG on release builds. See PR 4379.
62  if( NOT MSVC )
63    add_definitions( -D_DEBUG )
64  endif()
65  # On non-Debug builds cmake automatically defines NDEBUG, so we
66  # explicitly undefine it:
67  if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
68    # NOTE: use `add_compile_options` rather than `add_definitions` since
69    # `add_definitions` does not support generator expressions.
70    add_compile_options($<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-UNDEBUG>)
71    if (MSVC)
72      # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines.
73      foreach (flags_var_to_scrub
74          CMAKE_CXX_FLAGS_RELEASE
75          CMAKE_CXX_FLAGS_RELWITHDEBINFO
76          CMAKE_CXX_FLAGS_MINSIZEREL
77          CMAKE_C_FLAGS_RELEASE
78          CMAKE_C_FLAGS_RELWITHDEBINFO
79          CMAKE_C_FLAGS_MINSIZEREL)
80        string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " "
81          "${flags_var_to_scrub}" "${${flags_var_to_scrub}}")
82      endforeach()
83     endif()
84  endif()
85endif()
86
87if(LLVM_ENABLE_EXPENSIVE_CHECKS)
88  add_definitions(-DEXPENSIVE_CHECKS)
89
90  # In some libstdc++ versions, std::min_element is not constexpr when
91  # _GLIBCXX_DEBUG is enabled.
92  CHECK_CXX_SOURCE_COMPILES("
93    #define _GLIBCXX_DEBUG
94    #include <algorithm>
95    int main(int argc, char** argv) {
96      static constexpr int data[] = {0, 1};
97      constexpr const int* min_elt = std::min_element(&data[0], &data[2]);
98      return 0;
99    }" CXX_SUPPORTS_GLIBCXX_DEBUG)
100  if(CXX_SUPPORTS_GLIBCXX_DEBUG)
101    add_definitions(-D_GLIBCXX_DEBUG)
102  else()
103    add_definitions(-D_GLIBCXX_ASSERTIONS)
104  endif()
105endif()
106
107if (LLVM_ENABLE_STRICT_FIXED_SIZE_VECTORS)
108  add_definitions(-DSTRICT_FIXED_SIZE_VECTORS)
109endif()
110
111string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS)
112
113if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" )
114  if( LLVM_ENABLE_ASSERTIONS )
115    set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
116  endif()
117elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_ON" )
118  set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
119elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_OFF" )
120  # We don't need to do anything special to turn off ABI breaking checks.
121elseif( NOT DEFINED LLVM_ABI_BREAKING_CHECKS )
122  # Treat LLVM_ABI_BREAKING_CHECKS like "FORCE_OFF" when it has not been
123  # defined.
124else()
125  message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: \"${LLVM_ABI_BREAKING_CHECKS}\"!")
126endif()
127
128if( LLVM_REVERSE_ITERATION )
129  set( LLVM_ENABLE_REVERSE_ITERATION 1 )
130endif()
131
132if(WIN32)
133  set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
134  if(CYGWIN)
135    set(LLVM_ON_WIN32 0)
136    set(LLVM_ON_UNIX 1)
137  else(CYGWIN)
138    set(LLVM_ON_WIN32 1)
139    set(LLVM_ON_UNIX 0)
140  endif(CYGWIN)
141else(WIN32)
142  if(FUCHSIA OR UNIX)
143    set(LLVM_ON_WIN32 0)
144    set(LLVM_ON_UNIX 1)
145    if(APPLE OR ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
146      set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
147    else()
148      set(LLVM_HAVE_LINK_VERSION_SCRIPT 1)
149    endif()
150  else(FUCHSIA OR UNIX)
151    MESSAGE(SEND_ERROR "Unable to determine platform")
152  endif(FUCHSIA OR UNIX)
153endif(WIN32)
154
155if (CMAKE_SYSTEM_NAME MATCHES "OS390")
156  set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
157endif()
158
159set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX})
160set(LTDL_SHLIB_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
161
162# We use *.dylib rather than *.so on darwin, but we stick with *.so on AIX.
163if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
164  set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_MODULE_SUFFIX})
165else()
166  set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
167endif()
168
169if(APPLE)
170  if(LLVM_ENABLE_LLD AND LLVM_ENABLE_LTO)
171    message(FATAL_ERROR "lld does not support LTO on Darwin")
172  endif()
173  # Darwin-specific linker flags for loadable modules.
174  set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-flat_namespace -Wl,-undefined -Wl,suppress")
175endif()
176
177if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
178  # RHEL7 has ar and ranlib being non-deterministic by default. The D flag forces determinism,
179  # however only GNU version of ar and ranlib (2.27) have this option.
180  # RHEL DTS7 is also affected by this, which uses GNU binutils 2.28
181  execute_process(COMMAND ${CMAKE_AR} rD t.a
182                  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
183                  RESULT_VARIABLE AR_RESULT
184                  OUTPUT_QUIET
185                  ERROR_QUIET
186                  )
187  if(${AR_RESULT} EQUAL 0)
188    execute_process(COMMAND ${CMAKE_RANLIB} -D t.a
189                    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
190                    RESULT_VARIABLE RANLIB_RESULT
191                    OUTPUT_QUIET
192                    ERROR_QUIET
193                    )
194    if(${RANLIB_RESULT} EQUAL 0)
195      set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Dqc <TARGET> <LINK_FLAGS> <OBJECTS>")
196      set(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> Dq  <TARGET> <LINK_FLAGS> <OBJECTS>")
197      set(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARGET>")
198
199      set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> Dqc <TARGET> <LINK_FLAGS> <OBJECTS>")
200      set(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> Dq  <TARGET> <LINK_FLAGS> <OBJECTS>")
201      set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARGET>")
202    endif()
203    file(REMOVE ${CMAKE_BINARY_DIR}/t.a)
204  endif()
205endif()
206
207if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
208  # -fPIC does not enable the large code model for GCC on AIX but does for XL.
209  if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
210    append("-mcmodel=large" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
211  elseif(CMAKE_CXX_COMPILER_ID MATCHES "XL")
212    # XL generates a small number of relocations not of the large model, -bbigtoc is needed.
213    append("-Wl,-bbigtoc"
214           CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
215    # The default behaviour on AIX processes dynamic initialization of non-local variables with
216    # static storage duration even for archive members that are otherwise unreferenced.
217    # Since `--whole-archive` is not used by the LLVM build to keep such initializations for Linux,
218    # we can limit the processing for archive members to only those that are otherwise referenced.
219    append("-bcdtors:mbr"
220           CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
221  endif()
222  if(BUILD_SHARED_LIBS)
223    # See rpath handling in AddLLVM.cmake
224    # FIXME: Remove this warning if this rpath is no longer hardcoded.
225    message(WARNING "Build and install environment path info may be exposed; binaries will also be unrelocatable.")
226  endif()
227endif()
228
229# Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
230# build might work on ELF but fail on MachO/COFF.
231if(NOT (CMAKE_SYSTEM_NAME MATCHES "Darwin|FreeBSD|OpenBSD|DragonFly|AIX|SunOS|OS390" OR
232        WIN32 OR CYGWIN) AND
233   NOT LLVM_USE_SANITIZER)
234  set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
235endif()
236
237# Pass -Wl,-z,nodelete. This makes sure our shared libraries are not unloaded
238# by dlclose(). We need that since the CLI API relies on cross-references
239# between global objects which became horribly broken when one of the libraries
240# is unloaded.
241if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
242  set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,nodelete")
243  set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-z,nodelete")
244endif()
245
246
247function(append value)
248  foreach(variable ${ARGN})
249    set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
250  endforeach(variable)
251endfunction()
252
253function(append_if condition value)
254  if (${condition})
255    foreach(variable ${ARGN})
256      set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
257    endforeach(variable)
258  endif()
259endfunction()
260
261macro(add_flag_if_supported flag name)
262  check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
263  append_if("C_SUPPORTS_${name}" "${flag}" CMAKE_C_FLAGS)
264  check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
265  append_if("CXX_SUPPORTS_${name}" "${flag}" CMAKE_CXX_FLAGS)
266endmacro()
267
268function(add_flag_or_print_warning flag name)
269  check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
270  check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
271  if (C_SUPPORTS_${name} AND CXX_SUPPORTS_${name})
272    message(STATUS "Building with ${flag}")
273    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
274    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
275    set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} ${flag}" PARENT_SCOPE)
276  else()
277    message(WARNING "${flag} is not supported.")
278  endif()
279endfunction()
280
281if( LLVM_ENABLE_LLD )
282  if ( LLVM_USE_LINKER )
283    message(FATAL_ERROR "LLVM_ENABLE_LLD and LLVM_USE_LINKER can't be set at the same time")
284  endif()
285  # In case of MSVC cmake always invokes the linker directly, so the linker
286  # should be specified by CMAKE_LINKER cmake variable instead of by -fuse-ld
287  # compiler option.
288  if ( NOT MSVC )
289    set(LLVM_USE_LINKER "lld")
290  endif()
291endif()
292
293if( LLVM_USE_LINKER )
294  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
295  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fuse-ld=${LLVM_USE_LINKER}")
296  check_cxx_source_compiles("int main() { return 0; }" CXX_SUPPORTS_CUSTOM_LINKER)
297  if ( NOT CXX_SUPPORTS_CUSTOM_LINKER )
298    message(FATAL_ERROR "Host compiler does not support '-fuse-ld=${LLVM_USE_LINKER}'")
299  endif()
300  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
301  append("-fuse-ld=${LLVM_USE_LINKER}"
302    CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
303endif()
304
305if( LLVM_ENABLE_PIC )
306  if( XCODE )
307    # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't
308    # know how to disable this, so just force ENABLE_PIC off for now.
309    message(WARNING "-fPIC not supported with Xcode.")
310  elseif( WIN32 OR CYGWIN)
311    # On Windows all code is PIC. MinGW warns if -fPIC is used.
312  else()
313    add_flag_or_print_warning("-fPIC" FPIC)
314    # Enable interprocedural optimizations for non-inline functions which would
315    # otherwise be disabled due to GCC -fPIC's default.
316    # Note: GCC<10.3 has a bug on SystemZ.
317    #
318    # Note: Clang allows IPO for -fPIC so this optimization is less effective.
319    # Older Clang may support -fno-semantic-interposition but it used local
320    # aliases to optimize global variables, which is incompatible with copy
321    # relocations due to -fno-pic.
322    if ((CMAKE_COMPILER_IS_GNUCXX AND
323         NOT (LLVM_NATIVE_ARCH STREQUAL "SystemZ" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10.3))
324       OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND CMAKE_CXX_COMPILER_VERSION GREATER_EQUAL 13))
325      add_flag_if_supported("-fno-semantic-interposition" FNO_SEMANTIC_INTERPOSITION)
326    endif()
327  endif()
328  # GCC for MIPS can miscompile LLVM due to PR37701.
329  if(CMAKE_COMPILER_IS_GNUCXX AND LLVM_NATIVE_ARCH STREQUAL "Mips" AND
330         NOT Uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
331    add_flag_or_print_warning("-fno-shrink-wrap" FNO_SHRINK_WRAP)
332  endif()
333  # gcc with -O3 -fPIC generates TLS sequences that violate the spec on
334  # Solaris/sparcv9, causing executables created with the system linker
335  # to SEGV (GCC PR target/96607).
336  # clang with -O3 -fPIC generates code that SEGVs.
337  # Both can be worked around by compiling with -O instead.
338  if(${CMAKE_SYSTEM_NAME} STREQUAL "SunOS" AND LLVM_NATIVE_ARCH STREQUAL "Sparc")
339    llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O[23]" "-O")
340    llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O[23]" "-O")
341  endif()
342endif()
343
344if(NOT WIN32 AND NOT CYGWIN AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU"))
345  # MinGW warns if -fvisibility-inlines-hidden is used.
346  # GCC on AIX warns if -fvisibility-inlines-hidden is used.
347  check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG)
348  append_if(SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG "-fvisibility-inlines-hidden" CMAKE_CXX_FLAGS)
349endif()
350
351if(CMAKE_SIZEOF_VOID_P EQUAL 8 AND MINGW)
352  add_definitions( -D_FILE_OFFSET_BITS=64 )
353endif()
354
355if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
356  # TODO: support other platforms and toolchains.
357  if( LLVM_BUILD_32_BITS )
358    message(STATUS "Building 32 bits executables and libraries.")
359    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
360    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
361    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
362    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
363    set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32")
364
365    # FIXME: CMAKE_SIZEOF_VOID_P is still 8
366    add_definitions(-D_LARGEFILE_SOURCE)
367    add_definitions(-D_FILE_OFFSET_BITS=64)
368  endif( LLVM_BUILD_32_BITS )
369endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
370
371# If building on a GNU specific 32-bit system, make sure off_t is 64 bits
372# so that off_t can stored offset > 2GB.
373# Android until version N (API 24) doesn't support it.
374if (ANDROID AND (ANDROID_NATIVE_API_LEVEL LESS 24))
375  set(LLVM_FORCE_SMALLFILE_FOR_ANDROID TRUE)
376endif()
377if( CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT LLVM_FORCE_SMALLFILE_FOR_ANDROID)
378  # FIXME: It isn't handled in LLVM_BUILD_32_BITS.
379  add_definitions( -D_LARGEFILE_SOURCE )
380  add_definitions( -D_FILE_OFFSET_BITS=64 )
381endif()
382
383if( XCODE )
384  # For Xcode enable several build settings that correspond to
385  # many warnings that are on by default in Clang but are
386  # not enabled for historical reasons.  For versions of Xcode
387  # that do not support these options they will simply
388  # be ignored.
389  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_RETURN_TYPE "YES")
390  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE "YES")
391  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VALUE "YES")
392  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VARIABLE "YES")
393  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_SIGN_COMPARE "YES")
394  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_FUNCTION "YES")
395  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED "YES")
396  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS "YES")
397  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNINITIALIZED_AUTOS "YES")
398  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_BOOL_CONVERSION "YES")
399  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_EMPTY_BODY "YES")
400  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_ENUM_CONVERSION "YES")
401  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_INT_CONVERSION "YES")
402  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_CONSTANT_CONVERSION "YES")
403  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_NON_VIRTUAL_DESTRUCTOR "YES")
404endif()
405
406# On Win32 using MS tools, provide an option to set the number of parallel jobs
407# to use.
408if( MSVC_IDE )
409  set(LLVM_COMPILER_JOBS "0" CACHE STRING
410    "Number of parallel compiler jobs. 0 means use all processors. Default is 0.")
411  if( NOT LLVM_COMPILER_JOBS STREQUAL "1" )
412    if( LLVM_COMPILER_JOBS STREQUAL "0" )
413      add_definitions( /MP )
414    else()
415      message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS})
416      add_definitions( /MP${LLVM_COMPILER_JOBS} )
417    endif()
418  else()
419    message(STATUS "Parallel compilation disabled")
420  endif()
421endif()
422
423# set stack reserved size to ~10MB
424if(MSVC)
425  # CMake previously automatically set this value for MSVC builds, but the
426  # behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default
427  # value (1 MB) which is not enough for us in tasks such as parsing recursive
428  # C++ templates in Clang.
429  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000")
430elseif(MINGW) # FIXME: Also cygwin?
431  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216")
432
433  # Pass -mbig-obj to mingw gas to avoid COFF 2**16 section limit.
434  if (NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang")
435    append("-Wa,-mbig-obj" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
436  endif()
437endif()
438
439option(LLVM_ENABLE_WARNINGS "Enable compiler warnings." ON)
440
441if( MSVC )
442  include(ChooseMSVCCRT)
443
444  # Add definitions that make MSVC much less annoying.
445  add_definitions(
446    # For some reason MS wants to deprecate a bunch of standard functions...
447    -D_CRT_SECURE_NO_DEPRECATE
448    -D_CRT_SECURE_NO_WARNINGS
449    -D_CRT_NONSTDC_NO_DEPRECATE
450    -D_CRT_NONSTDC_NO_WARNINGS
451    -D_SCL_SECURE_NO_DEPRECATE
452    -D_SCL_SECURE_NO_WARNINGS
453    )
454
455  # Tell MSVC to use the Unicode version of the Win32 APIs instead of ANSI.
456  add_definitions(
457    -DUNICODE
458    -D_UNICODE
459  )
460
461  # Allow setting clang-cl's /winsysroot flag.
462  set(LLVM_WINSYSROOT "" CACHE STRING
463    "If set, argument to clang-cl's /winsysroot")
464  if (LLVM_WINSYSROOT)
465    if (NOT CLANG_CL)
466      message(ERROR "LLVM_WINSYSROOT requires clang-cl")
467    endif()
468    append("/winsysroot${LLVM_WINSYSROOT}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
469  endif()
470
471  if (LLVM_ENABLE_WERROR)
472    append("/WX" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
473  endif (LLVM_ENABLE_WERROR)
474
475  append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
476
477  # Some projects use the __cplusplus preprocessor macro to check support for
478  # a particular version of the C++ standard. When this option is not specified
479  # explicitly, macro's value is "199711L" that implies C++98 Standard.
480  # https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
481  append("/Zc:__cplusplus" CMAKE_CXX_FLAGS)
482
483  # Allow users to request PDBs in release mode. CMake offeres the
484  # RelWithDebInfo configuration, but it uses different optimization settings
485  # (/Ob1 vs /Ob2 or -O2 vs -O3). LLVM provides this flag so that users can get
486  # PDBs without changing codegen.
487  option(LLVM_ENABLE_PDB OFF)
488  if (LLVM_ENABLE_PDB AND uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE")
489    append("/Zi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
490    # /DEBUG disables linker GC and ICF, but we want those in Release mode.
491    append("/DEBUG /OPT:REF /OPT:ICF"
492          CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS
493          CMAKE_SHARED_LINKER_FLAGS)
494  endif()
495
496  # Get all linker flags in upper case form so we can search them.
497  set(all_linker_flags_uppercase
498    "${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}")
499  string(TOUPPER "${all_linker_flags_uppercase}" all_linker_flags_uppercase)
500
501  if (CLANG_CL AND LINKER_IS_LLD)
502    # If we are using clang-cl with lld-link and /debug is present in any of the
503    # linker flag variables, pass -gcodeview-ghash to the compiler to speed up
504    # linking. This flag is orthogonal from /Zi, /Z7, and other flags that
505    # enable debug info emission, and only has an effect if those are also in
506    # use.
507    string(FIND "${all_linker_flags_uppercase}" "/DEBUG" linker_flag_idx)
508    if (${linker_flag_idx} GREATER -1)
509      add_flag_if_supported("-gcodeview-ghash" GCODEVIEW_GHASH)
510    endif()
511  endif()
512
513  # Disable string literal const->non-const type conversion.
514  # "When specified, the compiler requires strict const-qualification
515  # conformance for pointers initialized by using string literals."
516  append("/Zc:strictStrings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
517
518  # "Generate Intrinsic Functions".
519  append("/Oi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
520
521  # "Enforce type conversion rules".
522  append("/Zc:rvalueCast" CMAKE_CXX_FLAGS)
523
524  if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT LLVM_ENABLE_LTO)
525    # clang-cl and cl by default produce non-deterministic binaries because
526    # link.exe /incremental requires a timestamp in the .obj file.  clang-cl
527    # has the flag /Brepro to force deterministic binaries. We want to pass that
528    # whenever you're building with clang unless you're passing /incremental
529    # or using LTO (/Brepro with LTO would result in a warning about the flag
530    # being unused, because we're not generating object files).
531    # This checks CMAKE_CXX_COMPILER_ID in addition to check_cxx_compiler_flag()
532    # because cl.exe does not emit an error on flags it doesn't understand,
533    # letting check_cxx_compiler_flag() claim it understands all flags.
534    check_cxx_compiler_flag("/Brepro" SUPPORTS_BREPRO)
535    if (SUPPORTS_BREPRO)
536      # Check if /INCREMENTAL is passed to the linker and complain that it
537      # won't work with /Brepro.
538      string(FIND "${all_linker_flags_uppercase}" "/INCREMENTAL" linker_flag_idx)
539      if (${linker_flag_idx} GREATER -1)
540        message(WARNING "/Brepro not compatible with /INCREMENTAL linking - builds will be non-deterministic")
541      else()
542        append("/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
543      endif()
544    endif()
545  endif()
546  # By default MSVC has a 2^16 limit on the number of sections in an object file,
547  # but in many objects files need more than that. This flag is to increase the
548  # number of sections.
549  append("/bigobj" CMAKE_CXX_FLAGS)
550endif( MSVC )
551
552# Warnings-as-errors handling for GCC-compatible compilers:
553if ( LLVM_COMPILER_IS_GCC_COMPATIBLE )
554  append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
555  append_if(LLVM_ENABLE_WERROR "-Wno-error" CMAKE_REQUIRED_FLAGS)
556endif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
557
558# Specific default warnings-as-errors for compilers accepting GCC-compatible warning flags:
559if ( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
560  add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
561  add_flag_if_supported("-Werror=unguarded-availability-new" WERROR_UNGUARDED_AVAILABILITY_NEW)
562endif( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
563
564# Modules enablement for GCC-compatible compilers:
565if ( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
566  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
567  set(module_flags "-fmodules -fmodules-cache-path=${PROJECT_BINARY_DIR}/module.cache")
568  if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
569    # On Darwin -fmodules does not imply -fcxx-modules.
570    set(module_flags "${module_flags} -fcxx-modules")
571  endif()
572  if (LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY)
573    set(module_flags "${module_flags} -Xclang -fmodules-local-submodule-visibility")
574  endif()
575  if (LLVM_ENABLE_MODULE_DEBUGGING AND
576      ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
577       (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
578    set(module_flags "${module_flags} -gmodules")
579  endif()
580  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${module_flags}")
581
582  # Check that we can build code with modules enabled, and that repeatedly
583  # including <cassert> still manages to respect NDEBUG properly.
584  CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG
585                             #include <cassert>
586                             #define NDEBUG
587                             #include <cassert>
588                             int main() { assert(this code is not compiled); }"
589                             CXX_SUPPORTS_MODULES)
590  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
591  if (CXX_SUPPORTS_MODULES)
592    append("${module_flags}" CMAKE_CXX_FLAGS)
593  else()
594    message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
595  endif()
596endif( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
597
598if (MSVC)
599  if (NOT CLANG_CL)
600    set(msvc_warning_flags
601      # Disabled warnings.
602      -wd4141 # Suppress ''modifier' : used more than once' (because of __forceinline combined with inline)
603      -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned'
604      -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data'
605      -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data'
606      -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception'
607      -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized'
608      -wd4456 # Suppress 'declaration of 'var' hides local variable'
609      -wd4457 # Suppress 'declaration of 'var' hides function parameter'
610      -wd4458 # Suppress 'declaration of 'var' hides class member'
611      -wd4459 # Suppress 'declaration of 'var' hides global declaration'
612      -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated'
613      -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible'
614      -wd4722 # Suppress 'function' : destructor never returns, potential memory leak
615      -wd4100 # Suppress 'unreferenced formal parameter'
616      -wd4127 # Suppress 'conditional expression is constant'
617      -wd4512 # Suppress 'assignment operator could not be generated'
618      -wd4505 # Suppress 'unreferenced local function has been removed'
619      -wd4610 # Suppress '<class> can never be instantiated'
620      -wd4510 # Suppress 'default constructor could not be generated'
621      -wd4702 # Suppress 'unreachable code'
622      -wd4245 # Suppress ''conversion' : conversion from 'type1' to 'type2', signed/unsigned mismatch'
623      -wd4706 # Suppress 'assignment within conditional expression'
624      -wd4310 # Suppress 'cast truncates constant value'
625      -wd4701 # Suppress 'potentially uninitialized local variable'
626      -wd4703 # Suppress 'potentially uninitialized local pointer variable'
627      -wd4389 # Suppress 'signed/unsigned mismatch'
628      -wd4611 # Suppress 'interaction between '_setjmp' and C++ object destruction is non-portable'
629      -wd4805 # Suppress 'unsafe mix of type <type> and type <type> in operation'
630      -wd4204 # Suppress 'nonstandard extension used : non-constant aggregate initializer'
631      -wd4577 # Suppress 'noexcept used with no exception handling mode specified; termination on exception is not guaranteed'
632      -wd4091 # Suppress 'typedef: ignored on left of '' when no variable is declared'
633          # C4592 is disabled because of false positives in Visual Studio 2015
634          # Update 1. Re-evaluate the usefulness of this diagnostic with Update 2.
635      -wd4592 # Suppress ''var': symbol will be dynamically initialized (implementation limitation)
636      -wd4319 # Suppress ''operator' : zero extending 'type' to 'type' of greater size'
637          # C4709 is disabled because of a bug with Visual Studio 2017 as of
638          # v15.8.8. Re-evaluate the usefulness of this diagnostic when the bug
639          # is fixed.
640      -wd4709 # Suppress comma operator within array index expression
641
642      # Ideally, we'd like this warning to be enabled, but even MSVC 2019 doesn't
643      # support the 'aligned' attribute in the way that clang sources requires (for
644      # any code that uses the LLVM_ALIGNAS macro), so this is must be disabled to
645      # avoid unwanted alignment warnings.
646      -wd4324 # Suppress 'structure was padded due to __declspec(align())'
647
648      # Promoted warnings.
649      -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
650
651      # Promoted warnings to errors.
652      -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
653      )
654  endif(NOT CLANG_CL)
655
656  # Enable warnings
657  if (LLVM_ENABLE_WARNINGS)
658    # Put /W4 in front of all the -we flags. cl.exe doesn't care, but for
659    # clang-cl having /W4 after the -we flags will re-enable the warnings
660    # disabled by -we.
661    set(msvc_warning_flags "/W4 ${msvc_warning_flags}")
662    # CMake appends /W3 by default, and having /W3 followed by /W4 will result in
663    # cl : Command line warning D9025 : overriding '/W3' with '/W4'.  Since this is
664    # a command line warning and not a compiler warning, it cannot be suppressed except
665    # by fixing the command line.
666    string(REGEX REPLACE " /W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
667    string(REGEX REPLACE " /W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
668
669    if (LLVM_ENABLE_PEDANTIC)
670      # No MSVC equivalent available
671    endif (LLVM_ENABLE_PEDANTIC)
672  endif (LLVM_ENABLE_WARNINGS)
673
674  foreach(flag ${msvc_warning_flags})
675    append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
676  endforeach(flag)
677endif (MSVC)
678
679if (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
680
681  # Don't add -Wall for clang-cl, because it maps -Wall to -Weverything for
682  # MSVC compatibility.  /W4 is added above instead.
683  if (NOT CLANG_CL)
684    append("-Wall" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
685  endif()
686
687  append("-Wextra -Wno-unused-parameter -Wwrite-strings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
688  append("-Wcast-qual" CMAKE_CXX_FLAGS)
689
690  # Turn off missing field initializer warnings for gcc to avoid noise from
691  # false positives with empty {}. Turn them on otherwise (they're off by
692  # default for clang).
693  check_cxx_compiler_flag("-Wmissing-field-initializers" CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
694  if (CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
695    if (CMAKE_COMPILER_IS_GNUCXX)
696      append("-Wno-missing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
697    else()
698      append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
699    endif()
700  endif()
701
702  if (LLVM_ENABLE_PEDANTIC AND LLVM_COMPILER_IS_GCC_COMPATIBLE)
703    append("-pedantic" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
704    append("-Wno-long-long" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
705
706    # GCC warns about redundant toplevel semicolons (enabled by -pedantic
707    # above), while Clang doesn't. Enable the corresponding Clang option to
708    # pick up on these even in builds with Clang.
709    add_flag_if_supported("-Wc++98-compat-extra-semi" CXX98_COMPAT_EXTRA_SEMI_FLAG)
710  endif()
711
712  add_flag_if_supported("-Wimplicit-fallthrough" IMPLICIT_FALLTHROUGH_FLAG)
713  add_flag_if_supported("-Wcovered-switch-default" COVERED_SWITCH_DEFAULT_FLAG)
714  append_if(USE_NO_UNINITIALIZED "-Wno-uninitialized" CMAKE_CXX_FLAGS)
715  append_if(USE_NO_MAYBE_UNINITIALIZED "-Wno-maybe-uninitialized" CMAKE_CXX_FLAGS)
716
717  # Disable -Wclass-memaccess, a C++-only warning from GCC 8 that fires on
718  # LLVM's ADT classes.
719  check_cxx_compiler_flag("-Wclass-memaccess" CXX_SUPPORTS_CLASS_MEMACCESS_FLAG)
720  append_if(CXX_SUPPORTS_CLASS_MEMACCESS_FLAG "-Wno-class-memaccess" CMAKE_CXX_FLAGS)
721
722  # Disable -Wredundant-move and -Wpessimizing-move on GCC>=9. GCC wants to
723  # remove std::move in code like "A foo(ConvertibleToA a) {
724  # return std::move(a); }", but this code does not compile (or uses the copy
725  # constructor instead) on clang<=3.8. Clang also has a -Wredundant-move and
726  # -Wpessimizing-move, but they only fire when the types match exactly, so we
727  # can keep them here.
728  if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
729    check_cxx_compiler_flag("-Wredundant-move" CXX_SUPPORTS_REDUNDANT_MOVE_FLAG)
730    append_if(CXX_SUPPORTS_REDUNDANT_MOVE_FLAG "-Wno-redundant-move" CMAKE_CXX_FLAGS)
731    check_cxx_compiler_flag("-Wpessimizing-move" CXX_SUPPORTS_PESSIMIZING_MOVE_FLAG)
732    append_if(CXX_SUPPORTS_PESSIMIZING_MOVE_FLAG "-Wno-pessimizing-move" CMAKE_CXX_FLAGS)
733  endif()
734
735  # The LLVM libraries have no stable C++ API, so -Wnoexcept-type is not useful.
736  check_cxx_compiler_flag("-Wnoexcept-type" CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG)
737  append_if(CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG "-Wno-noexcept-type" CMAKE_CXX_FLAGS)
738
739  # Check if -Wnon-virtual-dtor warns even though the class is marked final.
740  # If it does, don't add it. So it won't be added on clang 3.4 and older.
741  # This also catches cases when -Wnon-virtual-dtor isn't supported by
742  # the compiler at all.  This flag is not activated for gcc since it will
743  # incorrectly identify a protected non-virtual base when there is a friend
744  # declaration. Don't activate this in general on Windows as this warning has
745  # too many false positives on COM-style classes, which are destroyed with
746  # Release() (PR32286).
747  if (NOT CMAKE_COMPILER_IS_GNUCXX AND NOT WIN32)
748    set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
749    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11 -Werror=non-virtual-dtor")
750    CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();protected: ~base();};
751                               class derived final : public base { public: ~derived();};
752                               int main() { return 0; }"
753                              CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR)
754    set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
755    append_if(CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR
756              "-Wnon-virtual-dtor" CMAKE_CXX_FLAGS)
757  endif()
758
759  # Enable -Wdelete-non-virtual-dtor if available.
760  add_flag_if_supported("-Wdelete-non-virtual-dtor" DELETE_NON_VIRTUAL_DTOR_FLAG)
761
762  # Enable -Wsuggest-override if it's available, and only if it doesn't
763  # suggest adding 'override' to functions that are already marked 'final'
764  # (which means it is disabled for GCC < 9.2).
765  check_cxx_compiler_flag("-Wsuggest-override" CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG)
766  if (CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG)
767    set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
768    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror=suggest-override")
769    CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();};
770                               class derived : base {public: void anchor() final;};
771                               int main() { return 0; }"
772                              CXX_WSUGGEST_OVERRIDE_ALLOWS_ONLY_FINAL)
773    set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
774    append_if(CXX_WSUGGEST_OVERRIDE_ALLOWS_ONLY_FINAL "-Wsuggest-override" CMAKE_CXX_FLAGS)
775  endif()
776
777  # Check if -Wcomment is OK with an // comment ending with '\' if the next
778  # line is also a // comment.
779  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
780  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror -Wcomment")
781  CHECK_C_SOURCE_COMPILES("// \\\\\\n//\\nint main() {return 0;}"
782                          C_WCOMMENT_ALLOWS_LINE_WRAP)
783  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
784  if (NOT C_WCOMMENT_ALLOWS_LINE_WRAP)
785    append("-Wno-comment" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
786  endif()
787
788  # Enable -Wstring-conversion to catch misuse of string literals.
789  add_flag_if_supported("-Wstring-conversion" STRING_CONVERSION_FLAG)
790
791  # Prevent bugs that can happen with llvm's brace style.
792  add_flag_if_supported("-Wmisleading-indentation" MISLEADING_INDENTATION_FLAG)
793endif (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
794
795if (LLVM_COMPILER_IS_GCC_COMPATIBLE AND NOT LLVM_ENABLE_WARNINGS)
796  append("-w" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
797endif()
798
799macro(append_common_sanitizer_flags)
800  if (NOT MSVC)
801    # Append -fno-omit-frame-pointer and turn on debug info to get better
802    # stack traces.
803    add_flag_if_supported("-fno-omit-frame-pointer" FNO_OMIT_FRAME_POINTER)
804    if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND
805        NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")
806      add_flag_if_supported("-gline-tables-only" GLINE_TABLES_ONLY)
807    endif()
808    # Use -O1 even in debug mode, otherwise sanitizers slowdown is too large.
809    if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND LLVM_OPTIMIZE_SANITIZED_BUILDS)
810      add_flag_if_supported("-O1" O1)
811    endif()
812  elseif (CLANG_CL)
813    # Keep frame pointers around.
814    append("/Oy-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
815    # Always ask the linker to produce symbols with asan.
816    append("/Z7" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
817    append("-debug" CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
818  endif()
819endmacro()
820
821# Turn on sanitizers if necessary.
822if(LLVM_USE_SANITIZER)
823  if (LLVM_ON_UNIX)
824    if (LLVM_USE_SANITIZER STREQUAL "Address")
825      append_common_sanitizer_flags()
826      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
827    elseif (LLVM_USE_SANITIZER STREQUAL "HWAddress")
828      append_common_sanitizer_flags()
829      append("-fsanitize=hwaddress" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
830    elseif (LLVM_USE_SANITIZER MATCHES "Memory(WithOrigins)?")
831      append_common_sanitizer_flags()
832      append("-fsanitize=memory" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
833      if(LLVM_USE_SANITIZER STREQUAL "MemoryWithOrigins")
834        append("-fsanitize-memory-track-origins" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
835      endif()
836    elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
837      append_common_sanitizer_flags()
838      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
839    elseif (LLVM_USE_SANITIZER STREQUAL "Thread")
840      append_common_sanitizer_flags()
841      append("-fsanitize=thread" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
842    elseif (LLVM_USE_SANITIZER STREQUAL "DataFlow")
843      append("-fsanitize=dataflow" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
844    elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
845            LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
846      append_common_sanitizer_flags()
847      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
848      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
849    elseif (LLVM_USE_SANITIZER STREQUAL "Leaks")
850      append_common_sanitizer_flags()
851      append("-fsanitize=leak" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
852    else()
853      message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}")
854    endif()
855  elseif(MINGW)
856    if (LLVM_USE_SANITIZER STREQUAL "Address")
857      append_common_sanitizer_flags()
858      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
859    elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
860      append_common_sanitizer_flags()
861      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
862    elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
863            LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
864      append_common_sanitizer_flags()
865      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
866      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
867    else()
868      message(FATAL_ERROR "This sanitizer not yet supported in a MinGW environment: ${LLVM_USE_SANITIZER}")
869    endif()
870  elseif(MSVC)
871    if (LLVM_USE_SANITIZER STREQUAL "Address")
872      append_common_sanitizer_flags()
873      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
874    else()
875      message(FATAL_ERROR "This sanitizer not yet supported in the MSVC environment: ${LLVM_USE_SANITIZER}")
876    endif()
877  else()
878    message(FATAL_ERROR "LLVM_USE_SANITIZER is not supported on this platform.")
879  endif()
880  if (LLVM_USE_SANITIZER MATCHES "(Undefined;)?Address(;Undefined)?")
881    add_flag_if_supported("-fsanitize-address-use-after-scope"
882                          FSANITIZE_USE_AFTER_SCOPE_FLAG)
883  endif()
884  if (LLVM_USE_SANITIZE_COVERAGE)
885    append("-fsanitize=fuzzer-no-link" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
886  endif()
887  if (LLVM_USE_SANITIZER MATCHES ".*Undefined.*")
888    set(BLACKLIST_FILE "${CMAKE_SOURCE_DIR}/utils/sanitizers/ubsan_blacklist.txt")
889    if (EXISTS "${BLACKLIST_FILE}")
890      append("-fsanitize-blacklist=${BLACKLIST_FILE}"
891             CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
892    endif()
893  endif()
894endif()
895
896# Turn on -gsplit-dwarf if requested in debug builds.
897if (LLVM_USE_SPLIT_DWARF AND
898    ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
899     (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
900  # Limit to clang and gcc so far. Add compilers supporting this option.
901  if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
902      CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
903    add_compile_options(-gsplit-dwarf)
904  endif()
905endif()
906
907add_definitions( -D__STDC_CONSTANT_MACROS )
908add_definitions( -D__STDC_FORMAT_MACROS )
909add_definitions( -D__STDC_LIMIT_MACROS )
910
911# clang and gcc don't default-print colored diagnostics when invoked from Ninja.
912if (UNIX AND
913    CMAKE_GENERATOR STREQUAL "Ninja" AND
914    (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
915     (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
916      NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9))))
917  append("-fdiagnostics-color" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
918endif()
919
920# lld doesn't print colored diagnostics when invoked from Ninja
921if (UNIX AND CMAKE_GENERATOR STREQUAL "Ninja")
922  include(LLVMCheckLinkerFlag)
923  llvm_check_linker_flag(CXX "-Wl,--color-diagnostics" LINKER_SUPPORTS_COLOR_DIAGNOSTICS)
924  append_if(LINKER_SUPPORTS_COLOR_DIAGNOSTICS "-Wl,--color-diagnostics"
925    CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
926endif()
927
928# Add flags for add_dead_strip().
929# FIXME: With MSVS, consider compiling with /Gy and linking with /OPT:REF?
930# But MinSizeRel seems to add that automatically, so maybe disable these
931# flags instead if LLVM_NO_DEAD_STRIP is set.
932if(NOT CYGWIN AND NOT MSVC)
933  if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND
934     NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
935    check_c_compiler_flag("-Werror -fno-function-sections" C_SUPPORTS_FNO_FUNCTION_SECTIONS)
936    if (C_SUPPORTS_FNO_FUNCTION_SECTIONS)
937      # Don't add -ffunction-sections if it can't be disabled with -fno-function-sections.
938      # Doing so will break sanitizers.
939      add_flag_if_supported("-ffunction-sections" FFUNCTION_SECTIONS)
940    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
941      append("-qfuncsect" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
942    endif()
943    add_flag_if_supported("-fdata-sections" FDATA_SECTIONS)
944  endif()
945elseif(MSVC)
946  if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
947    append("/Gw" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
948  endif()
949endif()
950
951if(MSVC)
952  # Remove flags here, for exceptions and RTTI.
953  # Each target property or source property should be responsible to control
954  # them.
955  # CL.EXE complains to override flags like "/GR /GR-".
956  string(REGEX REPLACE "(^| ) */EH[-cs]+ *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
957  string(REGEX REPLACE "(^| ) */GR-? *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
958endif()
959
960# Provide public options to globally control RTTI and EH
961option(LLVM_ENABLE_EH "Enable Exception handling" OFF)
962option(LLVM_ENABLE_RTTI "Enable run time type information" OFF)
963if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI)
964  message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON")
965endif()
966
967option(LLVM_USE_NEWPM "Build LLVM using the experimental new pass manager" Off)
968mark_as_advanced(LLVM_USE_NEWPM)
969if (LLVM_USE_NEWPM)
970  append("-fexperimental-new-pass-manager"
971    CMAKE_CXX_FLAGS
972    CMAKE_C_FLAGS
973    CMAKE_EXE_LINKER_FLAGS
974    CMAKE_SHARED_LINKER_FLAGS)
975endif()
976
977option(LLVM_ENABLE_IR_PGO "Build LLVM and tools with IR PGO instrumentation (deprecated)" Off)
978mark_as_advanced(LLVM_ENABLE_IR_PGO)
979
980set(LLVM_BUILD_INSTRUMENTED OFF CACHE STRING "Build LLVM and tools with PGO instrumentation. May be specified as IR or Frontend")
981set(LLVM_VP_COUNTERS_PER_SITE "1.5" CACHE STRING "Value profile counters to use per site for IR PGO with Clang")
982mark_as_advanced(LLVM_BUILD_INSTRUMENTED LLVM_VP_COUNTERS_PER_SITE)
983string(TOUPPER "${LLVM_BUILD_INSTRUMENTED}" uppercase_LLVM_BUILD_INSTRUMENTED)
984
985if (LLVM_BUILD_INSTRUMENTED)
986  if (LLVM_ENABLE_IR_PGO OR uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "IR")
987    append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
988      CMAKE_CXX_FLAGS
989      CMAKE_C_FLAGS)
990    if(NOT LINKER_IS_LLD_LINK)
991        append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
992          CMAKE_EXE_LINKER_FLAGS
993          CMAKE_SHARED_LINKER_FLAGS)
994    endif()
995    # Set this to avoid running out of the value profile node section
996    # under clang in dynamic linking mode.
997    if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND
998        CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 11 AND
999        LLVM_LINK_LLVM_DYLIB)
1000      append("-Xclang -mllvm -Xclang -vp-counters-per-site=${LLVM_VP_COUNTERS_PER_SITE}"
1001        CMAKE_CXX_FLAGS
1002        CMAKE_C_FLAGS)
1003    endif()
1004  elseif(uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "CSIR")
1005    append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
1006      CMAKE_CXX_FLAGS
1007      CMAKE_C_FLAGS)
1008    if(NOT LINKER_IS_LLD_LINK)
1009      append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
1010        CMAKE_EXE_LINKER_FLAGS
1011        CMAKE_SHARED_LINKER_FLAGS)
1012    endif()
1013  else()
1014    append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
1015      CMAKE_CXX_FLAGS
1016      CMAKE_C_FLAGS)
1017    if(NOT LINKER_IS_LLD_LINK)
1018      append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
1019        CMAKE_EXE_LINKER_FLAGS
1020        CMAKE_SHARED_LINKER_FLAGS)
1021    endif()
1022  endif()
1023endif()
1024
1025# When using clang-cl with an instrumentation-based tool, add clang's library
1026# resource directory to the library search path. Because cmake invokes the
1027# linker directly, it isn't sufficient to pass -fsanitize=* to the linker.
1028if (CLANG_CL AND (LLVM_BUILD_INSTRUMENTED OR LLVM_USE_SANITIZER))
1029  execute_process(
1030    COMMAND ${CMAKE_CXX_COMPILER} /clang:-print-libgcc-file-name /clang:--rtlib=compiler-rt
1031    OUTPUT_VARIABLE clang_compiler_rt_file
1032    ERROR_VARIABLE clang_cl_stderr
1033    OUTPUT_STRIP_TRAILING_WHITESPACE
1034    ERROR_STRIP_TRAILING_WHITESPACE
1035    RESULT_VARIABLE clang_cl_exit_code)
1036  if (NOT "${clang_cl_exit_code}" STREQUAL "0")
1037    message(FATAL_ERROR
1038      "Unable to invoke clang-cl to find resource dir: ${clang_cl_stderr}")
1039  endif()
1040  file(TO_CMAKE_PATH "${clang_compiler_rt_file}" clang_compiler_rt_file)
1041  get_filename_component(clang_runtime_dir "${clang_compiler_rt_file}" DIRECTORY)
1042  append("/libpath:${clang_runtime_dir}"
1043    CMAKE_EXE_LINKER_FLAGS
1044    CMAKE_MODULE_LINKER_FLAGS
1045    CMAKE_SHARED_LINKER_FLAGS)
1046endif()
1047
1048if(LLVM_PROFDATA_FILE AND EXISTS ${LLVM_PROFDATA_FILE})
1049  if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
1050    append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
1051      CMAKE_CXX_FLAGS
1052      CMAKE_C_FLAGS)
1053    if(NOT LINKER_IS_LLD_LINK)
1054      append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
1055        CMAKE_EXE_LINKER_FLAGS
1056        CMAKE_SHARED_LINKER_FLAGS)
1057    endif()
1058  else()
1059    message(FATAL_ERROR "LLVM_PROFDATA_FILE can only be specified when compiling with clang")
1060  endif()
1061endif()
1062
1063option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation" Off)
1064mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE)
1065append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\" -fcoverage-mapping"
1066  CMAKE_CXX_FLAGS
1067  CMAKE_C_FLAGS
1068  CMAKE_EXE_LINKER_FLAGS
1069  CMAKE_SHARED_LINKER_FLAGS)
1070
1071if (LLVM_BUILD_INSTRUMENTED AND LLVM_BUILD_INSTRUMENTED_COVERAGE)
1072  message(FATAL_ERROR "LLVM_BUILD_INSTRUMENTED and LLVM_BUILD_INSTRUMENTED_COVERAGE cannot both be specified")
1073endif()
1074
1075if(LLVM_ENABLE_LTO AND LLVM_ON_WIN32 AND NOT LINKER_IS_LLD_LINK AND NOT MINGW)
1076  message(FATAL_ERROR "When compiling for Windows, LLVM_ENABLE_LTO requires using lld as the linker (point CMAKE_LINKER at lld-link.exe)")
1077endif()
1078if(uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
1079  append("-flto=thin" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1080  if(NOT LINKER_IS_LLD_LINK)
1081    append("-flto=thin" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1082  endif()
1083  # If the linker supports it, enable the lto cache. This improves initial build
1084  # time a little since we re-link a lot of the same objects, and significantly
1085  # improves incremental build time.
1086  # FIXME: We should move all this logic into the clang driver.
1087  if(APPLE)
1088    append("-Wl,-cache_path_lto,${PROJECT_BINARY_DIR}/lto.cache"
1089           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1090  elseif((UNIX OR MINGW) AND LLVM_USE_LINKER STREQUAL "lld")
1091    append("-Wl,--thinlto-cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
1092           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1093  elseif(LLVM_USE_LINKER STREQUAL "gold")
1094    append("-Wl,--plugin-opt,cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
1095           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1096  elseif(LINKER_IS_LLD_LINK)
1097    append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
1098           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1099  endif()
1100elseif(uppercase_LLVM_ENABLE_LTO STREQUAL "FULL")
1101  append("-flto=full" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1102  if(NOT LINKER_IS_LLD_LINK)
1103    append("-flto=full" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1104  endif()
1105elseif(LLVM_ENABLE_LTO)
1106  append("-flto" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1107  if(NOT LINKER_IS_LLD_LINK)
1108    append("-flto" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1109  endif()
1110endif()
1111
1112# Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we are
1113# doing dynamic linking (see below).
1114set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)
1115if (NOT (BUILD_SHARED_LIBS OR LLVM_LINK_LLVM_DYLIB))
1116  set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default ON)
1117endif()
1118
1119# This option makes utils/extract_symbols.py be used to determine the list of
1120# symbols to export from LLVM tools. This is necessary when on AIX or when using
1121# MSVC if you want to allow plugins. On AIX we don't show this option, and we
1122# enable it by default except when the LLVM libraries are set up for dynamic
1123# linking (due to incompatibility). With MSVC, note that the plugin has to
1124# explicitly link against (exactly one) tool so we can't unilaterally turn on
1125# LLVM_ENABLE_PLUGINS when it's enabled.
1126CMAKE_DEPENDENT_OPTION(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS
1127       "Export symbols from LLVM tools so that plugins can import them" OFF
1128       "NOT ${CMAKE_SYSTEM_NAME} MATCHES AIX" ${LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default})
1129if(BUILD_SHARED_LIBS AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1130  message(FATAL_ERROR "BUILD_SHARED_LIBS not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1131endif()
1132if(LLVM_LINK_LLVM_DYLIB AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1133  message(FATAL_ERROR "LLVM_LINK_LLVM_DYLIB not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1134endif()
1135
1136# By default we should enable LLVM_ENABLE_IDE only for multi-configuration
1137# generators. This option disables optional build system features that make IDEs
1138# less usable.
1139set(LLVM_ENABLE_IDE_default OFF)
1140if (CMAKE_CONFIGURATION_TYPES)
1141  set(LLVM_ENABLE_IDE_default ON)
1142endif()
1143option(LLVM_ENABLE_IDE
1144       "Disable optional build system features that cause problems for IDE generators"
1145       ${LLVM_ENABLE_IDE_default})
1146if (CMAKE_CONFIGURATION_TYPES AND NOT LLVM_ENABLE_IDE)
1147  message(WARNING "Disabling LLVM_ENABLE_IDE on multi-configuration generators is not recommended.")
1148endif()
1149
1150function(get_compile_definitions)
1151  get_directory_property(top_dir_definitions DIRECTORY ${CMAKE_SOURCE_DIR} COMPILE_DEFINITIONS)
1152  foreach(definition ${top_dir_definitions})
1153    if(DEFINED result)
1154      string(APPEND result " -D${definition}")
1155    else()
1156      set(result "-D${definition}")
1157    endif()
1158  endforeach()
1159  set(LLVM_DEFINITIONS "${result}" PARENT_SCOPE)
1160endfunction()
1161get_compile_definitions()
1162
1163option(LLVM_FORCE_ENABLE_STATS "Enable statistics collection for builds that wouldn't normally enable it" OFF)
1164
1165check_symbol_exists(os_signpost_interval_begin "os/signpost.h" macos_signposts_available)
1166if(macos_signposts_available)
1167  check_cxx_source_compiles(
1168    "#include <os/signpost.h>
1169    int main() { os_signpost_interval_begin(nullptr, 0, \"\", \"\"); return 0; }"
1170    macos_signposts_usable)
1171  if(macos_signposts_usable)
1172    set(LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS "WITH_ASSERTS" CACHE STRING
1173        "Enable support for Xcode signposts. Can be WITH_ASSERTS, FORCE_ON, FORCE_OFF")
1174    string(TOUPPER "${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}"
1175                   uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS)
1176    if( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "WITH_ASSERTS" )
1177      if( LLVM_ENABLE_ASSERTIONS )
1178        set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
1179      endif()
1180    elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_ON" )
1181      set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
1182    elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_OFF" )
1183      # We don't need to do anything special to turn off signposts.
1184    elseif( NOT DEFINED LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS )
1185      # Treat LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS like "FORCE_OFF" when it has not been
1186      # defined.
1187    else()
1188      message(FATAL_ERROR "Unknown value for LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS:"
1189                          " \"${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}\"!")
1190    endif()
1191  endif()
1192endif()
1193
1194set(LLVM_SOURCE_PREFIX "" CACHE STRING "Use prefix for sources")
1195
1196option(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO "Use relative paths in debug info" OFF)
1197
1198if(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO)
1199  check_c_compiler_flag("-fdebug-prefix-map=foo=bar" SUPPORTS_FDEBUG_PREFIX_MAP)
1200  if(LLVM_ENABLE_PROJECTS_USED)
1201    get_filename_component(source_root "${LLVM_MAIN_SRC_DIR}/.." ABSOLUTE)
1202  else()
1203    set(source_root "${LLVM_MAIN_SRC_DIR}")
1204  endif()
1205  file(RELATIVE_PATH relative_root "${source_root}" "${CMAKE_BINARY_DIR}")
1206  append_if(SUPPORTS_FDEBUG_PREFIX_MAP "-fdebug-prefix-map=${CMAKE_BINARY_DIR}=${relative_root}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1207  append_if(SUPPORTS_FDEBUG_PREFIX_MAP "-fdebug-prefix-map=${source_root}/=${LLVM_SOURCE_PREFIX}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1208  add_flag_if_supported("-no-canonical-prefixes" NO_CANONICAL_PREFIXES)
1209endif()
1210
1211option(LLVM_USE_RELATIVE_PATHS_IN_FILES "Use relative paths in sources and debug info" OFF)
1212
1213if(LLVM_USE_RELATIVE_PATHS_IN_FILES)
1214  check_c_compiler_flag("-ffile-prefix-map=foo=bar" SUPPORTS_FFILE_PREFIX_MAP)
1215  if(LLVM_ENABLE_PROJECTS_USED)
1216    get_filename_component(source_root "${LLVM_MAIN_SRC_DIR}/.." ABSOLUTE)
1217  else()
1218    set(source_root "${LLVM_MAIN_SRC_DIR}")
1219  endif()
1220  file(RELATIVE_PATH relative_root "${source_root}" "${CMAKE_BINARY_DIR}")
1221  append_if(SUPPORTS_FFILE_PREFIX_MAP "-ffile-prefix-map=${CMAKE_BINARY_DIR}=${relative_root}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1222  append_if(SUPPORTS_FFILE_PREFIX_MAP "-ffile-prefix-map=${source_root}/=${LLVM_SOURCE_PREFIX}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1223  add_flag_if_supported("-no-canonical-prefixes" NO_CANONICAL_PREFIXES)
1224endif()
1225
1226if(LLVM_INCLUDE_TESTS)
1227  # Lit test suite requires at least python 3.6
1228  set(LLVM_MINIMUM_PYTHON_VERSION 3.6)
1229else()
1230  # FIXME: it is unknown if this is the actual minimum bound
1231  set(LLVM_MINIMUM_PYTHON_VERSION 3.0)
1232endif()
1233