• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_COMPILER_SPECIFIC_H_
6 #define BASE_COMPILER_SPECIFIC_H_
7 
8 #include "build/build_config.h"
9 
10 #if defined(COMPILER_MSVC) && !defined(__clang__)
11 #error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
12 #endif
13 
14 // This is a wrapper around `__has_cpp_attribute`, which can be used to test for
15 // the presence of an attribute. In case the compiler does not support this
16 // macro it will simply evaluate to 0.
17 //
18 // References:
19 // https://wg21.link/sd6#testing-for-the-presence-of-an-attribute-__has_cpp_attribute
20 // https://wg21.link/cpp.cond#:__has_cpp_attribute
21 #if defined(__has_cpp_attribute)
22 #define HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
23 #else
24 #define HAS_CPP_ATTRIBUTE(x) 0
25 #endif
26 
27 // A wrapper around `__has_attribute`, similar to HAS_CPP_ATTRIBUTE.
28 #if defined(__has_attribute)
29 #define HAS_ATTRIBUTE(x) __has_attribute(x)
30 #else
31 #define HAS_ATTRIBUTE(x) 0
32 #endif
33 
34 // A wrapper around `__has_builtin`, similar to HAS_CPP_ATTRIBUTE.
35 #if defined(__has_builtin)
36 #define HAS_BUILTIN(x) __has_builtin(x)
37 #else
38 #define HAS_BUILTIN(x) 0
39 #endif
40 
41 // Annotate a function indicating it should not be inlined.
42 // Use like:
43 //   NOINLINE void DoStuff() { ... }
44 #if defined(__clang__) && HAS_ATTRIBUTE(noinline)
45 #define NOINLINE [[clang::noinline]]
46 #elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(noinline)
47 #define NOINLINE __attribute__((noinline))
48 #elif defined(COMPILER_MSVC)
49 #define NOINLINE __declspec(noinline)
50 #else
51 #define NOINLINE
52 #endif
53 
54 // Annotate a function indicating it should not be optimized.
55 #if defined(__clang__) && HAS_ATTRIBUTE(optnone)
56 #define NOOPT [[clang::optnone]]
57 #elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(optimize)
58 #define NOOPT __attribute__((optimize(0)))
59 #else
60 #define NOOPT
61 #endif
62 
63 #if defined(__clang__) && defined(NDEBUG) && HAS_ATTRIBUTE(always_inline)
64 #define ALWAYS_INLINE [[clang::always_inline]] inline
65 #elif defined(COMPILER_GCC) && defined(NDEBUG) && HAS_ATTRIBUTE(always_inline)
66 #define ALWAYS_INLINE inline __attribute__((__always_inline__))
67 #elif defined(COMPILER_MSVC) && defined(NDEBUG)
68 #define ALWAYS_INLINE __forceinline
69 #else
70 #define ALWAYS_INLINE inline
71 #endif
72 
73 // Annotate a function indicating it should never be tail called. Useful to make
74 // sure callers of the annotated function are never omitted from call-stacks.
75 // To provide the complementary behavior (prevent the annotated function from
76 // being omitted) look at NOINLINE. Also note that this doesn't prevent code
77 // folding of multiple identical caller functions into a single signature. To
78 // prevent code folding, see NO_CODE_FOLDING() in base/debug/alias.h.
79 // Use like:
80 //   NOT_TAIL_CALLED void FooBar();
81 #if defined(__clang__) && HAS_ATTRIBUTE(not_tail_called)
82 #define NOT_TAIL_CALLED [[clang::not_tail_called]]
83 #else
84 #define NOT_TAIL_CALLED
85 #endif
86 
87 // Specify memory alignment for structs, classes, etc.
88 // Use like:
89 //   class ALIGNAS(16) MyClass { ... }
90 //   ALIGNAS(16) int array[4];
91 //
92 // In most places you can use the C++11 keyword "alignas", which is preferred.
93 //
94 // Historically, compilers had trouble mixing __attribute__((...)) syntax with
95 // alignas(...) syntax. However, at least Clang is very accepting nowadays. It
96 // may be that this macro can be removed entirely.
97 #if defined(__clang__)
98 #define ALIGNAS(byte_alignment) alignas(byte_alignment)
99 #elif defined(COMPILER_MSVC)
100 #define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
101 #elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(aligned)
102 #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
103 #endif
104 
105 // In case the compiler supports it NO_UNIQUE_ADDRESS evaluates to the C++20
106 // attribute [[no_unique_address]]. This allows annotating data members so that
107 // they need not have an address distinct from all other non-static data members
108 // of its class.
109 //
110 // References:
111 // * https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
112 // * https://wg21.link/dcl.attr.nouniqueaddr
113 #if defined(COMPILER_MSVC) && HAS_CPP_ATTRIBUTE(msvc::no_unique_address)
114 // Unfortunately MSVC ignores [[no_unique_address]] (see
115 // https://devblogs.microsoft.com/cppblog/msvc-cpp20-and-the-std-cpp20-switch/#msvc-extensions-and-abi),
116 // and clang-cl matches it for ABI compatibility reasons. We need to prefer
117 // [[msvc::no_unique_address]] when available if we actually want any effect.
118 #define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
119 #elif HAS_CPP_ATTRIBUTE(no_unique_address)
120 #define NO_UNIQUE_ADDRESS [[no_unique_address]]
121 #else
122 #define NO_UNIQUE_ADDRESS
123 #endif
124 
125 // Tells the compiler a function is using a printf-style format string.
126 // |format_param| is the one-based index of the format string parameter;
127 // |dots_param| is the one-based index of the "..." parameter.
128 // For v*printf functions (which take a va_list), pass 0 for dots_param.
129 // (This is undocumented but matches what the system C headers do.)
130 // For member functions, the implicit this parameter counts as index 1.
131 #if (defined(COMPILER_GCC) || defined(__clang__)) && HAS_ATTRIBUTE(format)
132 #define PRINTF_FORMAT(format_param, dots_param) \
133   __attribute__((format(printf, format_param, dots_param)))
134 #else
135 #define PRINTF_FORMAT(format_param, dots_param)
136 #endif
137 
138 // WPRINTF_FORMAT is the same, but for wide format strings.
139 // This doesn't appear to yet be implemented in any compiler.
140 // See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 .
141 #define WPRINTF_FORMAT(format_param, dots_param)
142 // If available, it would look like:
143 //   __attribute__((format(wprintf, format_param, dots_param)))
144 
145 // Sanitizers annotations.
146 #if HAS_ATTRIBUTE(no_sanitize)
147 #define NO_SANITIZE(what) __attribute__((no_sanitize(what)))
148 #endif
149 #if !defined(NO_SANITIZE)
150 #define NO_SANITIZE(what)
151 #endif
152 
153 // MemorySanitizer annotations.
154 #if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL)
155 #include <sanitizer/msan_interface.h>
156 
157 // Mark a memory region fully initialized.
158 // Use this to annotate code that deliberately reads uninitialized data, for
159 // example a GC scavenging root set pointers from the stack.
160 #define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
161 
162 // Check a memory region for initializedness, as if it was being used here.
163 // If any bits are uninitialized, crash with an MSan report.
164 // Use this to sanitize data which MSan won't be able to track, e.g. before
165 // passing data to another process via shared memory.
166 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
167   __msan_check_mem_is_initialized(p, size)
168 #else  // MEMORY_SANITIZER
169 #define MSAN_UNPOISON(p, size)
170 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
171 #endif  // MEMORY_SANITIZER
172 
173 // DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
174 #if !defined(DISABLE_CFI_PERF)
175 #if defined(__clang__) && defined(OFFICIAL_BUILD)
176 #define DISABLE_CFI_PERF NO_SANITIZE("cfi")
177 #else
178 #define DISABLE_CFI_PERF
179 #endif
180 #endif
181 
182 // DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks.
183 // Security Note: if you just need to allow calling of dlsym functions use
184 // DISABLE_CFI_DLSYM.
185 #if !defined(DISABLE_CFI_ICALL)
186 #if BUILDFLAG(IS_WIN)
187 // Windows also needs __declspec(guard(nocf)).
188 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
189 #else
190 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
191 #endif
192 #endif
193 #if !defined(DISABLE_CFI_ICALL)
194 #define DISABLE_CFI_ICALL
195 #endif
196 
197 // DISABLE_CFI_DLSYM -- applies DISABLE_CFI_ICALL on platforms where dlsym
198 // functions must be called. Retains CFI checks on platforms where loaded
199 // modules participate in CFI (e.g. Windows).
200 #if !defined(DISABLE_CFI_DLSYM)
201 #if BUILDFLAG(IS_WIN)
202 // Windows modules register functions when loaded so can be checked by CFG.
203 #define DISABLE_CFI_DLSYM
204 #else
205 #define DISABLE_CFI_DLSYM DISABLE_CFI_ICALL
206 #endif
207 #endif
208 #if !defined(DISABLE_CFI_DLSYM)
209 #define DISABLE_CFI_DLSYM
210 #endif
211 
212 // Macro useful for writing cross-platform function pointers.
213 #if !defined(CDECL)
214 #if BUILDFLAG(IS_WIN)
215 #define CDECL __cdecl
216 #else  // BUILDFLAG(IS_WIN)
217 #define CDECL
218 #endif  // BUILDFLAG(IS_WIN)
219 #endif  // !defined(CDECL)
220 
221 // Macro for hinting that an expression is likely to be false.
222 #if !defined(UNLIKELY)
223 #if defined(COMPILER_GCC) || defined(__clang__)
224 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
225 #else
226 #define UNLIKELY(x) (x)
227 #endif  // defined(COMPILER_GCC)
228 #endif  // !defined(UNLIKELY)
229 
230 #if !defined(LIKELY)
231 #if defined(COMPILER_GCC) || defined(__clang__)
232 #define LIKELY(x) __builtin_expect(!!(x), 1)
233 #else
234 #define LIKELY(x) (x)
235 #endif  // defined(COMPILER_GCC)
236 #endif  // !defined(LIKELY)
237 
238 // Compiler feature-detection.
239 // clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
240 #if defined(__has_feature)
241 #define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
242 #else
243 #define HAS_FEATURE(FEATURE) 0
244 #endif
245 
246 #if defined(COMPILER_GCC)
247 #define PRETTY_FUNCTION __PRETTY_FUNCTION__
248 #elif defined(COMPILER_MSVC)
249 #define PRETTY_FUNCTION __FUNCSIG__
250 #else
251 // See https://en.cppreference.com/w/c/language/function_definition#func
252 #define PRETTY_FUNCTION __func__
253 #endif
254 
255 #if !defined(CPU_ARM_NEON)
256 #if defined(__arm__)
257 #if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \
258     !defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID)
259 #error Chromium does not support middle endian architecture
260 #endif
261 #if defined(__ARM_NEON__)
262 #define CPU_ARM_NEON 1
263 #endif
264 #endif  // defined(__arm__)
265 #endif  // !defined(CPU_ARM_NEON)
266 
267 #if !defined(HAVE_MIPS_MSA_INTRINSICS)
268 #if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
269 #define HAVE_MIPS_MSA_INTRINSICS 1
270 #endif
271 #endif
272 
273 #if defined(__clang__) && HAS_ATTRIBUTE(uninitialized)
274 // Attribute "uninitialized" disables -ftrivial-auto-var-init=pattern for
275 // the specified variable.
276 // Library-wide alternative is
277 // 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in .gn
278 // file.
279 //
280 // See "init_stack_vars" in build/config/compiler/BUILD.gn and
281 // http://crbug.com/977230
282 // "init_stack_vars" is enabled for non-official builds and we hope to enable it
283 // in official build in 2020 as well. The flag writes fixed pattern into
284 // uninitialized parts of all local variables. In rare cases such initialization
285 // is undesirable and attribute can be used:
286 //   1. Degraded performance
287 // In most cases compiler is able to remove additional stores. E.g. if memory is
288 // never accessed or properly initialized later. Preserved stores mostly will
289 // not affect program performance. However if compiler failed on some
290 // performance critical code we can get a visible regression in a benchmark.
291 //   2. memset, memcpy calls
292 // Compiler may replaces some memory writes with memset or memcpy calls. This is
293 // not -ftrivial-auto-var-init specific, but it can happen more likely with the
294 // flag. It can be a problem if code is not linked with C run-time library.
295 //
296 // Note: The flag is security risk mitigation feature. So in future the
297 // attribute uses should be avoided when possible. However to enable this
298 // mitigation on the most of the code we need to be less strict now and minimize
299 // number of exceptions later. So if in doubt feel free to use attribute, but
300 // please document the problem for someone who is going to cleanup it later.
301 // E.g. platform, bot, benchmark or test name in patch description or next to
302 // the attribute.
303 #define STACK_UNINITIALIZED [[clang::uninitialized]]
304 #else
305 #define STACK_UNINITIALIZED
306 #endif
307 
308 // Attribute "no_stack_protector" disables -fstack-protector for the specified
309 // function.
310 //
311 // "stack_protector" is enabled on most POSIX builds. The flag adds a canary
312 // to each stack frame, which on function return is checked against a reference
313 // canary. If the canaries do not match, it's likely that a stack buffer
314 // overflow has occurred, so immediately crashing will prevent exploitation in
315 // many cases.
316 //
317 // In some cases it's desirable to remove this, e.g. on hot functions, or if
318 // we have purposely changed the reference canary.
319 #if defined(COMPILER_GCC) || defined(__clang__)
320 #if HAS_ATTRIBUTE(__no_stack_protector__)
321 #define NO_STACK_PROTECTOR __attribute__((__no_stack_protector__))
322 #else
323 #define NO_STACK_PROTECTOR __attribute__((__optimize__("-fno-stack-protector")))
324 #endif
325 #else
326 #define NO_STACK_PROTECTOR
327 #endif
328 
329 // The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
330 // to Clang which control what code paths are statically analyzed,
331 // and is meant to be used in conjunction with assert & assert-like functions.
332 // The expression is passed straight through if analysis isn't enabled.
333 //
334 // ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
335 // codepath and any other branching codepaths that might follow.
336 #if defined(__clang_analyzer__)
337 
AnalyzerNoReturn()338 inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
339   return false;
340 }
341 
AnalyzerAssumeTrue(bool arg)342 inline constexpr bool AnalyzerAssumeTrue(bool arg) {
343   // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
344   // false.
345   return arg || AnalyzerNoReturn();
346 }
347 
348 #define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
349 #define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
350 
351 #else  // !defined(__clang_analyzer__)
352 
353 #define ANALYZER_ASSUME_TRUE(arg) (arg)
354 #define ANALYZER_SKIP_THIS_PATH()
355 
356 #endif  // defined(__clang_analyzer__)
357 
358 // Use nomerge attribute to disable optimization of merging multiple same calls.
359 #if defined(__clang__) && HAS_ATTRIBUTE(nomerge)
360 #define NOMERGE [[clang::nomerge]]
361 #else
362 #define NOMERGE
363 #endif
364 
365 // Marks a type as being eligible for the "trivial" ABI despite having a
366 // non-trivial destructor or copy/move constructor. Such types can be relocated
367 // after construction by simply copying their memory, which makes them eligible
368 // to be passed in registers. The canonical example is std::unique_ptr.
369 //
370 // Use with caution; this has some subtle effects on constructor/destructor
371 // ordering and will be very incorrect if the type relies on its address
372 // remaining constant. When used as a function argument (by value), the value
373 // may be constructed in the caller's stack frame, passed in a register, and
374 // then used and destructed in the callee's stack frame. A similar thing can
375 // occur when values are returned.
376 //
377 // TRIVIAL_ABI is not needed for types which have a trivial destructor and
378 // copy/move constructors, such as base::TimeTicks and other POD.
379 //
380 // It is also not likely to be effective on types too large to be passed in one
381 // or two registers on typical target ABIs.
382 //
383 // See also:
384 //   https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
385 //   https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
386 #if defined(__clang__) && HAS_ATTRIBUTE(trivial_abi)
387 #define TRIVIAL_ABI [[clang::trivial_abi]]
388 #else
389 #define TRIVIAL_ABI
390 #endif
391 
392 // Detect whether a type is trivially relocatable, ie. a move-and-destroy
393 // sequence can replaced with memmove(). This can be used to optimise the
394 // implementation of containers. This is automatically true for types that were
395 // defined with TRIVIAL_ABI such as scoped_refptr.
396 //
397 // See also:
398 //   https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p1144r8.html
399 //   https://clang.llvm.org/docs/LanguageExtensions.html#:~:text=__is_trivially_relocatable
400 #if defined(__clang__) && HAS_BUILTIN(__is_trivially_relocatable)
401 #define IS_TRIVIALLY_RELOCATABLE(t) __is_trivially_relocatable(t)
402 #else
403 #define IS_TRIVIALLY_RELOCATABLE(t) false
404 #endif
405 
406 // Marks a member function as reinitializing a moved-from variable.
407 // See also
408 // https://clang.llvm.org/extra/clang-tidy/checks/bugprone-use-after-move.html#reinitialization
409 #if defined(__clang__) && HAS_ATTRIBUTE(reinitializes)
410 #define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
411 #else
412 #define REINITIALIZES_AFTER_MOVE
413 #endif
414 
415 // Requires constant initialization. See constinit in C++20. Allows to rely on a
416 // variable being initialized before execution, and not requiring a global
417 // constructor.
418 #if HAS_ATTRIBUTE(require_constant_initialization)
419 #define CONSTINIT __attribute__((require_constant_initialization))
420 #endif
421 #if !defined(CONSTINIT)
422 #define CONSTINIT
423 #endif
424 
425 #if defined(__clang__)
426 #define GSL_OWNER [[gsl::Owner]]
427 #define GSL_POINTER [[gsl::Pointer]]
428 #else
429 #define GSL_OWNER
430 #define GSL_POINTER
431 #endif
432 
433 // Adds the "logically_const" tag to a symbol's mangled name. The "Mutable
434 // Constants" check [1] detects instances of constants that aren't in .rodata,
435 // e.g. due to a missing `const`. Using this tag suppresses the check for this
436 // symbol, allowing it to live outside .rodata without a warning.
437 //
438 // [1]:
439 // https://crsrc.org/c/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
440 #if defined(COMPILER_GCC) || defined(__clang__)
441 #define LOGICALLY_CONST [[gnu::abi_tag("logically_const")]]
442 #else
443 #define LOGICALLY_CONST
444 #endif
445 
446 // preserve_most clang's calling convention. Reduces register pressure for the
447 // caller and as such can be used for cold calls. Support for the
448 // "preserve_most" attribute is limited:
449 // - 32-bit platforms do not implement it,
450 // - component builds fail because _dl_runtime_resolve() clobbers registers,
451 // - there are crashes on arm64 on Windows (https://crbug.com/v8/14065), which
452 //   can hopefully be fixed in the future.
453 // Additionally, the initial implementation in clang <= 16 overwrote the return
454 // register(s) in the epilogue of a preserve_most function, so we only use
455 // preserve_most in clang >= 17 (see https://reviews.llvm.org/D143425).
456 // See https://clang.llvm.org/docs/AttributeReference.html#preserve-most for
457 // more details.
458 #if defined(ARCH_CPU_64_BITS) &&                       \
459     !(BUILDFLAG(IS_WIN) && defined(ARCH_CPU_ARM64)) && \
460     !defined(COMPONENT_BUILD) && defined(__clang__) && \
461     __clang_major__ >= 17 && HAS_ATTRIBUTE(preserve_most)
462 #define PRESERVE_MOST __attribute__((preserve_most))
463 #else
464 #define PRESERVE_MOST
465 #endif
466 
467 #endif  // BASE_COMPILER_SPECIFIC_H_
468