OSDN Git Service

[AIX][CMake] Changes for building on AIX with XL and GCC
[android-x86/external-llvm.git] / cmake / modules / HandleLLVMOptions.cmake
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.
7 string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE)
8
9 include(CheckCompilerVersion)
10 include(HandleLLVMStdlib)
11 include(CheckCCompilerFlag)
12 include(CheckCXXCompilerFlag)
13 include(CheckSymbolExists)
14
15 if(CMAKE_LINKER MATCHES "lld-link\.exe" OR (WIN32 AND LLVM_USE_LINKER STREQUAL "lld") OR LLVM_ENABLE_LLD)
16   set(LINKER_IS_LLD_LINK TRUE)
17 else()
18   set(LINKER_IS_LLD_LINK FALSE)
19 endif()
20
21 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")
22 string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
23
24 # Ninja Job Pool support
25 # The following only works with the Ninja generator in CMake >= 3.0.
26 set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
27   "Define the maximum number of concurrent compilation jobs (Ninja only).")
28 if(LLVM_PARALLEL_COMPILE_JOBS)
29   if(NOT CMAKE_MAKE_PROGRAM MATCHES "ninja")
30     message(WARNING "Job pooling is only available with Ninja generators.")
31   else()
32     set_property(GLOBAL APPEND PROPERTY JOB_POOLS compile_job_pool=${LLVM_PARALLEL_COMPILE_JOBS})
33     set(CMAKE_JOB_POOL_COMPILE compile_job_pool)
34   endif()
35 endif()
36
37 set(LLVM_PARALLEL_LINK_JOBS "" CACHE STRING
38   "Define the maximum number of concurrent link jobs (Ninja only).")
39 if(CMAKE_MAKE_PROGRAM MATCHES "ninja")
40   if(NOT LLVM_PARALLEL_LINK_JOBS AND uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
41     message(STATUS "ThinLTO provides its own parallel linking - limiting parallel link jobs to 2.")
42     set(LLVM_PARALLEL_LINK_JOBS "2")
43   endif()
44   if(LLVM_PARALLEL_LINK_JOBS)
45     set_property(GLOBAL APPEND PROPERTY JOB_POOLS link_job_pool=${LLVM_PARALLEL_LINK_JOBS})
46     set(CMAKE_JOB_POOL_LINK link_job_pool)
47   endif()
48 elseif(LLVM_PARALLEL_LINK_JOBS)
49   message(WARNING "Job pooling is only available with Ninja generators.")
50 endif()
51
52 if( LLVM_ENABLE_ASSERTIONS )
53   # MSVC doesn't like _DEBUG on release builds. See PR 4379.
54   if( NOT MSVC )
55     add_definitions( -D_DEBUG )
56   endif()
57   # On non-Debug builds cmake automatically defines NDEBUG, so we
58   # explicitly undefine it:
59   if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
60     add_definitions( -UNDEBUG )
61     # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines.
62     foreach (flags_var_to_scrub
63         CMAKE_CXX_FLAGS_RELEASE
64         CMAKE_CXX_FLAGS_RELWITHDEBINFO
65         CMAKE_CXX_FLAGS_MINSIZEREL
66         CMAKE_C_FLAGS_RELEASE
67         CMAKE_C_FLAGS_RELWITHDEBINFO
68         CMAKE_C_FLAGS_MINSIZEREL)
69       string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " "
70         "${flags_var_to_scrub}" "${${flags_var_to_scrub}}")
71     endforeach()
72   endif()
73 endif()
74
75 if(LLVM_ENABLE_EXPENSIVE_CHECKS)
76   add_definitions(-DEXPENSIVE_CHECKS)
77   add_definitions(-D_GLIBCXX_DEBUG)
78 endif()
79
80 string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS)
81
82 if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" )
83   if( LLVM_ENABLE_ASSERTIONS )
84     set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
85   endif()
86 elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_ON" )
87   set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
88 elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_OFF" )
89   # We don't need to do anything special to turn off ABI breaking checks.
90 elseif( NOT DEFINED LLVM_ABI_BREAKING_CHECKS )
91   # Treat LLVM_ABI_BREAKING_CHECKS like "FORCE_OFF" when it has not been
92   # defined.
93 else()
94   message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: \"${LLVM_ABI_BREAKING_CHECKS}\"!")
95 endif()
96
97 if( LLVM_REVERSE_ITERATION )
98   set( LLVM_ENABLE_REVERSE_ITERATION 1 )
99 endif()
100
101 if(WIN32)
102   set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
103   if(CYGWIN)
104     set(LLVM_ON_WIN32 0)
105     set(LLVM_ON_UNIX 1)
106   else(CYGWIN)
107     set(LLVM_ON_WIN32 1)
108     set(LLVM_ON_UNIX 0)
109   endif(CYGWIN)
110 else(WIN32)
111   if(FUCHSIA OR UNIX)
112     set(LLVM_ON_WIN32 0)
113     set(LLVM_ON_UNIX 1)
114     if(APPLE OR ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
115       set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
116     else()
117       set(LLVM_HAVE_LINK_VERSION_SCRIPT 1)
118     endif()
119   else(FUCHSIA OR UNIX)
120     MESSAGE(SEND_ERROR "Unable to determine platform")
121   endif(FUCHSIA OR UNIX)
122 endif(WIN32)
123
124 set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX})
125 set(LTDL_SHLIB_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
126
127 # We use *.dylib rather than *.so on darwin.
128 set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
129
130 if(APPLE)
131   if(LLVM_ENABLE_LLD AND LLVM_ENABLE_LTO)
132     message(FATAL_ERROR "lld does not support LTO on Darwin")
133   endif()
134   # Darwin-specific linker flags for loadable modules.
135   set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-flat_namespace -Wl,-undefined -Wl,suppress")
136 endif()
137
138 if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
139   if(NOT LLVM_BUILD_32_BITS)
140     if (CMAKE_CXX_COMPILER_ID MATCHES "XL")
141       append("-q64" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
142     else()
143       append("-maix64" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
144     endif()
145     set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> -X64 qc <TARGET> <LINK_FLAGS> <OBJECTS>")
146     set(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> -X64 q  <TARGET> <LINK_FLAGS> <OBJECTS>")
147     set(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -X64 <TARGET>")
148     set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -X64 <TARGET>")
149   endif()
150   # -fPIC does not enable the large code model for GCC on AIX but does for XL.
151   if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
152     append("-mcmodel=large" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
153   elseif(CMAKE_CXX_COMPILER_ID MATCHES "XL")
154     # XL generates a small number of relocations not of the large model, -bbigtoc is needed.
155     append("-Wl,-bbigtoc"
156            CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
157   endif()
158 endif()
159
160 # Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
161 # build might work on ELF but fail on MachO/COFF.
162 if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|FreeBSD|OpenBSD|DragonFly|AIX" OR
163         WIN32 OR CYGWIN) AND
164    NOT LLVM_USE_SANITIZER)
165   set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
166 endif()
167
168 # Pass -Wl,-z,nodelete. This makes sure our shared libraries are not unloaded
169 # by dlclose(). We need that since the CLI API relies on cross-references
170 # between global objects which became horribly broken when one of the libraries
171 # is unloaded.
172 if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
173   set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,nodelete")
174   set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-z,nodelete")
175 endif()
176
177
178 function(append value)
179   foreach(variable ${ARGN})
180     set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
181   endforeach(variable)
182 endfunction()
183
184 function(append_if condition value)
185   if (${condition})
186     foreach(variable ${ARGN})
187       set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
188     endforeach(variable)
189   endif()
190 endfunction()
191
192 macro(add_flag_if_supported flag name)
193   check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
194   append_if("C_SUPPORTS_${name}" "${flag}" CMAKE_C_FLAGS)
195   check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
196   append_if("CXX_SUPPORTS_${name}" "${flag}" CMAKE_CXX_FLAGS)
197 endmacro()
198
199 function(add_flag_or_print_warning flag name)
200   check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
201   check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
202   if (C_SUPPORTS_${name} AND CXX_SUPPORTS_${name})
203     message(STATUS "Building with ${flag}")
204     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
205     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
206     set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} ${flag}" PARENT_SCOPE)
207   else()
208     message(WARNING "${flag} is not supported.")
209   endif()
210 endfunction()
211
212 if( LLVM_ENABLE_LLD )
213         if ( LLVM_USE_LINKER )
214                 message(FATAL_ERROR "LLVM_ENABLE_LLD and LLVM_USE_LINKER can't be set at the same time")
215         endif()
216         set(LLVM_USE_LINKER "lld")
217 endif()
218
219 if( LLVM_USE_LINKER )
220   set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
221   set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fuse-ld=${LLVM_USE_LINKER}")
222   check_cxx_source_compiles("int main() { return 0; }" CXX_SUPPORTS_CUSTOM_LINKER)
223   if ( NOT CXX_SUPPORTS_CUSTOM_LINKER )
224           message(FATAL_ERROR "Host compiler does not support '-fuse-ld=${LLVM_USE_LINKER}'")
225   endif()
226   set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
227   append("-fuse-ld=${LLVM_USE_LINKER}"
228     CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
229 endif()
230
231 if( LLVM_ENABLE_PIC )
232   if( XCODE )
233     # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't
234     # know how to disable this, so just force ENABLE_PIC off for now.
235     message(WARNING "-fPIC not supported with Xcode.")
236   elseif( WIN32 OR CYGWIN)
237     # On Windows all code is PIC. MinGW warns if -fPIC is used.
238   else()
239     add_flag_or_print_warning("-fPIC" FPIC)
240   endif()
241 endif()
242
243 if(NOT WIN32 AND NOT CYGWIN AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU"))
244   # MinGW warns if -fvisibility-inlines-hidden is used.
245   # GCC on AIX warns if -fvisibility-inlines-hidden is used.
246   check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG)
247   append_if(SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG "-fvisibility-inlines-hidden" CMAKE_CXX_FLAGS)
248 endif()
249
250 if(CMAKE_SIZEOF_VOID_P EQUAL 8 AND MINGW)
251   add_definitions( -D_FILE_OFFSET_BITS=64 )
252 endif()
253
254 if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
255   # TODO: support other platforms and toolchains.
256   if( LLVM_BUILD_32_BITS )
257     message(STATUS "Building 32 bits executables and libraries.")
258     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
259     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
260     set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
261     set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
262     set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32")
263
264     # FIXME: CMAKE_SIZEOF_VOID_P is still 8
265     add_definitions(-D_LARGEFILE_SOURCE)
266     add_definitions(-D_FILE_OFFSET_BITS=64)
267   endif( LLVM_BUILD_32_BITS )
268 endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
269
270 # If building on a GNU specific 32-bit system, make sure off_t is 64 bits
271 # so that off_t can stored offset > 2GB.
272 # Android until version N (API 24) doesn't support it.
273 if (ANDROID AND (ANDROID_NATIVE_API_LEVEL LESS 24))
274   set(LLVM_FORCE_SMALLFILE_FOR_ANDROID TRUE)
275 endif()
276 if( CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT LLVM_FORCE_SMALLFILE_FOR_ANDROID)
277   # FIXME: It isn't handled in LLVM_BUILD_32_BITS.
278   add_definitions( -D_LARGEFILE_SOURCE )
279   add_definitions( -D_FILE_OFFSET_BITS=64 )
280 endif()
281
282 if( XCODE )
283   # For Xcode enable several build settings that correspond to
284   # many warnings that are on by default in Clang but are
285   # not enabled for historical reasons.  For versions of Xcode
286   # that do not support these options they will simply
287   # be ignored.
288   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_RETURN_TYPE "YES")
289   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE "YES")
290   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VALUE "YES")
291   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VARIABLE "YES")
292   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_SIGN_COMPARE "YES")
293   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_FUNCTION "YES")
294   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED "YES")
295   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS "YES")
296   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNINITIALIZED_AUTOS "YES")
297   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_BOOL_CONVERSION "YES")
298   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_EMPTY_BODY "YES")
299   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_ENUM_CONVERSION "YES")
300   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_INT_CONVERSION "YES")
301   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_CONSTANT_CONVERSION "YES")
302   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_NON_VIRTUAL_DESTRUCTOR "YES")
303 endif()
304
305 # On Win32 using MS tools, provide an option to set the number of parallel jobs
306 # to use.
307 if( MSVC_IDE )
308   set(LLVM_COMPILER_JOBS "0" CACHE STRING
309     "Number of parallel compiler jobs. 0 means use all processors. Default is 0.")
310   if( NOT LLVM_COMPILER_JOBS STREQUAL "1" )
311     if( LLVM_COMPILER_JOBS STREQUAL "0" )
312       add_definitions( /MP )
313     else()
314       message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS})
315       add_definitions( /MP${LLVM_COMPILER_JOBS} )
316     endif()
317   else()
318     message(STATUS "Parallel compilation disabled")
319   endif()
320 endif()
321
322 # set stack reserved size to ~10MB
323 if(MSVC)
324   # CMake previously automatically set this value for MSVC builds, but the
325   # behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default
326   # value (1 MB) which is not enough for us in tasks such as parsing recursive
327   # C++ templates in Clang.
328   set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000")
329 elseif(MINGW) # FIXME: Also cygwin?
330   set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216")
331
332   # Pass -mbig-obj to mingw gas on Win64. COFF has a 2**16 section limit, and
333   # on Win64, every COMDAT function creates at least 3 sections: .text, .pdata,
334   # and .xdata.
335   if (CMAKE_SIZEOF_VOID_P EQUAL 8)
336     append("-Wa,-mbig-obj" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
337   endif()
338 endif()
339
340 if( MSVC )
341   if( CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0 )
342     # For MSVC 2013, disable iterator null pointer checking in debug mode,
343     # especially so std::equal(nullptr, nullptr, nullptr) will not assert.
344     add_definitions("-D_DEBUG_POINTER_IMPL=")
345   endif()
346
347   include(ChooseMSVCCRT)
348
349   if( MSVC11 )
350     add_definitions(-D_VARIADIC_MAX=10)
351   endif()
352
353   # Add definitions that make MSVC much less annoying.
354   add_definitions(
355     # For some reason MS wants to deprecate a bunch of standard functions...
356     -D_CRT_SECURE_NO_DEPRECATE
357     -D_CRT_SECURE_NO_WARNINGS
358     -D_CRT_NONSTDC_NO_DEPRECATE
359     -D_CRT_NONSTDC_NO_WARNINGS
360     -D_SCL_SECURE_NO_DEPRECATE
361     -D_SCL_SECURE_NO_WARNINGS
362     )
363
364   # Tell MSVC to use the Unicode version of the Win32 APIs instead of ANSI.
365   add_definitions(
366     -DUNICODE
367     -D_UNICODE
368   )
369
370   if (LLVM_ENABLE_WERROR)
371     append("/WX" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
372   endif (LLVM_ENABLE_WERROR)
373
374   append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
375
376   # Allow users to request PDBs in release mode. CMake offeres the
377   # RelWithDebInfo configuration, but it uses different optimization settings
378   # (/Ob1 vs /Ob2 or -O2 vs -O3). LLVM provides this flag so that users can get
379   # PDBs without changing codegen.
380   option(LLVM_ENABLE_PDB OFF)
381   if (LLVM_ENABLE_PDB AND uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE")
382     append("/Zi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
383     # /DEBUG disables linker GC and ICF, but we want those in Release mode.
384     append("/DEBUG /OPT:REF /OPT:ICF"
385           CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS
386           CMAKE_SHARED_LINKER_FLAGS)
387   endif()
388
389   # /Zc:strictStrings is incompatible with VS12's (Visual Studio 2013's)
390   # debug mode headers. Instead of only enabling them in VS2013's debug mode,
391   # we'll just enable them for Visual Studio 2015 (VS 14, MSVC_VERSION 1900)
392   # and up.
393   if (NOT (MSVC_VERSION LESS 1900))
394     # Disable string literal const->non-const type conversion.
395     # "When specified, the compiler requires strict const-qualification
396     # conformance for pointers initialized by using string literals."
397     append("/Zc:strictStrings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
398   endif(NOT (MSVC_VERSION LESS 1900))
399
400   # "Generate Intrinsic Functions".
401   append("/Oi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
402
403   # "Enforce type conversion rules".
404   append("/Zc:rvalueCast" CMAKE_CXX_FLAGS)
405
406   if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT LLVM_ENABLE_LTO)
407     # clang-cl and cl by default produce non-deterministic binaries because
408     # link.exe /incremental requires a timestamp in the .obj file.  clang-cl
409     # has the flag /Brepro to force deterministic binaries. We want to pass that
410     # whenever you're building with clang unless you're passing /incremental
411     # or using LTO (/Brepro with LTO would result in a warning about the flag
412     # being unused, because we're not generating object files).
413     # This checks CMAKE_CXX_COMPILER_ID in addition to check_cxx_compiler_flag()
414     # because cl.exe does not emit an error on flags it doesn't understand,
415     # letting check_cxx_compiler_flag() claim it understands all flags.
416     check_cxx_compiler_flag("/Brepro" SUPPORTS_BREPRO)
417     if (SUPPORTS_BREPRO)
418       # Check if /INCREMENTAL is passed to the linker and complain that it
419       # won't work with /Brepro.
420       string(TOUPPER "${CMAKE_EXE_LINKER_FLAGS}" upper_exe_flags)
421       string(TOUPPER "${CMAKE_MODULE_LINKER_FLAGS}" upper_module_flags)
422       string(TOUPPER "${CMAKE_SHARED_LINKER_FLAGS}" upper_shared_flags)
423
424       string(FIND "${upper_exe_flags} ${upper_module_flags} ${upper_shared_flags}"
425         "/INCREMENTAL" linker_flag_idx)
426
427       if (${linker_flag_idx} GREATER -1)
428         message(WARNING "/Brepro not compatible with /INCREMENTAL linking - builds will be non-deterministic")
429       else()
430         append("/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
431       endif()
432     endif()
433   endif()
434
435 elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
436   append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
437   append_if(LLVM_ENABLE_WERROR "-Wno-error" CMAKE_REQUIRED_FLAGS)
438   add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
439   add_flag_if_supported("-Werror=unguarded-availability-new" WERROR_UNGUARDED_AVAILABILITY_NEW)
440   if (LLVM_ENABLE_CXX1Y)
441     check_cxx_compiler_flag("-std=c++1y" CXX_SUPPORTS_CXX1Y)
442     append_if(CXX_SUPPORTS_CXX1Y "-std=c++1y" CMAKE_CXX_FLAGS)
443   elseif(LLVM_ENABLE_CXX1Z)
444     check_cxx_compiler_flag("-std=c++1z" CXX_SUPPORTS_CXX1Z)
445     append_if(CXX_SUPPORTS_CXX1Z "-std=c++1z" CMAKE_CXX_FLAGS)
446   else()
447     check_cxx_compiler_flag("-std=c++11" CXX_SUPPORTS_CXX11)
448     if (CXX_SUPPORTS_CXX11)
449       if (CYGWIN OR MINGW)
450         # MinGW and Cygwin are a bit stricter and lack things like
451         # 'strdup', 'stricmp', etc in c++11 mode.
452         append("-std=gnu++11" CMAKE_CXX_FLAGS)
453       else()
454         append("-std=c++11" CMAKE_CXX_FLAGS)
455       endif()
456     else()
457       message(FATAL_ERROR "LLVM requires C++11 support but the '-std=c++11' flag isn't supported.")
458     endif()
459   endif()
460   if (LLVM_ENABLE_MODULES)
461     set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
462     set(module_flags "-fmodules -fmodules-cache-path=${PROJECT_BINARY_DIR}/module.cache")
463     if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
464       # On Darwin -fmodules does not imply -fcxx-modules.
465       set(module_flags "${module_flags} -fcxx-modules")
466     endif()
467     if (LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY)
468       set(module_flags "${module_flags} -Xclang -fmodules-local-submodule-visibility")
469     endif()
470     if (LLVM_ENABLE_MODULE_DEBUGGING AND
471         ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
472          (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
473       set(module_flags "${module_flags} -gmodules")
474     endif()
475     set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${module_flags}")
476
477     # Check that we can build code with modules enabled, and that repeatedly
478     # including <cassert> still manages to respect NDEBUG properly.
479     CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG
480                                #include <cassert>
481                                #define NDEBUG
482                                #include <cassert>
483                                int main() { assert(this code is not compiled); }"
484                                CXX_SUPPORTS_MODULES)
485     set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
486     if (CXX_SUPPORTS_MODULES)
487       append("${module_flags}" CMAKE_CXX_FLAGS)
488     else()
489       message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
490     endif()
491   endif(LLVM_ENABLE_MODULES)
492 endif( MSVC )
493
494 if (MSVC)
495   if (NOT CLANG_CL)
496     set(msvc_warning_flags
497       # Disabled warnings.
498       -wd4141 # Suppress ''modifier' : used more than once' (because of __forceinline combined with inline)
499       -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned'
500       -wd4180 # Suppress 'qualifier applied to function type has no meaning; ignored'
501       -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data'
502       -wd4258 # Suppress ''var' : definition from the for loop is ignored; the definition from the enclosing scope is used'
503       -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data'
504       -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception'
505       -wd4345 # Suppress 'behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized'
506       -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized'
507       -wd4355 # Suppress ''this' : used in base member initializer list'
508       -wd4456 # Suppress 'declaration of 'var' hides local variable'
509       -wd4457 # Suppress 'declaration of 'var' hides function parameter'
510       -wd4458 # Suppress 'declaration of 'var' hides class member'
511       -wd4459 # Suppress 'declaration of 'var' hides global declaration'
512       -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated'
513       -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible'
514       -wd4722 # Suppress 'function' : destructor never returns, potential memory leak
515       -wd4800 # Suppress ''type' : forcing value to bool 'true' or 'false' (performance warning)'
516       -wd4100 # Suppress 'unreferenced formal parameter'
517       -wd4127 # Suppress 'conditional expression is constant'
518       -wd4512 # Suppress 'assignment operator could not be generated'
519       -wd4505 # Suppress 'unreferenced local function has been removed'
520       -wd4610 # Suppress '<class> can never be instantiated'
521       -wd4510 # Suppress 'default constructor could not be generated'
522       -wd4702 # Suppress 'unreachable code'
523       -wd4245 # Suppress 'signed/unsigned mismatch'
524       -wd4706 # Suppress 'assignment within conditional expression'
525       -wd4310 # Suppress 'cast truncates constant value'
526       -wd4701 # Suppress 'potentially uninitialized local variable'
527       -wd4703 # Suppress 'potentially uninitialized local pointer variable'
528       -wd4389 # Suppress 'signed/unsigned mismatch'
529       -wd4611 # Suppress 'interaction between '_setjmp' and C++ object destruction is non-portable'
530       -wd4805 # Suppress 'unsafe mix of type <type> and type <type> in operation'
531       -wd4204 # Suppress 'nonstandard extension used : non-constant aggregate initializer'
532       -wd4577 # Suppress 'noexcept used with no exception handling mode specified; termination on exception is not guaranteed'
533       -wd4091 # Suppress 'typedef: ignored on left of '' when no variable is declared'
534           # C4592 is disabled because of false positives in Visual Studio 2015
535           # Update 1. Re-evaluate the usefulness of this diagnostic with Update 2.
536       -wd4592 # Suppress ''var': symbol will be dynamically initialized (implementation limitation)
537       -wd4319 # Suppress ''operator' : zero extending 'type' to 'type' of greater size'
538           # C4709 is disabled because of a bug with Visual Studio 2017 as of
539           # v15.8.8. Re-evaluate the usefulness of this diagnostic when the bug
540           # is fixed.
541       -wd4709 # Suppress comma operator within array index expression
542
543       # Ideally, we'd like this warning to be enabled, but MSVC 2013 doesn't
544       # support the 'aligned' attribute in the way that clang sources requires (for
545       # any code that uses the LLVM_ALIGNAS macro), so this is must be disabled to
546       # avoid unwanted alignment warnings.
547       # When we switch to requiring a version of MSVC that supports the 'alignas'
548       # specifier (MSVC 2015?) this warning can be re-enabled.
549       -wd4324 # Suppress 'structure was padded due to __declspec(align())'
550
551       # Promoted warnings.
552       -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
553
554       # Promoted warnings to errors.
555       -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
556       )
557   endif(NOT CLANG_CL)
558
559   # Enable warnings
560   if (LLVM_ENABLE_WARNINGS)
561     # Put /W4 in front of all the -we flags. cl.exe doesn't care, but for
562     # clang-cl having /W4 after the -we flags will re-enable the warnings
563     # disabled by -we.
564     set(msvc_warning_flags "/W4 ${msvc_warning_flags}")
565     # CMake appends /W3 by default, and having /W3 followed by /W4 will result in
566     # cl : Command line warning D9025 : overriding '/W3' with '/W4'.  Since this is
567     # a command line warning and not a compiler warning, it cannot be suppressed except
568     # by fixing the command line.
569     string(REGEX REPLACE " /W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
570     string(REGEX REPLACE " /W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
571
572     if (LLVM_ENABLE_PEDANTIC)
573       # No MSVC equivalent available
574     endif (LLVM_ENABLE_PEDANTIC)
575   endif (LLVM_ENABLE_WARNINGS)
576
577   foreach(flag ${msvc_warning_flags})
578     append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
579   endforeach(flag)
580 endif (MSVC)
581
582 if (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
583
584   # Don't add -Wall for clang-cl, because it maps -Wall to -Weverything for
585   # MSVC compatibility.  /W4 is added above instead.
586   if (NOT CLANG_CL)
587     append("-Wall" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
588   endif()
589
590   append("-Wextra -Wno-unused-parameter -Wwrite-strings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
591   append("-Wcast-qual" CMAKE_CXX_FLAGS)
592
593   # Turn off missing field initializer warnings for gcc to avoid noise from
594   # false positives with empty {}. Turn them on otherwise (they're off by
595   # default for clang).
596   check_cxx_compiler_flag("-Wmissing-field-initializers" CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
597   if (CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
598     if (CMAKE_COMPILER_IS_GNUCXX)
599       append("-Wno-missing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
600     else()
601       append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
602     endif()
603   endif()
604
605   if (LLVM_ENABLE_PEDANTIC AND LLVM_COMPILER_IS_GCC_COMPATIBLE)
606     append("-pedantic" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
607     append("-Wno-long-long" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
608   endif()
609
610   add_flag_if_supported("-Wimplicit-fallthrough" IMPLICIT_FALLTHROUGH_FLAG)
611   add_flag_if_supported("-Wcovered-switch-default" COVERED_SWITCH_DEFAULT_FLAG)
612   append_if(USE_NO_UNINITIALIZED "-Wno-uninitialized" CMAKE_CXX_FLAGS)
613   append_if(USE_NO_MAYBE_UNINITIALIZED "-Wno-maybe-uninitialized" CMAKE_CXX_FLAGS)
614
615   # Disable -Wclass-memaccess, a C++-only warning from GCC 8 that fires on
616   # LLVM's ADT classes.
617   check_cxx_compiler_flag("-Wclass-memaccess" CXX_SUPPORTS_CLASS_MEMACCESS_FLAG)
618   append_if(CXX_SUPPORTS_CLASS_MEMACCESS_FLAG "-Wno-class-memaccess" CMAKE_CXX_FLAGS)
619
620   # The LLVM libraries have no stable C++ API, so -Wnoexcept-type is not useful.
621   check_cxx_compiler_flag("-Wnoexcept-type" CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG)
622   append_if(CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG "-Wno-noexcept-type" CMAKE_CXX_FLAGS)
623
624   # Check if -Wnon-virtual-dtor warns even though the class is marked final.
625   # If it does, don't add it. So it won't be added on clang 3.4 and older.
626   # This also catches cases when -Wnon-virtual-dtor isn't supported by
627   # the compiler at all.  This flag is not activated for gcc since it will
628   # incorrectly identify a protected non-virtual base when there is a friend
629   # declaration. Don't activate this in general on Windows as this warning has
630   # too many false positives on COM-style classes, which are destroyed with
631   # Release() (PR32286).
632   if (NOT CMAKE_COMPILER_IS_GNUCXX AND NOT WIN32)
633     set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
634     set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11 -Werror=non-virtual-dtor")
635     CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();protected: ~base();};
636                                class derived final : public base { public: ~derived();};
637                                int main() { return 0; }"
638                               CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR)
639     set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
640     append_if(CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR
641               "-Wnon-virtual-dtor" CMAKE_CXX_FLAGS)
642   endif()
643
644   # Enable -Wdelete-non-virtual-dtor if available.
645   add_flag_if_supported("-Wdelete-non-virtual-dtor" DELETE_NON_VIRTUAL_DTOR_FLAG)
646
647   # Check if -Wcomment is OK with an // comment ending with '\' if the next
648   # line is also a // comment.
649   set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
650   set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror -Wcomment")
651   CHECK_C_SOURCE_COMPILES("// \\\\\\n//\\nint main() {return 0;}"
652                           C_WCOMMENT_ALLOWS_LINE_WRAP)
653   set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
654   if (NOT C_WCOMMENT_ALLOWS_LINE_WRAP)
655     append("-Wno-comment" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
656   endif()
657
658   # Enable -Wstring-conversion to catch misuse of string literals.
659   add_flag_if_supported("-Wstring-conversion" STRING_CONVERSION_FLAG)
660 endif (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
661
662 if (LLVM_COMPILER_IS_GCC_COMPATIBLE AND NOT LLVM_ENABLE_WARNINGS)
663   append("-w" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
664 endif()
665
666 macro(append_common_sanitizer_flags)
667   if (NOT MSVC)
668     # Append -fno-omit-frame-pointer and turn on debug info to get better
669     # stack traces.
670     add_flag_if_supported("-fno-omit-frame-pointer" FNO_OMIT_FRAME_POINTER)
671     if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND
672         NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")
673       add_flag_if_supported("-gline-tables-only" GLINE_TABLES_ONLY)
674     endif()
675     # Use -O1 even in debug mode, otherwise sanitizers slowdown is too large.
676     if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND LLVM_OPTIMIZE_SANITIZED_BUILDS)
677       add_flag_if_supported("-O1" O1)
678     endif()
679   elseif (CLANG_CL)
680     # Keep frame pointers around.
681     append("/Oy-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
682     if (LINKER_IS_LLD_LINK)
683       # Use DWARF debug info with LLD.
684       append("-gdwarf" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
685     else()
686       # Enable codeview otherwise.
687       append("/Z7" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
688     endif()
689     # Always ask the linker to produce symbols with asan.
690     append("-debug" CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
691   endif()
692 endmacro()
693
694 # Turn on sanitizers if necessary.
695 if(LLVM_USE_SANITIZER)
696   if (LLVM_ON_UNIX)
697     if (LLVM_USE_SANITIZER STREQUAL "Address")
698       append_common_sanitizer_flags()
699       append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
700     elseif (LLVM_USE_SANITIZER MATCHES "Memory(WithOrigins)?")
701       append_common_sanitizer_flags()
702       append("-fsanitize=memory" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
703       if(LLVM_USE_SANITIZER STREQUAL "MemoryWithOrigins")
704         append("-fsanitize-memory-track-origins" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
705       endif()
706     elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
707       append_common_sanitizer_flags()
708       append("-fsanitize=undefined -fno-sanitize=vptr,function -fno-sanitize-recover=all"
709               CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
710     elseif (LLVM_USE_SANITIZER STREQUAL "Thread")
711       append_common_sanitizer_flags()
712       append("-fsanitize=thread" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
713     elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
714             LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
715       append_common_sanitizer_flags()
716       append("-fsanitize=address,undefined -fno-sanitize=vptr,function -fno-sanitize-recover=all"
717               CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
718     elseif (LLVM_USE_SANITIZER STREQUAL "Leaks")
719       append_common_sanitizer_flags()
720       append("-fsanitize=leak" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
721     else()
722       message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}")
723     endif()
724   elseif(MSVC)
725     if (LLVM_USE_SANITIZER STREQUAL "Address")
726       append_common_sanitizer_flags()
727       append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
728     else()
729       message(FATAL_ERROR "This sanitizer not yet supported in the MSVC environment: ${LLVM_USE_SANITIZER}")
730     endif()
731   else()
732     message(FATAL_ERROR "LLVM_USE_SANITIZER is not supported on this platform.")
733   endif()
734   if (LLVM_USE_SANITIZER MATCHES "(Undefined;)?Address(;Undefined)?")
735     add_flag_if_supported("-fsanitize-address-use-after-scope"
736                           FSANITIZE_USE_AFTER_SCOPE_FLAG)
737   endif()
738   if (LLVM_USE_SANITIZE_COVERAGE)
739     append("-fsanitize=fuzzer-no-link" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
740   endif()
741   if (LLVM_USE_SANITIZER MATCHES ".*Undefined.*")
742     set(BLACKLIST_FILE "${CMAKE_SOURCE_DIR}/utils/sanitizers/ubsan_blacklist.txt")
743     if (EXISTS "${BLACKLIST_FILE}")
744       append("-fsanitize-blacklist=${BLACKLIST_FILE}"
745              CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
746     endif()
747   endif()
748 endif()
749
750 # Turn on -gsplit-dwarf if requested
751 if(LLVM_USE_SPLIT_DWARF)
752   add_definitions("-gsplit-dwarf")
753 endif()
754
755 add_definitions( -D__STDC_CONSTANT_MACROS )
756 add_definitions( -D__STDC_FORMAT_MACROS )
757 add_definitions( -D__STDC_LIMIT_MACROS )
758
759 # clang and gcc don't default-print colored diagnostics when invoked from Ninja.
760 if (UNIX AND
761     CMAKE_GENERATOR STREQUAL "Ninja" AND
762     (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
763      (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
764       NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9))))
765   append("-fdiagnostics-color" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
766 endif()
767
768 # lld doesn't print colored diagnostics when invoked from Ninja
769 if (UNIX AND CMAKE_GENERATOR STREQUAL "Ninja")
770   include(CheckLinkerFlag)
771   check_linker_flag("-Wl,--color-diagnostics" LINKER_SUPPORTS_COLOR_DIAGNOSTICS)
772   append_if(LINKER_SUPPORTS_COLOR_DIAGNOSTICS "-Wl,--color-diagnostics"
773     CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
774 endif()
775
776 # Add flags for add_dead_strip().
777 # FIXME: With MSVS, consider compiling with /Gy and linking with /OPT:REF?
778 # But MinSizeRel seems to add that automatically, so maybe disable these
779 # flags instead if LLVM_NO_DEAD_STRIP is set.
780 if(NOT CYGWIN AND NOT WIN32)
781   if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND
782      NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
783     check_c_compiler_flag("-Werror -fno-function-sections" C_SUPPORTS_FNO_FUNCTION_SECTIONS)
784     if (C_SUPPORTS_FNO_FUNCTION_SECTIONS)
785       # Don't add -ffunction-section if it can be disabled with -fno-function-sections.
786       # Doing so will break sanitizers.
787       add_flag_if_supported("-ffunction-sections" FFUNCTION_SECTIONS)
788     endif()
789     add_flag_if_supported("-fdata-sections" FDATA_SECTIONS)
790   endif()
791 endif()
792
793 if(MSVC)
794   # Remove flags here, for exceptions and RTTI.
795   # Each target property or source property should be responsible to control
796   # them.
797   # CL.EXE complains to override flags like "/GR /GR-".
798   string(REGEX REPLACE "(^| ) */EH[-cs]+ *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
799   string(REGEX REPLACE "(^| ) */GR-? *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
800 endif()
801
802 # Provide public options to globally control RTTI and EH
803 option(LLVM_ENABLE_EH "Enable Exception handling" OFF)
804 option(LLVM_ENABLE_RTTI "Enable run time type information" OFF)
805 if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI)
806   message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON")
807 endif()
808
809 option(LLVM_USE_NEWPM "Build LLVM using the experimental new pass manager" Off)
810 mark_as_advanced(LLVM_USE_NEWPM)
811 if (LLVM_USE_NEWPM)
812   append("-fexperimental-new-pass-manager"
813     CMAKE_CXX_FLAGS
814     CMAKE_C_FLAGS
815     CMAKE_EXE_LINKER_FLAGS
816     CMAKE_SHARED_LINKER_FLAGS)
817 endif()
818
819 option(LLVM_ENABLE_IR_PGO "Build LLVM and tools with IR PGO instrumentation (deprecated)" Off)
820 mark_as_advanced(LLVM_ENABLE_IR_PGO)
821
822 set(LLVM_BUILD_INSTRUMENTED OFF CACHE STRING "Build LLVM and tools with PGO instrumentation. May be specified as IR or Frontend")
823 mark_as_advanced(LLVM_BUILD_INSTRUMENTED)
824 string(TOUPPER "${LLVM_BUILD_INSTRUMENTED}" uppercase_LLVM_BUILD_INSTRUMENTED)
825
826 if (LLVM_BUILD_INSTRUMENTED)
827   if (LLVM_ENABLE_IR_PGO OR uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "IR")
828     append("-fprofile-generate='${LLVM_PROFILE_DATA_DIR}'"
829       CMAKE_CXX_FLAGS
830       CMAKE_C_FLAGS
831       CMAKE_EXE_LINKER_FLAGS
832       CMAKE_SHARED_LINKER_FLAGS)
833   elseif(uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "CSIR")
834     append("-fcs-profile-generate='${LLVM_CSPROFILE_DATA_DIR}'"
835       CMAKE_CXX_FLAGS
836       CMAKE_C_FLAGS
837       CMAKE_EXE_LINKER_FLAGS
838       CMAKE_SHARED_LINKER_FLAGS)
839   else()
840     append("-fprofile-instr-generate='${LLVM_PROFILE_FILE_PATTERN}'"
841       CMAKE_CXX_FLAGS
842       CMAKE_C_FLAGS
843       CMAKE_EXE_LINKER_FLAGS
844       CMAKE_SHARED_LINKER_FLAGS)
845   endif()
846 endif()
847
848 # Need to pass -fprofile-instr-use to linker for context-sensitive PGO
849 # compilation.
850 if(LLVM_PROFDATA_FILE AND EXISTS ${LLVM_PROFDATA_FILE})
851     append("-fprofile-instr-use='${LLVM_PROFDATA_FILE}'"
852       CMAKE_EXE_LINKER_FLAGS
853       CMAKE_SHARED_LINKER_FLAGS)
854 endif()
855
856 option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation" Off)
857 mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE)
858 append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate='${LLVM_PROFILE_FILE_PATTERN}' -fcoverage-mapping"
859   CMAKE_CXX_FLAGS
860   CMAKE_C_FLAGS
861   CMAKE_EXE_LINKER_FLAGS
862   CMAKE_SHARED_LINKER_FLAGS)
863
864 if (LLVM_BUILD_INSTRUMENTED AND LLVM_BUILD_INSTRUMENTED_COVERAGE)
865   message(FATAL_ERROR "LLVM_BUILD_INSTRUMENTED and LLVM_BUILD_INSTRUMENTED_COVERAGE cannot both be specified")
866 endif()
867
868 if(LLVM_ENABLE_LTO AND LLVM_ON_WIN32 AND NOT LINKER_IS_LLD_LINK)
869   message(FATAL_ERROR "When compiling for Windows, LLVM_ENABLE_LTO requires using lld as the linker (point CMAKE_LINKER at lld-link.exe)")
870 endif()
871 if(uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
872   append("-flto=thin" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
873   if(NOT LINKER_IS_LLD_LINK)
874     append("-flto=thin" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
875   endif()
876   # If the linker supports it, enable the lto cache. This improves initial build
877   # time a little since we re-link a lot of the same objects, and significantly
878   # improves incremental build time.
879   # FIXME: We should move all this logic into the clang driver.
880   if(APPLE)
881     append("-Wl,-cache_path_lto,${PROJECT_BINARY_DIR}/lto.cache"
882            CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
883   elseif(UNIX AND LLVM_USE_LINKER STREQUAL "lld")
884     append("-Wl,--thinlto-cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
885            CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
886   elseif(LLVM_USE_LINKER STREQUAL "gold")
887     append("-Wl,--plugin-opt,cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
888            CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
889   endif()
890 elseif(uppercase_LLVM_ENABLE_LTO STREQUAL "FULL")
891   append("-flto=full" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
892   if(NOT LINKER_IS_LLD_LINK)
893     append("-flto=full" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
894   endif()
895 elseif(LLVM_ENABLE_LTO)
896   append("-flto" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
897   if(NOT LINKER_IS_LLD_LINK)
898     append("-flto" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
899   endif()
900 endif()
901
902 # This option makes utils/extract_symbols.py be used to determine the list of
903 # symbols to export from LLVM tools. This is necessary when using MSVC if you
904 # want to allow plugins, though note that the plugin has to explicitly link
905 # against (exactly one) tool so we can't unilaterally turn on
906 # LLVM_ENABLE_PLUGINS when it's enabled.
907 option(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS "Export symbols from LLVM tools so that plugins can import them" OFF)
908 if(BUILD_SHARED_LIBS AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
909   message(FATAL_ERROR "BUILD_SHARED_LIBS not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
910 endif()
911 if(LLVM_LINK_LLVM_DYLIB AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
912   message(FATAL_ERROR "LLVM_LINK_LLVM_DYLIB not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
913 endif()
914
915 # Plugin support
916 # FIXME: Make this configurable.
917 if(WIN32 OR CYGWIN)
918   if(BUILD_SHARED_LIBS OR LLVM_BUILD_LLVM_DYLIB)
919     set(LLVM_ENABLE_PLUGINS ON)
920   else()
921     set(LLVM_ENABLE_PLUGINS OFF)
922   endif()
923 else()
924   set(LLVM_ENABLE_PLUGINS ON)
925 endif()
926
927 # By default we should enable LLVM_ENABLE_IDE only for multi-configuration
928 # generators. This option disables optional build system features that make IDEs
929 # less usable.
930 set(LLVM_ENABLE_IDE_default OFF)
931 if (CMAKE_CONFIGURATION_TYPES)
932   set(LLVM_ENABLE_IDE_default ON)
933 endif()
934 option(LLVM_ENABLE_IDE
935        "Disable optional build system features that cause problems for IDE generators"
936        ${LLVM_ENABLE_IDE_default})
937 if (CMAKE_CONFIGURATION_TYPES AND NOT LLVM_ENABLE_IDE)
938   message(WARNING "Disabling LLVM_ENABLE_IDE on multi-configuration generators is not recommended.")
939 endif()
940
941 function(get_compile_definitions)
942   get_directory_property(top_dir_definitions DIRECTORY ${CMAKE_SOURCE_DIR} COMPILE_DEFINITIONS)
943   foreach(definition ${top_dir_definitions})
944     if(DEFINED result)
945       string(APPEND result " -D${definition}")
946     else()
947       set(result "-D${definition}")
948     endif()
949   endforeach()
950   set(LLVM_DEFINITIONS "${result}" PARENT_SCOPE)
951 endfunction()
952 get_compile_definitions()
953
954 option(LLVM_FORCE_ENABLE_STATS "Enable statistics collection for builds that wouldn't normally enable it" OFF)
955
956 check_symbol_exists(os_signpost_interval_begin "os/signpost.h" macos_signposts_available)
957 if(macos_signposts_available)
958   check_cxx_source_compiles(
959     "#include <os/signpost.h>
960     int main() { os_signpost_interval_begin(nullptr, 0, \"\", \"\"); return 0; }"
961     macos_signposts_usable)
962   if(macos_signposts_usable)
963     set(LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS "WITH_ASSERTS" CACHE STRING
964         "Enable support for Xcode signposts. Can be WITH_ASSERTS, FORCE_ON, FORCE_OFF")
965     string(TOUPPER "${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}"
966                    uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS)
967     if( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "WITH_ASSERTS" )
968       if( LLVM_ENABLE_ASSERTIONS )
969         set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
970       endif()
971     elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_ON" )
972       set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
973     elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_OFF" )
974       # We don't need to do anything special to turn off signposts.
975     elseif( NOT DEFINED LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS )
976       # Treat LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS like "FORCE_OFF" when it has not been
977       # defined.
978     else()
979       message(FATAL_ERROR "Unknown value for LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS:"
980                           " \"${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}\"!")
981     endif()
982   endif()
983 endif()