Enable -Wdeprecated in the cmake build now that LLVM (& Clang, Polly, and LLD) are...
[oota-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(HandleLLVMStdlib)
10 include(AddLLVMDefinitions)
11 include(CheckCCompilerFlag)
12 include(CheckCXXCompilerFlag)
13
14 if(NOT LLVM_FORCE_USE_OLD_TOOLCHAIN)
15   if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
16     if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7)
17       message(FATAL_ERROR "Host GCC version must be at least 4.7!")
18     endif()
19   elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
20     if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
21       message(FATAL_ERROR "Host Clang version must be at least 3.1!")
22     endif()
23
24     if (CMAKE_CXX_SIMULATE_ID MATCHES "MSVC")
25       if (CMAKE_CXX_SIMULATE_VERSION VERSION_LESS 18.0)
26         message(FATAL_ERROR "Host Clang must have at least -fms-compatibility-version=18.0")
27       endif()
28       set(CLANG_CL 1)
29     elseif(NOT LLVM_ENABLE_LIBCXX)
30       # Otherwise, test that we aren't using too old of a version of libstdc++
31       # with the Clang compiler. This is tricky as there is no real way to
32       # check the version of libstdc++ directly. Instead we test for a known
33       # bug in libstdc++4.6 that is fixed in libstdc++4.7.
34       set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
35       set(OLD_CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
36       set(CMAKE_REQUIRED_FLAGS "-std=c++0x")
37       check_cxx_source_compiles("
38 #include <atomic>
39 std::atomic<float> x(0.0f);
40 int main() { return (float)x; }"
41         LLVM_NO_OLD_LIBSTDCXX)
42       if(NOT LLVM_NO_OLD_LIBSTDCXX)
43         message(FATAL_ERROR "Host Clang must be able to find libstdc++4.7 or newer!")
44       endif()
45       set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
46       set(CMAKE_REQUIRED_LIBRARIES ${OLD_CMAKE_REQUIRED_LIBRARIES})
47     endif()
48   elseif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
49     if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0)
50       message(FATAL_ERROR "Host Visual Studio must be at least 2013")
51     elseif(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0.31101)
52       message(WARNING "Host Visual Studio should at least be 2013 Update 4 (MSVC 18.0.31101)"
53         "  due to miscompiles from earlier versions")
54     endif()
55   endif()
56 endif()
57
58 if( LLVM_ENABLE_ASSERTIONS )
59   # MSVC doesn't like _DEBUG on release builds. See PR 4379.
60   if( NOT MSVC )
61     add_definitions( -D_DEBUG )
62   endif()
63   # On non-Debug builds cmake automatically defines NDEBUG, so we
64   # explicitly undefine it:
65   if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
66     add_definitions( -UNDEBUG )
67     # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines.
68     foreach (flags_var_to_scrub
69         CMAKE_CXX_FLAGS_RELEASE
70         CMAKE_CXX_FLAGS_RELWITHDEBINFO
71         CMAKE_CXX_FLAGS_MINSIZEREL
72         CMAKE_C_FLAGS_RELEASE
73         CMAKE_C_FLAGS_RELWITHDEBINFO
74         CMAKE_C_FLAGS_MINSIZEREL)
75       string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " "
76         "${flags_var_to_scrub}" "${${flags_var_to_scrub}}")
77     endforeach()
78   endif()
79 endif()
80
81 string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS)
82
83 if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" )
84   if( LLVM_ENABLE_ASSERTIONS )
85     set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
86   endif()
87 elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_ON" )
88   set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
89 elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_OFF" )
90   # We don't need to do anything special to turn off ABI breaking checks.
91 elseif( NOT DEFINED LLVM_ABI_BREAKING_CHECKS )
92   # Treat LLVM_ABI_BREAKING_CHECKS like "FORCE_OFF" when it has not been
93   # defined.
94 else()
95   message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: \"${LLVM_ABI_BREAKING_CHECKS}\"!")
96 endif()
97
98 if(WIN32)
99   set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
100   if(CYGWIN)
101     set(LLVM_ON_WIN32 0)
102     set(LLVM_ON_UNIX 1)
103   else(CYGWIN)
104     set(LLVM_ON_WIN32 1)
105     set(LLVM_ON_UNIX 0)
106   endif(CYGWIN)
107 else(WIN32)
108   if(UNIX)
109     set(LLVM_ON_WIN32 0)
110     set(LLVM_ON_UNIX 1)
111     if(APPLE)
112       set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
113     else(APPLE)
114       set(LLVM_HAVE_LINK_VERSION_SCRIPT 1)
115     endif(APPLE)
116   else(UNIX)
117     MESSAGE(SEND_ERROR "Unable to determine platform")
118   endif(UNIX)
119 endif(WIN32)
120
121 set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX})
122 set(LTDL_SHLIB_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
123
124 # We use *.dylib rather than *.so on darwin.
125 set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
126
127 if(APPLE)
128   # Darwin-specific linker flags for loadable modules.
129   set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-flat_namespace -Wl,-undefined -Wl,suppress")
130 endif()
131
132 # Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
133 # build might work on ELF but fail on MachO/COFF.
134 if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR WIN32 OR CYGWIN OR
135         ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD") AND
136    NOT LLVM_USE_SANITIZER)
137   set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
138 endif()
139
140
141 function(append value)
142   foreach(variable ${ARGN})
143     set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
144   endforeach(variable)
145 endfunction()
146
147 function(append_if condition value)
148   if (${condition})
149     foreach(variable ${ARGN})
150       set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
151     endforeach(variable)
152   endif()
153 endfunction()
154
155 macro(add_flag_if_supported flag name)
156   check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
157   append_if("C_SUPPORTS_${name}" "${flag}" CMAKE_C_FLAGS)
158   check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
159   append_if("CXX_SUPPORTS_${name}" "${flag}" CMAKE_CXX_FLAGS)
160 endmacro()
161
162 function(add_flag_or_print_warning flag name)
163   check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
164   check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
165   if (C_SUPPORTS_${name} AND CXX_SUPPORTS_${name})
166     message(STATUS "Building with ${flag}")
167     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
168     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
169     set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} ${flag}" PARENT_SCOPE)
170   else()
171     message(WARNING "${flag} is not supported.")
172   endif()
173 endfunction()
174
175 if( LLVM_ENABLE_PIC )
176   if( XCODE )
177     # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't
178     # know how to disable this, so just force ENABLE_PIC off for now.
179     message(WARNING "-fPIC not supported with Xcode.")
180   elseif( WIN32 OR CYGWIN)
181     # On Windows all code is PIC. MinGW warns if -fPIC is used.
182   else()
183     add_flag_or_print_warning("-fPIC" FPIC)
184
185     if( WIN32 OR CYGWIN)
186       # MinGW warns if -fvisibility-inlines-hidden is used.
187     else()
188       check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG)
189       append_if(SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG "-fvisibility-inlines-hidden" CMAKE_CXX_FLAGS)
190     endif()
191   endif()
192 endif()
193
194 if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
195   # TODO: support other platforms and toolchains.
196   if( LLVM_BUILD_32_BITS )
197     message(STATUS "Building 32 bits executables and libraries.")
198     add_llvm_definitions( -m32 )
199     set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
200     set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
201     set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32")
202   endif( LLVM_BUILD_32_BITS )
203 endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
204
205 if (LLVM_BUILD_STATIC)
206   set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
207 endif()
208
209 if( XCODE )
210   # For Xcode enable several build settings that correspond to
211   # many warnings that are on by default in Clang but are
212   # not enabled for historical reasons.  For versions of Xcode
213   # that do not support these options they will simply
214   # be ignored.
215   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_RETURN_TYPE "YES")
216   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE "YES")
217   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VALUE "YES")
218   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VARIABLE "YES")
219   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_SIGN_COMPARE "YES")
220   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_FUNCTION "YES")
221   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED "YES")
222   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS "YES")
223   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNINITIALIZED_AUTOS "YES")
224   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_BOOL_CONVERSION "YES")
225   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_EMPTY_BODY "YES")
226   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_ENUM_CONVERSION "YES")
227   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_INT_CONVERSION "YES")
228   set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_CONSTANT_CONVERSION "YES")
229   set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_NON_VIRTUAL_DESTRUCTOR "YES")
230 endif()
231
232 # On Win32 using MS tools, provide an option to set the number of parallel jobs
233 # to use.
234 if( MSVC_IDE )
235   set(LLVM_COMPILER_JOBS "0" CACHE STRING
236     "Number of parallel compiler jobs. 0 means use all processors. Default is 0.")
237   if( NOT LLVM_COMPILER_JOBS STREQUAL "1" )
238     if( LLVM_COMPILER_JOBS STREQUAL "0" )
239       add_llvm_definitions( /MP )
240     else()
241       message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS})
242       add_llvm_definitions( /MP${LLVM_COMPILER_JOBS} )
243     endif()
244   else()
245     message(STATUS "Parallel compilation disabled")
246   endif()
247 endif()
248
249 if( MSVC )
250   if( CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0 )
251     # For MSVC 2013, disable iterator null pointer checking in debug mode,
252     # especially so std::equal(nullptr, nullptr, nullptr) will not assert.
253     add_llvm_definitions("-D_DEBUG_POINTER_IMPL=")
254   endif()
255   
256   include(ChooseMSVCCRT)
257
258   if( NOT (${CMAKE_VERSION} VERSION_LESS 2.8.11) )
259     # set stack reserved size to ~10MB
260     # CMake previously automatically set this value for MSVC builds, but the
261     # behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default
262     # value (1 MB) which is not enough for us in tasks such as parsing recursive
263     # C++ templates in Clang.
264     set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000")
265   endif()
266
267   if( MSVC11 )
268     add_llvm_definitions(-D_VARIADIC_MAX=10)
269   endif()
270   
271   # Add definitions that make MSVC much less annoying.
272   add_llvm_definitions(
273     # For some reason MS wants to deprecate a bunch of standard functions...
274     -D_CRT_SECURE_NO_DEPRECATE
275     -D_CRT_SECURE_NO_WARNINGS
276     -D_CRT_NONSTDC_NO_DEPRECATE
277     -D_CRT_NONSTDC_NO_WARNINGS
278     -D_SCL_SECURE_NO_DEPRECATE
279     -D_SCL_SECURE_NO_WARNINGS
280     )
281
282   set(msvc_warning_flags
283     # Disabled warnings.
284     -wd4141 # Suppress ''modifier' : used more than once' (because of __forceinline combined with inline)
285     -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned'
286     -wd4180 # Suppress 'qualifier applied to function type has no meaning; ignored'
287     -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data'
288     -wd4258 # Suppress ''var' : definition from the for loop is ignored; the definition from the enclosing scope is used'
289     -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data'
290     -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception'
291     -wd4345 # Suppress 'behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized'
292     -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized'
293     -wd4355 # Suppress ''this' : used in base member initializer list'
294     -wd4456 # Suppress 'declaration of 'var' hides local variable'
295     -wd4457 # Suppress 'declaration of 'var' hides function parameter'
296     -wd4458 # Suppress 'declaration of 'var' hides class member'
297     -wd4459 # Suppress 'declaration of 'var' hides global declaration'
298     -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated'
299     -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible'
300     -wd4722 # Suppress 'function' : destructor never returns, potential memory leak
301     -wd4800 # Suppress ''type' : forcing value to bool 'true' or 'false' (performance warning)'
302     -wd4100 # Suppress 'unreferenced formal parameter'
303     -wd4127 # Suppress 'conditional expression is constant'
304     -wd4512 # Suppress 'assignment operator could not be generated'
305     -wd4505 # Suppress 'unreferenced local function has been removed'
306     -wd4610 # Suppress '<class> can never be instantiated'
307     -wd4510 # Suppress 'default constructor could not be generated'
308     -wd4702 # Suppress 'unreachable code'
309     -wd4245 # Suppress 'signed/unsigned mismatch'
310     -wd4706 # Suppress 'assignment within conditional expression'
311     -wd4310 # Suppress 'cast truncates constant value'
312     -wd4701 # Suppress 'potentially uninitialized local variable'
313     -wd4703 # Suppress 'potentially uninitialized local pointer variable'
314     -wd4389 # Suppress 'signed/unsigned mismatch'
315     -wd4611 # Suppress 'interaction between '_setjmp' and C++ object destruction is non-portable'
316     -wd4805 # Suppress 'unsafe mix of type <type> and type <type> in operation'
317     -wd4204 # Suppress 'nonstandard extension used : non-constant aggregate initializer'
318     -wd4577 # Suppress 'noexcept used with no exception handling mode specified; termination on exception is not guaranteed'
319     -wd4091 # Suppress 'typedef: ignored on left of '' when no variable is declared'
320
321         # Ideally, we'd like this warning to be enabled, but MSVC 2013 doesn't
322         # support the 'aligned' attribute in the way that clang sources requires (for
323         # any code that uses the LLVM_ALIGNAS macro), so this is must be disabled to
324         # avoid unwanted alignment warnings.
325         # When we switch to requiring a version of MSVC that supports the 'alignas'
326         # specifier (MSVC 2015?) this warning can be re-enabled.
327     -wd4324 # Suppress 'structure was padded due to __declspec(align())'
328             
329     # Promoted warnings.
330     -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
331
332     # Promoted warnings to errors.
333     -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
334     )
335
336   # Enable warnings
337   if (LLVM_ENABLE_WARNINGS)
338     append("/W4" msvc_warning_flags)
339     # CMake appends /W3 by default, and having /W3 followed by /W4 will result in 
340     # cl : Command line warning D9025 : overriding '/W3' with '/W4'.  Since this is
341     # a command line warning and not a compiler warning, it cannot be suppressed except
342     # by fixing the command line.
343     string(REGEX REPLACE " /W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
344     string(REGEX REPLACE " /W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
345
346     if (LLVM_ENABLE_PEDANTIC)
347       # No MSVC equivalent available
348     endif (LLVM_ENABLE_PEDANTIC)
349   endif (LLVM_ENABLE_WARNINGS)
350   if (LLVM_ENABLE_WERROR)
351     append("/WX" msvc_warning_flags)
352   endif (LLVM_ENABLE_WERROR)
353
354   foreach(flag ${msvc_warning_flags})
355     append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
356   endforeach(flag)
357
358   append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
359
360   # Disable sized deallocation if the flag is supported. MSVC fails to compile
361   # the operator new overload in User otherwise.
362   check_c_compiler_flag("/WX /Zc:sizedDealloc-" SUPPORTS_SIZED_DEALLOC)
363   append_if(SUPPORTS_SIZED_DEALLOC "/Zc:sizedDealloc-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
364
365 elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
366   if (LLVM_ENABLE_WARNINGS)
367     append("-Wall -W -Wno-unused-parameter -Wwrite-strings -Wdeprecated" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
368     append("-Wcast-qual" CMAKE_CXX_FLAGS)
369
370     # Turn off missing field initializer warnings for gcc to avoid noise from
371     # false positives with empty {}. Turn them on otherwise (they're off by
372     # default for clang).
373     check_cxx_compiler_flag("-Wmissing-field-initializers" CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
374     if (CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
375       if (CMAKE_COMPILER_IS_GNUCXX)
376         append("-Wno-missing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
377       else()
378         append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
379       endif()
380     endif()
381
382     append_if(LLVM_ENABLE_PEDANTIC "-pedantic -Wno-long-long" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
383     add_flag_if_supported("-Wcovered-switch-default" COVERED_SWITCH_DEFAULT_FLAG)
384     append_if(USE_NO_UNINITIALIZED "-Wno-uninitialized" CMAKE_CXX_FLAGS)
385     append_if(USE_NO_MAYBE_UNINITIALIZED "-Wno-maybe-uninitialized" CMAKE_CXX_FLAGS)
386
387     # Check if -Wnon-virtual-dtor warns even though the class is marked final.
388     # If it does, don't add it. So it won't be added on clang 3.4 and older.
389     # This also catches cases when -Wnon-virtual-dtor isn't supported by
390     # the compiler at all.
391     set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
392     set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11 -Werror=non-virtual-dtor")
393     CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();protected: ~base();};
394                                class derived final : public base { public: ~derived();};
395                                int main() { return 0; }"
396                               CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR)
397     set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
398     append_if(CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR
399               "-Wnon-virtual-dtor" CMAKE_CXX_FLAGS)
400
401     # Check if -Wcomment is OK with an // comment ending with '\' if the next
402     # line is also a // comment.
403     set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
404     set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror -Wcomment")
405     CHECK_C_SOURCE_COMPILES("// \\\\\\n//\\nint main() {return 0;}"
406                             C_WCOMMENT_ALLOWS_LINE_WRAP)
407     set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
408     if (NOT C_WCOMMENT_ALLOWS_LINE_WRAP)
409       append("-Wno-comment" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
410     endif()
411   endif (LLVM_ENABLE_WARNINGS)
412   append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
413   if (NOT LLVM_ENABLE_TIMESTAMPS)
414     add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
415   endif ()
416   if (LLVM_ENABLE_CXX1Y)
417     check_cxx_compiler_flag("-std=c++1y" CXX_SUPPORTS_CXX1Y)
418     append_if(CXX_SUPPORTS_CXX1Y "-std=c++1y" CMAKE_CXX_FLAGS)
419   else()
420     check_cxx_compiler_flag("-std=c++11" CXX_SUPPORTS_CXX11)
421     if (CXX_SUPPORTS_CXX11)
422       if (CYGWIN OR MINGW)
423         # MinGW and Cygwin are a bit stricter and lack things like
424         # 'strdup', 'stricmp', etc in c++11 mode.
425         append("-std=gnu++11" CMAKE_CXX_FLAGS)
426       else()
427         append("-std=c++11" CMAKE_CXX_FLAGS)
428       endif()
429     else()
430       message(FATAL_ERROR "LLVM requires C++11 support but the '-std=c++11' flag isn't supported.")
431     endif()
432   endif()
433   if (LLVM_ENABLE_MODULES)
434     set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
435     set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fmodules -fcxx-modules")
436     # Check that we can build code with modules enabled, and that repeatedly
437     # including <cassert> still manages to respect NDEBUG properly.
438     CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG
439                                #include <cassert>
440                                #define NDEBUG
441                                #include <cassert>
442                                int main() { assert(this code is not compiled); }"
443                                CXX_SUPPORTS_MODULES)
444     set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
445     if (CXX_SUPPORTS_MODULES)
446       append_if(CXX_SUPPORTS_MODULES "-fmodules" CMAKE_C_FLAGS)
447       append_if(CXX_SUPPORTS_MODULES "-fmodules -fcxx-modules" CMAKE_CXX_FLAGS)
448     else()
449       message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
450     endif()
451   endif(LLVM_ENABLE_MODULES)
452 endif( MSVC )
453
454 macro(append_common_sanitizer_flags)
455   if (NOT MSVC)
456     # Append -fno-omit-frame-pointer and turn on debug info to get better
457     # stack traces.
458     add_flag_if_supported("-fno-omit-frame-pointer" FNO_OMIT_FRAME_POINTER)
459     if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND
460         NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")
461       add_flag_if_supported("-gline-tables-only" GLINE_TABLES_ONLY)
462     endif()
463     # Use -O1 even in debug mode, otherwise sanitizers slowdown is too large.
464     if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
465       add_flag_if_supported("-O1" O1)
466     endif()
467   elseif (CLANG_CL)
468     # Keep frame pointers around.
469     append("/Oy-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
470     if (CMAKE_LINKER MATCHES "lld-link.exe")
471       # Use DWARF debug info with LLD.
472       append("-gdwarf" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
473       # Pass /MANIFEST:NO so that CMake doesn't run mt.exe on our binaries.
474       # Adding manifests with mt.exe breaks LLD's symbol tables. See PR24476.
475       append("/MANIFEST:NO"
476         CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
477     else()
478       # Enable codeview otherwise.
479       append("/Z7" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
480     endif()
481     # Always ask the linker to produce symbols with asan.
482     append("-debug" CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
483   endif()
484 endmacro()
485
486 # Turn on sanitizers if necessary.
487 if(LLVM_USE_SANITIZER)
488   if (LLVM_ON_UNIX)
489     if (LLVM_USE_SANITIZER STREQUAL "Address")
490       append_common_sanitizer_flags()
491       append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
492     elseif (LLVM_USE_SANITIZER MATCHES "Memory(WithOrigins)?")
493       append_common_sanitizer_flags()
494       append("-fsanitize=memory" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
495       if(LLVM_USE_SANITIZER STREQUAL "MemoryWithOrigins")
496         append("-fsanitize-memory-track-origins" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
497       endif()
498     elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
499       append_common_sanitizer_flags()
500       append("-fsanitize=undefined -fno-sanitize=vptr,function -fno-sanitize-recover=all"
501               CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
502     elseif (LLVM_USE_SANITIZER STREQUAL "Thread")
503       append_common_sanitizer_flags()
504       append("-fsanitize=thread" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
505     elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
506             LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
507       append_common_sanitizer_flags()
508       append("-fsanitize=address,undefined -fno-sanitize=vptr,function -fno-sanitize-recover=all"
509               CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
510     else()
511       message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}")
512     endif()
513   elseif(MSVC)
514     if (LLVM_USE_SANITIZER STREQUAL "Address")
515       append_common_sanitizer_flags()
516       append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
517     else()
518       message(FATAL_ERROR "This sanitizer not yet supported in the MSVC environment: ${LLVM_USE_SANITIZER}")
519     endif()
520   else()
521     message(FATAL_ERROR "LLVM_USE_SANITIZER is not supported on this platform.")
522   endif()
523   if (LLVM_USE_SANITIZE_COVERAGE)
524     append("-fsanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
525   endif()
526 endif()
527
528 # Turn on -gsplit-dwarf if requested
529 if(LLVM_USE_SPLIT_DWARF)
530   add_definitions("-gsplit-dwarf")
531 endif()
532
533 add_llvm_definitions( -D__STDC_CONSTANT_MACROS )
534 add_llvm_definitions( -D__STDC_FORMAT_MACROS )
535 add_llvm_definitions( -D__STDC_LIMIT_MACROS )
536
537 # clang doesn't print colored diagnostics when invoked from Ninja
538 if (UNIX AND
539     CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
540     CMAKE_GENERATOR STREQUAL "Ninja")
541   append("-fcolor-diagnostics" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
542 endif()
543
544 # Add flags for add_dead_strip().
545 # FIXME: With MSVS, consider compiling with /Gy and linking with /OPT:REF?
546 # But MinSizeRel seems to add that automatically, so maybe disable these
547 # flags instead if LLVM_NO_DEAD_STRIP is set.
548 if(NOT CYGWIN AND NOT WIN32)
549   if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND
550      NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
551     check_c_compiler_flag("-Werror -fno-function-sections" C_SUPPORTS_FNO_FUNCTION_SECTIONS)
552     if (C_SUPPORTS_FNO_FUNCTION_SECTIONS)
553       # Don't add -ffunction-section if it can be disabled with -fno-function-sections.
554       # Doing so will break sanitizers.
555       add_flag_if_supported("-ffunction-sections" FFUNCTION_SECTIONS)
556     endif()
557     add_flag_if_supported("-fdata-sections" FDATA_SECTIONS)
558   endif()
559 endif()
560
561 if(CYGWIN OR MINGW)
562   # Prune --out-implib from executables. It doesn't make sense even
563   # with --export-all-symbols.
564   string(REGEX REPLACE "-Wl,--out-implib,[^ ]+ " " "
565     CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE}")
566   string(REGEX REPLACE "-Wl,--out-implib,[^ ]+ " " "
567     CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE}")
568 endif()
569
570 if(MSVC)
571   # Remove flags here, for exceptions and RTTI.
572   # Each target property or source property should be responsible to control
573   # them.
574   # CL.EXE complains to override flags like "/GR /GR-".
575   string(REGEX REPLACE "(^| ) */EH[-cs]+ *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
576   string(REGEX REPLACE "(^| ) */GR-? *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
577 endif()
578
579 # Provide public options to globally control RTTI and EH
580 option(LLVM_ENABLE_EH "Enable Exception handling" OFF)
581 option(LLVM_ENABLE_RTTI "Enable run time type information" OFF)
582 if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI)
583   message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON")
584 endif()
585
586 # Plugin support
587 # FIXME: Make this configurable.
588 if(WIN32 OR CYGWIN)
589   if(BUILD_SHARED_LIBS)
590     set(LLVM_ENABLE_PLUGINS ON)
591   else()
592     set(LLVM_ENABLE_PLUGINS OFF)
593   endif()
594 else()
595   set(LLVM_ENABLE_PLUGINS ON)
596 endif()