blob: 89755cc0aad17bbec77126a50844b02e4c4b8701 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]f1ea2fa2008-08-21 22:26:064
5#ifndef BASE_COMPILER_SPECIFIC_H_
6#define BASE_COMPILER_SPECIFIC_H_
7
8#include "build/build_config.h"
9
Nico Weberfb053cc2020-03-03 13:33:0510#if defined(COMPILER_MSVC) && !defined(__clang__)
Nico Weber59791812019-07-27 04:02:1111#error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
12#endif
13
Jan Wilken Dörrief8d479d2020-11-23 12:21:1314// 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
Peter Kasting64c67dd2022-05-12 18:11:5127// 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
Jann Horn9e4b48552021-03-04 14:34:2734// 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
[email protected]2149cc622012-02-14 01:12:1241// Annotate a function indicating it should not be inlined.
42// Use like:
43// NOINLINE void DoStuff() { ... }
Peter Kastingf541f7782023-03-10 23:44:4644#if defined(__clang__) && HAS_ATTRIBUTE(noinline)
45#define NOINLINE [[clang::noinline]]
46#elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(noinline)
[email protected]2149cc622012-02-14 01:12:1247#define NOINLINE __attribute__((noinline))
48#elif defined(COMPILER_MSVC)
49#define NOINLINE __declspec(noinline)
50#else
[email protected]50795a02011-05-09 20:11:0151#define NOINLINE
[email protected]f50595102010-10-08 16:20:3252#endif
53
Jose Dapena Paz7cc1b1d42023-11-08 18:37:2854// 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
Peter Kastingf541f7782023-03-10 23:44:4663#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)
palmer58184a8282016-11-08 19:15:3966#define ALWAYS_INLINE inline __attribute__((__always_inline__))
Ivan Krasin9c098a0d2018-08-05 03:57:5767#elif defined(COMPILER_MSVC) && defined(NDEBUG)
palmer58184a8282016-11-08 19:15:3968#define ALWAYS_INLINE __forceinline
69#else
70#define ALWAYS_INLINE inline
71#endif
72
Olivier Li19d89252020-05-13 17:57:5573// 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
Bruce Dawson7915efd2021-01-27 18:07:5878// prevent code folding, see NO_CODE_FOLDING() in base/debug/alias.h.
Olivier Li19d89252020-05-13 17:57:5579// Use like:
Daniel Chengddf1b222023-02-02 02:41:5280// NOT_TAIL_CALLED void FooBar();
Peter Kasting64c67dd2022-05-12 18:11:5181#if defined(__clang__) && HAS_ATTRIBUTE(not_tail_called)
Peter Kastingf541f7782023-03-10 23:44:4682#define NOT_TAIL_CALLED [[clang::not_tail_called]]
Olivier Li19d89252020-05-13 17:57:5583#else
84#define NOT_TAIL_CALLED
85#endif
86
[email protected]cd924d62012-02-23 17:52:2087// Specify memory alignment for structs, classes, etc.
88// Use like:
89// class ALIGNAS(16) MyClass { ... }
90// ALIGNAS(16) int array[4];
brettw16289b3e2017-06-13 21:58:4091//
92// In most places you can use the C++11 keyword "alignas", which is preferred.
93//
Peter Kastingf541f7782023-03-10 23:44:4694// 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)
[email protected]cd924d62012-02-23 17:52:20100#define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
Peter Kastingf541f7782023-03-10 23:44:46101#elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(aligned)
[email protected]cd924d62012-02-23 17:52:20102#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
103#endif
104
Jan Wilken Dörrief8d479d2020-11-23 12:21:13105// 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
Peter Kasting8bc046d22023-11-14 00:38:03113#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.
Helmut Januschka13cd38b2023-12-22 03:31:47118#define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
Peter Kasting8bc046d22023-11-14 00:38:03119#elif HAS_CPP_ATTRIBUTE(no_unique_address)
Jan Wilken Dörrief8d479d2020-11-23 12:21:13120#define NO_UNIQUE_ADDRESS [[no_unique_address]]
121#else
122#define NO_UNIQUE_ADDRESS
123#endif
124
Peter Kastingf541f7782023-03-10 23:44:46125// Tells the compiler a function is using a printf-style format string.
[email protected]34b2b002009-11-20 06:53:28126// |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.)
Nico Weberfc7c8dd2019-02-28 21:28:44130// For member functions, the implicit this parameter counts as index 1.
Peter Kastingf541f7782023-03-10 23:44:46131#if (defined(COMPILER_GCC) || defined(__clang__)) && HAS_ATTRIBUTE(format)
[email protected]34b2b002009-11-20 06:53:28132#define PRINTF_FORMAT(format_param, dots_param) \
Vitaly Buka2b790762019-12-20 21:11:48133 __attribute__((format(printf, format_param, dots_param)))
[email protected]f50595102010-10-08 16:20:32134#else
135#define PRINTF_FORMAT(format_param, dots_param)
136#endif
[email protected]34b2b002009-11-20 06:53:28137
138// WPRINTF_FORMAT is the same, but for wide format strings.
[email protected]f50595102010-10-08 16:20:32139// This doesn't appear to yet be implemented in any compiler.
[email protected]34b2b002009-11-20 06:53:28140// 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
etienneb4e9250a2016-11-18 18:47:53145// Sanitizers annotations.
Peter Kasting64c67dd2022-05-12 18:11:51146#if HAS_ATTRIBUTE(no_sanitize)
etienneb4e9250a2016-11-18 18:47:53147#define NO_SANITIZE(what) __attribute__((no_sanitize(what)))
148#endif
etienneb4e9250a2016-11-18 18:47:53149#if !defined(NO_SANITIZE)
150#define NO_SANITIZE(what)
151#endif
152
[email protected]75086be2013-03-20 21:18:22153// MemorySanitizer annotations.
Xiaohan Wang38e4ebb2022-01-19 06:57:43154#if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL)
[email protected]eb82dfb2014-02-03 19:51:17155#include <sanitizer/msan_interface.h>
[email protected]75086be2013-03-20 21:18:22156
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.
Vitaly Buka2b790762019-12-20 21:11:48160#define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
thestig1a42b4072015-03-16 22:36:55161
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) \
Vitaly Buka2b790762019-12-20 21:11:48167 __msan_check_mem_is_initialized(p, size)
[email protected]75086be2013-03-20 21:18:22168#else // MEMORY_SANITIZER
thestig1a42b4072015-03-16 22:36:55169#define MSAN_UNPOISON(p, size)
170#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
[email protected]75086be2013-03-20 21:18:22171#endif // MEMORY_SANITIZER
172
krasin825ce482016-08-27 11:01:11173// DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
174#if !defined(DISABLE_CFI_PERF)
krasin40f7c782016-09-22 19:04:27175#if defined(__clang__) && defined(OFFICIAL_BUILD)
Peter Kastingf541f7782023-03-10 23:44:46176#define DISABLE_CFI_PERF NO_SANITIZE("cfi")
krasin825ce482016-08-27 11:01:11177#else
178#define DISABLE_CFI_PERF
179#endif
180#endif
181
Will Harris9a033b02020-07-11 01:26:54182// DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks.
Alex Gough36579802022-07-25 20:20:46183// Security Note: if you just need to allow calling of dlsym functions use
184// DISABLE_CFI_DLSYM.
Will Harris9a033b02020-07-11 01:26:54185#if !defined(DISABLE_CFI_ICALL)
Xiaohan Wang38e4ebb2022-01-19 06:57:43186#if BUILDFLAG(IS_WIN)
Will Harris9a033b02020-07-11 01:26:54187// 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
Alex Gough36579802022-07-25 20:20:46197// 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
[email protected]5a8d4ce2013-12-18 17:42:27212// Macro useful for writing cross-platform function pointers.
213#if !defined(CDECL)
Xiaohan Wang38e4ebb2022-01-19 06:57:43214#if BUILDFLAG(IS_WIN)
[email protected]5a8d4ce2013-12-18 17:42:27215#define CDECL __cdecl
Xiaohan Wang38e4ebb2022-01-19 06:57:43216#else // BUILDFLAG(IS_WIN)
[email protected]5a8d4ce2013-12-18 17:42:27217#define CDECL
Xiaohan Wang38e4ebb2022-01-19 06:57:43218#endif // BUILDFLAG(IS_WIN)
[email protected]5a8d4ce2013-12-18 17:42:27219#endif // !defined(CDECL)
220
[email protected]2bc0c6992014-02-13 16:11:04221// Macro for hinting that an expression is likely to be false.
222#if !defined(UNLIKELY)
Vladimir Levin6b777712017-09-09 00:12:05223#if defined(COMPILER_GCC) || defined(__clang__)
[email protected]2bc0c6992014-02-13 16:11:04224#define UNLIKELY(x) __builtin_expect(!!(x), 0)
225#else
226#define UNLIKELY(x) (x)
227#endif // defined(COMPILER_GCC)
228#endif // !defined(UNLIKELY)
229
palmer58184a8282016-11-08 19:15:39230#if !defined(LIKELY)
Vladimir Levin6b777712017-09-09 00:12:05231#if defined(COMPILER_GCC) || defined(__clang__)
Chris Palmerad4cb83f2016-11-18 20:02:25232#define LIKELY(x) __builtin_expect(!!(x), 1)
palmer58184a8282016-11-08 19:15:39233#else
234#define LIKELY(x) (x)
235#endif // defined(COMPILER_GCC)
236#endif // !defined(LIKELY)
237
jfbd81c1ce2016-04-05 20:50:35238// Compiler feature-detection.
jfba8dc9dd82016-04-06 20:20:31239// 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
jfbd81c1ce2016-04-05 20:50:35244#endif
245
Alex Clarke23c6cf72018-11-21 13:22:27246#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
Henrique Ferreiro6daf71db2019-04-03 13:12:42255#if !defined(CPU_ARM_NEON)
Matt Reynolds96ad2252023-06-05 20:01:48256#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__)
Henrique Ferreiro6daf71db2019-04-03 13:12:42262#define CPU_ARM_NEON 1
263#endif
Matt Reynolds96ad2252023-06-05 20:01:48264#endif // defined(__arm__)
Henrique Ferreiro6daf71db2019-04-03 13:12:42265#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
Peter Kasting64c67dd2022-05-12 18:11:51273#if defined(__clang__) && HAS_ATTRIBUTE(uninitialized)
Vitaly Buka2b790762019-12-20 21:11:48274// 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.
Peter Kastingf541f7782023-03-10 23:44:46303#define STACK_UNINITIALIZED [[clang::uninitialized]]
Vitaly Buka2b790762019-12-20 21:11:48304#else
305#define STACK_UNINITIALIZED
306#endif
307
Matthew Dentonbb0b03e2021-07-22 16:18:13308// 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__)
Peter Kasting64c67dd2022-05-12 18:11:51320#if HAS_ATTRIBUTE(__no_stack_protector__)
Stephan Hartmann4b456e72021-08-10 03:25:02321#define NO_STACK_PROTECTOR __attribute__((__no_stack_protector__))
Peter Kasting64c67dd2022-05-12 18:11:51322#else
Stephan Hartmann4b456e72021-08-10 03:25:02323#define NO_STACK_PROTECTOR __attribute__((__optimize__("-fno-stack-protector")))
324#endif
Matthew Dentonbb0b03e2021-07-22 16:18:13325#else
326#define NO_STACK_PROTECTOR
327#endif
328
Hans Wennborg12aea3e2020-04-14 15:29:00329// 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
338inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
339 return false;
340}
341
342inline constexpr bool AnalyzerAssumeTrue(bool arg) {
343 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
344 // false.
345 return arg || AnalyzerNoReturn();
346}
347
George Burgess IVa09d235d2020-04-17 13:32:50348#define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
349#define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
Hans Wennborg12aea3e2020-04-14 15:29:00350
351#else // !defined(__clang_analyzer__)
352
353#define ANALYZER_ASSUME_TRUE(arg) (arg)
354#define ANALYZER_SKIP_THIS_PATH()
Hans Wennborg12aea3e2020-04-14 15:29:00355
356#endif // defined(__clang_analyzer__)
357
Zequan Wu9909f142021-02-10 03:26:00358// Use nomerge attribute to disable optimization of merging multiple same calls.
Peter Kasting64c67dd2022-05-12 18:11:51359#if defined(__clang__) && HAS_ATTRIBUTE(nomerge)
Zequan Wu9909f142021-02-10 03:26:00360#define NOMERGE [[clang::nomerge]]
361#else
362#define NOMERGE
363#endif
364
Jeremy Roman810d98d2021-04-06 16:46:07365// 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
Peter Kasting64c67dd2022-05-12 18:11:51386#if defined(__clang__) && HAS_ATTRIBUTE(trivial_abi)
Jeremy Roman810d98d2021-04-06 16:46:07387#define TRIVIAL_ABI [[clang::trivial_abi]]
388#else
389#define TRIVIAL_ABI
390#endif
391
Adam Ricefb288d02023-10-13 08:36:21392// 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
Lukasz Anforowicz3be38fbb2021-04-14 20:29:29406// Marks a member function as reinitializing a moved-from variable.
407// See also
Lei Zhangdd1e6fe2024-02-01 08:51:35408// https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#reinitialization
Peter Kasting64c67dd2022-05-12 18:11:51409#if defined(__clang__) && HAS_ATTRIBUTE(reinitializes)
Lukasz Anforowicz3be38fbb2021-04-14 20:29:29410#define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
411#else
412#define REINITIALIZES_AFTER_MOVE
413#endif
414
danakjceb17022022-02-11 23:52:01415#if defined(__clang__)
Daniel Cheng8ac305b2022-02-17 00:05:11416#define GSL_OWNER [[gsl::Owner]]
danakjceb17022022-02-11 23:52:01417#define GSL_POINTER [[gsl::Pointer]]
418#else
Jose Dapena Paz1183b142022-02-18 16:28:25419#define GSL_OWNER
danakjceb17022022-02-11 23:52:01420#define GSL_POINTER
421#endif
422
Daniel Chengf2c05382022-09-16 02:51:42423// Adds the "logically_const" tag to a symbol's mangled name. The "Mutable
424// Constants" check [1] detects instances of constants that aren't in .rodata,
425// e.g. due to a missing `const`. Using this tag suppresses the check for this
426// symbol, allowing it to live outside .rodata without a warning.
427//
428// [1]:
429// https://crsrc.org/c/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
Anthony Vallee-Dubois9dbbbda32022-08-26 01:25:31430#if defined(COMPILER_GCC) || defined(__clang__)
431#define LOGICALLY_CONST [[gnu::abi_tag("logically_const")]]
432#else
433#define LOGICALLY_CONST
434#endif
435
Anton Bikineev4d23e842023-06-14 10:46:19436// preserve_most clang's calling convention. Reduces register pressure for the
437// caller and as such can be used for cold calls. Support for the
438// "preserve_most" attribute is limited:
439// - 32-bit platforms do not implement it,
440// - component builds fail because _dl_runtime_resolve() clobbers registers,
441// - there are crashes on arm64 on Windows (https://crbug.com/v8/14065), which
442// can hopefully be fixed in the future.
443// Additionally, the initial implementation in clang <= 16 overwrote the return
444// register(s) in the epilogue of a preserve_most function, so we only use
445// preserve_most in clang >= 17 (see https://reviews.llvm.org/D143425).
kxxt120045d2024-02-13 04:22:39446// Clang only supports preserve_most on X86-64 and AArch64 for now.
Anton Bikineev4d23e842023-06-14 10:46:19447// See https://clang.llvm.org/docs/AttributeReference.html#preserve-most for
448// more details.
kxxt120045d2024-02-13 04:22:39449#if (defined(ARCH_CPU_ARM64) || defined(ARCH_CPU_X86_64)) && \
450 !(BUILDFLAG(IS_WIN) && defined(ARCH_CPU_ARM64)) && \
451 !defined(COMPONENT_BUILD) && defined(__clang__) && \
Anton Bikineev4d23e842023-06-14 10:46:19452 __clang_major__ >= 17 && HAS_ATTRIBUTE(preserve_most)
453#define PRESERVE_MOST __attribute__((preserve_most))
454#else
455#define PRESERVE_MOST
456#endif
457
danakjc077a30e2024-03-22 19:25:36458// Mark parameters or return types as having a lifetime attached to the class.
459//
460// When used to mark a method's pointer/reference parameter, the compiler is
461// made aware that it will be stored internally in the class and the pointee
462// must outlive the class. Typically used on constructor arguments. It should
463// appear to the right of the parameter's variable name.
464//
465// Example:
466// ```
467// struct S {
468// S(int* p LIFETIME_BOUND) : ptr_(p) {}
469//
470// int* ptr_;
471// };
472// ```
473//
474// When used on a method with a return value, the compiler is made aware that
475// the returned type is/has a pointer to the internals of the class, and must
476// not outlive the class object. It should appear after any method qualifiers.
477//
478// Example:
479// ```
480// struct S {
481// int* GetPtr() const LIFETIME_BOUND { return i_; };
482//
483// int i_;
484// };
485// ```
486//
487// This allows the compiler to warn in (a limited set of) cases where the
488// pointer would otherwise be left dangling, especially in cases where the
489// pointee would be a destroyed temporary.
490//
491// Docs: https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
492#if defined(__clang__)
493#define LIFETIME_BOUND [[clang::lifetimebound]]
494#else
495#define LIFETIME_BOUND
496#endif
497
498// Mark a function as pure, meaning that it does not have side effects, meaning
499// that it does not write anything external to the function's local variables
500// and return value.
501//
502// WARNING: If this attribute is mis-used it will result in UB and
503// miscompilation, as the optimizator may fold multiple calls into one and
504// reorder them inappropriately. This shouldn't appear outside of key vocabulary
505// types. It allows callers to work with the vocab type directly, and call its
506// methods without having to worry about caching things into local variables in
507// hot code.
508//
509// This attribute must not appear on functions that make use of function
510// pointers, virtual methods, or methods of templates (including operators like
511// comparison), as the "pure" function can not know what those functions do and
512// can not guarantee there will never be sideeffects.
513#if defined(COMPILER_GCC) || defined(__clang__)
514#define PURE_FUNCTION [[gnu::pure]]
515#else
516#define PURE_FUNCTION
517#endif
518
danakj59f56d92024-02-01 15:31:35519// Functions should be marked with UNSAFE_BUFFER_USAGE when they lead to
520// out-of-bounds bugs when called with incorrect inputs.
521//
522// Ideally such functions should be paired with a safer version that works with
523// safe primitives like `base::span`. Otherwise, another safer coding pattern
524// should be documented along side the use of `UNSAFE_BUFFER_USAGE`.
525//
526// All functions marked with UNSAFE_BUFFER_USAGE should come with a safety
527// comment that explains the requirements of the function to prevent any chance
528// of an out-of-bounds bug. For example:
529// ```
530// // Function to do things between `input` and `end`.
531// //
532// // # Safety
533// // The `input` must point to an array with size at least 5. The `end` must
534// // point within the same allocation of `input` and not come before `input`.
535// ```
536#if defined(__clang__) && HAS_ATTRIBUTE(unsafe_buffer_usage)
537#define UNSAFE_BUFFER_USAGE [[clang::unsafe_buffer_usage]]
538#else
539#define UNSAFE_BUFFER_USAGE
540#endif
541
542// UNSAFE_BUFFERS() wraps code that violates the -Wunsafe-buffer-usage warning,
543// such as:
544// - pointer arithmetic,
545// - pointer subscripting, and
546// - calls to functions annotated with UNSAFE_BUFFER_USAGE.
547//
548// ** USE OF THIS MACRO SHOULD BE VERY RARE.** Reviewers should push back when
549// it is not strictly necessary. Prefer to use `base::span` instead of pointers,
550// or other safer coding patterns (like std containers) that avoid the
551// opportunity for out-of-bounds bugs to creep into the code. Any use of
552// UNSAFE_BUFFERS() can lead to a critical security bug if any assumptions are
553// wrong, or ever become wrong in the future.
554//
555// The macro should be used to wrap the minimum necessary code, to make it clear
556// what is unsafe, and prevent accidentally opting extra things out of the
557// warning.
558//
559// All usage of UNSAFE_BUFFERS() should come with a `// SAFETY: ...` comment
560// that explains how we have guaranteed (ideally directly above, with conditions
561// or CHECKs) that the pointer usage can never go out-of-bounds, or that the
562// requirements of the UNSAFE_BUFFER_USAGE function are met. If the safety
563// explanation requires cooperation of code that is not fully encapsulated close
564// to the UNSAFE_BUFFERS() usage, it should be rejected and replaced with safer
565// coding patterns or stronger guarantees.
danakj59f56d92024-02-01 15:31:35566#if defined(__clang__)
567// clang-format off
568// Formatting is off so that we can put each _Pragma on its own line, as
569// recommended by the gcc docs.
570#define UNSAFE_BUFFERS(...) \
571 _Pragma("clang unsafe_buffer_usage begin") \
572 __VA_ARGS__ \
573 _Pragma("clang unsafe_buffer_usage end")
574// clang-format on
danakj59f56d92024-02-01 15:31:35575#else
576#define UNSAFE_BUFFERS(...) __VA_ARGS__
danakj59f56d92024-02-01 15:31:35577#endif
578
danakjc077a30e2024-03-22 19:25:36579// Defines a condition for a function to be checked at compile time if the
580// parameter's value is known at compile time. If the condition is failed, the
581// function is omitted from the overload set resolution, much like `requires`.
582//
583// If the parameter is a runtime value, then the condition is unable to be
584// checked and the function will be omitted from the overload set resolution.
585// This ensures the function can only be called with values known at compile
586// time. This is a clang extension.
587//
588// Example:
589// ```
590// void f(int a) ENABLE_IF_ATTR(a > 0) {}
591// f(1); // Ok.
592// f(0); // Error: no valid f() found.
593// ```
594//
595// The `ENABLE_IF_ATTR` annotation is preferred over `consteval` with a check
596// that breaks compile because metaprogramming does not observe such checks. So
597// with `consteval`, the function looks callable to concepts/type_traits but is
598// not and will fail to compile even though it reports it's usable. Whereas
599// `ENABLE_IF_ATTR` interacts correctly with metaprogramming. This is especially
600// painful for constructors. See also
601// https://github.com/chromium/subspace/issues/266.
602#if defined(__clang__)
603#define ENABLE_IF_ATTR(cond, msg) __attribute__((enable_if(cond, msg)))
604#else
605#define ENABLE_IF_ATTR(cond, msg)
606#endif
607
[email protected]dd9afc0b2008-11-21 23:58:09608#endif // BASE_COMPILER_SPECIFIC_H_