1 # This CMake module is responsible for interpreting the user defined LLVM_
2 # options and executing the appropriate CMake commands to realize the users'
5 # This is commonly needed so make sure it's defined before we include anything
7 string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE)
9 include(CheckCompilerVersion)
10 include(HandleLLVMStdlib)
11 include(CheckCCompilerFlag)
12 include(CheckCXXCompilerFlag)
13 include(CheckSymbolExists)
14 include(CMakeDependentOption)
15 include(LLVMProcessSources)
17 if(CMAKE_LINKER MATCHES ".*lld" OR (LLVM_USE_LINKER STREQUAL "lld" OR LLVM_ENABLE_LLD))
18 set(LINKER_IS_LLD TRUE)
20 set(LINKER_IS_LLD FALSE)
23 if(CMAKE_LINKER MATCHES "lld-link" OR (MSVC AND (LLVM_USE_LINKER STREQUAL "lld" OR LLVM_ENABLE_LLD)))
24 set(LINKER_IS_LLD_LINK TRUE)
26 set(LINKER_IS_LLD_LINK FALSE)
29 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")
30 string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
32 # Ninja Job Pool support
33 # The following only works with the Ninja generator in CMake >= 3.0.
34 set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
35 "Define the maximum number of concurrent compilation jobs (Ninja only).")
36 if(LLVM_PARALLEL_COMPILE_JOBS)
37 if(NOT CMAKE_GENERATOR STREQUAL "Ninja")
38 message(WARNING "Job pooling is only available with Ninja generators.")
40 set_property(GLOBAL APPEND PROPERTY JOB_POOLS compile_job_pool=${LLVM_PARALLEL_COMPILE_JOBS})
41 set(CMAKE_JOB_POOL_COMPILE compile_job_pool)
45 set(LLVM_PARALLEL_LINK_JOBS "" CACHE STRING
46 "Define the maximum number of concurrent link jobs (Ninja only).")
47 if(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")
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)
56 elseif(LLVM_PARALLEL_LINK_JOBS)
57 message(WARNING "Job pooling is only available with Ninja generators.")
60 if( LLVM_ENABLE_ASSERTIONS )
61 # MSVC doesn't like _DEBUG on release builds. See PR 4379.
63 add_definitions( -D_DEBUG )
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>)
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
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}}")
87 if(LLVM_ENABLE_EXPENSIVE_CHECKS)
88 add_definitions(-DEXPENSIVE_CHECKS)
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
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]);
99 }" CXX_SUPPORTS_GLIBCXX_DEBUG)
100 if(CXX_SUPPORTS_GLIBCXX_DEBUG)
101 add_definitions(-D_GLIBCXX_DEBUG)
103 add_definitions(-D_GLIBCXX_ASSERTIONS)
107 if (LLVM_ENABLE_STRICT_FIXED_SIZE_VECTORS)
108 add_definitions(-DSTRICT_FIXED_SIZE_VECTORS)
111 string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS)
113 if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" )
114 if( LLVM_ENABLE_ASSERTIONS )
115 set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
117 elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_ON" )
118 set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
119 elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_OFF" )
120 # We don't need to do anything special to turn off ABI breaking checks.
121 elseif( NOT DEFINED LLVM_ABI_BREAKING_CHECKS )
122 # Treat LLVM_ABI_BREAKING_CHECKS like "FORCE_OFF" when it has not been
125 message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: \"${LLVM_ABI_BREAKING_CHECKS}\"!")
128 if( LLVM_REVERSE_ITERATION )
129 set( LLVM_ENABLE_REVERSE_ITERATION 1 )
133 set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
145 if(APPLE OR ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
146 set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
148 set(LLVM_HAVE_LINK_VERSION_SCRIPT 1)
150 else(FUCHSIA OR UNIX)
151 MESSAGE(SEND_ERROR "Unable to determine platform")
152 endif(FUCHSIA OR UNIX)
155 if (CMAKE_SYSTEM_NAME MATCHES "OS390")
156 set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
159 set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX})
160 set(LTDL_SHLIB_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
162 # We use *.dylib rather than *.so on darwin, but we stick with *.so on AIX.
163 if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
164 set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_MODULE_SUFFIX})
166 set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
170 if(LLVM_ENABLE_LLD AND LLVM_ENABLE_LTO)
171 message(FATAL_ERROR "lld does not support LTO on Darwin")
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")
177 if(${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
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
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>")
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>")
203 file(REMOVE ${CMAKE_BINARY_DIR}/t.a)
207 if(${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)
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.")
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.
231 if(NOT (CMAKE_SYSTEM_NAME MATCHES "Darwin|FreeBSD|OpenBSD|DragonFly|AIX|SunOS|OS390" OR
233 NOT LLVM_USE_SANITIZER)
234 set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
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
241 if(${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")
247 function(append value)
248 foreach(variable ${ARGN})
249 set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
253 function(append_if condition value)
255 foreach(variable ${ARGN})
256 set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
261 macro(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)
268 function(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)
277 message(WARNING "${flag} is not supported.")
281 if( 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")
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
289 set(LLVM_USE_LINKER "lld")
293 if( 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}'")
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)
305 if( LLVM_ENABLE_PIC )
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.
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.
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)
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)
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")
344 if(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)
351 if(CMAKE_SIZEOF_VOID_P EQUAL 8 AND MINGW)
352 add_definitions( -D_FILE_OFFSET_BITS=64 )
355 if( 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")
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 )
369 endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
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.
374 if (ANDROID AND (ANDROID_NATIVE_API_LEVEL LESS 24))
375 set(LLVM_FORCE_SMALLFILE_FOR_ANDROID TRUE)
377 if( 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 )
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
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")
406 # On Win32 using MS tools, provide an option to set the number of parallel jobs
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 )
415 message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS})
416 add_definitions( /MP${LLVM_COMPILER_JOBS} )
419 message(STATUS "Parallel compilation disabled")
423 # set stack reserved size to ~10MB
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")
430 elseif(MINGW) # FIXME: Also cygwin?
431 set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216")
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)
439 option(LLVM_ENABLE_WARNINGS "Enable compiler warnings." ON)
442 include(ChooseMSVCCRT)
444 # Add definitions that make MSVC much less annoying.
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
455 # Tell MSVC to use the Unicode version of the Win32 APIs instead of ANSI.
461 # Allow setting clang-cl's /winsysroot flag.
462 set(LLVM_WINSYSROOT "" CACHE STRING
463 "If set, argument to clang-cl's /winsysroot")
466 message(ERROR "LLVM_WINSYSROOT requires clang-cl")
468 append("/winsysroot${LLVM_WINSYSROOT}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
471 if (LLVM_ENABLE_WERROR)
472 append("/WX" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
473 endif (LLVM_ENABLE_WERROR)
475 append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
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)
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)
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)
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
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)
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)
518 # "Generate Intrinsic Functions".
519 append("/Oi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
521 # "Enforce type conversion rules".
522 append("/Zc:rvalueCast" CMAKE_CXX_FLAGS)
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)
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")
542 append("/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
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)
552 # Warnings-as-errors handling for GCC-compatible compilers:
553 if ( 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)
556 endif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
558 # Specific default warnings-as-errors for compilers accepting GCC-compatible warning flags:
559 if ( 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)
562 endif( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
564 # Modules enablement for GCC-compatible compilers:
565 if ( 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")
572 if (LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY)
573 set(module_flags "${module_flags} -Xclang -fmodules-local-submodule-visibility")
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")
580 set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${module_flags}")
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
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)
594 message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
596 endif( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
600 set(msvc_warning_flags
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
640 -wd4709 # Suppress comma operator within array index expression
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())'
649 -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
651 # Promoted warnings to errors.
652 -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
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
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}")
669 if (LLVM_ENABLE_PEDANTIC)
670 # No MSVC equivalent available
671 endif (LLVM_ENABLE_PEDANTIC)
672 endif (LLVM_ENABLE_WARNINGS)
674 foreach(flag ${msvc_warning_flags})
675 append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
679 if (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
681 # Don't add -Wall for clang-cl, because it maps -Wall to -Weverything for
682 # MSVC compatibility. /W4 is added above instead.
684 append("-Wall" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
687 append("-Wextra -Wno-unused-parameter -Wwrite-strings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
688 append("-Wcast-qual" CMAKE_CXX_FLAGS)
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)
698 append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
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)
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)
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)
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)
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)
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)
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)
759 # Enable -Wdelete-non-virtual-dtor if available.
760 add_flag_if_supported("-Wdelete-non-virtual-dtor" DELETE_NON_VIRTUAL_DTOR_FLAG)
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)
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)
788 # Enable -Wstring-conversion to catch misuse of string literals.
789 add_flag_if_supported("-Wstring-conversion" STRING_CONVERSION_FLAG)
791 # Prevent bugs that can happen with llvm's brace style.
792 add_flag_if_supported("-Wmisleading-indentation" MISLEADING_INDENTATION_FLAG)
793 endif (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
795 if (LLVM_COMPILER_IS_GCC_COMPATIBLE AND NOT LLVM_ENABLE_WARNINGS)
796 append("-w" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
799 macro(append_common_sanitizer_flags)
801 # Append -fno-omit-frame-pointer and turn on debug info to get better
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)
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)
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)
821 # Turn on sanitizers if necessary.
822 if(LLVM_USE_SANITIZER)
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)
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)
853 message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}")
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)
868 message(FATAL_ERROR "This sanitizer not yet supported in a MinGW environment: ${LLVM_USE_SANITIZER}")
871 if (LLVM_USE_SANITIZER STREQUAL "Address")
872 append_common_sanitizer_flags()
873 append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
875 message(FATAL_ERROR "This sanitizer not yet supported in the MSVC environment: ${LLVM_USE_SANITIZER}")
878 message(FATAL_ERROR "LLVM_USE_SANITIZER is not supported on this platform.")
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)
884 if (LLVM_USE_SANITIZE_COVERAGE)
885 append("-fsanitize=fuzzer-no-link" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
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)
896 # Turn on -gsplit-dwarf if requested in debug builds.
897 if (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)
907 add_definitions( -D__STDC_CONSTANT_MACROS )
908 add_definitions( -D__STDC_FORMAT_MACROS )
909 add_definitions( -D__STDC_LIMIT_MACROS )
911 # clang and gcc don't default-print colored diagnostics when invoked from Ninja.
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)
920 # lld doesn't print colored diagnostics when invoked from Ninja
921 if (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)
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.
932 if(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)
943 add_flag_if_supported("-fdata-sections" FDATA_SECTIONS)
946 if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
947 append("/Gw" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
952 # Remove flags here, for exceptions and RTTI.
953 # Each target property or source property should be responsible to control
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}")
960 # Provide public options to globally control RTTI and EH
961 option(LLVM_ENABLE_EH "Enable Exception handling" OFF)
962 option(LLVM_ENABLE_RTTI "Enable run time type information" OFF)
963 if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI)
964 message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON")
967 option(LLVM_USE_NEWPM "Build LLVM using the experimental new pass manager" Off)
968 mark_as_advanced(LLVM_USE_NEWPM)
970 append("-fexperimental-new-pass-manager"
973 CMAKE_EXE_LINKER_FLAGS
974 CMAKE_SHARED_LINKER_FLAGS)
977 option(LLVM_ENABLE_IR_PGO "Build LLVM and tools with IR PGO instrumentation (deprecated)" Off)
978 mark_as_advanced(LLVM_ENABLE_IR_PGO)
980 set(LLVM_BUILD_INSTRUMENTED OFF CACHE STRING "Build LLVM and tools with PGO instrumentation. May be specified as IR or Frontend")
981 set(LLVM_VP_COUNTERS_PER_SITE "1.5" CACHE STRING "Value profile counters to use per site for IR PGO with Clang")
982 mark_as_advanced(LLVM_BUILD_INSTRUMENTED LLVM_VP_COUNTERS_PER_SITE)
983 string(TOUPPER "${LLVM_BUILD_INSTRUMENTED}" uppercase_LLVM_BUILD_INSTRUMENTED)
985 if (LLVM_BUILD_INSTRUMENTED)
986 if (LLVM_ENABLE_IR_PGO OR uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "IR")
987 append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
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)
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}"
1004 elseif(uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "CSIR")
1005 append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
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)
1014 append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
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)
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.
1028 if (CLANG_CL AND (LLVM_BUILD_INSTRUMENTED OR LLVM_USE_SANITIZER))
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")
1038 "Unable to invoke clang-cl to find resource dir: ${clang_cl_stderr}")
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)
1048 if(LLVM_PROFDATA_FILE AND EXISTS ${LLVM_PROFDATA_FILE})
1049 if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
1050 append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
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)
1059 message(FATAL_ERROR "LLVM_PROFDATA_FILE can only be specified when compiling with clang")
1063 option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation" Off)
1064 mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE)
1065 append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\" -fcoverage-mapping"
1068 CMAKE_EXE_LINKER_FLAGS
1069 CMAKE_SHARED_LINKER_FLAGS)
1071 if (LLVM_BUILD_INSTRUMENTED AND LLVM_BUILD_INSTRUMENTED_COVERAGE)
1072 message(FATAL_ERROR "LLVM_BUILD_INSTRUMENTED and LLVM_BUILD_INSTRUMENTED_COVERAGE cannot both be specified")
1075 if(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)")
1078 if(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)
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.
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)
1100 elseif(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)
1105 elseif(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)
1112 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we are
1113 # doing dynamic linking (see below).
1114 set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)
1115 if (NOT (BUILD_SHARED_LIBS OR LLVM_LINK_LLVM_DYLIB))
1116 set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default ON)
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.
1126 CMAKE_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})
1129 if(BUILD_SHARED_LIBS AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1130 message(FATAL_ERROR "BUILD_SHARED_LIBS not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1132 if(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")
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
1139 set(LLVM_ENABLE_IDE_default OFF)
1140 if (CMAKE_CONFIGURATION_TYPES)
1141 set(LLVM_ENABLE_IDE_default ON)
1143 option(LLVM_ENABLE_IDE
1144 "Disable optional build system features that cause problems for IDE generators"
1145 ${LLVM_ENABLE_IDE_default})
1146 if (CMAKE_CONFIGURATION_TYPES AND NOT LLVM_ENABLE_IDE)
1147 message(WARNING "Disabling LLVM_ENABLE_IDE on multi-configuration generators is not recommended.")
1150 function(get_compile_definitions)
1151 get_directory_property(top_dir_definitions DIRECTORY ${CMAKE_SOURCE_DIR} COMPILE_DEFINITIONS)
1152 foreach(definition ${top_dir_definitions})
1154 string(APPEND result " -D${definition}")
1156 set(result "-D${definition}")
1159 set(LLVM_DEFINITIONS "${result}" PARENT_SCOPE)
1161 get_compile_definitions()
1163 option(LLVM_FORCE_ENABLE_STATS "Enable statistics collection for builds that wouldn't normally enable it" OFF)
1165 check_symbol_exists(os_signpost_interval_begin "os/signpost.h" macos_signposts_available)
1166 if(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 )
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
1188 message(FATAL_ERROR "Unknown value for LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS:"
1189 " \"${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}\"!")
1194 set(LLVM_SOURCE_PREFIX "" CACHE STRING "Use prefix for sources")
1196 option(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO "Use relative paths in debug info" OFF)
1198 if(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)
1203 set(source_root "${LLVM_MAIN_SRC_DIR}")
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)
1211 option(LLVM_USE_RELATIVE_PATHS_IN_FILES "Use relative paths in sources and debug info" OFF)
1213 if(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)
1218 set(source_root "${LLVM_MAIN_SRC_DIR}")
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)
1226 if(LLVM_INCLUDE_TESTS)
1227 # Lit test suite requires at least python 3.6
1228 set(LLVM_MINIMUM_PYTHON_VERSION 3.6)
1230 # FIXME: it is unknown if this is the actual minimum bound
1231 set(LLVM_MINIMUM_PYTHON_VERSION 3.0)