[M68k] always use movem for register spills (#106715)
[llvm-project.git] / clang / docs / LanguageExtensions.rst
blobdd7513ceaa4e4bf74c3cd13509e463f418987950
1 =========================
2 Clang Language Extensions
3 =========================
5 .. contents::
6    :local:
7    :depth: 1
9 .. toctree::
10    :hidden:
12    ObjectiveCLiterals
13    BlockLanguageSpec
14    Block-ABI-Apple
15    AutomaticReferenceCounting
16    PointerAuthentication
17    MatrixTypes
19 Introduction
20 ============
22 This document describes the language extensions provided by Clang.  In addition
23 to the language extensions listed here, Clang aims to support a broad range of
24 GCC extensions.  Please see the `GCC manual
25 <https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
26 these extensions.
28 .. _langext-feature_check:
30 Feature Checking Macros
31 =======================
33 Language extensions can be very useful, but only if you know you can depend on
34 them.  In order to allow fine-grain features checks, we support three builtin
35 function-like macros.  This allows you to directly test for a feature in your
36 code without having to resort to something like autoconf or fragile "compiler
37 version checks".
39 ``__has_builtin``
40 -----------------
42 This function-like macro takes a single identifier argument that is the name of
43 a builtin function, a builtin pseudo-function (taking one or more type
44 arguments), or a builtin template.
45 It evaluates to 1 if the builtin is supported or 0 if not.
46 It can be used like this:
48 .. code-block:: c++
50   #ifndef __has_builtin         // Optional of course.
51     #define __has_builtin(x) 0  // Compatibility with non-clang compilers.
52   #endif
54   ...
55   #if __has_builtin(__builtin_trap)
56     __builtin_trap();
57   #else
58     abort();
59   #endif
60   ...
62 .. note::
64   Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin
65   pseudo-functions.
67   ``__has_builtin`` should not be used to detect support for a builtin macro;
68   use ``#ifdef`` instead.
70 ``__has_constexpr_builtin``
71 ---------------------------
73 This function-like macro takes a single identifier argument that is the name of
74 a builtin function, a builtin pseudo-function (taking one or more type
75 arguments), or a builtin template.
76 It evaluates to 1 if the builtin is supported and can be constant evaluated or
77 0 if not. It can be used for writing conditionally constexpr code like this:
79 .. code-block:: c++
81   #ifndef __has_constexpr_builtin         // Optional of course.
82     #define __has_constexpr_builtin(x) 0  // Compatibility with non-clang compilers.
83   #endif
85   ...
86   #if __has_constexpr_builtin(__builtin_fmax)
87     constexpr
88   #endif
89     double money_fee(double amount) {
90         return __builtin_fmax(amount * 0.03, 10.0);
91     }
92   ...
94 For example, ``__has_constexpr_builtin`` is used in libcxx's implementation of
95 the ``<cmath>`` header file to conditionally make a function constexpr whenever
96 the constant evaluation of the corresponding builtin (for example,
97 ``std::fmax`` calls ``__builtin_fmax``) is supported in Clang.
99 .. _langext-__has_feature-__has_extension:
101 ``__has_feature`` and ``__has_extension``
102 -----------------------------------------
104 These function-like macros take a single identifier argument that is the name
105 of a feature.  ``__has_feature`` evaluates to 1 if the feature is both
106 supported by Clang and standardized in the current language standard or 0 if
107 not (but see :ref:`below <langext-has-feature-back-compat>`), while
108 ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
109 current language (either as a language extension or a standard language
110 feature) or 0 if not.  They can be used like this:
112 .. code-block:: c++
114   #ifndef __has_feature         // Optional of course.
115     #define __has_feature(x) 0  // Compatibility with non-clang compilers.
116   #endif
117   #ifndef __has_extension
118     #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
119   #endif
121   ...
122   #if __has_feature(cxx_rvalue_references)
123   // This code will only be compiled with the -std=c++11 and -std=gnu++11
124   // options, because rvalue references are only standardized in C++11.
125   #endif
127   #if __has_extension(cxx_rvalue_references)
128   // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
129   // and -std=gnu++98 options, because rvalue references are supported as a
130   // language extension in C++98.
131   #endif
133 .. _langext-has-feature-back-compat:
135 For backward compatibility, ``__has_feature`` can also be used to test
136 for support for non-standardized features, i.e. features not prefixed ``c_``,
137 ``cxx_`` or ``objc_``.
139 Another use of ``__has_feature`` is to check for compiler features not related
140 to the language standard, such as e.g. :doc:`AddressSanitizer
141 <AddressSanitizer>`.
143 If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
144 to ``__has_feature``.
146 The feature tag is described along with the language feature below.
148 The feature name or extension name can also be specified with a preceding and
149 following ``__`` (double underscore) to avoid interference from a macro with
150 the same name.  For instance, ``__cxx_rvalue_references__`` can be used instead
151 of ``cxx_rvalue_references``.
153 ``__has_cpp_attribute``
154 -----------------------
156 This function-like macro is available in C++20 by default, and is provided as an
157 extension in earlier language standards. It takes a single argument that is the
158 name of a double-square-bracket-style attribute. The argument can either be a
159 single identifier or a scoped identifier. If the attribute is supported, a
160 nonzero value is returned. If the attribute is a standards-based attribute, this
161 macro returns a nonzero value based on the year and month in which the attribute
162 was voted into the working draft. See `WG21 SD-6
163 <https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
164 for the list of values returned for standards-based attributes. If the attribute
165 is not supported by the current compilation target, this macro evaluates to 0.
166 It can be used like this:
168 .. code-block:: c++
170   #ifndef __has_cpp_attribute         // For backwards compatibility
171     #define __has_cpp_attribute(x) 0
172   #endif
174   ...
175   #if __has_cpp_attribute(clang::fallthrough)
176   #define FALLTHROUGH [[clang::fallthrough]]
177   #else
178   #define FALLTHROUGH
179   #endif
180   ...
182 The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
183 the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
184 of these namespaces can be specified with a preceding and following ``__``
185 (double underscore) to avoid interference from a macro with the same name. For
186 instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
188 ``__has_c_attribute``
189 ---------------------
191 This function-like macro takes a single argument that is the name of an
192 attribute exposed with the double square-bracket syntax in C mode. The argument
193 can either be a single identifier or a scoped identifier. If the attribute is
194 supported, a nonzero value is returned. If the attribute is not supported by the
195 current compilation target, this macro evaluates to 0. It can be used like this:
197 .. code-block:: c
199   #ifndef __has_c_attribute         // Optional of course.
200     #define __has_c_attribute(x) 0  // Compatibility with non-clang compilers.
201   #endif
203   ...
204   #if __has_c_attribute(fallthrough)
205     #define FALLTHROUGH [[fallthrough]]
206   #else
207     #define FALLTHROUGH
208   #endif
209   ...
211 The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
212 the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
213 of these namespaces can be specified with a preceding and following ``__``
214 (double underscore) to avoid interference from a macro with the same name. For
215 instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
217 ``__has_attribute``
218 -------------------
220 This function-like macro takes a single identifier argument that is the name of
221 a GNU-style attribute.  It evaluates to 1 if the attribute is supported by the
222 current compilation target, or 0 if not.  It can be used like this:
224 .. code-block:: c++
226   #ifndef __has_attribute         // Optional of course.
227     #define __has_attribute(x) 0  // Compatibility with non-clang compilers.
228   #endif
230   ...
231   #if __has_attribute(always_inline)
232   #define ALWAYS_INLINE __attribute__((always_inline))
233   #else
234   #define ALWAYS_INLINE
235   #endif
236   ...
238 The attribute name can also be specified with a preceding and following ``__``
239 (double underscore) to avoid interference from a macro with the same name.  For
240 instance, ``__always_inline__`` can be used instead of ``always_inline``.
243 ``__has_declspec_attribute``
244 ----------------------------
246 This function-like macro takes a single identifier argument that is the name of
247 an attribute implemented as a Microsoft-style ``__declspec`` attribute.  It
248 evaluates to 1 if the attribute is supported by the current compilation target,
249 or 0 if not.  It can be used like this:
251 .. code-block:: c++
253   #ifndef __has_declspec_attribute         // Optional of course.
254     #define __has_declspec_attribute(x) 0  // Compatibility with non-clang compilers.
255   #endif
257   ...
258   #if __has_declspec_attribute(dllexport)
259   #define DLLEXPORT __declspec(dllexport)
260   #else
261   #define DLLEXPORT
262   #endif
263   ...
265 The attribute name can also be specified with a preceding and following ``__``
266 (double underscore) to avoid interference from a macro with the same name.  For
267 instance, ``__dllexport__`` can be used instead of ``dllexport``.
269 ``__is_identifier``
270 -------------------
272 This function-like macro takes a single identifier argument that might be either
273 a reserved word or a regular identifier. It evaluates to 1 if the argument is just
274 a regular identifier and not a reserved word, in the sense that it can then be
275 used as the name of a user-defined function or variable. Otherwise it evaluates
276 to 0.  It can be used like this:
278 .. code-block:: c++
280   ...
281   #ifdef __is_identifier          // Compatibility with non-clang compilers.
282     #if __is_identifier(__wchar_t)
283       typedef wchar_t __wchar_t;
284     #endif
285   #endif
287   __wchar_t WideCharacter;
288   ...
290 Include File Checking Macros
291 ============================
293 Not all developments systems have the same include files.  The
294 :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
295 you to check for the existence of an include file before doing a possibly
296 failing ``#include`` directive.  Include file checking macros must be used
297 as expressions in ``#if`` or ``#elif`` preprocessing directives.
299 .. _langext-__has_include:
301 ``__has_include``
302 -----------------
304 This function-like macro takes a single file name string argument that is the
305 name of an include file.  It evaluates to 1 if the file can be found using the
306 include paths, or 0 otherwise:
308 .. code-block:: c++
310   // Note the two possible file name string formats.
311   #if __has_include("myinclude.h") && __has_include(<stdint.h>)
312   # include "myinclude.h"
313   #endif
315 To test for this feature, use ``#if defined(__has_include)``:
317 .. code-block:: c++
319   // To avoid problem with non-clang compilers not having this macro.
320   #if defined(__has_include)
321   #if __has_include("myinclude.h")
322   # include "myinclude.h"
323   #endif
324   #endif
326 .. _langext-__has_include_next:
328 ``__has_include_next``
329 ----------------------
331 This function-like macro takes a single file name string argument that is the
332 name of an include file.  It is like ``__has_include`` except that it looks for
333 the second instance of the given file found in the include paths.  It evaluates
334 to 1 if the second instance of the file can be found using the include paths,
335 or 0 otherwise:
337 .. code-block:: c++
339   // Note the two possible file name string formats.
340   #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
341   # include_next "myinclude.h"
342   #endif
344   // To avoid problem with non-clang compilers not having this macro.
345   #if defined(__has_include_next)
346   #if __has_include_next("myinclude.h")
347   # include_next "myinclude.h"
348   #endif
349   #endif
351 Note that ``__has_include_next``, like the GNU extension ``#include_next``
352 directive, is intended for use in headers only, and will issue a warning if
353 used in the top-level compilation file.  A warning will also be issued if an
354 absolute path is used in the file argument.
356 ``__has_warning``
357 -----------------
359 This function-like macro takes a string literal that represents a command line
360 option for a warning and returns true if that is a valid warning option.
362 .. code-block:: c++
364   #if __has_warning("-Wformat")
365   ...
366   #endif
368 .. _languageextensions-builtin-macros:
370 Builtin Macros
371 ==============
373 ``__BASE_FILE__``
374   Defined to a string that contains the name of the main input file passed to
375   Clang.
377 ``__FILE_NAME__``
378   Clang-specific extension that functions similar to ``__FILE__`` but only
379   renders the last path component (the filename) instead of an invocation
380   dependent full path to that file.
382 ``__COUNTER__``
383   Defined to an integer value that starts at zero and is incremented each time
384   the ``__COUNTER__`` macro is expanded.
386 ``__INCLUDE_LEVEL__``
387   Defined to an integral value that is the include depth of the file currently
388   being translated.  For the main file, this value is zero.
390 ``__TIMESTAMP__``
391   Defined to the date and time of the last modification of the current source
392   file.
394 ``__clang__``
395   Defined when compiling with Clang
397 ``__clang_major__``
398   Defined to the major marketing version number of Clang (e.g., the 2 in
399   2.0.1).  Note that marketing version numbers should not be used to check for
400   language features, as different vendors use different numbering schemes.
401   Instead, use the :ref:`langext-feature_check`.
403 ``__clang_minor__``
404   Defined to the minor version number of Clang (e.g., the 0 in 2.0.1).  Note
405   that marketing version numbers should not be used to check for language
406   features, as different vendors use different numbering schemes.  Instead, use
407   the :ref:`langext-feature_check`.
409 ``__clang_patchlevel__``
410   Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
412 ``__clang_version__``
413   Defined to a string that captures the Clang marketing version, including the
414   Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
416 ``__clang_literal_encoding__``
417   Defined to a narrow string literal that represents the current encoding of
418   narrow string literals, e.g., ``"hello"``. This macro typically expands to
419   "UTF-8" (but may change in the future if the
420   ``-fexec-charset="Encoding-Name"`` option is implemented.)
422 ``__clang_wide_literal_encoding__``
423   Defined to a narrow string literal that represents the current encoding of
424   wide string literals, e.g., ``L"hello"``. This macro typically expands to
425   "UTF-16" or "UTF-32" (but may change in the future if the
426   ``-fwide-exec-charset="Encoding-Name"`` option is implemented.)
428 Implementation-defined keywords
429 ===============================
431 __datasizeof
432 ------------
434 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of the
435 type ignoring tail padding.
437 _BitInt, _ExtInt
438 ----------------
440 Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
441 and in C++. This type was previously implemented in Clang with the same
442 semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
443 favor of the standard type.
445 Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
446 so this type should not yet be used in interfaces that require ABI stability.
448 C keywords supported in all language modes
449 ------------------------------------------
451 Clang supports ``_Alignas``, ``_Alignof``, ``_Atomic``, ``_Complex``,
452 ``_Generic``, ``_Imaginary``, ``_Noreturn``, ``_Static_assert``,
453 ``_Thread_local``, and ``_Float16`` in all language modes with the C semantics.
455 __alignof, __alignof__
456 ----------------------
458 ``__alignof`` and ``__alignof__`` return, in contrast to ``_Alignof`` and
459 ``alignof``, the preferred alignment of a type. This may be larger than the
460 required alignment for improved performance.
462 __extension__
463 -------------
465 ``__extension__`` suppresses extension diagnostics in the statement it is
466 prepended to.
468 __auto_type
469 -----------
471 ``__auto_type`` behaves the same as ``auto`` in C++11 but is available in all
472 language modes.
474 __imag, __imag__
475 ----------------
477 ``__imag`` and ``__imag__`` can be used to get the imaginary part of a complex
478 value.
480 __real, __real__
481 ----------------
483 ``__real`` and ``__real__`` can be used to get the real part of a complex value.
485 __asm, __asm__
486 --------------
488 ``__asm`` and ``__asm__`` are alternate spellings for ``asm``, but available in
489 all language modes.
491 __complex, __complex__
492 ----------------------
494 ``__complex`` and ``__complex__`` are alternate spellings for ``_Complex``.
496 __const, __const__, __volatile, __volatile__, __restrict, __restrict__
497 ----------------------------------------------------------------------
499 These are alternate spellings for their non-underscore counterparts, but are
500 available in all langauge modes.
502 __decltype
503 ----------
505 ``__decltype`` is an alternate spelling for ``decltype``, but is also available
506 in C++ modes before C++11.
508 __inline, __inline__
509 --------------------
511 ``__inline`` and ``__inline__`` are alternate spellings for ``inline``, but are
512 available in all language modes.
514 __nullptr
515 ---------
517 ``__nullptr`` is an alternate spelling for ``nullptr``. It is available in all C and C++ language modes.
519 __signed, __signed__
520 --------------------
522 ``__signed`` and ``__signed__`` are alternate spellings for ``signed``.
523 ``__unsigned`` and ``__unsigned__`` are **not** supported.
525 __typeof, __typeof__, __typeof_unqual, __typeof_unqual__
526 --------------------------------------------------------
528 ``__typeof`` and ``__typeof__`` are alternate spellings for ``typeof``, but are
529 available in all langauge modes. These spellings result in the operand,
530 retaining all qualifiers.
532 ``__typeof_unqual`` and ``__typeof_unqual__`` are alternate spellings for the
533 C23 ``typeof_unqual`` type specifier, but are available in all language modes.
534 These spellings result in the type of the operand, stripping all qualifiers.
536 __char16_t, __char32_t
537 ----------------------
539 ``__char16_t`` and ``__char32_t`` are alternate spellings for ``char16_t`` and
540 ``char32_t`` respectively, but are also available in C++ modes before C++11.
541 They are only supported in C++. ``__char8_t`` is not available.
544   FIXME: This should list all the keyword extensions
546 .. _langext-vectors:
548 Vectors and Extended Vectors
549 ============================
551 Supports the GCC, OpenCL, AltiVec, NEON and SVE vector extensions.
553 OpenCL vector types are created using the ``ext_vector_type`` attribute.  It
554 supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL.  An example
557 .. code-block:: c++
559   typedef float float4 __attribute__((ext_vector_type(4)));
560   typedef float float2 __attribute__((ext_vector_type(2)));
562   float4 foo(float2 a, float2 b) {
563     float4 c;
564     c.xz = a;
565     c.yw = b;
566     return c;
567   }
569 Query for this feature with ``__has_attribute(ext_vector_type)``.
571 Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
572 and functions.  For example:
574 .. code-block:: c++
576   vector float foo(vector int a) {
577     vector int b;
578     b = vec_add(a, a) + a;
579     return (vector float)b;
580   }
582 NEON vector types are created using ``neon_vector_type`` and
583 ``neon_polyvector_type`` attributes.  For example:
585 .. code-block:: c++
587   typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
588   typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
590   int8x8_t foo(int8x8_t a) {
591     int8x8_t v;
592     v = a;
593     return v;
594   }
596 GCC vector types are created using the ``vector_size(N)`` attribute.  The
597 argument ``N`` specifies the number of bytes that will be allocated for an
598 object of this type.  The size has to be multiple of the size of the vector
599 element type. For example:
601 .. code-block:: c++
603   // OK: This declares a vector type with four 'int' elements
604   typedef int int4 __attribute__((vector_size(4 * sizeof(int))));
606   // ERROR: '11' is not a multiple of sizeof(int)
607   typedef int int_impossible __attribute__((vector_size(11)));
609   int4 foo(int4 a) {
610     int4 v;
611     v = a;
612     return v;
613   }
616 Boolean Vectors
617 ---------------
619 Clang also supports the ext_vector_type attribute with boolean element types in
620 C and C++.  For example:
622 .. code-block:: c++
624   // legal for Clang, error for GCC:
625   typedef bool bool4 __attribute__((ext_vector_type(4)));
626   // Objects of bool4 type hold 8 bits, sizeof(bool4) == 1
628   bool4 foo(bool4 a) {
629     bool4 v;
630     v = a;
631     return v;
632   }
634 Boolean vectors are a Clang extension of the ext vector type.  Boolean vectors
635 are intended, though not guaranteed, to map to vector mask registers.  The size
636 parameter of a boolean vector type is the number of bits in the vector.  The
637 boolean vector is dense and each bit in the boolean vector is one vector
638 element.
640 The semantics of boolean vectors borrows from C bit-fields with the following
641 differences:
643 * Distinct boolean vectors are always distinct memory objects (there is no
644   packing).
645 * Only the operators `?:`, `!`, `~`, `|`, `&`, `^` and comparison are allowed on
646   boolean vectors.
647 * Casting a scalar bool value to a boolean vector type means broadcasting the
648   scalar value onto all lanes (same as general ext_vector_type).
649 * It is not possible to access or swizzle elements of a boolean vector
650   (different than general ext_vector_type).
652 The size and alignment are both the number of bits rounded up to the next power
653 of two, but the alignment is at most the maximum vector alignment of the
654 target.
657 Vector Literals
658 ---------------
660 Vector literals can be used to create vectors from a set of scalars, or
661 vectors.  Either parentheses or braces form can be used.  In the parentheses
662 form the number of literal values specified must be one, i.e. referring to a
663 scalar value, or must match the size of the vector type being created.  If a
664 single scalar literal value is specified, the scalar literal value will be
665 replicated to all the components of the vector type.  In the brackets form any
666 number of literals can be specified.  For example:
668 .. code-block:: c++
670   typedef int v4si __attribute__((__vector_size__(16)));
671   typedef float float4 __attribute__((ext_vector_type(4)));
672   typedef float float2 __attribute__((ext_vector_type(2)));
674   v4si vsi = (v4si){1, 2, 3, 4};
675   float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
676   vector int vi1 = (vector int)(1);    // vi1 will be (1, 1, 1, 1).
677   vector int vi2 = (vector int){1};    // vi2 will be (1, 0, 0, 0).
678   vector int vi3 = (vector int)(1, 2); // error
679   vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
680   vector int vi5 = (vector int)(1, 2, 3, 4);
681   float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
683 Vector Operations
684 -----------------
686 The table below shows the support for each operation by vector extension.  A
687 dash indicates that an operation is not accepted according to a corresponding
688 specification.
690 ============================== ======= ======= ============= ======= =====
691          Operator              OpenCL  AltiVec     GCC        NEON    SVE
692 ============================== ======= ======= ============= ======= =====
693 []                               yes     yes       yes         yes    yes
694 unary operators +, --            yes     yes       yes         yes    yes
695 ++, -- --                        yes     yes       yes         no     no
696 +,--,*,/,%                       yes     yes       yes         yes    yes
697 bitwise operators &,|,^,~        yes     yes       yes         yes    yes
698 >>,<<                            yes     yes       yes         yes    yes
699 !, &&, ||                        yes     --        yes         yes    yes
700 ==, !=, >, <, >=, <=             yes     yes       yes         yes    yes
701 =                                yes     yes       yes         yes    yes
702 ?: [#]_                          yes     --        yes         yes    yes
703 sizeof                           yes     yes       yes         yes    yes [#]_
704 C-style cast                     yes     yes       yes         no     no
705 reinterpret_cast                 yes     no        yes         no     no
706 static_cast                      yes     no        yes         no     no
707 const_cast                       no      no        no          no     no
708 address &v[i]                    no      no        no [#]_     no     no
709 ============================== ======= ======= ============= ======= =====
711 See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
713 .. [#] ternary operator(?:) has different behaviors depending on condition
714   operand's vector type. If the condition is a GNU vector (i.e. __vector_size__),
715   a NEON vector or an SVE vector, it's only available in C++ and uses normal bool
716   conversions (that is, != 0).
717   If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.
718   And it selects base on signedness of the condition operands (OpenCL v1.1 s6.3.9).
719 .. [#] sizeof can only be used on vector length specific SVE types.
720 .. [#] Clang does not allow the address of an element to be taken while GCC
721    allows this. This is intentional for vectors with a boolean element type and
722    not implemented otherwise.
724 Vector Builtins
725 ---------------
727 **Note: The implementation of vector builtins is work-in-progress and incomplete.**
729 In addition to the operators mentioned above, Clang provides a set of builtins
730 to perform additional operations on certain scalar and vector types.
732 Let ``T`` be one of the following types:
734 * an integer type (as in C23 6.2.5p22), but excluding enumerated types and ``bool``
735 * the standard floating types float or double
736 * a half-precision floating point type, if one is supported on the target
737 * a vector type.
739 For scalar types, consider the operation applied to a vector with a single element.
741 *Vector Size*
742 To determine the number of elements in a vector, use ``__builtin_vectorelements()``.
743 For fixed-sized vectors, e.g., defined via ``__attribute__((vector_size(N)))`` or ARM
744 NEON's vector types (e.g., ``uint16x8_t``), this returns the constant number of
745 elements at compile-time. For scalable vectors, e.g., SVE or RISC-V V, the number of
746 elements is not known at compile-time and is determined at runtime. This builtin can
747 be used, e.g., to increment the loop-counter in vector-type agnostic loops.
749 *Elementwise Builtins*
751 Each builtin returns a vector equivalent to applying the specified operation
752 elementwise to the input.
754 Unless specified otherwise operation(±0) = Â±0 and operation(±infinity) = Â±infinity
756 The integer elementwise intrinsics, including ``__builtin_elementwise_popcount``,
757 ``__builtin_elementwise_bitreverse``, ``__builtin_elementwise_add_sat``,
758 ``__builtin_elementwise_sub_sat`` can be called in a ``constexpr`` context.
760 No implicit promotion of integer types takes place. The mixing of integer types
761 of different sizes and signs is forbidden in binary and ternary builtins.
763 ============================================== ====================================================================== =========================================
764          Name                                   Operation                                                             Supported element types
765 ============================================== ====================================================================== =========================================
766  T __builtin_elementwise_abs(T x)               return the absolute value of a number x; the absolute value of         signed integer and floating point types
767                                                 the most negative integer remains the most negative integer
768  T __builtin_elementwise_fma(T x, T y, T z)     fused multiply add, (x * y) +  z.                                      floating point types
769  T __builtin_elementwise_ceil(T x)              return the smallest integral value greater than or equal to x          floating point types
770  T __builtin_elementwise_sin(T x)               return the sine of x interpreted as an angle in radians                floating point types
771  T __builtin_elementwise_cos(T x)               return the cosine of x interpreted as an angle in radians              floating point types
772  T __builtin_elementwise_tan(T x)               return the tangent of x interpreted as an angle in radians             floating point types
773  T __builtin_elementwise_asin(T x)              return the arcsine of x interpreted as an angle in radians             floating point types
774  T __builtin_elementwise_acos(T x)              return the arccosine of x interpreted as an angle in radians           floating point types
775  T __builtin_elementwise_atan(T x)              return the arctangent of x interpreted as an angle in radians          floating point types
776  T __builtin_elementwise_atan2(T y, T x)        return the arctangent of y/x                                           floating point types
777  T __builtin_elementwise_sinh(T x)              return the hyperbolic sine of angle x in radians                       floating point types
778  T __builtin_elementwise_cosh(T x)              return the hyperbolic cosine of angle x in radians                     floating point types
779  T __builtin_elementwise_tanh(T x)              return the hyperbolic tangent of angle x in radians                    floating point types
780  T __builtin_elementwise_floor(T x)             return the largest integral value less than or equal to x              floating point types
781  T __builtin_elementwise_log(T x)               return the natural logarithm of x                                      floating point types
782  T __builtin_elementwise_log2(T x)              return the base 2 logarithm of x                                       floating point types
783  T __builtin_elementwise_log10(T x)             return the base 10 logarithm of x                                      floating point types
784  T __builtin_elementwise_popcount(T x)          return the number of 1 bits in x                                       integer types
785  T __builtin_elementwise_pow(T x, T y)          return x raised to the power of y                                      floating point types
786  T __builtin_elementwise_bitreverse(T x)        return the integer represented after reversing the bits of x           integer types
787  T __builtin_elementwise_exp(T x)               returns the base-e exponential, e^x, of the specified value            floating point types
788  T __builtin_elementwise_exp2(T x)              returns the base-2 exponential, 2^x, of the specified value            floating point types
790  T __builtin_elementwise_sqrt(T x)              return the square root of a floating-point number                      floating point types
791  T __builtin_elementwise_roundeven(T x)         round x to the nearest integer value in floating point format,         floating point types
792                                                 rounding halfway cases to even (that is, to the nearest value
793                                                 that is an even integer), regardless of the current rounding
794                                                 direction.
795  T __builtin_elementwise_round(T x)             round x to the nearest  integer value in floating point format,        floating point types
796                                                 rounding halfway cases away from zero, regardless of the
797                                                 current rounding direction. May raise floating-point
798                                                 exceptions.
799  T __builtin_elementwise_trunc(T x)             return the integral value nearest to but no larger in                  floating point types
800                                                 magnitude than x
802   T __builtin_elementwise_nearbyint(T x)        round x to the nearest  integer value in floating point format,        floating point types
803                                                 rounding according to the current rounding direction.
804                                                 May not raise the inexact floating-point exception. This is
805                                                 treated the same as ``__builtin_elementwise_rint`` unless
806                                                 :ref:`FENV_ACCESS is enabled <floating-point-environment>`.
808  T __builtin_elementwise_rint(T x)              round x to the nearest  integer value in floating point format,        floating point types
809                                                 rounding according to the current rounding
810                                                 direction. May raise floating-point exceptions. This is treated
811                                                 the same as ``__builtin_elementwise_nearbyint`` unless
812                                                 :ref:`FENV_ACCESS is enabled <floating-point-environment>`.
814  T __builtin_elementwise_canonicalize(T x)      return the platform specific canonical encoding                        floating point types
815                                                 of a floating-point number
816  T __builtin_elementwise_copysign(T x, T y)     return the magnitude of x with the sign of y.                          floating point types
817  T __builtin_elementwise_fmod(T x, T y)         return The floating-point remainder of (x/y) whose sign                floating point types
818                                                 matches the sign of x.
819  T __builtin_elementwise_max(T x, T y)          return x or y, whichever is larger                                     integer and floating point types
820  T __builtin_elementwise_min(T x, T y)          return x or y, whichever is smaller                                    integer and floating point types
821  T __builtin_elementwise_add_sat(T x, T y)      return the sum of x and y, clamped to the range of                     integer types
822                                                 representable values for the signed/unsigned integer type.
823  T __builtin_elementwise_sub_sat(T x, T y)      return the difference of x and y, clamped to the range of              integer types
824                                                 representable values for the signed/unsigned integer type.
825  T __builtin_elementwise_maximum(T x, T y)      return x or y, whichever is larger. Follows IEEE 754-2019              floating point types
826                                                 semantics, see `LangRef
827                                                 <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_
828                                                 for the comparison.
829  T __builtin_elementwise_minimum(T x, T y)      return x or y, whichever is smaller. Follows IEEE 754-2019             floating point types
830                                                 semantics, see `LangRef
831                                                 <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_
832                                                 for the comparison.
833 ============================================== ====================================================================== =========================================
836 *Reduction Builtins*
838 Each builtin returns a scalar equivalent to applying the specified
839 operation(x, y) as recursive even-odd pairwise reduction to all vector
840 elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping
841 even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with
842 ``i in [0, Number of elements / 2)``. If the numbers of elements is not a
843 power of 2, the vector is widened with neutral elements for the reduction
844 at the end to the next power of 2.
846 These reductions support both fixed-sized and scalable vector types.
848 The integer reduction intrinsics, including ``__builtin_reduce_max``,
849 ``__builtin_reduce_min``, ``__builtin_reduce_add``, ``__builtin_reduce_mul``,
850 ``__builtin_reduce_and``, ``__builtin_reduce_or``, and ``__builtin_reduce_xor``,
851 can be called in a ``constexpr`` context.
853 Example:
855 .. code-block:: c++
857     __builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0])
858                                            = (e3 + e2) + (e1 + e0)
861 Let ``VT`` be a vector type and ``ET`` the element type of ``VT``.
863 ======================================= ====================================================================== ==================================
864          Name                            Operation                                                              Supported element types
865 ======================================= ====================================================================== ==================================
866  ET __builtin_reduce_max(VT a)           return the largest element of the vector. The floating point result    integer and floating point types
867                                          will always be a number unless all elements of the vector are NaN.
868  ET __builtin_reduce_min(VT a)           return the smallest element of the vector. The floating point result   integer and floating point types
869                                          will always be a number unless all elements of the vector are NaN.
870  ET __builtin_reduce_add(VT a)           \+                                                                     integer types
871  ET __builtin_reduce_mul(VT a)           \*                                                                     integer types
872  ET __builtin_reduce_and(VT a)           &                                                                      integer types
873  ET __builtin_reduce_or(VT a)            \|                                                                     integer types
874  ET __builtin_reduce_xor(VT a)           ^                                                                      integer types
875  ET __builtin_reduce_maximum(VT a)       return the largest element of the vector. Follows IEEE 754-2019        floating point types
876                                          semantics, see `LangRef
877                                          <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_
878                                          for the comparison.
879  ET __builtin_reduce_minimum(VT a)       return the smallest element of the vector. Follows IEEE 754-2019       floating point types
880                                          semantics, see `LangRef
881                                          <http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_
882                                          for the comparison.
883 ======================================= ====================================================================== ==================================
885 Matrix Types
886 ============
888 Clang provides an extension for matrix types, which is currently being
889 implemented. See :ref:`the draft specification <matrixtypes>` for more details.
891 For example, the code below uses the matrix types extension to multiply two 4x4
892 float matrices and add the result to a third 4x4 matrix.
894 .. code-block:: c++
896   typedef float m4x4_t __attribute__((matrix_type(4, 4)));
898   m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) {
899     return a + b * c;
900   }
902 The matrix type extension also supports operations on a matrix and a scalar.
904 .. code-block:: c++
906   typedef float m4x4_t __attribute__((matrix_type(4, 4)));
908   m4x4_t f(m4x4_t a) {
909     return (a + 23) * 12;
910   }
912 The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix.
914 .. code-block:: c++
916   typedef float m4x4_t __attribute__((matrix_type(4, 4)));
918   m4x4_t f(m4x4_t a) {
919     a = a / 3.0;
920     return a;
921   }
923 The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices
924 and on a matrix and a scalar, provided their types are consistent.
926 .. code-block:: c++
928   typedef float m4x4_t __attribute__((matrix_type(4, 4)));
930   m4x4_t f(m4x4_t a, m4x4_t b) {
931     a += b;
932     a -= b;
933     a *= b;
934     a += 23;
935     a -= 12;
936     return a;
937   }
939 The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed.
941 .. code-block:: c++
943   typedef int ix5x5 __attribute__((matrix_type(5, 5)));
944   typedef float fx5x5 __attribute__((matrix_type(5, 5)));
946   fx5x5 f1(ix5x5 i, fx5x5 f) {
947     return (fx5x5) i;
948   }
951   template <typename X>
952   using matrix_4_4 = X __attribute__((matrix_type(4, 4)));
954   void f2() {
955     matrix_5_5<double> d;
956     matrix_5_5<int> i;
957     i = (matrix_5_5<int>)d;
958     i = static_cast<matrix_5_5<int>>(d);
959   }
961 Half-Precision Floating Point
962 =============================
964 Clang supports three half-precision (16-bit) floating point types:
965 ``__fp16``, ``_Float16`` and ``__bf16``. These types are supported
966 in all language modes, but their support differs between targets.
967 A target is said to have "native support" for a type if the target
968 processor offers instructions for directly performing basic arithmetic
969 on that type.  In the absence of native support, a type can still be
970 supported if the compiler can emulate arithmetic on the type by promoting
971 to ``float``; see below for more information on this emulation.
973 * ``__fp16`` is supported on all targets. The special semantics of this
974   type mean that no arithmetic is ever performed directly on ``__fp16`` values;
975   see below.
977 * ``_Float16`` is supported on the following targets:
979   * 32-bit ARM (natively on some architecture versions)
980   * 64-bit ARM (AArch64) (natively on ARMv8.2a and above)
981   * AMDGPU (natively)
982   * NVPTX (natively)
983   * SPIR (natively)
984   * X86 (if SSE2 is available; natively if AVX512-FP16 is also available)
985   * RISC-V (natively if Zfh or Zhinx is available)
987 * ``__bf16`` is supported on the following targets (currently never natively):
989   * 32-bit ARM
990   * 64-bit ARM (AArch64)
991   * RISC-V
992   * X86 (when SSE2 is available)
994 (For X86, SSE2 is available on 64-bit and all recent 32-bit processors.)
996 ``__fp16`` and ``_Float16`` both use the binary16 format from IEEE
997 754-2008, which provides a 5-bit exponent and an 11-bit significand
998 (counting the implicit leading 1). ``__bf16`` uses the `bfloat16
999 <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format>`_ format,
1000 which provides an 8-bit exponent and an 8-bit significand; this is the same
1001 exponent range as `float`, just with greatly reduced precision.
1003 ``_Float16`` and ``__bf16`` follow the usual rules for arithmetic
1004 floating-point types. Most importantly, this means that arithmetic operations
1005 on operands of these types are formally performed in the type and produce
1006 values of the type. ``__fp16`` does not follow those rules: most operations
1007 immediately promote operands of type ``__fp16`` to ``float``, and so
1008 arithmetic operations are defined to be performed in ``float`` and so result in
1009 a value of type ``float`` (unless further promoted because of other operands).
1010 See below for more information on the exact specifications of these types.
1012 When compiling arithmetic on ``_Float16`` and ``__bf16`` for a target without
1013 native support, Clang will perform the arithmetic in ``float``, inserting
1014 extensions and truncations as necessary. This can be done in a way that
1015 exactly matches the operation-by-operation behavior of native support,
1016 but that can require many extra truncations and extensions. By default,
1017 when emulating ``_Float16`` and ``__bf16`` arithmetic using ``float``, Clang
1018 does not truncate intermediate operands back to their true type unless the
1019 operand is the result of an explicit cast or assignment. This is generally
1020 much faster but can generate different results from strict operation-by-operation
1021 emulation. Usually the results are more precise. This is permitted by the
1022 C and C++ standards under the rules for excess precision in intermediate operands;
1023 see the discussion of evaluation formats in the C standard and [expr.pre] in
1024 the C++ standard.
1026 The use of excess precision can be independently controlled for these two
1027 types with the ``-ffloat16-excess-precision=`` and
1028 ``-fbfloat16-excess-precision=`` options. Valid values include:
1030 * ``none``: meaning to perform strict operation-by-operation emulation
1031 * ``standard``: meaning that excess precision is permitted under the rules
1032   described in the standard, i.e. never across explicit casts or statements
1033 * ``fast``: meaning that excess precision is permitted whenever the
1034   optimizer sees an opportunity to avoid truncations; currently this has no
1035   effect beyond ``standard``
1037 The ``_Float16`` type is an interchange floating type specified in
1038 ISO/IEC TS 18661-3:2015 ("Floating-point extensions for C"). It will
1039 be supported on more targets as they define ABIs for it.
1041 The ``__bf16`` type is a non-standard extension, but it generally follows
1042 the rules for arithmetic interchange floating types from ISO/IEC TS
1043 18661-3:2015. In previous versions of Clang, it was a storage-only type
1044 that forbade arithmetic operations. It will be supported on more targets
1045 as they define ABIs for it.
1047 The ``__fp16`` type was originally an ARM extension and is specified
1048 by the `ARM C Language Extensions <https://github.com/ARM-software/acle/releases>`_.
1049 Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``,
1050 not the ARM alternative format. Operators that expect arithmetic operands
1051 immediately promote ``__fp16`` operands to ``float``.
1053 It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
1054 as it has been defined by the C standards committee and has behavior that is
1055 more familiar to most programmers.
1057 Because ``__fp16`` operands are always immediately promoted to ``float``, the
1058 common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
1059 arithmetic conversions is ``float``.
1061 A literal can be given ``_Float16`` type using the suffix ``f16``. For example,
1062 ``3.14f16``.
1064 Because default argument promotion only applies to the standard floating-point
1065 types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
1066 or untyped arguments. As a consequence, some caution must be taken when using
1067 certain library facilities with ``_Float16``; for example, there is no ``printf`` format
1068 specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
1069 ``double`` when passed to ``printf``, so the programmer must explicitly cast it to
1070 ``double`` before using it with an ``%f`` or similar specifier.
1072 Messages on ``deprecated`` and ``unavailable`` Attributes
1073 =========================================================
1075 An optional string message can be added to the ``deprecated`` and
1076 ``unavailable`` attributes.  For example:
1078 .. code-block:: c++
1080   void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
1082 If the deprecated or unavailable declaration is used, the message will be
1083 incorporated into the appropriate diagnostic:
1085 .. code-block:: none
1087   harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
1088         [-Wdeprecated-declarations]
1089     explode();
1090     ^
1092 Query for this feature with
1093 ``__has_extension(attribute_deprecated_with_message)`` and
1094 ``__has_extension(attribute_unavailable_with_message)``.
1096 Attributes on Enumerators
1097 =========================
1099 Clang allows attributes to be written on individual enumerators.  This allows
1100 enumerators to be deprecated, made unavailable, etc.  The attribute must appear
1101 after the enumerator name and before any initializer, like so:
1103 .. code-block:: c++
1105   enum OperationMode {
1106     OM_Invalid,
1107     OM_Normal,
1108     OM_Terrified __attribute__((deprecated)),
1109     OM_AbortOnError __attribute__((deprecated)) = 4
1110   };
1112 Attributes on the ``enum`` declaration do not apply to individual enumerators.
1114 Query for this feature with ``__has_extension(enumerator_attributes)``.
1116 C++11 Attributes on using-declarations
1117 ======================================
1119 Clang allows C++-style ``[[]]`` attributes to be written on using-declarations.
1120 For instance:
1122 .. code-block:: c++
1124   [[clang::using_if_exists]] using foo::bar;
1125   using foo::baz [[clang::using_if_exists]];
1127 You can test for support for this extension with
1128 ``__has_extension(cxx_attributes_on_using_declarations)``.
1130 'User-Specified' System Frameworks
1131 ==================================
1133 Clang provides a mechanism by which frameworks can be built in such a way that
1134 they will always be treated as being "system frameworks", even if they are not
1135 present in a system framework directory.  This can be useful to system
1136 framework developers who want to be able to test building other applications
1137 with development builds of their framework, including the manner in which the
1138 compiler changes warning behavior for system headers.
1140 Framework developers can opt-in to this mechanism by creating a
1141 "``.system_framework``" file at the top-level of their framework.  That is, the
1142 framework should have contents like:
1144 .. code-block:: none
1146   .../TestFramework.framework
1147   .../TestFramework.framework/.system_framework
1148   .../TestFramework.framework/Headers
1149   .../TestFramework.framework/Headers/TestFramework.h
1150   ...
1152 Clang will treat the presence of this file as an indicator that the framework
1153 should be treated as a system framework, regardless of how it was found in the
1154 framework search path.  For consistency, we recommend that such files never be
1155 included in installed versions of the framework.
1157 Checks for Standard Language Features
1158 =====================================
1160 The ``__has_feature`` macro can be used to query if certain standard language
1161 features are enabled.  The ``__has_extension`` macro can be used to query if
1162 language features are available as an extension when compiling for a standard
1163 which does not provide them.  The features which can be tested are listed here.
1165 Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
1166 These are macros with names of the form ``__cpp_<feature_name>``, and are
1167 intended to be a portable way to query the supported features of the compiler.
1168 See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
1169 information on the version of SD-6 supported by each Clang release, and the
1170 macros provided by that revision of the recommendations.
1172 C++98
1173 -----
1175 The features listed below are part of the C++98 standard.  These features are
1176 enabled by default when compiling C++ code.
1178 C++ exceptions
1179 ^^^^^^^^^^^^^^
1181 Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
1182 enabled.  For example, compiling code with ``-fno-exceptions`` disables C++
1183 exceptions.
1185 C++ RTTI
1186 ^^^^^^^^
1188 Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled.  For
1189 example, compiling code with ``-fno-rtti`` disables the use of RTTI.
1191 C++11
1192 -----
1194 The features listed below are part of the C++11 standard.  As a result, all
1195 these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
1196 when compiling C++ code.
1198 C++11 SFINAE includes access control
1199 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1201 Use ``__has_feature(cxx_access_control_sfinae)`` or
1202 ``__has_extension(cxx_access_control_sfinae)`` to determine whether
1203 access-control errors (e.g., calling a private constructor) are considered to
1204 be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
1205 <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
1207 C++11 alias templates
1208 ^^^^^^^^^^^^^^^^^^^^^
1210 Use ``__has_feature(cxx_alias_templates)`` or
1211 ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
1212 alias declarations and alias templates is enabled.
1214 C++11 alignment specifiers
1215 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1217 Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
1218 determine if support for alignment specifiers using ``alignas`` is enabled.
1220 Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
1221 determine if support for the ``alignof`` keyword is enabled.
1223 C++11 attributes
1224 ^^^^^^^^^^^^^^^^
1226 Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
1227 determine if support for attribute parsing with C++11's square bracket notation
1228 is enabled.
1230 C++11 generalized constant expressions
1231 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1233 Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
1234 constant expressions (e.g., ``constexpr``) is enabled.
1236 C++11 ``decltype()``
1237 ^^^^^^^^^^^^^^^^^^^^
1239 Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
1240 determine if support for the ``decltype()`` specifier is enabled.  C++11's
1241 ``decltype`` does not require type-completeness of a function call expression.
1242 Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
1243 ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
1244 support for this feature is enabled.
1246 C++11 default template arguments in function templates
1247 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1249 Use ``__has_feature(cxx_default_function_template_args)`` or
1250 ``__has_extension(cxx_default_function_template_args)`` to determine if support
1251 for default template arguments in function templates is enabled.
1253 C++11 ``default``\ ed functions
1254 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1256 Use ``__has_feature(cxx_defaulted_functions)`` or
1257 ``__has_extension(cxx_defaulted_functions)`` to determine if support for
1258 defaulted function definitions (with ``= default``) is enabled.
1260 C++11 delegating constructors
1261 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1263 Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
1264 delegating constructors is enabled.
1266 C++11 ``deleted`` functions
1267 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1269 Use ``__has_feature(cxx_deleted_functions)`` or
1270 ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
1271 function definitions (with ``= delete``) is enabled.
1273 C++11 explicit conversion functions
1274 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1276 Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
1277 ``explicit`` conversion functions is enabled.
1279 C++11 generalized initializers
1280 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1282 Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
1283 generalized initializers (using braced lists and ``std::initializer_list``) is
1284 enabled.
1286 C++11 implicit move constructors/assignment operators
1287 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1289 Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
1290 generate move constructors and move assignment operators where needed.
1292 C++11 inheriting constructors
1293 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1295 Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
1296 inheriting constructors is enabled.
1298 C++11 inline namespaces
1299 ^^^^^^^^^^^^^^^^^^^^^^^
1301 Use ``__has_feature(cxx_inline_namespaces)`` or
1302 ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
1303 namespaces is enabled.
1305 C++11 lambdas
1306 ^^^^^^^^^^^^^
1308 Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
1309 determine if support for lambdas is enabled.
1311 C++11 local and unnamed types as template arguments
1312 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1314 Use ``__has_feature(cxx_local_type_template_args)`` or
1315 ``__has_extension(cxx_local_type_template_args)`` to determine if support for
1316 local and unnamed types as template arguments is enabled.
1318 C++11 noexcept
1319 ^^^^^^^^^^^^^^
1321 Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
1322 determine if support for noexcept exception specifications is enabled.
1324 C++11 in-class non-static data member initialization
1325 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1327 Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
1328 initialization of non-static data members is enabled.
1330 C++11 ``nullptr``
1331 ^^^^^^^^^^^^^^^^^
1333 Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
1334 determine if support for ``nullptr`` is enabled.
1336 C++11 ``override control``
1337 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1339 Use ``__has_feature(cxx_override_control)`` or
1340 ``__has_extension(cxx_override_control)`` to determine if support for the
1341 override control keywords is enabled.
1343 C++11 reference-qualified functions
1344 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1346 Use ``__has_feature(cxx_reference_qualified_functions)`` or
1347 ``__has_extension(cxx_reference_qualified_functions)`` to determine if support
1348 for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
1349 applied to ``*this``) is enabled.
1351 C++11 range-based ``for`` loop
1352 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1354 Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
1355 determine if support for the range-based for loop is enabled.
1357 C++11 raw string literals
1358 ^^^^^^^^^^^^^^^^^^^^^^^^^
1360 Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
1361 string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
1363 C++11 rvalue references
1364 ^^^^^^^^^^^^^^^^^^^^^^^
1366 Use ``__has_feature(cxx_rvalue_references)`` or
1367 ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
1368 references is enabled.
1370 C++11 ``static_assert()``
1371 ^^^^^^^^^^^^^^^^^^^^^^^^^
1373 Use ``__has_feature(cxx_static_assert)`` or
1374 ``__has_extension(cxx_static_assert)`` to determine if support for compile-time
1375 assertions using ``static_assert`` is enabled.
1377 C++11 ``thread_local``
1378 ^^^^^^^^^^^^^^^^^^^^^^
1380 Use ``__has_feature(cxx_thread_local)`` to determine if support for
1381 ``thread_local`` variables is enabled.
1383 C++11 type inference
1384 ^^^^^^^^^^^^^^^^^^^^
1386 Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
1387 determine C++11 type inference is supported using the ``auto`` specifier.  If
1388 this is disabled, ``auto`` will instead be a storage class specifier, as in C
1389 or C++98.
1391 C++11 strongly typed enumerations
1392 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1394 Use ``__has_feature(cxx_strong_enums)`` or
1395 ``__has_extension(cxx_strong_enums)`` to determine if support for strongly
1396 typed, scoped enumerations is enabled.
1398 C++11 trailing return type
1399 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1401 Use ``__has_feature(cxx_trailing_return)`` or
1402 ``__has_extension(cxx_trailing_return)`` to determine if support for the
1403 alternate function declaration syntax with trailing return type is enabled.
1405 C++11 Unicode string literals
1406 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1408 Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
1409 string literals is enabled.
1411 C++11 unrestricted unions
1412 ^^^^^^^^^^^^^^^^^^^^^^^^^
1414 Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
1415 unrestricted unions is enabled.
1417 C++11 user-defined literals
1418 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1420 Use ``__has_feature(cxx_user_literals)`` to determine if support for
1421 user-defined literals is enabled.
1423 C++11 variadic templates
1424 ^^^^^^^^^^^^^^^^^^^^^^^^
1426 Use ``__has_feature(cxx_variadic_templates)`` or
1427 ``__has_extension(cxx_variadic_templates)`` to determine if support for
1428 variadic templates is enabled.
1430 C++14
1431 -----
1433 The features listed below are part of the C++14 standard.  As a result, all
1434 these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
1435 when compiling C++ code.
1437 C++14 binary literals
1438 ^^^^^^^^^^^^^^^^^^^^^
1440 Use ``__has_feature(cxx_binary_literals)`` or
1441 ``__has_extension(cxx_binary_literals)`` to determine whether
1442 binary literals (for instance, ``0b10010``) are recognized. Clang supports this
1443 feature as an extension in all language modes.
1445 C++14 contextual conversions
1446 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1448 Use ``__has_feature(cxx_contextual_conversions)`` or
1449 ``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
1450 are used when performing an implicit conversion for an array bound in a
1451 *new-expression*, the operand of a *delete-expression*, an integral constant
1452 expression, or a condition in a ``switch`` statement.
1454 C++14 decltype(auto)
1455 ^^^^^^^^^^^^^^^^^^^^
1457 Use ``__has_feature(cxx_decltype_auto)`` or
1458 ``__has_extension(cxx_decltype_auto)`` to determine if support
1459 for the ``decltype(auto)`` placeholder type is enabled.
1461 C++14 default initializers for aggregates
1462 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1464 Use ``__has_feature(cxx_aggregate_nsdmi)`` or
1465 ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
1466 for default initializers in aggregate members is enabled.
1468 C++14 digit separators
1469 ^^^^^^^^^^^^^^^^^^^^^^
1471 Use ``__cpp_digit_separators`` to determine if support for digit separators
1472 using single quotes (for instance, ``10'000``) is enabled. At this time, there
1473 is no corresponding ``__has_feature`` name
1475 C++14 generalized lambda capture
1476 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1478 Use ``__has_feature(cxx_init_captures)`` or
1479 ``__has_extension(cxx_init_captures)`` to determine if support for
1480 lambda captures with explicit initializers is enabled
1481 (for instance, ``[n(0)] { return ++n; }``).
1483 C++14 generic lambdas
1484 ^^^^^^^^^^^^^^^^^^^^^
1486 Use ``__has_feature(cxx_generic_lambdas)`` or
1487 ``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
1488 (polymorphic) lambdas is enabled
1489 (for instance, ``[] (auto x) { return x + 1; }``).
1491 C++14 relaxed constexpr
1492 ^^^^^^^^^^^^^^^^^^^^^^^
1494 Use ``__has_feature(cxx_relaxed_constexpr)`` or
1495 ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
1496 declarations, local variable modification, and control flow constructs
1497 are permitted in ``constexpr`` functions.
1499 C++14 return type deduction
1500 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1502 Use ``__has_feature(cxx_return_type_deduction)`` or
1503 ``__has_extension(cxx_return_type_deduction)`` to determine if support
1504 for return type deduction for functions (using ``auto`` as a return type)
1505 is enabled.
1507 C++14 runtime-sized arrays
1508 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1510 Use ``__has_feature(cxx_runtime_array)`` or
1511 ``__has_extension(cxx_runtime_array)`` to determine if support
1512 for arrays of runtime bound (a restricted form of variable-length arrays)
1513 is enabled.
1514 Clang's implementation of this feature is incomplete.
1516 C++14 variable templates
1517 ^^^^^^^^^^^^^^^^^^^^^^^^
1519 Use ``__has_feature(cxx_variable_templates)`` or
1520 ``__has_extension(cxx_variable_templates)`` to determine if support for
1521 templated variable declarations is enabled.
1526 The features listed below are part of the C11 standard.  As a result, all these
1527 features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
1528 compiling C code.  Additionally, because these features are all
1529 backward-compatible, they are available as extensions in all language modes.
1531 C11 alignment specifiers
1532 ^^^^^^^^^^^^^^^^^^^^^^^^
1534 Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
1535 if support for alignment specifiers using ``_Alignas`` is enabled.
1537 Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
1538 if support for the ``_Alignof`` keyword is enabled.
1540 C11 atomic operations
1541 ^^^^^^^^^^^^^^^^^^^^^
1543 Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
1544 if support for atomic types using ``_Atomic`` is enabled.  Clang also provides
1545 :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
1546 the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
1547 ``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
1548 is available.
1550 Clang will use the system's ``<stdatomic.h>`` header when one is available, and
1551 will otherwise use its own. When using its own, implementations of the atomic
1552 operations are provided as macros. In the cases where C11 also requires a real
1553 function, this header provides only the declaration of that function (along
1554 with a shadowing macro implementation), and you must link to a library which
1555 provides a definition of the function if you use it instead of the macro.
1557 C11 generic selections
1558 ^^^^^^^^^^^^^^^^^^^^^^
1560 Use ``__has_feature(c_generic_selections)`` or
1561 ``__has_extension(c_generic_selections)`` to determine if support for generic
1562 selections is enabled.
1564 As an extension, the C11 generic selection expression is available in all
1565 languages supported by Clang.  The syntax is the same as that given in the C11
1566 standard.
1568 In C, type compatibility is decided according to the rules given in the
1569 appropriate standard, but in C++, which lacks the type compatibility rules used
1570 in C, types are considered compatible only if they are equivalent.
1572 Clang also supports an extended form of ``_Generic`` with a controlling type
1573 rather than a controlling expression. Unlike with a controlling expression, a
1574 controlling type argument does not undergo any conversions and thus is suitable
1575 for use when trying to match qualified types, incomplete types, or function
1576 types. Variable-length array types lack the necessary compile-time information
1577 to resolve which association they match with and thus are not allowed as a
1578 controlling type argument.
1580 Use ``__has_extension(c_generic_selection_with_controlling_type)`` to determine
1581 if support for this extension is enabled.
1583 C11 ``_Static_assert()``
1584 ^^^^^^^^^^^^^^^^^^^^^^^^
1586 Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
1587 to determine if support for compile-time assertions using ``_Static_assert`` is
1588 enabled.
1590 C11 ``_Thread_local``
1591 ^^^^^^^^^^^^^^^^^^^^^
1593 Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
1594 to determine if support for ``_Thread_local`` variables is enabled.
1596 Modules
1597 -------
1599 Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1600 For example, compiling code with ``-fmodules`` enables the use of Modules.
1602 More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
1604 Language Extensions Back-ported to Previous Standards
1605 =====================================================
1607 ============================================ ================================ ============= =============
1608 Feature                                      Feature Test Macro               Introduced In Backported To
1609 ============================================ ================================ ============= =============
1610 variadic templates                           __cpp_variadic_templates         C++11         C++03
1611 Alias templates                              __cpp_alias_templates            C++11         C++03
1612 Non-static data member initializers          __cpp_nsdmi                      C++11         C++03
1613 Range-based ``for`` loop                     __cpp_range_based_for            C++11         C++03
1614 RValue references                            __cpp_rvalue_references          C++11         C++03
1615 Attributes                                   __cpp_attributes                 C++11         C++03
1616 Lambdas                                      __cpp_lambdas                    C++11         C++03
1617 Generalized lambda captures                  __cpp_init_captures              C++14         C++03
1618 Generic lambda expressions                   __cpp_generic_lambdas            C++14         C++03
1619 variable templates                           __cpp_variable_templates         C++14         C++03
1620 Binary literals                              __cpp_binary_literals            C++14         C++03
1621 Relaxed constexpr                            __cpp_constexpr                  C++14         C++11
1622 Static assert with no message                __cpp_static_assert >= 201411L   C++17         C++11
1623 Pack expansion in generalized lambda-capture __cpp_init_captures              C++17         C++03
1624 ``if constexpr``                             __cpp_if_constexpr               C++17         C++11
1625 fold expressions                             __cpp_fold_expressions           C++17         C++03
1626 Lambda capture of \*this by value            __cpp_capture_star_this          C++17         C++03
1627 Attributes on enums                          __cpp_enumerator_attributes      C++17         C++03
1628 Guaranteed copy elision                      __cpp_guaranteed_copy_elision    C++17         C++03
1629 Hexadecimal floating literals                __cpp_hex_float                  C++17         C++03
1630 ``inline`` variables                         __cpp_inline_variables           C++17         C++03
1631 Attributes on namespaces                     __cpp_namespace_attributes       C++17         C++11
1632 Structured bindings                          __cpp_structured_bindings        C++17         C++03
1633 template template arguments                  __cpp_template_template_args     C++17         C++03
1634 Familiar template syntax for generic lambdas __cpp_generic_lambdas            C++20         C++03
1635 ``static operator[]``                        __cpp_multidimensional_subscript C++20         C++03
1636 Designated initializers                      __cpp_designated_initializers    C++20         C++03
1637 Conditional ``explicit``                     __cpp_conditional_explicit       C++20         C++03
1638 ``using enum``                               __cpp_using_enum                 C++20         C++03
1639 ``if consteval``                             __cpp_if_consteval               C++23         C++20
1640 ``static operator()``                        __cpp_static_call_operator       C++23         C++03
1641 Attributes on Lambda-Expressions                                              C++23         C++11
1642 Attributes on Structured Bindings            __cpp_structured_bindings        C++26         C++03
1643 Static assert with user-generated message    __cpp_static_assert >= 202306L   C++26         C++11
1644 Pack Indexing                                __cpp_pack_indexing              C++26         C++03
1645 ``= delete ("should have a reason");``       __cpp_deleted_function           C++26         C++03
1646 Variadic Friends                             __cpp_variadic_friend            C++26         C++03
1647 -------------------------------------------- -------------------------------- ------------- -------------
1648 Designated initializers (N494)                                                C99           C89
1649 Array & element qualification (N2607)                                         C23           C89
1650 Attributes (N2335)                                                            C23           C89
1651 ``#embed`` (N3017)                                                            C23           C89, C++
1652 ============================================ ================================ ============= =============
1654 Builtin type aliases
1655 ====================
1657 Clang provides a few builtin aliases to improve the throughput of certain metaprogramming facilities.
1659 __builtin_common_type
1660 ---------------------
1662 .. code-block:: c++
1664   template <template <class... Args> class BaseTemplate,
1665             template <class TypeMember> class HasTypeMember,
1666             class HasNoTypeMember,
1667             class... Ts>
1668   using __builtin_common_type = ...;
1670 This alias is used for implementing ``std::common_type``. If ``std::common_type`` should contain a ``type`` member,
1671 it is an alias to ``HasTypeMember<TheCommonType>``. Otherwise it is an alias to ``HasNoTypeMember``. The
1672 ``BaseTemplate`` is usually ``std::common_type``. ``Ts`` are the arguments to ``std::common_type``.
1674 __type_pack_element
1675 -------------------
1677 .. code-block:: c++
1679   template <std::size_t Index, class... Ts>
1680   using __type_pack_element = ...;
1682 This alias returns the type at ``Index`` in the parameter pack ``Ts``.
1684 __make_integer_seq
1685 ------------------
1687 .. code-block:: c++
1689   template <template <class IntSeqT, IntSeqT... Ints> class IntSeq, class T, T N>
1690   using __make_integer_seq = ...;
1692 This alias returns ``IntSeq`` instantiated with ``IntSeqT = T``and ``Ints`` being the pack ``0, ..., N - 1``.
1694 Type Trait Primitives
1695 =====================
1697 Type trait primitives are special builtin constant expressions that can be used
1698 by the standard C++ library to facilitate or simplify the implementation of
1699 user-facing type traits in the <type_traits> header.
1701 They are not intended to be used directly by user code because they are
1702 implementation-defined and subject to change -- as such they're tied closely to
1703 the supported set of system headers, currently:
1705 * LLVM's own libc++
1706 * GNU libstdc++
1707 * The Microsoft standard C++ library
1709 Clang supports the `GNU C++ type traits
1710 <https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
1711 `Microsoft Visual C++ type traits
1712 <https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,
1713 as well as nearly all of the
1714 `Embarcadero C++ type traits
1715 <http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.
1717 The following type trait primitives are supported by Clang. Those traits marked
1718 (C++) provide implementations for type traits specified by the C++ standard;
1719 ``__X(...)`` has the same semantics and constraints as the corresponding
1720 ``std::X_t<...>`` or ``std::X_v<...>`` type trait.
1722 * ``__array_rank(type)`` (Embarcadero):
1723   Returns the number of levels of array in the type ``type``:
1724   ``0`` if ``type`` is not an array type, and
1725   ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.
1726 * ``__array_extent(type, dim)`` (Embarcadero):
1727   The ``dim``'th array bound in the type ``type``, or ``0`` if
1728   ``dim >= __array_rank(type)``.
1729 * ``__builtin_is_implicit_lifetime`` (C++, GNU, Microsoft)
1730 * ``__builtin_is_virtual_base_of`` (C++, GNU, Microsoft)
1731 * ``__can_pass_in_regs`` (C++)
1732   Returns whether a class can be passed in registers under the current
1733   ABI. This type can only be applied to unqualified class types.
1734   This is not a portable type trait.
1735 * ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero):
1736   Deprecated, use ``__is_nothrow_assignable`` instead.
1737 * ``__has_nothrow_move_assign`` (GNU, Microsoft):
1738   Deprecated, use ``__is_nothrow_assignable`` instead.
1739 * ``__has_nothrow_copy`` (GNU, Microsoft):
1740   Deprecated, use ``__is_nothrow_constructible`` instead.
1741 * ``__has_nothrow_constructor`` (GNU, Microsoft):
1742   Deprecated, use ``__is_nothrow_constructible`` instead.
1743 * ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero):
1744   Deprecated, use ``__is_trivially_assignable`` instead.
1745 * ``__has_trivial_move_assign`` (GNU, Microsoft):
1746   Deprecated, use ``__is_trivially_assignable`` instead.
1747 * ``__has_trivial_copy`` (GNU, Microsoft):
1748   Deprecated, use ``__is_trivially_copyable`` instead.
1749 * ``__has_trivial_constructor`` (GNU, Microsoft):
1750   Deprecated, use ``__is_trivially_constructible`` instead.
1751 * ``__has_trivial_move_constructor`` (GNU, Microsoft):
1752   Deprecated, use ``__is_trivially_constructible`` instead.
1753 * ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero):
1754   Deprecated, use ``__is_trivially_destructible`` instead.
1755 * ``__has_unique_object_representations`` (C++, GNU)
1756 * ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero)
1757 * ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero)
1758 * ``__is_aggregate`` (C++, GNU, Microsoft)
1759 * ``__is_arithmetic`` (C++, Embarcadero)
1760 * ``__is_array`` (C++, Embarcadero)
1761 * ``__is_assignable`` (C++, MSVC 2015)
1762 * ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero)
1763 * ``__is_bounded_array`` (C++, GNU, Microsoft, Embarcadero)
1764 * ``__is_class`` (C++, GNU, Microsoft, Embarcadero)
1765 * ``__is_complete_type(type)`` (Embarcadero):
1766   Return ``true`` if ``type`` is a complete type.
1767   Warning: this trait is dangerous because it can return different values at
1768   different points in the same program.
1769 * ``__is_compound`` (C++, Embarcadero)
1770 * ``__is_const`` (C++, Embarcadero)
1771 * ``__is_constructible`` (C++, MSVC 2013)
1772 * ``__is_convertible`` (C++, Embarcadero)
1773 * ``__is_nothrow_convertible`` (C++, GNU)
1774 * ``__is_convertible_to`` (Microsoft):
1775   Synonym for ``__is_convertible``.
1776 * ``__is_destructible`` (C++, MSVC 2013)
1777 * ``__is_empty`` (C++, GNU, Microsoft, Embarcadero)
1778 * ``__is_enum`` (C++, GNU, Microsoft, Embarcadero)
1779 * ``__is_final`` (C++, GNU, Microsoft)
1780 * ``__is_floating_point`` (C++, Embarcadero)
1781 * ``__is_function`` (C++, Embarcadero)
1782 * ``__is_fundamental`` (C++, Embarcadero)
1783 * ``__is_integral`` (C++, Embarcadero)
1784 * ``__is_interface_class`` (Microsoft):
1785   Returns ``false``, even for types defined with ``__interface``.
1786 * ``__is_layout_compatible`` (C++, GNU, Microsoft)
1787 * ``__is_literal`` (Clang):
1788   Synonym for ``__is_literal_type``.
1789 * ``__is_literal_type`` (C++, GNU, Microsoft):
1790   Note, the corresponding standard trait was deprecated in C++17
1791   and removed in C++20.
1792 * ``__is_lvalue_reference`` (C++, Embarcadero)
1793 * ``__is_member_object_pointer`` (C++, Embarcadero)
1794 * ``__is_member_function_pointer`` (C++, Embarcadero)
1795 * ``__is_member_pointer`` (C++, Embarcadero)
1796 * ``__is_nothrow_assignable`` (C++, MSVC 2013)
1797 * ``__is_nothrow_constructible`` (C++, MSVC 2013)
1798 * ``__is_nothrow_destructible`` (C++, MSVC 2013)
1799 * ``__is_object`` (C++, Embarcadero)
1800 * ``__is_pod`` (C++, GNU, Microsoft, Embarcadero):
1801   Note, the corresponding standard trait was deprecated in C++20.
1802 * ``__is_pointer`` (C++, Embarcadero)
1803 * ``__is_pointer_interconvertible_base_of`` (C++, GNU, Microsoft)
1804 * ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero)
1805 * ``__is_reference`` (C++, Embarcadero)
1806 * ``__is_referenceable`` (C++, GNU, Microsoft, Embarcadero):
1807   Returns true if a type is referenceable, and false otherwise. A referenceable
1808   type is a type that's either an object type, a reference type, or an unqualified
1809   function type. This trait is deprecated and will be removed in Clang 21.
1810 * ``__is_rvalue_reference`` (C++, Embarcadero)
1811 * ``__is_same`` (C++, Embarcadero)
1812 * ``__is_same_as`` (GCC): Synonym for ``__is_same``.
1813 * ``__is_scalar`` (C++, Embarcadero)
1814 * ``__is_scoped_enum`` (C++, GNU, Microsoft, Embarcadero)
1815 * ``__is_sealed`` (Microsoft):
1816   Synonym for ``__is_final``.
1817 * ``__is_signed`` (C++, Embarcadero):
1818   Returns false for enumeration types, and returns true for floating-point
1819   types. Note, before Clang 10, returned true for enumeration types if the
1820   underlying type was signed, and returned false for floating-point types.
1821 * ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero)
1822 * ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero)
1823 * ``__is_trivially_assignable`` (C++, GNU, Microsoft)
1824 * ``__is_trivially_constructible`` (C++, GNU, Microsoft)
1825 * ``__is_trivially_copyable`` (C++, GNU, Microsoft)
1826 * ``__is_trivially_destructible`` (C++, MSVC 2013)
1827 * ``__is_trivially_relocatable`` (Clang): Returns true if moving an object
1828   of the given type, and then destroying the source object, is known to be
1829   functionally equivalent to copying the underlying bytes and then dropping the
1830   source object on the floor. This is true of trivial types and types which
1831   were made trivially relocatable via the ``clang::trivial_abi`` attribute.
1832 * ``__is_trivially_equality_comparable`` (Clang): Returns true if comparing two
1833   objects of the provided type is known to be equivalent to comparing their
1834   object representations. Note that types containing padding bytes are never
1835   trivially equality comparable.
1836 * ``__is_unbounded_array`` (C++, GNU, Microsoft, Embarcadero)
1837 * ``__is_union`` (C++, GNU, Microsoft, Embarcadero)
1838 * ``__is_unsigned`` (C++, Embarcadero):
1839   Returns false for enumeration types. Note, before Clang 13, returned true for
1840   enumeration types if the underlying type was unsigned.
1841 * ``__is_void`` (C++, Embarcadero)
1842 * ``__is_volatile`` (C++, Embarcadero)
1843 * ``__reference_binds_to_temporary(T, U)`` (Clang):  Determines whether a
1844   reference of type ``T`` bound to an expression of type ``U`` would bind to a
1845   materialized temporary object. If ``T`` is not a reference type the result
1846   is false. Note this trait will also return false when the initialization of
1847   ``T`` from ``U`` is ill-formed.
1848   Deprecated, use ``__reference_constructs_from_temporary``.
1849 * ``__reference_constructs_from_temporary(T, U)`` (C++)
1850   Returns true if a reference ``T`` can be direct-initialized from a temporary of type
1851   a non-cv-qualified ``U``.
1852 * ``__reference_converts_from_temporary(T, U)`` (C++)
1853     Returns true if a reference ``T`` can be copy-initialized from a temporary of type
1854     a non-cv-qualified ``U``.
1855 * ``__underlying_type`` (C++, GNU, Microsoft)
1857 In addition, the following expression traits are supported:
1859 * ``__is_lvalue_expr(e)`` (Embarcadero):
1860   Returns true if ``e`` is an lvalue expression.
1861   Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.
1862 * ``__is_rvalue_expr(e)`` (Embarcadero):
1863   Returns true if ``e`` is a prvalue expression.
1864   Deprecated, use ``!__is_reference(decltype((e)))`` instead.
1866 There are multiple ways to detect support for a type trait ``__X`` in the
1867 compiler, depending on the oldest version of Clang you wish to support.
1869 * From Clang 10 onwards, ``__has_builtin(__X)`` can be used.
1870 * From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.
1871 * From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports
1872   the following traits:
1874   * ``__has_nothrow_assign``
1875   * ``__has_nothrow_copy``
1876   * ``__has_nothrow_constructor``
1877   * ``__has_trivial_assign``
1878   * ``__has_trivial_copy``
1879   * ``__has_trivial_constructor``
1880   * ``__has_trivial_destructor``
1881   * ``__has_virtual_destructor``
1882   * ``__is_abstract``
1883   * ``__is_base_of``
1884   * ``__is_class``
1885   * ``__is_constructible``
1886   * ``__is_convertible_to``
1887   * ``__is_empty``
1888   * ``__is_enum``
1889   * ``__is_final``
1890   * ``__is_literal``
1891   * ``__is_standard_layout``
1892   * ``__is_pod``
1893   * ``__is_polymorphic``
1894   * ``__is_sealed``
1895   * ``__is_trivial``
1896   * ``__is_trivially_assignable``
1897   * ``__is_trivially_constructible``
1898   * ``__is_trivially_copyable``
1899   * ``__is_union``
1900   * ``__underlying_type``
1902 A simplistic usage example as might be seen in standard C++ headers follows:
1904 .. code-block:: c++
1906   #if __has_builtin(__is_convertible_to)
1907   template<typename From, typename To>
1908   struct is_convertible_to {
1909     static const bool value = __is_convertible_to(From, To);
1910   };
1911   #else
1912   // Emulate type trait for compatibility with other compilers.
1913   #endif
1915 Blocks
1916 ======
1918 The syntax and high level language feature description is in
1919 :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1920 the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
1922 Query for this feature with ``__has_extension(blocks)``.
1924 ASM Goto with Output Constraints
1925 ================================
1927 Outputs may be used along any branches from the ``asm goto`` whether the
1928 branches are taken or not.
1930 Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.
1932 Prior to clang-16, the output may only be used safely when the indirect
1933 branches are not taken.  Query for this difference with
1934 ``__has_extension(gnu_asm_goto_with_outputs_full)``.
1936 When using tied-outputs (i.e. outputs that are inputs and outputs, not just
1937 outputs) with the `+r` constraint, there is a hidden input that's created
1938 before the label, so numeric references to operands must account for that.
1940 .. code-block:: c++
1942   int foo(int x) {
1943       // %0 and %1 both refer to x
1944       // %l2 refers to err
1945       asm goto("# %0 %1 %l2" : "+r"(x) : : : err);
1946       return x;
1947     err:
1948       return -1;
1949   }
1951 This was changed to match GCC in clang-13; for better portability, symbolic
1952 references can be used instead of numeric references.
1954 .. code-block:: c++
1956   int foo(int x) {
1957       asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err);
1958       return x;
1959     err:
1960       return -1;
1961   }
1963 Objective-C Features
1964 ====================
1966 Related result types
1967 --------------------
1969 According to Cocoa conventions, Objective-C methods with certain names
1970 ("``init``", "``alloc``", etc.) always return objects that are an instance of
1971 the receiving class's type.  Such methods are said to have a "related result
1972 type", meaning that a message send to one of these methods will have the same
1973 static type as an instance of the receiver class.  For example, given the
1974 following classes:
1976 .. code-block:: objc
1978   @interface NSObject
1979   + (id)alloc;
1980   - (id)init;
1981   @end
1983   @interface NSArray : NSObject
1984   @end
1986 and this common initialization pattern
1988 .. code-block:: objc
1990   NSArray *array = [[NSArray alloc] init];
1992 the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1993 ``alloc`` implicitly has a related result type.  Similarly, the type of the
1994 expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1995 related result type and its receiver is known to have the type ``NSArray *``.
1996 If neither ``alloc`` nor ``init`` had a related result type, the expressions
1997 would have had type ``id``, as declared in the method signature.
1999 A method with a related result type can be declared by using the type
2000 ``instancetype`` as its result type.  ``instancetype`` is a contextual keyword
2001 that is only permitted in the result type of an Objective-C method, e.g.
2003 .. code-block:: objc
2005   @interface A
2006   + (instancetype)constructAnA;
2007   @end
2009 The related result type can also be inferred for some methods.  To determine
2010 whether a method has an inferred related result type, the first word in the
2011 camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
2012 and the method will have a related result type if its return type is compatible
2013 with the type of its class and if:
2015 * the first word is "``alloc``" or "``new``", and the method is a class method,
2016   or
2018 * the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
2019   and the method is an instance method.
2021 If a method with a related result type is overridden by a subclass method, the
2022 subclass method must also return a type that is compatible with the subclass
2023 type.  For example:
2025 .. code-block:: objc
2027   @interface NSString : NSObject
2028   - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
2029   @end
2031 Related result types only affect the type of a message send or property access
2032 via the given method.  In all other respects, a method with a related result
2033 type is treated the same way as method that returns ``id``.
2035 Use ``__has_feature(objc_instancetype)`` to determine whether the
2036 ``instancetype`` contextual keyword is available.
2038 Automatic reference counting
2039 ----------------------------
2041 Clang provides support for :doc:`automated reference counting
2042 <AutomaticReferenceCounting>` in Objective-C, which eliminates the need
2043 for manual ``retain``/``release``/``autorelease`` message sends.  There are three
2044 feature macros associated with automatic reference counting:
2045 ``__has_feature(objc_arc)`` indicates the availability of automated reference
2046 counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
2047 automated reference counting also includes support for ``__weak`` pointers to
2048 Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
2049 are allowed to have fields that are pointers to Objective-C objects managed by
2050 automatic reference counting.
2052 .. _objc-weak:
2054 Weak references
2055 ---------------
2057 Clang supports ARC-style weak and unsafe references in Objective-C even
2058 outside of ARC mode.  Weak references must be explicitly enabled with
2059 the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
2060 to test whether they are enabled.  Unsafe references are enabled
2061 unconditionally.  ARC-style weak and unsafe references cannot be used
2062 when Objective-C garbage collection is enabled.
2064 Except as noted below, the language rules for the ``__weak`` and
2065 ``__unsafe_unretained`` qualifiers (and the ``weak`` and
2066 ``unsafe_unretained`` property attributes) are just as laid out
2067 in the :doc:`ARC specification <AutomaticReferenceCounting>`.
2068 In particular, note that some classes do not support forming weak
2069 references to their instances, and note that special care must be
2070 taken when storing weak references in memory where initialization
2071 and deinitialization are outside the responsibility of the compiler
2072 (such as in ``malloc``-ed memory).
2074 Loading from a ``__weak`` variable always implicitly retains the
2075 loaded value.  In non-ARC modes, this retain is normally balanced
2076 by an implicit autorelease.  This autorelease can be suppressed
2077 by performing the load in the receiver position of a ``-retain``
2078 message send (e.g. ``[weakReference retain]``); note that this performs
2079 only a single retain (the retain done when primitively loading from
2080 the weak reference).
2082 For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
2083 default behavior of variables and therefore is not needed.  However,
2084 it does have an effect on the semantics of block captures: normally,
2085 copying a block which captures an Objective-C object or block pointer
2086 causes the captured pointer to be retained or copied, respectively,
2087 but that behavior is suppressed when the captured variable is qualified
2088 with ``__unsafe_unretained``.
2090 Note that the ``__weak`` qualifier formerly meant the GC qualifier in
2091 all non-ARC modes and was silently ignored outside of GC modes.  It now
2092 means the ARC-style qualifier in all non-GC modes and is no longer
2093 allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
2094 It is expected that ``-fobjc-weak`` will eventually be enabled by default
2095 in all non-GC Objective-C modes.
2097 .. _objc-fixed-enum:
2099 Enumerations with a fixed underlying type
2100 -----------------------------------------
2102 Clang provides support for C++11 enumerations with a fixed underlying type
2103 within Objective-C and C `prior to C23 <https://open-std.org/JTC1/SC22/WG14/www/docs/n3030.htm>`_.  For example, one can write an enumeration type as:
2105 .. code-block:: c++
2107   typedef enum : unsigned char { Red, Green, Blue } Color;
2109 This specifies that the underlying type, which is used to store the enumeration
2110 value, is ``unsigned char``.
2112 Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
2113 underlying types is available in Objective-C.
2115 Use ``__has_extension(c_fixed_enum)`` to determine whether support for fixed
2116 underlying types is available in C prior to C23. This will also report ``true`` in C23
2117 and later modes as the functionality is available even if it's not an extension in
2118 those modes.
2120 Use ``__has_feature(c_fixed_enum)`` to determine whether support for fixed
2121 underlying types is available in C23 and later.
2123 Interoperability with C++11 lambdas
2124 -----------------------------------
2126 Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
2127 permitting a lambda to be implicitly converted to a block pointer with the
2128 corresponding signature.  For example, consider an API such as ``NSArray``'s
2129 array-sorting method:
2131 .. code-block:: objc
2133   - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
2135 ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
2136 (^)(id, id)``, and parameters of this type are generally provided with block
2137 literals as arguments.  However, one can also use a C++11 lambda so long as it
2138 provides the same signature (in this case, accepting two parameters of type
2139 ``id`` and returning an ``NSComparisonResult``):
2141 .. code-block:: objc
2143   NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
2144                      @"String 02"];
2145   const NSStringCompareOptions comparisonOptions
2146     = NSCaseInsensitiveSearch | NSNumericSearch |
2147       NSWidthInsensitiveSearch | NSForcedOrderingSearch;
2148   NSLocale *currentLocale = [NSLocale currentLocale];
2149   NSArray *sorted
2150     = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
2151                NSRange string1Range = NSMakeRange(0, [s1 length]);
2152                return [s1 compare:s2 options:comparisonOptions
2153                range:string1Range locale:currentLocale];
2154        }];
2155   NSLog(@"sorted: %@", sorted);
2157 This code relies on an implicit conversion from the type of the lambda
2158 expression (an unnamed, local class type called the *closure type*) to the
2159 corresponding block pointer type.  The conversion itself is expressed by a
2160 conversion operator in that closure type that produces a block pointer with the
2161 same signature as the lambda itself, e.g.,
2163 .. code-block:: objc
2165   operator NSComparisonResult (^)(id, id)() const;
2167 This conversion function returns a new block that simply forwards the two
2168 parameters to the lambda object (which it captures by copy), then returns the
2169 result.  The returned block is first copied (with ``Block_copy``) and then
2170 autoreleased.  As an optimization, if a lambda expression is immediately
2171 converted to a block pointer (as in the first example, above), then the block
2172 is not copied and autoreleased: rather, it is given the same lifetime as a
2173 block literal written at that point in the program, which avoids the overhead
2174 of copying a block to the heap in the common case.
2176 The conversion from a lambda to a block pointer is only available in
2177 Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
2178 management (autorelease).
2180 Object Literals and Subscripting
2181 --------------------------------
2183 Clang provides support for :doc:`Object Literals and Subscripting
2184 <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
2185 programming patterns, makes programs more concise, and improves the safety of
2186 container creation.  There are several feature macros associated with object
2187 literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
2188 availability of array literals; ``__has_feature(objc_dictionary_literals)``
2189 tests the availability of dictionary literals;
2190 ``__has_feature(objc_subscripting)`` tests the availability of object
2191 subscripting.
2193 Objective-C Autosynthesis of Properties
2194 ---------------------------------------
2196 Clang provides support for autosynthesis of declared properties.  Using this
2197 feature, clang provides default synthesis of those properties not declared
2198 @dynamic and not having user provided backing getter and setter methods.
2199 ``__has_feature(objc_default_synthesize_properties)`` checks for availability
2200 of this feature in version of clang being used.
2202 .. _langext-objc-retain-release:
2204 Objective-C retaining behavior attributes
2205 -----------------------------------------
2207 In Objective-C, functions and methods are generally assumed to follow the
2208 `Cocoa Memory Management
2209 <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
2210 conventions for ownership of object arguments and
2211 return values. However, there are exceptions, and so Clang provides attributes
2212 to allow these exceptions to be documented. This are used by ARC and the
2213 `static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
2214 better described using the ``objc_method_family`` attribute instead.
2216 **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
2217 ``ns_returns_autoreleased``, ``cf_returns_retained``, and
2218 ``cf_returns_not_retained`` attributes can be placed on methods and functions
2219 that return Objective-C or CoreFoundation objects. They are commonly placed at
2220 the end of a function prototype or method declaration:
2222 .. code-block:: objc
2224   id foo() __attribute__((ns_returns_retained));
2226   - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
2228 The ``*_returns_retained`` attributes specify that the returned object has a +1
2229 retain count.  The ``*_returns_not_retained`` attributes specify that the return
2230 object has a +0 retain count, even if the normal convention for its selector
2231 would be +1.  ``ns_returns_autoreleased`` specifies that the returned object is
2232 +0, but is guaranteed to live at least as long as the next flush of an
2233 autorelease pool.
2235 **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
2236 a parameter declaration; they specify that the argument is expected to have a
2237 +1 retain count, which will be balanced in some way by the function or method.
2238 The ``ns_consumes_self`` attribute can only be placed on an Objective-C
2239 method; it specifies that the method expects its ``self`` parameter to have a
2240 +1 retain count, which it will balance in some way.
2242 .. code-block:: objc
2244   void foo(__attribute__((ns_consumed)) NSString *string);
2246   - (void) bar __attribute__((ns_consumes_self));
2247   - (void) baz:(id) __attribute__((ns_consumed)) x;
2249 Further examples of these attributes are available in the static analyzer's
2250 `list of annotations for analysis <analyzer/user-docs/Annotations.html#cocoa-mem>`__.
2252 Query for these features with ``__has_attribute(ns_consumed)``,
2253 ``__has_attribute(ns_returns_retained)``, etc.
2255 Objective-C @available
2256 ----------------------
2258 It is possible to use the newest SDK but still build a program that can run on
2259 older versions of macOS and iOS by passing ``-mmacos-version-min=`` /
2260 ``-miphoneos-version-min=``.
2262 Before LLVM 5.0, when calling a function that exists only in the OS that's
2263 newer than the target OS (as determined by the minimum deployment version),
2264 programmers had to carefully check if the function exists at runtime, using
2265 null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
2266 and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
2267 Objective-C methods.  If such a check was missed, the program would compile
2268 fine, run fine on newer systems, but crash on older systems.
2270 As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
2271 <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
2272 with the new ``@available()`` keyword to assist with this issue.
2273 When a method that's introduced in the OS newer than the target OS is called, a
2274 -Wunguarded-availability warning is emitted if that call is not guarded:
2276 .. code-block:: objc
2278   void my_fun(NSSomeClass* var) {
2279     // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
2280     // built with -mmacos-version-min=10.11, then this unconditional call
2281     // will emit a -Wunguarded-availability warning:
2282     [var fancyNewMethod];
2283   }
2285 To fix the warning and to avoid the crash on macOS 10.11, wrap it in
2286 ``if(@available())``:
2288 .. code-block:: objc
2290   void my_fun(NSSomeClass* var) {
2291     if (@available(macOS 10.12, *)) {
2292       [var fancyNewMethod];
2293     } else {
2294       // Put fallback behavior for old macOS versions (and for non-mac
2295       // platforms) here.
2296     }
2297   }
2299 The ``*`` is required and means that platforms not explicitly listed will take
2300 the true branch, and the compiler will emit ``-Wunguarded-availability``
2301 warnings for unlisted platforms based on those platform's deployment target.
2302 More than one platform can be listed in ``@available()``:
2304 .. code-block:: objc
2306   void my_fun(NSSomeClass* var) {
2307     if (@available(macOS 10.12, iOS 10, *)) {
2308       [var fancyNewMethod];
2309     }
2310   }
2312 If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
2313 on 10.12, then add an `availability attribute
2314 <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
2315 which will also suppress the warning and require that calls to my_fun() are
2316 checked:
2318 .. code-block:: objc
2320   API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
2321     [var fancyNewMethod];  // Now ok.
2322   }
2324 ``@available()`` is only available in Objective-C code.  To use the feature
2325 in C and C++ code, use the ``__builtin_available()`` spelling instead.
2327 If existing code uses null checks or ``-respondsToSelector:``, it should
2328 be changed to use ``@available()`` (or ``__builtin_available``) instead.
2330 ``-Wunguarded-availability`` is disabled by default, but
2331 ``-Wunguarded-availability-new``, which only emits this warning for APIs
2332 that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
2333 tvOS >= 11, is enabled by default.
2335 .. _langext-overloading:
2337 Objective-C++ ABI: protocol-qualifier mangling of parameters
2338 ------------------------------------------------------------
2340 Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
2341 type is a qualified-``id`` (e.g., ``id<Foo>``).  This mangling allows such
2342 parameters to be differentiated from those with the regular unqualified ``id``
2343 type.
2345 This was a non-backward compatible mangling change to the ABI.  This change
2346 allows proper overloading, and also prevents mangling conflicts with template
2347 parameters of protocol-qualified type.
2349 Query the presence of this new mangling with
2350 ``__has_feature(objc_protocol_qualifier_mangling)``.
2352 Initializer lists for complex numbers in C
2353 ==========================================
2355 clang supports an extension which allows the following in C:
2357 .. code-block:: c++
2359   #include <math.h>
2360   #include <complex.h>
2361   complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
2363 This construct is useful because there is no way to separately initialize the
2364 real and imaginary parts of a complex variable in standard C, given that clang
2365 does not support ``_Imaginary``.  (Clang also supports the ``__real__`` and
2366 ``__imag__`` extensions from gcc, which help in some cases, but are not usable
2367 in static initializers.)
2369 Note that this extension does not allow eliding the braces; the meaning of the
2370 following two lines is different:
2372 .. code-block:: c++
2374   complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
2375   complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
2377 This extension also works in C++ mode, as far as that goes, but does not apply
2378 to the C++ ``std::complex``.  (In C++11, list initialization allows the same
2379 syntax to be used with ``std::complex`` with the same meaning.)
2381 For GCC compatibility, ``__builtin_complex(re, im)`` can also be used to
2382 construct a complex number from the given real and imaginary components.
2384 OpenCL Features
2385 ===============
2387 Clang supports internal OpenCL extensions documented below.
2389 ``__cl_clang_bitfields``
2390 --------------------------------
2392 With this extension it is possible to enable bitfields in structs
2393 or unions using the OpenCL extension pragma mechanism detailed in
2394 `the OpenCL Extension Specification, section 1.2
2395 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2397 Use of bitfields in OpenCL kernels can result in reduced portability as struct
2398 layout is not guaranteed to be consistent when compiled by different compilers.
2399 If structs with bitfields are used as kernel function parameters, it can result
2400 in incorrect functionality when the layout is different between the host and
2401 device code.
2403 **Example of Use**:
2405 .. code-block:: c++
2407   #pragma OPENCL EXTENSION __cl_clang_bitfields : enable
2408   struct with_bitfield {
2409     unsigned int i : 5; // compiled - no diagnostic generated
2410   };
2412   #pragma OPENCL EXTENSION __cl_clang_bitfields : disable
2413   struct without_bitfield {
2414     unsigned int i : 5; // error - bitfields are not supported
2415   };
2417 ``__cl_clang_function_pointers``
2418 --------------------------------
2420 With this extension it is possible to enable various language features that
2421 are relying on function pointers using regular OpenCL extension pragma
2422 mechanism detailed in `the OpenCL Extension Specification,
2423 section 1.2
2424 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2426 In C++ for OpenCL this also enables:
2428 - Use of member function pointers;
2430 - Unrestricted use of references to functions;
2432 - Virtual member functions.
2434 Such functionality is not conformant and does not guarantee to compile
2435 correctly in any circumstances. It can be used if:
2437 - the kernel source does not contain call expressions to (member-) function
2438   pointers, or virtual functions. For example this extension can be used in
2439   metaprogramming algorithms to be able to specify/detect types generically.
2441 - the generated kernel binary does not contain indirect calls because they
2442   are eliminated using compiler optimizations e.g. devirtualization.
2444 - the selected target supports the function pointer like functionality e.g.
2445   most CPU targets.
2447 **Example of Use**:
2449 .. code-block:: c++
2451   #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable
2452   void foo()
2453   {
2454     void (*fp)(); // compiled - no diagnostic generated
2455   }
2457   #pragma OPENCL EXTENSION __cl_clang_function_pointers : disable
2458   void bar()
2459   {
2460     void (*fp)(); // error - pointers to function are not allowed
2461   }
2463 ``__cl_clang_variadic_functions``
2464 ---------------------------------
2466 With this extension it is possible to enable variadic arguments in functions
2467 using regular OpenCL extension pragma mechanism detailed in `the OpenCL
2468 Extension Specification, section 1.2
2469 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2471 This is not conformant behavior and it can only be used portably when the
2472 functions with variadic prototypes do not get generated in binary e.g. the
2473 variadic prototype is used to specify a function type with any number of
2474 arguments in metaprogramming algorithms in C++ for OpenCL.
2476 This extensions can also be used when the kernel code is intended for targets
2477 supporting the variadic arguments e.g. majority of CPU targets.
2479 **Example of Use**:
2481 .. code-block:: c++
2483   #pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable
2484   void foo(int a, ...); // compiled - no diagnostic generated
2486   #pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable
2487   void bar(int a, ...); // error - variadic prototype is not allowed
2489 ``__cl_clang_non_portable_kernel_param_types``
2490 ----------------------------------------------
2492 With this extension it is possible to enable the use of some restricted types
2493 in kernel parameters specified in `C++ for OpenCL v1.0 s2.4
2494 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_.
2495 The restrictions can be relaxed using regular OpenCL extension pragma mechanism
2496 detailed in `the OpenCL Extension Specification, section 1.2
2497 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2499 This is not a conformant behavior and it can only be used when the
2500 kernel arguments are not accessed on the host side or the data layout/size
2501 between the host and device is known to be compatible.
2503 **Example of Use**:
2505 .. code-block:: c++
2507   // Plain Old Data type.
2508   struct Pod {
2509     int a;
2510     int b;
2511   };
2513   // Not POD type because of the constructor.
2514   // Standard layout type because there is only one access control.
2515   struct OnlySL {
2516     int a;
2517     int b;
2518     OnlySL() : a(0), b(0) {}
2519   };
2521   // Not standard layout type because of two different access controls.
2522   struct NotSL {
2523     int a;
2524   private:
2525     int b;
2526   };
2528   #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable
2529   kernel void kernel_main(
2530     Pod a,
2532     OnlySL b,
2533     global NotSL *c,
2534     global OnlySL *d
2535   );
2536   #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable
2538 Remove address space builtin function
2539 -------------------------------------
2541 ``__remove_address_space`` allows to derive types in C++ for OpenCL
2542 that have address space qualifiers removed. This utility only affects
2543 address space qualifiers, therefore, other type qualifiers such as
2544 ``const`` or ``volatile`` remain unchanged.
2546 **Example of Use**:
2548 .. code-block:: c++
2550   template<typename T>
2551   void foo(T *par){
2552     T var1; // error - local function variable with global address space
2553     __private T var2; // error - conflicting address space qualifiers
2554     __private __remove_address_space<T>::type var3; // var3 is __private int
2555   }
2557   void bar(){
2558     __global int* ptr;
2559     foo(ptr);
2560   }
2562 Legacy 1.x atomics with generic address space
2563 ---------------------------------------------
2565 Clang allows use of atomic functions from the OpenCL 1.x standards
2566 with the generic address space pointer in C++ for OpenCL mode.
2568 This is a non-portable feature and might not be supported by all
2569 targets.
2571 **Example of Use**:
2573 .. code-block:: c++
2575   void foo(__generic volatile unsigned int* a) {
2576     atomic_add(a, 1);
2577   }
2579 WebAssembly Features
2580 ====================
2582 Clang supports the WebAssembly features documented below. For further
2583 information related to the semantics of the builtins, please refer to the `WebAssembly Specification <https://webassembly.github.io/spec/core/>`_.
2584 In this section, when we refer to reference types, we are referring to
2585 WebAssembly reference types, not C++ reference types unless stated
2586 otherwise.
2588 ``__builtin_wasm_table_set``
2589 ----------------------------
2591 This builtin function stores a value in a WebAssembly table.
2592 It takes three arguments.
2593 The first argument is the table to store a value into, the second
2594 argument is the index to which to store the value into, and the
2595 third argument is a value of reference type to store in the table.
2596 It returns nothing.
2598 .. code-block:: c++
2600   static __externref_t table[0];
2601   extern __externref_t JSObj;
2603   void store(int index) {
2604     __builtin_wasm_table_set(table, index, JSObj);
2605   }
2607 ``__builtin_wasm_table_get``
2608 ----------------------------
2610 This builtin function is the counterpart to ``__builtin_wasm_table_set``
2611 and loads a value from a WebAssembly table of reference typed values.
2612 It takes 2 arguments.
2613 The first argument is a table of reference typed values and the
2614 second argument is an index from which to load the value. It returns
2615 the loaded reference typed value.
2617 .. code-block:: c++
2619   static __externref_t table[0];
2621   __externref_t load(int index) {
2622     __externref_t Obj = __builtin_wasm_table_get(table, index);
2623     return Obj;
2624   }
2626 ``__builtin_wasm_table_size``
2627 -----------------------------
2629 This builtin function returns the size of the WebAssembly table.
2630 Takes the table as an argument and returns an unsigned integer (``size_t``)
2631 with the current table size.
2633 .. code-block:: c++
2635   typedef void (*__funcref funcref_t)();
2636   static __funcref table[0];
2638   size_t getSize() {
2639     return __builtin_wasm_table_size(table);
2640   }
2642 ``__builtin_wasm_table_grow``
2643 -----------------------------
2645 This builtin function grows the WebAssembly table by a certain amount.
2646 Currently, as all WebAssembly tables created in C/C++ are zero-sized,
2647 this always needs to be called to grow the table.
2649 It takes three arguments. The first argument is the WebAssembly table
2650 to grow. The second argument is the reference typed value to store in
2651 the new table entries (the initialization value), and the third argument
2652 is the amount to grow the table by. It returns the previous table size
2653 or -1. It will return -1 if not enough space could be allocated.
2655 .. code-block:: c++
2657   typedef void (*__funcref funcref_t)();
2658   static __funcref table[0];
2660   // grow returns the new table size or -1 on error.
2661   int grow(__funcref fn, int delta) {
2662     int prevSize = __builtin_wasm_table_grow(table, fn, delta);
2663     if (prevSize == -1)
2664       return -1;
2665     return prevSize + delta;
2666   }
2668 ``__builtin_wasm_table_fill``
2669 -----------------------------
2671 This builtin function sets all the entries of a WebAssembly table to a given
2672 reference typed value. It takes four arguments. The first argument is
2673 the WebAssembly table, the second argument is the index that starts the
2674 range, the third argument is the value to set in the new entries, and
2675 the fourth and the last argument is the size of the range. It returns
2676 nothing.
2678 .. code-block:: c++
2680   static __externref_t table[0];
2682   // resets a table by setting all of its entries to a given value.
2683   void reset(__externref_t Obj) {
2684     int Size = __builtin_wasm_table_size(table);
2685     __builtin_wasm_table_fill(table, 0, Obj, Size);
2686   }
2688 ``__builtin_wasm_table_copy``
2689 -----------------------------
2691 This builtin function copies elements from a source WebAssembly table
2692 to a possibly overlapping destination region. It takes five arguments.
2693 The first argument is the destination WebAssembly table, and the second
2694 argument is the source WebAssembly table. The third argument is the
2695 destination index from where the copy starts, the fourth argument is the
2696 source index from there the copy starts, and the fifth and last argument
2697 is the number of elements to copy. It returns nothing.
2699 .. code-block:: c++
2701   static __externref_t tableSrc[0];
2702   static __externref_t tableDst[0];
2704   // Copy nelem elements from [src, src + nelem - 1] in tableSrc to
2705   // [dst, dst + nelem - 1] in tableDst
2706   void copy(int dst, int src, int nelem) {
2707     __builtin_wasm_table_copy(tableDst, tableSrc, dst, src, nelem);
2708   }
2711 Builtin Functions
2712 =================
2714 Clang supports a number of builtin library functions with the same syntax as
2715 GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
2716 ``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
2717 ``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc.  In addition to
2718 the GCC builtins, Clang supports a number of builtins that GCC does not, which
2719 are listed here.
2721 Please note that Clang does not and will not support all of the GCC builtins
2722 for vector operations.  Instead of using builtins, you should use the functions
2723 defined in target-specific header files like ``<xmmintrin.h>``, which define
2724 portable wrappers for these.  Many of the Clang versions of these functions are
2725 implemented directly in terms of :ref:`extended vector support
2726 <langext-vectors>` instead of builtins, in order to reduce the number of
2727 builtins that we need to implement.
2729 ``__builtin_alloca``
2730 --------------------
2732 ``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory
2733 is automatically freed upon function termination.
2735 **Syntax**:
2737 .. code-block:: c++
2739   __builtin_alloca(size_t n)
2741 **Example of Use**:
2743 .. code-block:: c++
2745   void init(float* data, size_t nbelems);
2746   void process(float* data, size_t nbelems);
2747   int foo(size_t n) {
2748     auto mem = (float*)__builtin_alloca(n * sizeof(float));
2749     init(mem, n);
2750     process(mem, n);
2751     /* mem is automatically freed at this point */
2752   }
2754 **Description**:
2756 ``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory
2757 on the stack. This amount is subject to stack allocation limits.
2759 Query for this feature with ``__has_builtin(__builtin_alloca)``.
2761 ``__builtin_alloca_with_align``
2762 -------------------------------
2764 ``__builtin_alloca_with_align`` is used to dynamically allocate memory on the
2765 stack while controlling its alignment. Memory is automatically freed upon
2766 function termination.
2769 **Syntax**:
2771 .. code-block:: c++
2773   __builtin_alloca_with_align(size_t n, size_t align)
2775 **Example of Use**:
2777 .. code-block:: c++
2779   void init(float* data, size_t nbelems);
2780   void process(float* data, size_t nbelems);
2781   int foo(size_t n) {
2782     auto mem = (float*)__builtin_alloca_with_align(
2783                         n * sizeof(float),
2784                         CHAR_BIT * alignof(float));
2785     init(mem, n);
2786     process(mem, n);
2787     /* mem is automatically freed at this point */
2788   }
2790 **Description**:
2792 ``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory
2793 on the stack. It is similar to ``__builtin_alloca`` but accepts a second
2794 argument whose value is the alignment constraint, as a power of 2 in *bits*.
2796 Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``.
2798 .. _langext-__builtin_assume:
2800 ``__builtin_assume``
2801 --------------------
2803 ``__builtin_assume`` is used to provide the optimizer with a boolean
2804 invariant that is defined to be true.
2806 **Syntax**:
2808 .. code-block:: c++
2810     __builtin_assume(bool)
2812 **Example of Use**:
2814 .. code-block:: c++
2816   int foo(int x) {
2817       __builtin_assume(x != 0);
2818       // The optimizer may short-circuit this check using the invariant.
2819       if (x == 0)
2820             return do_something();
2821       return do_something_else();
2822   }
2824 **Description**:
2826 The boolean argument to this function is defined to be true. The optimizer may
2827 analyze the form of the expression provided as the argument and deduce from
2828 that information used to optimize the program. If the condition is violated
2829 during execution, the behavior is undefined. The argument itself is never
2830 evaluated, so any side effects of the expression will be discarded.
2832 Query for this feature with ``__has_builtin(__builtin_assume)``.
2834 .. _langext-__builtin_assume_separate_storage:
2836 ``__builtin_assume_separate_storage``
2837 -------------------------------------
2839 ``__builtin_assume_separate_storage`` is used to provide the optimizer with the
2840 knowledge that its two arguments point to separately allocated objects.
2842 **Syntax**:
2844 .. code-block:: c++
2846     __builtin_assume_separate_storage(const volatile void *, const volatile void *)
2848 **Example of Use**:
2850 .. code-block:: c++
2852   int foo(int *x, int *y) {
2853       __builtin_assume_separate_storage(x, y);
2854       *x = 0;
2855       *y = 1;
2856       // The optimizer may optimize this to return 0 without reloading from *x.
2857       return *x;
2858   }
2860 **Description**:
2862 The arguments to this function are assumed to point into separately allocated
2863 storage (either different variable definitions or different dynamic storage
2864 allocations). The optimizer may use this fact to aid in alias analysis. If the
2865 arguments point into the same storage, the behavior is undefined. Note that the
2866 definition of "storage" here refers to the outermost enclosing allocation of any
2867 particular object (so for example, it's never correct to call this function
2868 passing the addresses of fields in the same struct, elements of the same array,
2869 etc.).
2871 Query for this feature with ``__has_builtin(__builtin_assume_separate_storage)``.
2874 ``__builtin_offsetof``
2875 ----------------------
2877 ``__builtin_offsetof`` is used to implement the ``offsetof`` macro, which
2878 calculates the offset (in bytes) to a given member of the given type.
2880 **Syntax**:
2882 .. code-block:: c++
2884     __builtin_offsetof(type-name, member-designator)
2886 **Example of Use**:
2888 .. code-block:: c++
2890   struct S {
2891     char c;
2892     int i;
2893     struct T {
2894       float f[2];
2895     } t;
2896   };
2898   const int offset_to_i = __builtin_offsetof(struct S, i);
2899   const int ext1 = __builtin_offsetof(struct U { int i; }, i); // C extension
2900   const int offset_to_subobject = __builtin_offsetof(struct S, t.f[1]);
2902 **Description**:
2904 This builtin is usable in an integer constant expression which returns a value
2905 of type ``size_t``. The value returned is the offset in bytes to the subobject
2906 designated by the member-designator from the beginning of an object of type
2907 ``type-name``. Clang extends the required standard functionality in the
2908 following way:
2910 * In C language modes, the first argument may be the definition of a new type.
2911   Any type declared this way is scoped to the nearest scope containing the call
2912   to the builtin.
2914 Query for this feature with ``__has_builtin(__builtin_offsetof)``.
2916 ``__builtin_call_with_static_chain``
2917 ------------------------------------
2919 ``__builtin_call_with_static_chain`` is used to perform a static call while
2920 setting updating the static chain register.
2922 **Syntax**:
2924 .. code-block:: c++
2926   T __builtin_call_with_static_chain(T expr, void* ptr)
2928 **Example of Use**:
2930 .. code-block:: c++
2932   auto v = __builtin_call_with_static_chain(foo(3), foo);
2934 **Description**:
2936 This builtin returns ``expr`` after checking that ``expr`` is a non-member
2937 static call expression. The call to that expression is made while using ``ptr``
2938 as a function pointer stored in a dedicated register to implement *static chain*
2939 calling convention, as used by some language to implement closures or nested
2940 functions.
2942 Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``.
2944 ``__builtin_readcyclecounter``
2945 ------------------------------
2947 ``__builtin_readcyclecounter`` is used to access the cycle counter register (or
2948 a similar low-latency, high-accuracy clock) on those targets that support it.
2950 **Syntax**:
2952 .. code-block:: c++
2954   __builtin_readcyclecounter()
2956 **Example of Use**:
2958 .. code-block:: c++
2960   unsigned long long t0 = __builtin_readcyclecounter();
2961   do_something();
2962   unsigned long long t1 = __builtin_readcyclecounter();
2963   unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
2965 **Description**:
2967 The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
2968 which may be either global or process/thread-specific depending on the target.
2969 As the backing counters often overflow quickly (on the order of seconds) this
2970 should only be used for timing small intervals.  When not supported by the
2971 target, the return value is always zero.  This builtin takes no arguments and
2972 produces an unsigned long long result.
2974 Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
2975 that even if present, its use may depend on run-time privilege or other OS
2976 controlled state.
2978 ``__builtin_readsteadycounter``
2979 -------------------------------
2981 ``__builtin_readsteadycounter`` is used to access the fixed frequency counter
2982 register (or a similar steady-rate clock) on those targets that support it.
2983 The function is similar to ``__builtin_readcyclecounter`` above except that the
2984 frequency is fixed, making it suitable for measuring elapsed time.
2986 **Syntax**:
2988 .. code-block:: c++
2990   __builtin_readsteadycounter()
2992 **Example of Use**:
2994 .. code-block:: c++
2996   unsigned long long t0 = __builtin_readsteadycounter();
2997   do_something();
2998   unsigned long long t1 = __builtin_readsteadycounter();
2999   unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
3001 **Description**:
3003 The ``__builtin_readsteadycounter()`` builtin returns the frequency counter value.
3004 When not supported by the target, the return value is always zero. This builtin
3005 takes no arguments and produces an unsigned long long result. The builtin does
3006 not guarantee any particular frequency, only that it is stable. Knowledge of the
3007 counter's true frequency will need to be provided by the user.
3009 Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.
3011 ``__builtin_cpu_supports``
3012 --------------------------
3014 **Syntax**:
3016 .. code-block:: c++
3018   int __builtin_cpu_supports(const char *features);
3020 **Example of Use:**:
3022 .. code-block:: c++
3024   if (__builtin_cpu_supports("sve"))
3025     sve_code();
3027 **Description**:
3029 The ``__builtin_cpu_supports`` function detects if the run-time CPU supports
3030 features specified in string argument. It returns a positive integer if all
3031 features are supported and 0 otherwise. Feature names are target specific. On
3032 AArch64 features are combined using ``+`` like this
3033 ``__builtin_cpu_supports("flagm+sha3+lse+rcpc2+fcma+memtag+bti+sme2")``.
3034 If a feature name is not supported, Clang will issue a warning and replace
3035 builtin by the constant 0.
3037 Query for this feature with ``__has_builtin(__builtin_cpu_supports)``.
3039 ``__builtin_dump_struct``
3040 -------------------------
3042 **Syntax**:
3044 .. code-block:: c++
3046     __builtin_dump_struct(&some_struct, some_printf_func, args...);
3048 **Examples**:
3050 .. code-block:: c++
3052     struct S {
3053       int x, y;
3054       float f;
3055       struct T {
3056         int i;
3057       } t;
3058     };
3060     void func(struct S *s) {
3061       __builtin_dump_struct(s, printf);
3062     }
3064 Example output:
3066 .. code-block:: none
3068     struct S {
3069       int x = 100
3070       int y = 42
3071       float f = 3.141593
3072       struct T t = {
3073         int i = 1997
3074       }
3075     }
3077 .. code-block:: c++
3079     #include <string>
3080     struct T { int a, b; };
3081     constexpr void constexpr_sprintf(std::string &out, const char *format,
3082                                      auto ...args) {
3083       // ...
3084     }
3085     constexpr std::string dump_struct(auto &x) {
3086       std::string s;
3087       __builtin_dump_struct(&x, constexpr_sprintf, s);
3088       return s;
3089     }
3090     static_assert(dump_struct(T{1, 2}) == R"(struct T {
3091       int a = 1
3092       int b = 2
3093     }
3094     )");
3096 **Description**:
3098 The ``__builtin_dump_struct`` function is used to print the fields of a simple
3099 structure and their values for debugging purposes. The first argument of the
3100 builtin should be a pointer to a complete record type to dump. The second argument ``f``
3101 should be some callable expression, and can be a function object or an overload
3102 set. The builtin calls ``f``, passing any further arguments ``args...``
3103 followed by a ``printf``-compatible format string and the corresponding
3104 arguments. ``f`` may be called more than once, and ``f`` and ``args`` will be
3105 evaluated once per call. In C++, ``f`` may be a template or overload set and
3106 resolve to different functions for each call.
3108 In the format string, a suitable format specifier will be used for builtin
3109 types that Clang knows how to format. This includes standard builtin types, as
3110 well as aggregate structures, ``void*`` (printed with ``%p``), and ``const
3111 char*`` (printed with ``%s``). A ``*%p`` specifier will be used for a field
3112 that Clang doesn't know how to format, and the corresponding argument will be a
3113 pointer to the field. This allows a C++ templated formatting function to detect
3114 this case and implement custom formatting. A ``*`` will otherwise not precede a
3115 format specifier.
3117 This builtin does not return a value.
3119 This builtin can be used in constant expressions.
3121 Query for this feature with ``__has_builtin(__builtin_dump_struct)``
3123 .. _langext-__builtin_shufflevector:
3125 ``__builtin_shufflevector``
3126 ---------------------------
3128 ``__builtin_shufflevector`` is used to express generic vector
3129 permutation/shuffle/swizzle operations.  This builtin is also very important
3130 for the implementation of various target-specific header files like
3131 ``<xmmintrin.h>``. This builtin can be used within constant expressions.
3133 **Syntax**:
3135 .. code-block:: c++
3137   __builtin_shufflevector(vec1, vec2, index1, index2, ...)
3139 **Examples**:
3141 .. code-block:: c++
3143   // identity operation - return 4-element vector v1.
3144   __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
3146   // "Splat" element 0 of V1 into a 4-element result.
3147   __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
3149   // Reverse 4-element vector V1.
3150   __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
3152   // Concatenate every other element of 4-element vectors V1 and V2.
3153   __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
3155   // Concatenate every other element of 8-element vectors V1 and V2.
3156   __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
3158   // Shuffle v1 with some elements being undefined. Not allowed in constexpr.
3159   __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
3161 **Description**:
3163 The first two arguments to ``__builtin_shufflevector`` are vectors that have
3164 the same element type.  The remaining arguments are a list of integers that
3165 specify the elements indices of the first two vectors that should be extracted
3166 and returned in a new vector.  These element indices are numbered sequentially
3167 starting with the first vector, continuing into the second vector.  Thus, if
3168 ``vec1`` is a 4-element vector, index 5 would refer to the second element of
3169 ``vec2``. An index of -1 can be used to indicate that the corresponding element
3170 in the returned vector is a don't care and can be optimized by the backend.
3171 Values of -1 are not supported in constant expressions.
3173 The result of ``__builtin_shufflevector`` is a vector with the same element
3174 type as ``vec1``/``vec2`` but that has an element count equal to the number of
3175 indices specified.
3177 Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
3179 .. _langext-__builtin_convertvector:
3181 ``__builtin_convertvector``
3182 ---------------------------
3184 ``__builtin_convertvector`` is used to express generic vector
3185 type-conversion operations. The input vector and the output vector
3186 type must have the same number of elements. This builtin can be used within
3187 constant expressions.
3189 **Syntax**:
3191 .. code-block:: c++
3193   __builtin_convertvector(src_vec, dst_vec_type)
3195 **Examples**:
3197 .. code-block:: c++
3199   typedef double vector4double __attribute__((__vector_size__(32)));
3200   typedef float  vector4float  __attribute__((__vector_size__(16)));
3201   typedef short  vector4short  __attribute__((__vector_size__(8)));
3202   vector4float vf; vector4short vs;
3204   // convert from a vector of 4 floats to a vector of 4 doubles.
3205   __builtin_convertvector(vf, vector4double)
3206   // equivalent to:
3207   (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
3209   // convert from a vector of 4 shorts to a vector of 4 floats.
3210   __builtin_convertvector(vs, vector4float)
3211   // equivalent to:
3212   (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
3214 **Description**:
3216 The first argument to ``__builtin_convertvector`` is a vector, and the second
3217 argument is a vector type with the same number of elements as the first
3218 argument.
3220 The result of ``__builtin_convertvector`` is a vector with the same element
3221 type as the second argument, with a value defined in terms of the action of a
3222 C-style cast applied to each element of the first argument.
3224 Query for this feature with ``__has_builtin(__builtin_convertvector)``.
3226 ``__builtin_bitreverse``
3227 ------------------------
3229 * ``__builtin_bitreverse8``
3230 * ``__builtin_bitreverse16``
3231 * ``__builtin_bitreverse32``
3232 * ``__builtin_bitreverse64``
3234 **Syntax**:
3236 .. code-block:: c++
3238      __builtin_bitreverse32(x)
3240 **Examples**:
3242 .. code-block:: c++
3244       uint8_t rev_x = __builtin_bitreverse8(x);
3245       uint16_t rev_x = __builtin_bitreverse16(x);
3246       uint32_t rev_y = __builtin_bitreverse32(y);
3247       uint64_t rev_z = __builtin_bitreverse64(z);
3249 **Description**:
3251 The '``__builtin_bitreverse``' family of builtins is used to reverse
3252 the bitpattern of an integer value; for example ``0b10110110`` becomes
3253 ``0b01101101``. These builtins can be used within constant expressions.
3255 ``__builtin_rotateleft``
3256 ------------------------
3258 * ``__builtin_rotateleft8``
3259 * ``__builtin_rotateleft16``
3260 * ``__builtin_rotateleft32``
3261 * ``__builtin_rotateleft64``
3263 **Syntax**:
3265 .. code-block:: c++
3267      __builtin_rotateleft32(x, y)
3269 **Examples**:
3271 .. code-block:: c++
3273       uint8_t rot_x = __builtin_rotateleft8(x, y);
3274       uint16_t rot_x = __builtin_rotateleft16(x, y);
3275       uint32_t rot_x = __builtin_rotateleft32(x, y);
3276       uint64_t rot_x = __builtin_rotateleft64(x, y);
3278 **Description**:
3280 The '``__builtin_rotateleft``' family of builtins is used to rotate
3281 the bits in the first argument by the amount in the second argument.
3282 For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
3283 The shift value is treated as an unsigned amount modulo the size of
3284 the arguments. Both arguments and the result have the bitwidth specified
3285 by the name of the builtin. These builtins can be used within constant
3286 expressions.
3288 ``__builtin_rotateright``
3289 -------------------------
3291 * ``__builtin_rotateright8``
3292 * ``__builtin_rotateright16``
3293 * ``__builtin_rotateright32``
3294 * ``__builtin_rotateright64``
3296 **Syntax**:
3298 .. code-block:: c++
3300      __builtin_rotateright32(x, y)
3302 **Examples**:
3304 .. code-block:: c++
3306       uint8_t rot_x = __builtin_rotateright8(x, y);
3307       uint16_t rot_x = __builtin_rotateright16(x, y);
3308       uint32_t rot_x = __builtin_rotateright32(x, y);
3309       uint64_t rot_x = __builtin_rotateright64(x, y);
3311 **Description**:
3313 The '``__builtin_rotateright``' family of builtins is used to rotate
3314 the bits in the first argument by the amount in the second argument.
3315 For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
3316 The shift value is treated as an unsigned amount modulo the size of
3317 the arguments. Both arguments and the result have the bitwidth specified
3318 by the name of the builtin. These builtins can be used within constant
3319 expressions.
3321 ``__builtin_unreachable``
3322 -------------------------
3324 ``__builtin_unreachable`` is used to indicate that a specific point in the
3325 program cannot be reached, even if the compiler might otherwise think it can.
3326 This is useful to improve optimization and eliminates certain warnings.  For
3327 example, without the ``__builtin_unreachable`` in the example below, the
3328 compiler assumes that the inline asm can fall through and prints a "function
3329 declared '``noreturn``' should not return" warning.
3331 **Syntax**:
3333 .. code-block:: c++
3335     __builtin_unreachable()
3337 **Example of use**:
3339 .. code-block:: c++
3341   void myabort(void) __attribute__((noreturn));
3342   void myabort(void) {
3343     asm("int3");
3344     __builtin_unreachable();
3345   }
3347 **Description**:
3349 The ``__builtin_unreachable()`` builtin has completely undefined behavior.
3350 Since it has undefined behavior, it is a statement that it is never reached and
3351 the optimizer can take advantage of this to produce better code.  This builtin
3352 takes no arguments and produces a void result.
3354 Query for this feature with ``__has_builtin(__builtin_unreachable)``.
3356 ``__builtin_unpredictable``
3357 ---------------------------
3359 ``__builtin_unpredictable`` is used to indicate that a branch condition is
3360 unpredictable by hardware mechanisms such as branch prediction logic.
3362 **Syntax**:
3364 .. code-block:: c++
3366     __builtin_unpredictable(long long)
3368 **Example of use**:
3370 .. code-block:: c++
3372   if (__builtin_unpredictable(x > 0)) {
3373      foo();
3374   }
3376 **Description**:
3378 The ``__builtin_unpredictable()`` builtin is expected to be used with control
3379 flow conditions such as in ``if`` and ``switch`` statements.
3381 Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
3384 ``__builtin_expect``
3385 --------------------
3387 ``__builtin_expect`` is used to indicate that the value of an expression is
3388 anticipated to be the same as a statically known result.
3390 **Syntax**:
3392 .. code-block:: c++
3394     long __builtin_expect(long expr, long val)
3396 **Example of use**:
3398 .. code-block:: c++
3400   if (__builtin_expect(x, 0)) {
3401      bar();
3402   }
3404 **Description**:
3406 The ``__builtin_expect()`` builtin is typically used with control flow
3407 conditions such as in ``if`` and ``switch`` statements to help branch
3408 prediction. It means that its first argument ``expr`` is expected to take the
3409 value of its second argument ``val``. It always returns ``expr``.
3411 Query for this feature with ``__has_builtin(__builtin_expect)``.
3413 ``__builtin_expect_with_probability``
3414 -------------------------------------
3416 ``__builtin_expect_with_probability`` is similar to ``__builtin_expect`` but it
3417 takes a probability as third argument.
3419 **Syntax**:
3421 .. code-block:: c++
3423     long __builtin_expect_with_probability(long expr, long val, double p)
3425 **Example of use**:
3427 .. code-block:: c++
3429   if (__builtin_expect_with_probability(x, 0, .3)) {
3430      bar();
3431   }
3433 **Description**:
3435 The ``__builtin_expect_with_probability()`` builtin is typically used with
3436 control flow conditions such as in ``if`` and ``switch`` statements to help
3437 branch prediction. It means that its first argument ``expr`` is expected to take
3438 the value of its second argument ``val`` with probability ``p``. ``p`` must be
3439 within ``[0.0 ; 1.0]`` bounds. This builtin always returns the value of ``expr``.
3441 Query for this feature with ``__has_builtin(__builtin_expect_with_probability)``.
3443 ``__builtin_prefetch``
3444 ----------------------
3446 ``__builtin_prefetch`` is used to communicate with the cache handler to bring
3447 data into the cache before it gets used.
3449 **Syntax**:
3451 .. code-block:: c++
3453     void __builtin_prefetch(const void *addr, int rw=0, int locality=3)
3455 **Example of use**:
3457 .. code-block:: c++
3459     __builtin_prefetch(a + i);
3461 **Description**:
3463 The ``__builtin_prefetch(addr, rw, locality)`` builtin is expected to be used to
3464 avoid cache misses when the developer has a good understanding of which data
3465 are going to be used next. ``addr`` is the address that needs to be brought into
3466 the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and ``1``
3467 for *write*. In case of *read write* access, ``1`` is to be used. ``locality``
3468 indicates the expected persistence of data in cache, from ``0`` which means that
3469 data can be discarded from cache after its next use to ``3`` which means that
3470 data is going to be reused a lot once in cache. ``1`` and ``2`` provide
3471 intermediate behavior between these two extremes.
3473 Query for this feature with ``__has_builtin(__builtin_prefetch)``.
3475 ``__sync_swap``
3476 ---------------
3478 ``__sync_swap`` is used to atomically swap integers or pointers in memory.
3480 **Syntax**:
3482 .. code-block:: c++
3484   type __sync_swap(type *ptr, type value, ...)
3486 **Example of Use**:
3488 .. code-block:: c++
3490   int old_value = __sync_swap(&value, new_value);
3492 **Description**:
3494 The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
3495 atomic intrinsics to allow code to atomically swap the current value with the
3496 new value.  More importantly, it helps developers write more efficient and
3497 correct code by avoiding expensive loops around
3498 ``__sync_bool_compare_and_swap()`` or relying on the platform specific
3499 implementation details of ``__sync_lock_test_and_set()``.  The
3500 ``__sync_swap()`` builtin is a full barrier.
3502 ``__builtin_addressof``
3503 -----------------------
3505 ``__builtin_addressof`` performs the functionality of the built-in ``&``
3506 operator, ignoring any ``operator&`` overload.  This is useful in constant
3507 expressions in C++11, where there is no other way to take the address of an
3508 object that overloads ``operator&``. Clang automatically adds
3509 ``[[clang::lifetimebound]]`` to the parameter of ``__builtin_addressof``.
3511 **Example of use**:
3513 .. code-block:: c++
3515   template<typename T> constexpr T *addressof(T &value) {
3516     return __builtin_addressof(value);
3517   }
3519 ``__builtin_function_start``
3520 -----------------------------
3522 ``__builtin_function_start`` returns the address of a function body.
3524 **Syntax**:
3526 .. code-block:: c++
3528   void *__builtin_function_start(function)
3530 **Example of use**:
3532 .. code-block:: c++
3534   void a() {}
3535   void *p = __builtin_function_start(a);
3537   class A {
3538   public:
3539     void a(int n);
3540     void a();
3541   };
3543   void A::a(int n) {}
3544   void A::a() {}
3546   void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a);
3547   void *pa2 = __builtin_function_start((void(A::*)()) &A::a);
3549 **Description**:
3551 The ``__builtin_function_start`` builtin accepts an argument that can be
3552 constant-evaluated to a function, and returns the address of the function
3553 body.  This builtin is not supported on all targets.
3555 The returned pointer may differ from the normally taken function address
3556 and is not safe to call.  For example, with ``-fsanitize=cfi``, taking a
3557 function address produces a callable pointer to a CFI jump table, while
3558 ``__builtin_function_start`` returns an address that fails
3559 :doc:`cfi-icall<ControlFlowIntegrity>` checks.
3561 ``__builtin_operator_new`` and ``__builtin_operator_delete``
3562 ------------------------------------------------------------
3564 A call to ``__builtin_operator_new(args)`` is exactly the same as a call to
3565 ``::operator new(args)``, except that it allows certain optimizations
3566 that the C++ standard does not permit for a direct function call to
3567 ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
3568 merging allocations), and that the call is required to resolve to a
3569 `replaceable global allocation function
3570 <https://en.cppreference.com/w/cpp/memory/new/operator_new>`_.
3572 Likewise, ``__builtin_operator_delete`` is exactly the same as a call to
3573 ``::operator delete(args)``, except that it permits optimizations
3574 and that the call is required to resolve to a
3575 `replaceable global deallocation function
3576 <https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_.
3578 These builtins are intended for use in the implementation of ``std::allocator``
3579 and other similar allocation libraries, and are only available in C++.
3581 Query for this feature with ``__has_builtin(__builtin_operator_new)`` or
3582 ``__has_builtin(__builtin_operator_delete)``:
3584   * If the value is at least ``201802L``, the builtins behave as described above.
3586   * If the value is non-zero, the builtins may not support calling arbitrary
3587     replaceable global (de)allocation functions, but do support calling at least
3588     ``::operator new(size_t)`` and ``::operator delete(void*)``.
3590 ``__builtin_preserve_access_index``
3591 -----------------------------------
3593 ``__builtin_preserve_access_index`` specifies a code section where
3594 array subscript access and structure/union member access are relocatable
3595 under bpf compile-once run-everywhere framework. Debuginfo (typically
3596 with ``-g``) is needed, otherwise, the compiler will exit with an error.
3597 The return type for the intrinsic is the same as the type of the
3598 argument.
3600 **Syntax**:
3602 .. code-block:: c
3604   type __builtin_preserve_access_index(type arg)
3606 **Example of Use**:
3608 .. code-block:: c
3610   struct t {
3611     int i;
3612     int j;
3613     union {
3614       int a;
3615       int b;
3616     } c[4];
3617   };
3618   struct t *v = ...;
3619   int *pb =__builtin_preserve_access_index(&v->c[3].b);
3620   __builtin_preserve_access_index(v->j);
3622 ``__builtin_debugtrap``
3623 -----------------------
3625 ``__builtin_debugtrap`` causes the program to stop its execution in such a way that a debugger can catch it.
3627 **Syntax**:
3629 .. code-block:: c++
3631     __builtin_debugtrap()
3633 **Description**
3635 ``__builtin_debugtrap`` is lowered to the ` ``llvm.debugtrap`` <https://llvm.org/docs/LangRef.html#llvm-debugtrap-intrinsic>`_ builtin. It should have the same effect as setting a breakpoint on the line where the builtin is called.
3637 Query for this feature with ``__has_builtin(__builtin_debugtrap)``.
3640 ``__builtin_trap``
3641 ------------------
3643 ``__builtin_trap`` causes the program to stop its execution abnormally.
3645 **Syntax**:
3647 .. code-block:: c++
3649     __builtin_trap()
3651 **Description**
3653 ``__builtin_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.
3655 Query for this feature with ``__has_builtin(__builtin_trap)``.
3657 ``__builtin_arm_trap``
3658 ----------------------
3660 ``__builtin_arm_trap`` is an AArch64 extension to ``__builtin_trap`` which also accepts a compile-time constant value, encoded directly into the trap instruction for later inspection.
3662 **Syntax**:
3664 .. code-block:: c++
3666     __builtin_arm_trap(const unsigned short payload)
3668 **Description**
3670 ``__builtin_arm_trap`` is lowered to the ``llvm.aarch64.break`` builtin, and then to ``brk #payload``.
3672 ``__builtin_verbose_trap``
3673 --------------------------
3675 ``__builtin_verbose_trap`` causes the program to stop its execution abnormally
3676 and shows a human-readable description of the reason for the termination when a
3677 debugger is attached or in a symbolicated crash log.
3679 **Syntax**:
3681 .. code-block:: c++
3683     __builtin_verbose_trap(const char *category, const char *reason)
3685 **Description**
3687 ``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.
3688 Additionally, clang emits debugging information that represents an artificial
3689 inline frame whose name encodes the category and reason strings passed to the builtin,
3690 prefixed by a "magic" prefix.
3692 For example, consider the following code:
3694 .. code-block:: c++
3696     void foo(int* p) {
3697       if (p == nullptr)
3698         __builtin_verbose_trap("check null", "Argument must not be null!");
3699     }
3701 The debugging information would look as if it were produced for the following code:
3703 .. code-block:: c++
3705     __attribute__((always_inline))
3706     inline void "__clang_trap_msg$check null$Argument must not be null!"() {
3707       __builtin_trap();
3708     }
3710     void foo(int* p) {
3711       if (p == nullptr)
3712         "__clang_trap_msg$check null$Argument must not be null!"();
3713     }
3715 However, the generated code would not actually contain a call to the artificial
3716 function â€” it only exists in the debugging information.
3718 Query for this feature with ``__has_builtin(__builtin_verbose_trap)``. Note that
3719 users need to enable debug information to enable this feature. A call to this
3720 builtin is equivalent to a call to ``__builtin_trap`` if debug information isn't
3721 enabled.
3723 The optimizer can merge calls to trap with different messages, which degrades
3724 the debugging experience.
3726 ``__builtin_allow_runtime_check``
3727 ---------------------------------
3729 ``__builtin_allow_runtime_check`` returns true if the check at the current
3730 program location should be executed. It is expected to be used to implement
3731 ``assert`` like checks which can be safely removed by optimizer.
3733 **Syntax**:
3735 .. code-block:: c++
3737     bool __builtin_allow_runtime_check(const char* kind)
3739 **Example of use**:
3741 .. code-block:: c++
3743   if (__builtin_allow_runtime_check("mycheck") && !ExpensiveCheck()) {
3744      abort();
3745   }
3747 **Description**
3749 ``__builtin_allow_runtime_check`` is lowered to the `llvm.allow.runtime.check
3750 <https://llvm.org/docs/LangRef.html#llvm-allow-runtime-check-intrinsic>`_
3751 intrinsic.
3753 The ``__builtin_allow_runtime_check()`` can be used within control structures
3754 like ``if`` to guard expensive runtime checks. The return value is determined
3755 by the following compiler options and may differ per call site:
3757 * ``-mllvm -lower-allow-check-percentile-cutoff-hot=N``: Disable checks in hot
3758   code marked by the profile summary with a hotness cutoff in the range
3759   ``[0, 999999]`` (a larger N disables more checks).
3760 * ``-mllvm -lower-allow-check-random-rate=P``: Keep a check with probability P,
3761   a floating point number in the range ``[0.0, 1.0]``.
3762 * If both options are specified, a check is disabled if either condition is satisfied.
3763 * If neither is specified, all checks are allowed.
3765 Parameter ``kind``, currently unused, is a string literal specifying the check
3766 kind. Future compiler versions may use this to allow for more granular control,
3767 such as applying different hotness cutoffs to different check kinds.
3769 Query for this feature with ``__has_builtin(__builtin_allow_runtime_check)``.
3771 ``__builtin_nondeterministic_value``
3772 ------------------------------------
3774 ``__builtin_nondeterministic_value`` returns a valid nondeterministic value of the same type as the provided argument.
3776 **Syntax**:
3778 .. code-block:: c++
3780     type __builtin_nondeterministic_value(type x)
3782 **Examples**:
3784 .. code-block:: c++
3786     int x = __builtin_nondeterministic_value(x);
3787     float y = __builtin_nondeterministic_value(y);
3788     __m256i a = __builtin_nondeterministic_value(a);
3790 **Description**
3792 Each call to ``__builtin_nondeterministic_value`` returns a valid value of the type given by the argument.
3794 The types currently supported are: integer types, floating-point types, vector types.
3796 Query for this feature with ``__has_builtin(__builtin_nondeterministic_value)``.
3798 ``__builtin_sycl_unique_stable_name``
3799 -------------------------------------
3801 ``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and
3802 produces a string literal containing a unique name for the type that is stable
3803 across split compilations, mainly to support SYCL/Data Parallel C++ language.
3805 In cases where the split compilation needs to share a unique token for a type
3806 across the boundary (such as in an offloading situation), this name can be used
3807 for lookup purposes, such as in the SYCL Integration Header.
3809 The value of this builtin is computed entirely at compile time, so it can be
3810 used in constant expressions. This value encodes lambda functions based on a
3811 stable numbering order in which they appear in their local declaration contexts.
3812 Once this builtin is evaluated in a constexpr context, it is erroneous to use
3813 it in an instantiation which changes its value.
3815 In order to produce the unique name, the current implementation of the builtin
3816 uses Itanium mangling even if the host compilation uses a different name
3817 mangling scheme at runtime. The mangler marks all the lambdas required to name
3818 the SYCL kernel and emits a stable local ordering of the respective lambdas.
3819 The resulting pattern is demanglable.  When non-lambda types are passed to the
3820 builtin, the mangler emits their usual pattern without any special treatment.
3822 **Syntax**:
3824 .. code-block:: c
3826   // Computes a unique stable name for the given type.
3827   constexpr const char * __builtin_sycl_unique_stable_name( type-id );
3829 ``__builtin_popcountg``
3830 -----------------------
3832 ``__builtin_popcountg`` returns the number of 1 bits in the argument. The
3833 argument can be of any unsigned integer type.
3835 **Syntax**:
3837 .. code-block:: c++
3839   int __builtin_popcountg(type x)
3841 **Examples**:
3843 .. code-block:: c++
3845   unsigned int x = 1;
3846   int x_pop = __builtin_popcountg(x);
3848   unsigned long y = 3;
3849   int y_pop = __builtin_popcountg(y);
3851   unsigned _BitInt(128) z = 7;
3852   int z_pop = __builtin_popcountg(z);
3854 **Description**:
3856 ``__builtin_popcountg`` is meant to be a type-generic alternative to the
3857 ``__builtin_popcount{,l,ll}`` builtins, with support for other integer types,
3858 such as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.
3860 ``__builtin_clzg`` and ``__builtin_ctzg``
3861 -----------------------------------------
3863 ``__builtin_clzg`` (respectively ``__builtin_ctzg``) returns the number of
3864 leading (respectively trailing) 0 bits in the first argument. The first argument
3865 can be of any unsigned integer type.
3867 If the first argument is 0 and an optional second argument of ``int`` type is
3868 provided, then the second argument is returned. If the first argument is 0, but
3869 only one argument is provided, then the behavior is undefined.
3871 **Syntax**:
3873 .. code-block:: c++
3875   int __builtin_clzg(type x[, int fallback])
3876   int __builtin_ctzg(type x[, int fallback])
3878 **Examples**:
3880 .. code-block:: c++
3882   unsigned int x = 1;
3883   int x_lz = __builtin_clzg(x);
3884   int x_tz = __builtin_ctzg(x);
3886   unsigned long y = 2;
3887   int y_lz = __builtin_clzg(y);
3888   int y_tz = __builtin_ctzg(y);
3890   unsigned _BitInt(128) z = 4;
3891   int z_lz = __builtin_clzg(z);
3892   int z_tz = __builtin_ctzg(z);
3894 **Description**:
3896 ``__builtin_clzg`` (respectively ``__builtin_ctzg``) is meant to be a
3897 type-generic alternative to the ``__builtin_clz{,l,ll}`` (respectively
3898 ``__builtin_ctz{,l,ll}``) builtins, with support for other integer types, such
3899 as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.
3901 ``__builtin_counted_by_ref``
3902 ----------------------------
3904 ``__builtin_counted_by_ref`` returns a pointer to the count field from the
3905 ``counted_by`` attribute.
3907 The argument must be a flexible array member. If the argument isn't a flexible
3908 array member or doesn't have the ``counted_by`` attribute, the builtin returns
3909 ``(void *)0``.
3911 **Syntax**:
3913 .. code-block:: c
3915   T *__builtin_counted_by_ref(void *array)
3917 **Examples**:
3919 .. code-block:: c
3921   #define alloc(P, FAM, COUNT) ({                                 \
3922      size_t __ignored_assignment;                                 \
3923      typeof(P) __p = NULL;                                        \
3924      __p = malloc(MAX(sizeof(*__p),                               \
3925                       sizeof(*__p) + sizeof(*__p->FAM) * COUNT)); \
3926                                                                   \
3927      *_Generic(                                                   \
3928        __builtin_counted_by_ref(__p->FAM),                        \
3929          void *: &__ignored_assignment,                           \
3930          default: __builtin_counted_by_ref(__p->FAM)) = COUNT;    \
3931                                                                   \
3932      __p;                                                         \
3933   })
3935 **Description**:
3937 The ``__builtin_counted_by_ref`` builtin allows the programmer to prevent a
3938 common error associated with the ``counted_by`` attribute. When using the
3939 ``counted_by`` attribute, the ``count`` field **must** be set before the
3940 flexible array member can be accessed. Otherwise, the sanitizers may view such
3941 accesses as false positives. For instance, it's not uncommon for programmers to
3942 initialize the flexible array before setting the ``count`` field:
3944 .. code-block:: c
3946   struct s {
3947     int dummy;
3948     short count;
3949     long array[] __attribute__((counted_by(count)));
3950   };
3952   struct s *ptr = malloc(sizeof(struct s) + sizeof(long) * COUNT);
3954   for (int i = 0; i < COUNT; ++i)
3955     ptr->array[i] = i;
3957   ptr->count = COUNT;
3959 Enforcing the rule that ``ptr->count = COUNT;`` must occur after every
3960 allocation of a struct with a flexible array member with the ``counted_by``
3961 attribute is prone to failure in large code bases. This builtin mitigates this
3962 for allocators (like in Linux) that are implemented in a way where the counter
3963 assignment can happen automatically.
3965 **Note:** The value returned by ``__builtin_counted_by_ref`` cannot be assigned
3966 to a variable, have its address taken, or passed into or returned from a
3967 function, because doing so violates bounds safety conventions.
3969 Multiprecision Arithmetic Builtins
3970 ----------------------------------
3972 Clang provides a set of builtins which expose multiprecision arithmetic in a
3973 manner amenable to C. They all have the following form:
3975 .. code-block:: c
3977   unsigned x = ..., y = ..., carryin = ..., carryout;
3978   unsigned sum = __builtin_addc(x, y, carryin, &carryout);
3980 Thus one can form a multiprecision addition chain in the following manner:
3982 .. code-block:: c
3984   unsigned *x, *y, *z, carryin=0, carryout;
3985   z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
3986   carryin = carryout;
3987   z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
3988   carryin = carryout;
3989   z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
3990   carryin = carryout;
3991   z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
3993 The complete list of builtins are:
3995 .. code-block:: c
3997   unsigned char      __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
3998   unsigned short     __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
3999   unsigned           __builtin_addc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
4000   unsigned long      __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
4001   unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
4002   unsigned char      __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
4003   unsigned short     __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
4004   unsigned           __builtin_subc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
4005   unsigned long      __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
4006   unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
4008 Checked Arithmetic Builtins
4009 ---------------------------
4011 Clang provides a set of builtins that implement checked arithmetic for security
4012 critical applications in a manner that is fast and easily expressible in C. As
4013 an example of their usage:
4015 .. code-block:: c
4017   errorcode_t security_critical_application(...) {
4018     unsigned x, y, result;
4019     ...
4020     if (__builtin_mul_overflow(x, y, &result))
4021       return kErrorCodeHackers;
4022     ...
4023     use_multiply(result);
4024     ...
4025   }
4027 Clang provides the following checked arithmetic builtins:
4029 .. code-block:: c
4031   bool __builtin_add_overflow   (type1 x, type2 y, type3 *sum);
4032   bool __builtin_sub_overflow   (type1 x, type2 y, type3 *diff);
4033   bool __builtin_mul_overflow   (type1 x, type2 y, type3 *prod);
4034   bool __builtin_uadd_overflow  (unsigned x, unsigned y, unsigned *sum);
4035   bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
4036   bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
4037   bool __builtin_usub_overflow  (unsigned x, unsigned y, unsigned *diff);
4038   bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
4039   bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
4040   bool __builtin_umul_overflow  (unsigned x, unsigned y, unsigned *prod);
4041   bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
4042   bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
4043   bool __builtin_sadd_overflow  (int x, int y, int *sum);
4044   bool __builtin_saddl_overflow (long x, long y, long *sum);
4045   bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
4046   bool __builtin_ssub_overflow  (int x, int y, int *diff);
4047   bool __builtin_ssubl_overflow (long x, long y, long *diff);
4048   bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
4049   bool __builtin_smul_overflow  (int x, int y, int *prod);
4050   bool __builtin_smull_overflow (long x, long y, long *prod);
4051   bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
4053 Each builtin performs the specified mathematical operation on the
4054 first two arguments and stores the result in the third argument.  If
4055 possible, the result will be equal to mathematically-correct result
4056 and the builtin will return 0.  Otherwise, the builtin will return
4057 1 and the result will be equal to the unique value that is equivalent
4058 to the mathematically-correct result modulo two raised to the *k*
4059 power, where *k* is the number of bits in the result type.  The
4060 behavior of these builtins is well-defined for all argument values.
4062 The first three builtins work generically for operands of any integer type,
4063 including boolean types.  The operands need not have the same type as each
4064 other, or as the result.  The other builtins may implicitly promote or
4065 convert their operands before performing the operation.
4067 Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
4069 Floating point builtins
4070 ---------------------------------------
4072 ``__builtin_isfpclass``
4073 -----------------------
4075 ``__builtin_isfpclass`` is used to test if the specified floating-point values
4076 fall into one of the specified floating-point classes.
4078 **Syntax**:
4080 .. code-block:: c++
4082     int __builtin_isfpclass(fp_type expr, int mask)
4083     int_vector __builtin_isfpclass(fp_vector expr, int mask)
4085 **Example of use**:
4087 .. code-block:: c++
4089   if (__builtin_isfpclass(x, 448)) {
4090      // `x` is positive finite value
4091          ...
4092   }
4094 **Description**:
4096 The ``__builtin_isfpclass()`` builtin is a generalization of functions ``isnan``,
4097 ``isinf``, ``isfinite`` and some others defined by the C standard. It tests if
4098 the floating-point value, specified by the first argument, falls into any of data
4099 classes, specified by the second argument. The latter is an integer constant
4100 bitmask expression, in which each data class is represented by a bit
4101 using the encoding:
4103 ========== =================== ======================
4104 Mask value Data class          Macro
4105 ========== =================== ======================
4106 0x0001     Signaling NaN       __FPCLASS_SNAN
4107 0x0002     Quiet NaN           __FPCLASS_QNAN
4108 0x0004     Negative infinity   __FPCLASS_NEGINF
4109 0x0008     Negative normal     __FPCLASS_NEGNORMAL
4110 0x0010     Negative subnormal  __FPCLASS_NEGSUBNORMAL
4111 0x0020     Negative zero       __FPCLASS_NEGZERO
4112 0x0040     Positive zero       __FPCLASS_POSZERO
4113 0x0080     Positive subnormal  __FPCLASS_POSSUBNORMAL
4114 0x0100     Positive normal     __FPCLASS_POSNORMAL
4115 0x0200     Positive infinity   __FPCLASS_POSINF
4116 ========== =================== ======================
4118 For convenience preprocessor defines macros for these values. The function
4119 returns 1 if ``expr`` falls into one of the specified data classes, 0 otherwise.
4121 In the example above the mask value 448 (0x1C0) contains the bits selecting
4122 positive zero, positive subnormal and positive normal classes.
4123 ``__builtin_isfpclass(x, 448)`` would return true only if ``x`` if of any of
4124 these data classes. Using suitable mask value, the function can implement any of
4125 the standard classification functions, for example, ``__builtin_isfpclass(x, 3)``
4126 is identical to ``isnan``,``__builtin_isfpclass(x, 504)`` - to ``isfinite``
4127 and so on.
4129 If the first argument is a vector, the function is equivalent to the set of
4130 scalar calls of ``__builtin_isfpclass`` applied to the input elementwise.
4132 The result of ``__builtin_isfpclass`` is a boolean value, if the first argument
4133 is a scalar, or an integer vector with the same element count as the first
4134 argument. The element type in this vector has the same bit length as the
4135 element of the first argument type.
4137 This function never raises floating-point exceptions and does not canonicalize
4138 its input. The floating-point argument is not promoted, its data class is
4139 determined based on its representation in its actual semantic type.
4141 ``__builtin_canonicalize``
4142 --------------------------
4144 .. code-block:: c
4146    double __builtin_canonicalize(double);
4147    float __builtin_canonicalizef(float);
4148    long double __builtin_canonicalizel(long double);
4150 Returns the platform specific canonical encoding of a floating point
4151 number. This canonicalization is useful for implementing certain
4152 numeric primitives such as frexp. See `LLVM canonicalize intrinsic
4153 <https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
4154 more information on the semantics.
4156 ``__builtin_flt_rounds`` and ``__builtin_set_flt_rounds``
4157 ---------------------------------------------------------
4159 .. code-block:: c
4161    int __builtin_flt_rounds();
4162    void __builtin_set_flt_rounds(int);
4164 Returns and sets current floating point rounding mode. The encoding of returned
4165 values and input parameters is same as the result of FLT_ROUNDS, specified by C
4166 standard:
4167 - ``0``  - toward zero
4168 - ``1``  - to nearest, ties to even
4169 - ``2``  - toward positive infinity
4170 - ``3``  - toward negative infinity
4171 - ``4``  - to nearest, ties away from zero
4172 The effect of passing some other value to ``__builtin_flt_rounds`` is
4173 implementation-defined. ``__builtin_set_flt_rounds`` is currently only supported
4174 to work on x86, x86_64, powerpc, powerpc64, Arm and AArch64 targets. These builtins
4175 read and modify the floating-point environment, which is not always allowed and may
4176 have unexpected behavior. Please see the section on `Accessing the floating point environment <https://clang.llvm.org/docs/UsersManual.html#accessing-the-floating-point-environment>`_ for more information.
4178 String builtins
4179 ---------------
4181 Clang provides constant expression evaluation support for builtins forms of
4182 the following functions from the C standard library headers
4183 ``<string.h>`` and ``<wchar.h>``:
4185 * ``memchr``
4186 * ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``)
4187 * ``strchr``
4188 * ``strcmp``
4189 * ``strlen``
4190 * ``strncmp``
4191 * ``wcschr``
4192 * ``wcscmp``
4193 * ``wcslen``
4194 * ``wcsncmp``
4195 * ``wmemchr``
4196 * ``wmemcmp``
4198 In each case, the builtin form has the name of the C library function prefixed
4199 by ``__builtin_``. Example:
4201 .. code-block:: c
4203   void *p = __builtin_memchr("foobar", 'b', 5);
4205 In addition to the above, one further builtin is provided:
4207 .. code-block:: c
4209   char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
4211 ``__builtin_char_memchr(a, b, c)`` is identical to
4212 ``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
4213 constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
4214 is disallowed in general).
4216 Constant evaluation support for the ``__builtin_mem*`` functions is provided
4217 only for arrays of ``char``, ``signed char``, ``unsigned char``, or ``char8_t``,
4218 despite these functions accepting an argument of type ``const void*``.
4220 Support for constant expression evaluation for the above builtins can be detected
4221 with ``__has_feature(cxx_constexpr_string_builtins)``.
4223 Variadic function builtins
4224 --------------------------
4226 Clang provides several builtins for working with variadic functions from the C
4227 standard library ``<stdarg.h>`` header:
4229 * ``__builtin_va_list``
4231 A predefined typedef for the target-specific ``va_list`` type. It is undefined
4232 behavior to use a byte-wise copy of this type produced by calling ``memcpy``,
4233 ``memmove``, or similar. Valid explicit copies are only produced by calling
4234 ``va_copy`` or ``__builtin_va_copy``.
4236 * ``void __builtin_va_start(__builtin_va_list list, <parameter-name>)``
4238 A builtin function for the target-specific ``va_start`` function-like macro.
4239 The ``parameter-name`` argument is the name of the parameter preceding the
4240 ellipsis (``...``) in the function signature. Alternatively, in C23 mode or
4241 later, it may be the integer literal ``0`` if there is no parameter preceding
4242 the ellipsis. This function initializes the given ``__builtin_va_list`` object.
4243 It is undefined behavior to call this function on an already initialized
4244 ``__builtin_va_list`` object.
4246 * ``void __builtin_va_end(__builtin_va_list list)``
4248 A builtin function for the target-specific ``va_end`` function-like macro. This
4249 function finalizes the given ``__builtin_va_list`` object such that it is no
4250 longer usable unless re-initialized with a call to ``__builtin_va_start`` or
4251 ``__builtin_va_copy``. It is undefined behavior to call this function with a
4252 ``list`` that has not been initialized by either ``__builtin_va_start`` or
4253 ``__builtin_va_copy``.
4255 * ``<type-name> __builtin_va_arg(__builtin_va_list list, <type-name>)``
4257 A builtin function for the target-specific ``va_arg`` function-like macro. This
4258 function returns the value of the next variadic argument to the call. It is
4259 undefined behavior to call this builtin when there is no next variadic argument
4260 to retrieve or if the next variadic argument does not have a type compatible
4261 with the given ``type-name``. The return type of the function is the
4262 ``type-name`` given as the second argument. It is undefined behavior to call
4263 this function with a ``list`` that has not been initialized by either
4264 ``__builtin_va_start`` or ``__builtin_va_copy``.
4266 * ``void __builtin_va_copy(__builtin_va_list dest, __builtin_va_list src)``
4268 A builtin function for the target-specific ``va_copy`` function-like macro.
4269 This function initializes ``dest`` as a copy of ``src``. It is undefined
4270 behavior to call this function with an already initialized ``dest`` argument.
4272 Memory builtins
4273 ---------------
4275 Clang provides constant expression evaluation support for builtin forms of the
4276 following functions from the C standard library headers
4277 ``<string.h>`` and ``<wchar.h>``:
4279 * ``memcpy``
4280 * ``memmove``
4281 * ``wmemcpy``
4282 * ``wmemmove``
4284 In each case, the builtin form has the name of the C library function prefixed
4285 by ``__builtin_``.
4287 Constant evaluation support is only provided when the source and destination
4288 are pointers to arrays with the same trivially copyable element type, and the
4289 given size is an exact multiple of the element size that is no greater than
4290 the number of elements accessible through the source and destination operands.
4292 Guaranteed inlined copy
4293 ^^^^^^^^^^^^^^^^^^^^^^^
4295 .. code-block:: c
4297   void __builtin_memcpy_inline(void *dst, const void *src, size_t size);
4300 ``__builtin_memcpy_inline`` has been designed as a building block for efficient
4301 ``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also
4302 guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline
4303 <https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic
4304 for more information.
4306 This is useful to implement a custom version of ``memcpy``, implement a
4307 ``libc`` memcpy or work around the absence of a ``libc``.
4309 Note that the `size` argument must be a compile time constant.
4311 Note that this intrinsic cannot yet be called in a ``constexpr`` context.
4313 Guaranteed inlined memset
4314 ^^^^^^^^^^^^^^^^^^^^^^^^^
4316 .. code-block:: c
4318   void __builtin_memset_inline(void *dst, int value, size_t size);
4321 ``__builtin_memset_inline`` has been designed as a building block for efficient
4322 ``memset`` implementations. It is identical to ``__builtin_memset`` but also
4323 guarantees not to call any external functions. See LLVM IR `llvm.memset.inline
4324 <https://llvm.org/docs/LangRef.html#llvm-memset-inline-intrinsic>`_ intrinsic
4325 for more information.
4327 This is useful to implement a custom version of ``memset``, implement a
4328 ``libc`` memset or work around the absence of a ``libc``.
4330 Note that the `size` argument must be a compile time constant.
4332 Note that this intrinsic cannot yet be called in a ``constexpr`` context.
4334 ``__is_bitwise_cloneable``
4335 --------------------------
4337 A type trait is used to check whether a type can be safely copied by memcpy.
4339 **Syntax**:
4341 .. code-block:: c++
4343   bool __is_bitwise_cloneable(Type)
4345 **Description**:
4347 Objects of bitwise cloneable types can be bitwise copied by memcpy/memmove. The
4348 Clang compiler warrants that this behavior is well defined, and won't be
4349 broken by compiler optimizations and sanitizers.
4351 For implicit-lifetime types, the lifetime of the new object is implicitly
4352 started after the copy. For other types (e.g., classes with virtual methods),
4353 the lifetime isn't started, and using the object results in undefined behavior
4354 according to the C++ Standard.
4356 This builtin can be used in constant expressions.
4358 Atomic Min/Max builtins with memory ordering
4359 --------------------------------------------
4361 There are two atomic builtins with min/max in-memory comparison and swap.
4362 The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
4364 * ``__atomic_fetch_min``
4365 * ``__atomic_fetch_max``
4367 The builtins work with signed and unsigned integers and require to specify memory ordering.
4368 The return value is the original value that was stored in memory before comparison.
4370 Example:
4372 .. code-block:: c
4374   unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
4376 The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
4377 ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
4378 ``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
4380 In terms of acquire-release ordering barriers these two operations are always
4381 considered as operations with *load-store* semantics, even when the original value
4382 is not actually modified after comparison.
4384 .. _langext-__c11_atomic:
4386 __c11_atomic builtins
4387 ---------------------
4389 Clang provides a set of builtins which are intended to be used to implement
4390 C11's ``<stdatomic.h>`` header.  These builtins provide the semantics of the
4391 ``_explicit`` form of the corresponding C11 operation, and are named with a
4392 ``__c11_`` prefix.  The supported operations, and the differences from
4393 the corresponding C11 operations, are:
4395 * ``__c11_atomic_init``
4396 * ``__c11_atomic_thread_fence``
4397 * ``__c11_atomic_signal_fence``
4398 * ``__c11_atomic_is_lock_free`` (The argument is the size of the
4399   ``_Atomic(...)`` object, instead of its address)
4400 * ``__c11_atomic_store``
4401 * ``__c11_atomic_load``
4402 * ``__c11_atomic_exchange``
4403 * ``__c11_atomic_compare_exchange_strong``
4404 * ``__c11_atomic_compare_exchange_weak``
4405 * ``__c11_atomic_fetch_add``
4406 * ``__c11_atomic_fetch_sub``
4407 * ``__c11_atomic_fetch_and``
4408 * ``__c11_atomic_fetch_or``
4409 * ``__c11_atomic_fetch_xor``
4410 * ``__c11_atomic_fetch_nand`` (Nand is not presented in ``<stdatomic.h>``)
4411 * ``__c11_atomic_fetch_max``
4412 * ``__c11_atomic_fetch_min``
4414 The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
4415 ``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
4416 provided, with values corresponding to the enumerators of C11's
4417 ``memory_order`` enumeration.
4419 (Note that Clang additionally provides GCC-compatible ``__atomic_*``
4420 builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
4421 atomic builtins are an explicit form of the corresponding OpenCL 2.0
4422 builtin function, and are named with a ``__opencl_`` prefix. The macros
4423 ``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
4424 ``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
4425 and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
4426 corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
4428 __scoped_atomic builtins
4429 ------------------------
4431 Clang provides a set of atomics taking a memory scope argument. These atomics
4432 are identical to the standard GNU / GCC atomic builtins but taking an extra
4433 memory scope argument. These are designed to be a generic alternative to the
4434 ``__opencl_atomic_*`` builtin functions for targets that support atomic memory
4435 scopes.
4437 Atomic memory scopes are designed to assist optimizations for systems with
4438 several levels of memory hierarchy like GPUs. The following memory scopes are
4439 currently supported:
4441 * ``__MEMORY_SCOPE_SYSTEM``
4442 * ``__MEMORY_SCOPE_DEVICE``
4443 * ``__MEMORY_SCOPE_WRKGRP``
4444 * ``__MEMORY_SCOPE_WVFRNT``
4445 * ``__MEMORY_SCOPE_SINGLE``
4447 This controls whether or not the atomic operation is ordered with respect to the
4448 whole system, the current device, an OpenCL workgroup, wavefront, or just a
4449 single thread. If these are used on a target that does not support atomic
4450 scopes, then they will behave exactly as the standard GNU atomic builtins.
4452 Low-level ARM exclusive memory builtins
4453 ---------------------------------------
4455 Clang provides overloaded builtins giving direct access to the three key ARM
4456 instructions for implementing atomic operations.
4458 .. code-block:: c
4460   T __builtin_arm_ldrex(const volatile T *addr);
4461   T __builtin_arm_ldaex(const volatile T *addr);
4462   int __builtin_arm_strex(T val, volatile T *addr);
4463   int __builtin_arm_stlex(T val, volatile T *addr);
4464   void __builtin_arm_clrex(void);
4466 The types ``T`` currently supported are:
4468 * Integer types with width at most 64 bits (or 128 bits on AArch64).
4469 * Floating-point types
4470 * Pointer types.
4472 Note that the compiler does not guarantee it will not insert stores which clear
4473 the exclusive monitor in between an ``ldrex`` type operation and its paired
4474 ``strex``. In practice this is only usually a risk when the extra store is on
4475 the same cache line as the variable being modified and Clang will only insert
4476 stack stores on its own, so it is best not to use these operations on variables
4477 with automatic storage duration.
4479 Also, loads and stores may be implicit in code written between the ``ldrex`` and
4480 ``strex``. Clang will not necessarily mitigate the effects of these either, so
4481 care should be exercised.
4483 For these reasons the higher level atomic primitives should be preferred where
4484 possible.
4486 Non-temporal load/store builtins
4487 --------------------------------
4489 Clang provides overloaded builtins allowing generation of non-temporal memory
4490 accesses.
4492 .. code-block:: c
4494   T __builtin_nontemporal_load(T *addr);
4495   void __builtin_nontemporal_store(T value, T *addr);
4497 The types ``T`` currently supported are:
4499 * Integer types.
4500 * Floating-point types.
4501 * Vector types.
4503 Note that the compiler does not guarantee that non-temporal loads or stores
4504 will be used.
4506 C++ Coroutines support builtins
4507 --------------------------------
4509 .. warning::
4510   This is a work in progress. Compatibility across Clang/LLVM releases is not
4511   guaranteed.
4513 Clang provides experimental builtins to support C++ Coroutines as defined by
4514 https://wg21.link/P0057. The following four are intended to be used by the
4515 standard library to implement the ``std::coroutine_handle`` type.
4517 **Syntax**:
4519 .. code-block:: c
4521   void  __builtin_coro_resume(void *addr);
4522   void  __builtin_coro_destroy(void *addr);
4523   bool  __builtin_coro_done(void *addr);
4524   void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
4526 **Example of use**:
4528 .. code-block:: c++
4530   template <> struct coroutine_handle<void> {
4531     void resume() const { __builtin_coro_resume(ptr); }
4532     void destroy() const { __builtin_coro_destroy(ptr); }
4533     bool done() const { return __builtin_coro_done(ptr); }
4534     // ...
4535   protected:
4536     void *ptr;
4537   };
4539   template <typename Promise> struct coroutine_handle : coroutine_handle<> {
4540     // ...
4541     Promise &promise() const {
4542       return *reinterpret_cast<Promise *>(
4543         __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
4544     }
4545     static coroutine_handle from_promise(Promise &promise) {
4546       coroutine_handle p;
4547       p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
4548                                                       /*from-promise=*/true);
4549       return p;
4550     }
4551   };
4554 Other coroutine builtins are either for internal clang use or for use during
4555 development of the coroutine feature. See `Coroutines in LLVM
4556 <https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
4557 more information on their semantics. Note that builtins matching the intrinsics
4558 that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
4559 llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
4560 an appropriate value during the emission.
4562 **Syntax**:
4564 .. code-block:: c
4566   size_t __builtin_coro_size()
4567   void  *__builtin_coro_frame()
4568   void  *__builtin_coro_free(void *coro_frame)
4570   void  *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
4571   bool   __builtin_coro_alloc()
4572   void  *__builtin_coro_begin(void *memory)
4573   void   __builtin_coro_end(void *coro_frame, bool unwind)
4574   char   __builtin_coro_suspend(bool final)
4576 Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
4577 automatically will insert one if the first argument to `llvm.coro.suspend` is
4578 token `none`. If a user calls `__builtin_suspend`, clang will insert `token none`
4579 as the first argument to the intrinsic.
4581 Source location builtins
4582 ------------------------
4584 Clang provides builtins to support C++ standard library implementation
4585 of ``std::source_location`` as specified in C++20.  With the exception
4586 of ``__builtin_COLUMN``, ``__builtin_FILE_NAME`` and ``__builtin_FUNCSIG``,
4587 these builtins are also implemented by GCC.
4589 **Syntax**:
4591 .. code-block:: c
4593   const char *__builtin_FILE();
4594   const char *__builtin_FILE_NAME(); // Clang only
4595   const char *__builtin_FUNCTION();
4596   const char *__builtin_FUNCSIG(); // Microsoft
4597   unsigned    __builtin_LINE();
4598   unsigned    __builtin_COLUMN(); // Clang only
4599   const std::source_location::__impl *__builtin_source_location();
4601 **Example of use**:
4603 .. code-block:: c++
4605   void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
4606                  const char* file = __builtin_FILE(),
4607                  const char* function = __builtin_FUNCTION()) {
4608     if (pred) return;
4609     printf("%s:%d assertion failed in function %s\n", file, line, function);
4610     std::abort();
4611   }
4613   struct MyAggregateType {
4614     int x;
4615     int line = __builtin_LINE(); // captures line where aggregate initialization occurs
4616   };
4617   static_assert(MyAggregateType{42}.line == __LINE__);
4619   struct MyClassType {
4620     int line = __builtin_LINE(); // captures line of the constructor used during initialization
4621     constexpr MyClassType(int) { assert(line == __LINE__); }
4622   };
4624 **Description**:
4626 The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, ``__builtin_FUNCSIG``,
4627 ``__builtin_FILE`` and ``__builtin_FILE_NAME`` return the values, at the
4628 "invocation point", for ``__LINE__``, ``__FUNCTION__``, ``__FUNCSIG__``,
4629 ``__FILE__`` and ``__FILE_NAME__`` respectively. ``__builtin_COLUMN`` similarly
4630 returns the column, though there is no corresponding macro. These builtins are
4631 constant expressions.
4633 When the builtins appear as part of a default function argument the invocation
4634 point is the location of the caller. When the builtins appear as part of a
4635 default member initializer, the invocation point is the location of the
4636 constructor or aggregate initialization used to create the object. Otherwise
4637 the invocation point is the same as the location of the builtin.
4639 When the invocation point of ``__builtin_FUNCTION`` is not a function scope, the
4640 empty string is returned.
4642 The builtin ``__builtin_COLUMN`` returns the offset from the start of the line,
4643 beginning from column 1. `This may differ from other implementations.
4644 <https://eel.is/c++draft/support.srcloc#tab:support.srcloc.current-row-3-column-2-sentence-2>`_
4646 The builtin ``__builtin_source_location`` returns a pointer to constant static
4647 data of type ``std::source_location::__impl``. This type must have already been
4648 defined, and must contain exactly four fields: ``const char *_M_file_name``,
4649 ``const char *_M_function_name``, ``<any-integral-type> _M_line``, and
4650 ``<any-integral-type> _M_column``. The fields will be populated in the same
4651 manner as the above four builtins, except that ``_M_function_name`` is populated
4652 with ``__PRETTY_FUNCTION__`` rather than ``__FUNCTION__``.
4655 Alignment builtins
4656 ------------------
4657 Clang provides builtins to support checking and adjusting alignment of
4658 pointers and integers.
4659 These builtins can be used to avoid relying on implementation-defined behavior
4660 of arithmetic on integers derived from pointers.
4661 Additionally, these builtins retain type information and, unlike bitwise
4662 arithmetic, they can perform semantic checking on the alignment value.
4664 **Syntax**:
4666 .. code-block:: c
4668   Type __builtin_align_up(Type value, size_t alignment);
4669   Type __builtin_align_down(Type value, size_t alignment);
4670   bool __builtin_is_aligned(Type value, size_t alignment);
4673 **Example of use**:
4675 .. code-block:: c++
4677   char* global_alloc_buffer;
4678   void* my_aligned_allocator(size_t alloc_size, size_t alignment) {
4679     char* result = __builtin_align_up(global_alloc_buffer, alignment);
4680     // result now contains the value of global_alloc_buffer rounded up to the
4681     // next multiple of alignment.
4682     global_alloc_buffer = result + alloc_size;
4683     return result;
4684   }
4686   void* get_start_of_page(void* ptr) {
4687     return __builtin_align_down(ptr, PAGE_SIZE);
4688   }
4690   void example(char* buffer) {
4691      if (__builtin_is_aligned(buffer, 64)) {
4692        do_fast_aligned_copy(buffer);
4693      } else {
4694        do_unaligned_copy(buffer);
4695      }
4696   }
4698   // In addition to pointers, the builtins can also be used on integer types
4699   // and are evaluatable inside constant expressions.
4700   static_assert(__builtin_align_up(123, 64) == 128, "");
4701   static_assert(__builtin_align_down(123u, 64) == 64u, "");
4702   static_assert(!__builtin_is_aligned(123, 64), "");
4705 **Description**:
4707 The builtins ``__builtin_align_up``, ``__builtin_align_down``, return their
4708 first argument aligned up/down to the next multiple of the second argument.
4709 If the value is already sufficiently aligned, it is returned unchanged.
4710 The builtin ``__builtin_is_aligned`` returns whether the first argument is
4711 aligned to a multiple of the second argument.
4712 All of these builtins expect the alignment to be expressed as a number of bytes.
4714 These builtins can be used for all integer types as well as (non-function)
4715 pointer types. For pointer types, these builtins operate in terms of the integer
4716 address of the pointer and return a new pointer of the same type (including
4717 qualifiers such as ``const``) with an adjusted address.
4718 When aligning pointers up or down, the resulting value must be within the same
4719 underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]).
4720 This means that arbitrary integer values stored in pointer-type variables must
4721 not be passed to these builtins. For those use cases, the builtins can still be
4722 used, but the operation must be performed on the pointer cast to ``uintptr_t``.
4724 If Clang can determine that the alignment is not a power of two at compile time,
4725 it will result in a compilation failure. If the alignment argument is not a
4726 power of two at run time, the behavior of these builtins is undefined.
4728 Non-standard C++11 Attributes
4729 =============================
4731 Clang's non-standard C++11 attributes live in the ``clang`` attribute
4732 namespace.
4734 Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
4735 are accepted with the ``__attribute__((foo))`` syntax are also accepted as
4736 ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
4737 (see the list of `GCC function attributes
4738 <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
4739 attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
4740 `GCC type attributes
4741 <https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
4742 implementation, these attributes must appertain to the *declarator-id* in a
4743 declaration, which means they must go either at the start of the declaration or
4744 immediately after the name being declared.
4746 For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
4747 also applies the GNU ``noreturn`` attribute to ``f``.
4749 Examples:
4750 .. code-block:: c++
4752   [[gnu::unused]] int a, f [[gnu::noreturn]] ();
4754 Target-Specific Extensions
4755 ==========================
4757 Clang supports some language features conditionally on some targets.
4759 AMDGPU Language Extensions
4760 --------------------------
4762 __builtin_amdgcn_fence
4763 ^^^^^^^^^^^^^^^^^^^^^^
4765 ``__builtin_amdgcn_fence`` emits a fence.
4767 * ``unsigned`` atomic ordering, e.g. ``__ATOMIC_ACQUIRE``
4768 * ``const char *`` synchronization scope, e.g. ``workgroup``
4769 * Zero or more ``const char *`` address spaces names.
4771 The address spaces arguments must be one of the following string literals:
4773 * ``"local"``
4774 * ``"global"``
4776 If one or more address space name are provided, the code generator will attempt
4777 to emit potentially faster instructions that order access to at least those
4778 address spaces.
4779 Emitting such instructions may not always be possible and the compiler is free
4780 to fence more aggressively.
4782 If no address spaces names are provided, all address spaces are fenced.
4784 .. code-block:: c++
4786   // Fence all address spaces.
4787   __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
4788   __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
4790   // Fence only requested address spaces.
4791   __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")
4792   __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local", "global")
4795 ARM/AArch64 Language Extensions
4796 -------------------------------
4798 Memory Barrier Intrinsics
4799 ^^^^^^^^^^^^^^^^^^^^^^^^^
4800 Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
4801 in the `Arm C Language Extensions
4802 <https://github.com/ARM-software/acle/releases>`_.
4803 Note that these intrinsics are implemented as motion barriers that block
4804 reordering of memory accesses and side effect instructions. Other instructions
4805 like simple arithmetic may be reordered around the intrinsic. If you expect to
4806 have no reordering at all, use inline assembly instead.
4808 Pointer Authentication
4809 ^^^^^^^^^^^^^^^^^^^^^^
4810 See :doc:`PointerAuthentication`.
4812 X86/X86-64 Language Extensions
4813 ------------------------------
4815 The X86 backend has these language extensions:
4817 Memory references to specified segments
4818 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4820 Annotating a pointer with address space #256 causes it to be code generated
4821 relative to the X86 GS segment register, address space #257 causes it to be
4822 relative to the X86 FS segment, and address space #258 causes it to be
4823 relative to the X86 SS segment.  Note that this is a very very low-level
4824 feature that should only be used if you know what you're doing (for example in
4825 an OS kernel).
4827 Here is an example:
4829 .. code-block:: c++
4831   #define GS_RELATIVE __attribute__((address_space(256)))
4832   int foo(int GS_RELATIVE *P) {
4833     return *P;
4834   }
4836 Which compiles to (on X86-32):
4838 .. code-block:: gas
4840   _foo:
4841           movl    4(%esp), %eax
4842           movl    %gs:(%eax), %eax
4843           ret
4845 You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for
4846 the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``
4847 indicate their support.
4849 PowerPC Language Extensions
4850 ---------------------------
4852 Set the Floating Point Rounding Mode
4853 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4854 PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
4855 the floating point rounding mode. This function will use the least significant
4856 two bits of integer argument to set the floating point rounding mode.
4858 .. code-block:: c++
4860   double __builtin_setrnd(int mode);
4862 The effective values for mode are:
4864     - 0 - round to nearest
4865     - 1 - round to zero
4866     - 2 - round to +infinity
4867     - 3 - round to -infinity
4869 Note that the mode argument will modulo 4, so if the integer argument is greater
4870 than 3, it will only use the least significant two bits of the mode.
4871 Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
4873 PowerPC cache builtins
4874 ^^^^^^^^^^^^^^^^^^^^^^
4876 The PowerPC architecture specifies instructions implementing cache operations.
4877 Clang provides builtins that give direct programmer access to these cache
4878 instructions.
4880 Currently the following builtins are implemented in clang:
4882 ``__builtin_dcbf`` copies the contents of a modified block from the data cache
4883 to main memory and flushes the copy from the data cache.
4885 **Syntax**:
4887 .. code-block:: c
4889   void __dcbf(const void* addr); /* Data Cache Block Flush */
4891 **Example of Use**:
4893 .. code-block:: c
4895   int a = 1;
4896   __builtin_dcbf (&a);
4898 Extensions for Static Analysis
4899 ==============================
4901 Clang supports additional attributes that are useful for documenting program
4902 invariants and rules for static analysis tools, such as the `Clang Static
4903 Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
4904 in the analyzer's `list of annotations for analysis
4905 <analyzer/user-docs/Annotations.html>`__.
4908 Extensions for Dynamic Analysis
4909 ===============================
4911 Use ``__has_feature(address_sanitizer)`` to check if the code is being built
4912 with :doc:`AddressSanitizer`.
4914 Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
4915 with :doc:`ThreadSanitizer`.
4917 Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
4918 with :doc:`MemorySanitizer`.
4920 Use ``__has_feature(dataflow_sanitizer)`` to check if the code is being built
4921 with :doc:`DataFlowSanitizer`.
4923 Use ``__has_feature(safe_stack)`` to check if the code is being built
4924 with :doc:`SafeStack`.
4927 Extensions for selectively disabling optimization
4928 =================================================
4930 Clang provides a mechanism for selectively disabling optimizations in functions
4931 and methods.
4933 To disable optimizations in a single function definition, the GNU-style or C++11
4934 non-standard attribute ``optnone`` can be used.
4936 .. code-block:: c++
4938   // The following functions will not be optimized.
4939   // GNU-style attribute
4940   __attribute__((optnone)) int foo() {
4941     // ... code
4942   }
4943   // C++11 attribute
4944   [[clang::optnone]] int bar() {
4945     // ... code
4946   }
4948 To facilitate disabling optimization for a range of function definitions, a
4949 range-based pragma is provided. Its syntax is ``#pragma clang optimize``
4950 followed by ``off`` or ``on``.
4952 All function definitions in the region between an ``off`` and the following
4953 ``on`` will be decorated with the ``optnone`` attribute unless doing so would
4954 conflict with explicit attributes already present on the function (e.g. the
4955 ones that control inlining).
4957 .. code-block:: c++
4959   #pragma clang optimize off
4960   // This function will be decorated with optnone.
4961   int foo() {
4962     // ... code
4963   }
4965   // optnone conflicts with always_inline, so bar() will not be decorated.
4966   __attribute__((always_inline)) int bar() {
4967     // ... code
4968   }
4969   #pragma clang optimize on
4971 If no ``on`` is found to close an ``off`` region, the end of the region is the
4972 end of the compilation unit.
4974 Note that a stray ``#pragma clang optimize on`` does not selectively enable
4975 additional optimizations when compiling at low optimization levels. This feature
4976 can only be used to selectively disable optimizations.
4978 The pragma has an effect on functions only at the point of their definition; for
4979 function templates, this means that the state of the pragma at the point of an
4980 instantiation is not necessarily relevant. Consider the following example:
4982 .. code-block:: c++
4984   template<typename T> T twice(T t) {
4985     return 2 * t;
4986   }
4988   #pragma clang optimize off
4989   template<typename T> T thrice(T t) {
4990     return 3 * t;
4991   }
4993   int container(int a, int b) {
4994     return twice(a) + thrice(b);
4995   }
4996   #pragma clang optimize on
4998 In this example, the definition of the template function ``twice`` is outside
4999 the pragma region, whereas the definition of ``thrice`` is inside the region.
5000 The ``container`` function is also in the region and will not be optimized, but
5001 it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
5002 these two instantiations, ``twice`` will be optimized (because its definition
5003 was outside the region) and ``thrice`` will not be optimized.
5005 Clang also implements MSVC's range-based pragma,
5006 ``#pragma optimize("[optimization-list]", on | off)``. At the moment, Clang only
5007 supports an empty optimization list, whereas MSVC supports the arguments, ``s``,
5008 ``g``, ``t``, and ``y``. Currently, the implementation of ``pragma optimize`` behaves
5009 the same as ``#pragma clang optimize``. All functions
5010 between ``off`` and ``on`` will be decorated with the ``optnone`` attribute.
5012 .. code-block:: c++
5014   #pragma optimize("", off)
5015   // This function will be decorated with optnone.
5016   void f1() {}
5018   #pragma optimize("", on)
5019   // This function will be optimized with whatever was specified on
5020   // the commandline.
5021   void f2() {}
5023   // This will warn with Clang's current implementation.
5024   #pragma optimize("g", on)
5025   void f3() {}
5027 For MSVC, an empty optimization list and ``off`` parameter will turn off
5028 all optimizations, ``s``, ``g``, ``t``, and ``y``. An empty optimization and
5029 ``on`` parameter will reset the optimizations to the ones specified on the
5030 commandline.
5032 .. list-table:: Parameters (unsupported by Clang)
5034    * - Parameter
5035      - Type of optimization
5036    * - g
5037      - Deprecated
5038    * - s or t
5039      - Short or fast sequences of machine code
5040    * - y
5041      - Enable frame pointers
5043 Extensions for loop hint optimizations
5044 ======================================
5046 The ``#pragma clang loop`` directive is used to specify hints for optimizing the
5047 subsequent for, while, do-while, or c++11 range-based for loop. The directive
5048 provides options for vectorization, interleaving, predication, unrolling and
5049 distribution. Loop hints can be specified before any loop and will be ignored if
5050 the optimization is not safe to apply.
5052 There are loop hints that control transformations (e.g. vectorization, loop
5053 unrolling) and there are loop hints that set transformation options (e.g.
5054 ``vectorize_width``, ``unroll_count``).  Pragmas setting transformation options
5055 imply the transformation is enabled, as if it was enabled via the corresponding
5056 transformation pragma (e.g. ``vectorize(enable)``). If the transformation is
5057 disabled  (e.g. ``vectorize(disable)``), that takes precedence over
5058 transformations option pragmas implying that transformation.
5060 Vectorization, Interleaving, and Predication
5061 --------------------------------------------
5063 A vectorized loop performs multiple iterations of the original loop
5064 in parallel using vector instructions. The instruction set of the target
5065 processor determines which vector instructions are available and their vector
5066 widths. This restricts the types of loops that can be vectorized. The vectorizer
5067 automatically determines if the loop is safe and profitable to vectorize. A
5068 vector instruction cost model is used to select the vector width.
5070 Interleaving multiple loop iterations allows modern processors to further
5071 improve instruction-level parallelism (ILP) using advanced hardware features,
5072 such as multiple execution units and out-of-order execution. The vectorizer uses
5073 a cost model that depends on the register pressure and generated code size to
5074 select the interleaving count.
5076 Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
5077 by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
5078 manually enable vectorization or interleaving.
5080 .. code-block:: c++
5082   #pragma clang loop vectorize(enable)
5083   #pragma clang loop interleave(enable)
5084   for(...) {
5085     ...
5086   }
5088 The vector width is specified by
5089 ``vectorize_width(_value_[, fixed|scalable])``, where _value_ is a positive
5090 integer and the type of vectorization can be specified with an optional
5091 second parameter. The default for the second parameter is 'fixed' and
5092 refers to fixed width vectorization, whereas 'scalable' indicates the
5093 compiler should use scalable vectors instead. Another use of vectorize_width
5094 is ``vectorize_width(fixed|scalable)`` where the user can hint at the type
5095 of vectorization to use without specifying the exact width. In both variants
5096 of the pragma the vectorizer may decide to fall back on fixed width
5097 vectorization if the target does not support scalable vectors.
5099 The interleave count is specified by ``interleave_count(_value_)``, where
5100 _value_ is a positive integer. This is useful for specifying the optimal
5101 width/count of the set of target architectures supported by your application.
5103 .. code-block:: c++
5105   #pragma clang loop vectorize_width(2)
5106   #pragma clang loop interleave_count(2)
5107   for(...) {
5108     ...
5109   }
5111 Specifying a width/count of 1 disables the optimization, and is equivalent to
5112 ``vectorize(disable)`` or ``interleave(disable)``.
5114 Vector predication is enabled by ``vectorize_predicate(enable)``, for example:
5116 .. code-block:: c++
5118   #pragma clang loop vectorize(enable)
5119   #pragma clang loop vectorize_predicate(enable)
5120   for(...) {
5121     ...
5122   }
5124 This predicates (masks) all instructions in the loop, which allows the scalar
5125 remainder loop (the tail) to be folded into the main vectorized loop. This
5126 might be more efficient when vector predication is efficiently supported by the
5127 target platform.
5129 Loop Unrolling
5130 --------------
5132 Unrolling a loop reduces the loop control overhead and exposes more
5133 opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
5134 eliminates the loop and replaces it with an enumerated sequence of loop
5135 iterations. Full unrolling is only possible if the loop trip count is known at
5136 compile time. Partial unrolling replicates the loop body within the loop and
5137 reduces the trip count.
5139 If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
5140 loop if the trip count is known at compile time. If the fully unrolled code size
5141 is greater than an internal limit the loop will be partially unrolled up to this
5142 limit. If the trip count is not known at compile time the loop will be partially
5143 unrolled with a heuristically chosen unroll factor.
5145 .. code-block:: c++
5147   #pragma clang loop unroll(enable)
5148   for(...) {
5149     ...
5150   }
5152 If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
5153 loop if the trip count is known at compile time identically to
5154 ``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
5155 if the loop count is not known at compile time.
5157 .. code-block:: c++
5159   #pragma clang loop unroll(full)
5160   for(...) {
5161     ...
5162   }
5164 The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
5165 _value_ is a positive integer. If this value is greater than the trip count the
5166 loop will be fully unrolled. Otherwise the loop is partially unrolled subject
5167 to the same code size limit as with ``unroll(enable)``.
5169 .. code-block:: c++
5171   #pragma clang loop unroll_count(8)
5172   for(...) {
5173     ...
5174   }
5176 Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
5178 Loop unroll parameters can be controlled by options
5179 `-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`.
5181 Loop Distribution
5182 -----------------
5184 Loop Distribution allows splitting a loop into multiple loops.  This is
5185 beneficial for example when the entire loop cannot be vectorized but some of the
5186 resulting loops can.
5188 If ``distribute(enable))`` is specified and the loop has memory dependencies
5189 that inhibit vectorization, the compiler will attempt to isolate the offending
5190 operations into a new loop.  This optimization is not enabled by default, only
5191 loops marked with the pragma are considered.
5193 .. code-block:: c++
5195   #pragma clang loop distribute(enable)
5196   for (i = 0; i < N; ++i) {
5197     S1: A[i + 1] = A[i] + B[i];
5198     S2: C[i] = D[i] * E[i];
5199   }
5201 This loop will be split into two loops between statements S1 and S2.  The
5202 second loop containing S2 will be vectorized.
5204 Loop Distribution is currently not enabled by default in the optimizer because
5205 it can hurt performance in some cases.  For example, instruction-level
5206 parallelism could be reduced by sequentializing the execution of the
5207 statements S1 and S2 above.
5209 If Loop Distribution is turned on globally with
5210 ``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
5211 be used the disable it on a per-loop basis.
5213 Additional Information
5214 ----------------------
5216 For convenience multiple loop hints can be specified on a single line.
5218 .. code-block:: c++
5220   #pragma clang loop vectorize_width(4) interleave_count(8)
5221   for(...) {
5222     ...
5223   }
5225 If an optimization cannot be applied any hints that apply to it will be ignored.
5226 For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
5227 proven safe to vectorize. To identify and diagnose optimization issues use
5228 `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
5229 user guide for details.
5231 Extensions to specify floating-point flags
5232 ====================================================
5234 The ``#pragma clang fp`` pragma allows floating-point options to be specified
5235 for a section of the source code. This pragma can only appear at file scope or
5236 at the start of a compound statement (excluding comments). When using within a
5237 compound statement, the pragma is active within the scope of the compound
5238 statement.
5240 Currently, the following settings can be controlled with this pragma:
5242 ``#pragma clang fp reassociate`` allows control over the reassociation
5243 of floating point expressions. When enabled, this pragma allows the expression
5244 ``x + (y + z)`` to be reassociated as ``(x + y) + z``.
5245 Reassociation can also occur across multiple statements.
5246 This pragma can be used to disable reassociation when it is otherwise
5247 enabled for the translation unit with the ``-fassociative-math`` flag.
5248 The pragma can take two values: ``on`` and ``off``.
5250 .. code-block:: c++
5252   float f(float x, float y, float z)
5253   {
5254     // Enable floating point reassociation across statements
5255     #pragma clang fp reassociate(on)
5256     float t = x + y;
5257     float v = t + z;
5258   }
5260 ``#pragma clang fp reciprocal`` allows control over using reciprocal
5261 approximations in floating point expressions. When enabled, this
5262 pragma allows the expression ``x / y`` to be approximated as ``x *
5263 (1.0 / y)``.  This pragma can be used to disable reciprocal
5264 approximation when it is otherwise enabled for the translation unit
5265 with the ``-freciprocal-math`` flag or other fast-math options. The
5266 pragma can take two values: ``on`` and ``off``.
5268 .. code-block:: c++
5270   float f(float x, float y)
5271   {
5272     // Enable floating point reciprocal approximation
5273     #pragma clang fp reciprocal(on)
5274     return x / y;
5275   }
5277 ``#pragma clang fp contract`` specifies whether the compiler should
5278 contract a multiply and an addition (or subtraction) into a fused FMA
5279 operation when supported by the target.
5281 The pragma can take three values: ``on``, ``fast`` and ``off``.  The ``on``
5282 option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
5283 fusion as specified the language standard.  The ``fast`` option allows fusion
5284 in cases when the language standard does not make this possible (e.g. across
5285 statements in C).
5287 .. code-block:: c++
5289   for(...) {
5290     #pragma clang fp contract(fast)
5291     a = b[i] * c[i];
5292     d[i] += a;
5293   }
5296 The pragma can also be used with ``off`` which turns FP contraction off for a
5297 section of the code. This can be useful when fast contraction is otherwise
5298 enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag.
5299 Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and
5300 addition across statements regardless of any controlling pragmas.
5302 ``#pragma clang fp exceptions`` specifies floating point exception behavior. It
5303 may take one of the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of
5304 these values is same as for `constrained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics>`_.
5306 .. code-block:: c++
5308   {
5309     // Preserve floating point exceptions
5310     #pragma clang fp exceptions(strict)
5311     z = x + y;
5312     if (fetestexcept(FE_OVERFLOW))
5313       ...
5314   }
5316 A ``#pragma clang fp`` pragma may contain any number of options:
5318 .. code-block:: c++
5320   void func(float *dest, float a, float b) {
5321     #pragma clang fp exceptions(maytrap) contract(fast) reassociate(on)
5322     ...
5323   }
5325 ``#pragma clang fp eval_method`` allows floating-point behavior to be specified
5326 for a section of the source code. This pragma can appear at file or namespace
5327 scope, or at the start of a compound statement (excluding comments).
5328 The pragma is active within the scope of the compound statement.
5330 When ``pragma clang fp eval_method(source)`` is enabled, the section of code
5331 governed by the pragma behaves as though the command-line option
5332 ``-ffp-eval-method=source`` is enabled. Rounds intermediate results to
5333 source-defined precision.
5335 When ``pragma clang fp eval_method(double)`` is enabled, the section of code
5336 governed by the pragma behaves as though the command-line option
5337 ``-ffp-eval-method=double`` is enabled. Rounds intermediate results to
5338 ``double`` precision.
5340 When ``pragma clang fp eval_method(extended)`` is enabled, the section of code
5341 governed by the pragma behaves as though the command-line option
5342 ``-ffp-eval-method=extended`` is enabled. Rounds intermediate results to
5343 target-dependent ``long double`` precision. In Win32 programming, for instance,
5344 the long double data type maps to the double, 64-bit precision data type.
5346 The full syntax this pragma supports is
5347 ``#pragma clang fp eval_method(source|double|extended)``.
5349 .. code-block:: c++
5351   for(...) {
5352     // The compiler will use long double as the floating-point evaluation
5353     // method.
5354     #pragma clang fp eval_method(extended)
5355     a = b[i] * c[i] + e;
5356   }
5358 Note: ``math.h`` defines the typedefs ``float_t`` and ``double_t`` based on the active
5359 evaluation method at the point where the header is included, not where the
5360 typedefs are used.  Because of this, it is unwise to combine these typedefs with
5361 ``#pragma clang fp eval_method``.  To catch obvious bugs, Clang will emit an
5362 error for any references to these typedefs within the scope of this pragma;
5363 however, this is not a fool-proof protection, and programmers must take care.
5365 The ``#pragma float_control`` pragma allows precise floating-point
5366 semantics and floating-point exception behavior to be specified
5367 for a section of the source code. This pragma can only appear at file or
5368 namespace scope, within a language linkage specification or at the start of a
5369 compound statement (excluding comments). When used within a compound statement,
5370 the pragma is active within the scope of the compound statement.  This pragma
5371 is modeled after a Microsoft pragma with the same spelling and syntax.  For
5372 pragmas specified at file or namespace scope, or within a language linkage
5373 specification, a stack is supported so that the ``pragma float_control``
5374 settings can be pushed or popped.
5376 When ``pragma float_control(precise, on)`` is enabled, the section of code
5377 governed by the pragma uses precise floating point semantics, effectively
5378 ``-ffast-math`` is disabled and ``-ffp-contract=on``
5379 (fused multiply add) is enabled. This pragma enables ``-fmath-errno``.
5381 When ``pragma float_control(precise, off)`` is enabled, unsafe-floating point
5382 optimizations are enabled in the section of code governed by the pragma.
5383 Effectively ``-ffast-math`` is enabled and ``-ffp-contract=fast``. This pragma
5384 disables ``-fmath-errno``.
5386 When ``pragma float_control(except, on)`` is enabled, the section of code
5387 governed by the pragma behaves as though the command-line option
5388 ``-ffp-exception-behavior=strict`` is enabled,
5389 when ``pragma float_control(except, off)`` is enabled, the section of code
5390 governed by the pragma behaves as though the command-line option
5391 ``-ffp-exception-behavior=ignore`` is enabled.
5393 The full syntax this pragma supports is
5394 ``float_control(except|precise, on|off [, push])`` and
5395 ``float_control(push|pop)``.
5396 The ``push`` and ``pop`` forms, including using ``push`` as the optional
5397 third argument, can only occur at file scope.
5399 .. code-block:: c++
5401   for(...) {
5402     // This block will be compiled with -fno-fast-math and -ffp-contract=on
5403     #pragma float_control(precise, on)
5404     a = b[i] * c[i] + e;
5405   }
5407 Specifying an attribute for multiple declarations (#pragma clang attribute)
5408 ===========================================================================
5410 The ``#pragma clang attribute`` directive can be used to apply an attribute to
5411 multiple declarations. The ``#pragma clang attribute push`` variation of the
5412 directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
5413 can be added to. The ``#pragma clang attribute (...)`` variation adds an
5414 attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
5415 the scope. You can also use ``#pragma clang attribute push (...)``, which is a
5416 shorthand for when you want to add one attribute to a new scope. Multiple push
5417 directives can be nested inside each other.
5419 The attributes that are used in the ``#pragma clang attribute`` directives
5420 can be written using the GNU-style syntax:
5422 .. code-block:: c++
5424   #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
5426   void function(); // The function now has the annotate("custom") attribute
5428   #pragma clang attribute pop
5430 The attributes can also be written using the C++11 style syntax:
5432 .. code-block:: c++
5434   #pragma clang attribute push ([[noreturn]], apply_to = function)
5436   void function(); // The function now has the [[noreturn]] attribute
5438   #pragma clang attribute pop
5440 The ``__declspec`` style syntax is also supported:
5442 .. code-block:: c++
5444   #pragma clang attribute push (__declspec(dllexport), apply_to = function)
5446   void function(); // The function now has the __declspec(dllexport) attribute
5448   #pragma clang attribute pop
5450 A single push directive can contain multiple attributes, however,
5451 only one syntax style can be used within a single directive:
5453 .. code-block:: c++
5455   #pragma clang attribute push ([[noreturn, noinline]], apply_to = function)
5457   void function1(); // The function now has the [[noreturn]] and [[noinline]] attributes
5459   #pragma clang attribute pop
5461   #pragma clang attribute push (__attribute((noreturn, noinline)), apply_to = function)
5463   void function2(); // The function now has the __attribute((noreturn)) and __attribute((noinline)) attributes
5465   #pragma clang attribute pop
5467 Because multiple push directives can be nested, if you're writing a macro that
5468 expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
5469 required) to add a namespace to your push/pop directives. A pop directive with a
5470 namespace will pop the innermost push that has that same namespace. This will
5471 ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
5472 that an ``pop`` without a namespace will pop the innermost ``push`` without a
5473 namespace. ``push``es with a namespace can only be popped by ``pop`` with the
5474 same namespace. For instance:
5476 .. code-block:: c++
5478    #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
5479    #define ASSUME_NORETURN_END   _Pragma("clang attribute AssumeNoreturn.pop")
5481    #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
5482    #define ASSUME_UNAVAILABLE_END   _Pragma("clang attribute Unavailable.pop")
5485    ASSUME_NORETURN_BEGIN
5486    ASSUME_UNAVAILABLE_BEGIN
5487    void function(); // function has [[noreturn]] and __attribute__((unavailable))
5488    ASSUME_NORETURN_END
5489    void other_function(); // function has __attribute__((unavailable))
5490    ASSUME_UNAVAILABLE_END
5492 Without the namespaces on the macros, ``other_function`` will be annotated with
5493 ``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
5494 a contrived example, but its very possible for this kind of situation to appear
5495 in real code if the pragmas are spread out across a large file. You can test if
5496 your version of clang supports namespaces on ``#pragma clang attribute`` with
5497 ``__has_extension(pragma_clang_attribute_namespaces)``.
5499 Subject Match Rules
5500 -------------------
5502 The set of declarations that receive a single attribute from the attribute stack
5503 depends on the subject match rules that were specified in the pragma. Subject
5504 match rules are specified after the attribute. The compiler expects an
5505 identifier that corresponds to the subject set specifier. The ``apply_to``
5506 specifier is currently the only supported subject set specifier. It allows you
5507 to specify match rules that form a subset of the attribute's allowed subject
5508 set, i.e. the compiler doesn't require all of the attribute's subjects. For
5509 example, an attribute like ``[[nodiscard]]`` whose subject set includes
5510 ``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
5511 least one of these rules after ``apply_to``:
5513 .. code-block:: c++
5515   #pragma clang attribute push([[nodiscard]], apply_to = enum)
5517   enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
5519   struct Record1 { }; // The struct will *not* receive [[nodiscard]]
5521   #pragma clang attribute pop
5523   #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
5525   enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
5527   struct Record2 { }; // The struct *will* receive [[nodiscard]]
5529   #pragma clang attribute pop
5531   // This is an error, since [[nodiscard]] can't be applied to namespaces:
5532   #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
5534   #pragma clang attribute pop
5536 Multiple match rules can be specified using the ``any`` match rule, as shown
5537 in the example above. The ``any`` rule applies attributes to all declarations
5538 that are matched by at least one of the rules in the ``any``. It doesn't nest
5539 and can't be used inside the other match rules. Redundant match rules or rules
5540 that conflict with one another should not be used inside of ``any``. Failing to
5541 specify a rule within the ``any`` rule results in an error.
5543 Clang supports the following match rules:
5545 - ``function``: Can be used to apply attributes to functions. This includes C++
5546   member functions, static functions, operators, and constructors/destructors.
5548 - ``function(is_member)``: Can be used to apply attributes to C++ member
5549   functions. This includes members like static functions, operators, and
5550   constructors/destructors.
5552 - ``hasType(functionType)``: Can be used to apply attributes to functions, C++
5553   member functions, and variables/fields whose type is a function pointer. It
5554   does not apply attributes to Objective-C methods or blocks.
5556 - ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
5557   and C++11 type aliases.
5559 - ``record``: Can be used to apply attributes to ``struct``, ``class``, and
5560   ``union`` declarations.
5562 - ``record(unless(is_union))``: Can be used to apply attributes only to
5563   ``struct`` and ``class`` declarations.
5565 - ``enum``: Can be used to apply attributes to enumeration declarations.
5567 - ``enum_constant``: Can be used to apply attributes to enumerators.
5569 - ``variable``: Can be used to apply attributes to variables, including
5570   local variables, parameters, global variables, and static member variables.
5571   It does not apply attributes to instance member variables or Objective-C
5572   ivars.
5574 - ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
5575   variables only.
5577 - ``variable(is_global)``: Can be used to apply attributes to global variables
5578   only.
5580 - ``variable(is_local)``: Can be used to apply attributes to local variables
5581   only.
5583 - ``variable(is_parameter)``: Can be used to apply attributes to parameters
5584   only.
5586 - ``variable(unless(is_parameter))``: Can be used to apply attributes to all
5587   the variables that are not parameters.
5589 - ``field``: Can be used to apply attributes to non-static member variables
5590   in a record. This includes Objective-C ivars.
5592 - ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
5594 - ``objc_interface``: Can be used to apply attributes to ``@interface``
5595   declarations.
5597 - ``objc_protocol``: Can be used to apply attributes to ``@protocol``
5598   declarations.
5600 - ``objc_category``: Can be used to apply attributes to category declarations,
5601   including class extensions.
5603 - ``objc_method``: Can be used to apply attributes to Objective-C methods,
5604   including instance and class methods. Implicit methods like implicit property
5605   getters and setters do not receive the attribute.
5607 - ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
5608   instance methods.
5610 - ``objc_property``: Can be used to apply attributes to ``@property``
5611   declarations.
5613 - ``block``: Can be used to apply attributes to block declarations. This does
5614   not include variables/fields of block pointer type.
5616 The use of ``unless`` in match rules is currently restricted to a strict set of
5617 sub-rules that are used by the supported attributes. That means that even though
5618 ``variable(unless(is_parameter))`` is a valid match rule,
5619 ``variable(unless(is_thread_local))`` is not.
5621 Supported Attributes
5622 --------------------
5624 Not all attributes can be used with the ``#pragma clang attribute`` directive.
5625 Notably, statement attributes like ``[[fallthrough]]`` or type attributes
5626 like ``address_space`` aren't supported by this directive. You can determine
5627 whether or not an attribute is supported by the pragma by referring to the
5628 :doc:`individual documentation for that attribute <AttributeReference>`.
5630 The attributes are applied to all matching declarations individually, even when
5631 the attribute is semantically incorrect. The attributes that aren't applied to
5632 any declaration are not verified semantically.
5634 Specifying section names for global objects (#pragma clang section)
5635 ===================================================================
5637 The ``#pragma clang section`` directive provides a means to assign section-names
5638 to global variables, functions and static variables.
5640 The section names can be specified as:
5642 .. code-block:: c++
5644   #pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText"
5646 The section names can be reverted back to default name by supplying an empty
5647 string to the section kind, for example:
5649 .. code-block:: c++
5651   #pragma clang section bss="" data="" text="" rodata="" relro=""
5653 The ``#pragma clang section`` directive obeys the following rules:
5655 * The pragma applies to all global variable, statics and function declarations
5656   from the pragma to the end of the translation unit.
5658 * The pragma clang section is enabled automatically, without need of any flags.
5660 * This feature is only defined to work sensibly for ELF, Mach-O and COFF targets.
5662 * If section name is specified through _attribute_((section("myname"))), then
5663   the attribute name gains precedence.
5665 * Global variables that are initialized to zero will be placed in the named
5666   bss section, if one is present.
5668 * The ``#pragma clang section`` directive does not try to infer section-kind
5669   from the name. For example, naming a section "``.bss.mySec``" does NOT mean
5670   it will be a bss section name.
5672 * The decision about which section-kind applies to each global is taken in the back-end.
5673   Once the section-kind is known, appropriate section name, as specified by the user using
5674   ``#pragma clang section`` directive, is applied to that global.
5676 Specifying Linker Options on ELF Targets
5677 ========================================
5679 The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
5680 The second parameter is the library name (without the traditional Unix prefix of
5681 ``lib``).  This allows you to provide an implicit link of dependent libraries.
5683 Evaluating Object Size
5684 ======================
5686 Clang supports the builtins ``__builtin_object_size`` and
5687 ``__builtin_dynamic_object_size``. The semantics are compatible with GCC's
5688 builtins of the same names, but the details are slightly different.
5690 .. code-block:: c
5692   size_t __builtin_[dynamic_]object_size(const void *ptr, int type)
5694 Returns the number of accessible bytes ``n`` past ``ptr``. The value returned
5695 depends on ``type``, which is required to be an integer constant between 0 and
5698 * If ``type & 2 == 0``, the least ``n`` is returned such that accesses to
5699   ``(const char*)ptr + n`` and beyond are known to be out of bounds. This is
5700   ``(size_t)-1`` if no better bound is known.
5701 * If ``type & 2 == 2``, the greatest ``n`` is returned such that accesses to
5702   ``(const char*)ptr + i`` are known to be in bounds, for 0 <= ``i`` < ``n``.
5703   This is ``(size_t)0`` if no better bound is known.
5705 .. code-block:: c
5707   char small[10], large[100];
5708   bool cond;
5709   // Returns 100: writes of more than 100 bytes are known to be out of bounds.
5710   int n100 = __builtin_object_size(cond ? small : large, 0);
5711   // Returns 10: writes of 10 or fewer bytes are known to be in bounds.
5712   int n10 = __builtin_object_size(cond ? small : large, 2);
5714 * If ``type & 1 == 0``, pointers are considered to be in bounds if they point
5715   into the same storage as ``ptr`` -- that is, the same stack object, global
5716   variable, or heap allocation.
5717 * If ``type & 1 == 1``, pointers are considered to be in bounds if they point
5718   to the same subobject that ``ptr`` points to. If ``ptr`` points to an array
5719   element, other elements of the same array, but not of enclosing arrays, are
5720   considered in bounds.
5722 .. code-block:: c
5724   struct X { char a, b, c; } x;
5725   static_assert(__builtin_object_size(&x, 0) == 3);
5726   static_assert(__builtin_object_size(&x.b, 0) == 2);
5727   static_assert(__builtin_object_size(&x.b, 1) == 1);
5729 .. code-block:: c
5731   char a[10][10][10];
5732   static_assert(__builtin_object_size(&a, 1) == 1000);
5733   static_assert(__builtin_object_size(&a[1], 1) == 900);
5734   static_assert(__builtin_object_size(&a[1][1], 1) == 90);
5735   static_assert(__builtin_object_size(&a[1][1][1], 1) == 9);
5737 The values returned by this builtin are a best effort conservative approximation
5738 of the correct answers. When ``type & 2 == 0``, the true value is less than or
5739 equal to the value returned by the builtin, and when ``type & 2 == 1``, the true
5740 value is greater than or equal to the value returned by the builtin.
5742 For ``__builtin_object_size``, the value is determined entirely at compile time.
5743 With optimization enabled, better results will be produced, especially when the
5744 call to ``__builtin_object_size`` is in a different function from the formation
5745 of the pointer. Unlike in GCC, enabling optimization in Clang does not allow
5746 more information about subobjects to be determined, so the ``type & 1 == 1``
5747 case will often give imprecise results when used across a function call boundary
5748 even when optimization is enabled.
5750 `The pass_object_size and pass_dynamic_object_size attributes <https://clang.llvm.org/docs/AttributeReference.html#pass-object-size-pass-dynamic-object-size>`_
5751 can be used to invisibly pass the object size for a pointer parameter alongside
5752 the pointer in a function call. This allows more precise object sizes to be
5753 determined both when building without optimizations and in the ``type & 1 == 1``
5754 case.
5756 For ``__builtin_dynamic_object_size``, the result is not limited to being a
5757 compile time constant. Instead, a small amount of runtime evaluation is
5758 permitted to determine the size of the object, in order to give a more precise
5759 result. ``__builtin_dynamic_object_size`` is meant to be used as a drop-in
5760 replacement for ``__builtin_object_size`` in libraries that support it. For
5761 instance, here is a program that ``__builtin_dynamic_object_size`` will make
5762 safer:
5764 .. code-block:: c
5766   void copy_into_buffer(size_t size) {
5767     char* buffer = malloc(size);
5768     strlcpy(buffer, "some string", strlen("some string"));
5769     // Previous line preprocesses to:
5770     // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
5771   }
5773 Since the size of ``buffer`` can't be known at compile time, Clang will fold
5774 ``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
5775 as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
5776 ``size``, providing some extra runtime safety.
5778 Deprecating Macros
5779 ==================
5781 Clang supports the pragma ``#pragma clang deprecated``, which can be used to
5782 provide deprecation warnings for macro uses. For example:
5784 .. code-block:: c
5786    #define MIN(x, y) x < y ? x : y
5787    #pragma clang deprecated(MIN, "use std::min instead")
5789    int min(int a, int b) {
5790      return MIN(a, b); // warning: MIN is deprecated: use std::min instead
5791    }
5793 ``#pragma clang deprecated`` should be preferred for this purpose over
5794 ``#pragma GCC warning`` because the warning can be controlled with
5795 ``-Wdeprecated``.
5797 Restricted Expansion Macros
5798 ===========================
5800 Clang supports the pragma ``#pragma clang restrict_expansion``, which can be
5801 used restrict macro expansion in headers. This can be valuable when providing
5802 headers with ABI stability requirements. Any expansion of the annotated macro
5803 processed by the preprocessor after the ``#pragma`` annotation will log a
5804 warning. Redefining the macro or undefining the macro will not be diagnosed, nor
5805 will expansion of the macro within the main source file. For example:
5807 .. code-block:: c
5809    #define TARGET_ARM 1
5810    #pragma clang restrict_expansion(TARGET_ARM, "<reason>")
5812    /// Foo.h
5813    struct Foo {
5814    #if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason>
5815      uint32_t X;
5816    #else
5817      uint64_t X;
5818    #endif
5819    };
5821    /// main.c
5822    #include "foo.h"
5823    #if TARGET_ARM // No warning in main source file
5824    X_TYPE uint32_t
5825    #else
5826    X_TYPE uint64_t
5827    #endif
5829 This warning is controlled by ``-Wpedantic-macros``.
5831 Final Macros
5832 ============
5834 Clang supports the pragma ``#pragma clang final``, which can be used to
5835 mark macros as final, meaning they cannot be undef'd or re-defined. For example:
5837 .. code-block:: c
5839    #define FINAL_MACRO 1
5840    #pragma clang final(FINAL_MACRO)
5842    #define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined
5843    #undef FINAL_MACRO  // warning: FINAL_MACRO is marked final and should not be undefined
5845 This is useful for enforcing system-provided macros that should not be altered
5846 in user headers or code. This is controlled by ``-Wpedantic-macros``. Final
5847 macros will always warn on redefinition, including situations with identical
5848 bodies and in system headers.
5850 Line Control
5851 ============
5853 Clang supports an extension for source line control, which takes the
5854 form of a preprocessor directive starting with an unsigned integral
5855 constant. In addition to the standard ``#line`` directive, this form
5856 allows control of an include stack and header file type, which is used
5857 in issuing diagnostics. These lines are emitted in preprocessed
5858 output.
5860 .. code-block:: c
5862    # <line:number> <filename:string> <header-type:numbers>
5864 The filename is optional, and if unspecified indicates no change in
5865 source filename. The header-type is an optional, whitespace-delimited,
5866 sequence of magic numbers as follows.
5868 * ``1:`` Push the current source file name onto the include stack and
5869   enter a new file.
5871 * ``2``: Pop the include stack and return to the specified file. If
5872   the filename is ``""``, the name popped from the include stack is
5873   used. Otherwise there is no requirement that the specified filename
5874   matches the current source when originally pushed.
5876 * ``3``: Enter a system-header region. System headers often contain
5877   implementation-specific source that would normally emit a diagnostic.
5879 * ``4``: Enter an implicit ``extern "C"`` region. This is not required on
5880   modern systems where system headers are C++-aware.
5882 At most a single ``1`` or ``2`` can be present, and values must be in
5883 ascending order.
5885 Examples are:
5887 .. code-block:: c
5889    # 57 // Advance (or return) to line 57 of the current source file
5890    # 57 "frob" // Set to line 57 of "frob"
5891    # 1 "foo.h" 1 // Enter "foo.h" at line 1
5892    # 59 "main.c" 2 // Leave current include and return to "main.c"
5893    # 1 "/usr/include/stdio.h" 1 3 // Enter a system header
5894    # 60 "" 2 // return to "main.c"
5895    # 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
5897 Intrinsics Support within Constant Expressions
5898 ==============================================
5900 The following builtin intrinsics can be used in constant expressions:
5902 * ``__builtin_addcb``
5903 * ``__builtin_addcs``
5904 * ``__builtin_addc``
5905 * ``__builtin_addcl``
5906 * ``__builtin_addcll``
5907 * ``__builtin_bitreverse8``
5908 * ``__builtin_bitreverse16``
5909 * ``__builtin_bitreverse32``
5910 * ``__builtin_bitreverse64``
5911 * ``__builtin_bswap16``
5912 * ``__builtin_bswap32``
5913 * ``__builtin_bswap64``
5914 * ``__builtin_clrsb``
5915 * ``__builtin_clrsbl``
5916 * ``__builtin_clrsbll``
5917 * ``__builtin_clz``
5918 * ``__builtin_clzl``
5919 * ``__builtin_clzll``
5920 * ``__builtin_clzs``
5921 * ``__builtin_clzg``
5922 * ``__builtin_ctz``
5923 * ``__builtin_ctzl``
5924 * ``__builtin_ctzll``
5925 * ``__builtin_ctzs``
5926 * ``__builtin_ctzg``
5927 * ``__builtin_ffs``
5928 * ``__builtin_ffsl``
5929 * ``__builtin_ffsll``
5930 * ``__builtin_fmax``
5931 * ``__builtin_fmin``
5932 * ``__builtin_fpclassify``
5933 * ``__builtin_inf``
5934 * ``__builtin_isinf``
5935 * ``__builtin_isinf_sign``
5936 * ``__builtin_isfinite``
5937 * ``__builtin_isnan``
5938 * ``__builtin_isnormal``
5939 * ``__builtin_nan``
5940 * ``__builtin_nans``
5941 * ``__builtin_parity``
5942 * ``__builtin_parityl``
5943 * ``__builtin_parityll``
5944 * ``__builtin_popcount``
5945 * ``__builtin_popcountl``
5946 * ``__builtin_popcountll``
5947 * ``__builtin_popcountg``
5948 * ``__builtin_rotateleft8``
5949 * ``__builtin_rotateleft16``
5950 * ``__builtin_rotateleft32``
5951 * ``__builtin_rotateleft64``
5952 * ``__builtin_rotateright8``
5953 * ``__builtin_rotateright16``
5954 * ``__builtin_rotateright32``
5955 * ``__builtin_rotateright64``
5956 * ``__builtin_subcb``
5957 * ``__builtin_subcs``
5958 * ``__builtin_subc``
5959 * ``__builtin_subcl``
5960 * ``__builtin_subcll``
5962 The following x86-specific intrinsics can be used in constant expressions:
5964 * ``_addcarry_u32``
5965 * ``_addcarry_u64``
5966 * ``_bit_scan_forward``
5967 * ``_bit_scan_reverse``
5968 * ``__bsfd``
5969 * ``__bsfq``
5970 * ``__bsrd``
5971 * ``__bsrq``
5972 * ``__bswap``
5973 * ``__bswapd``
5974 * ``__bswap64``
5975 * ``__bswapq``
5976 * ``_castf32_u32``
5977 * ``_castf64_u64``
5978 * ``_castu32_f32``
5979 * ``_castu64_f64``
5980 * ``__lzcnt16``
5981 * ``__lzcnt``
5982 * ``__lzcnt64``
5983 * ``_mm_popcnt_u32``
5984 * ``_mm_popcnt_u64``
5985 * ``_popcnt32``
5986 * ``_popcnt64``
5987 * ``__popcntd``
5988 * ``__popcntq``
5989 * ``__popcnt16``
5990 * ``__popcnt``
5991 * ``__popcnt64``
5992 * ``__rolb``
5993 * ``__rolw``
5994 * ``__rold``
5995 * ``__rolq``
5996 * ``__rorb``
5997 * ``__rorw``
5998 * ``__rord``
5999 * ``__rorq``
6000 * ``_rotl``
6001 * ``_rotr``
6002 * ``_rotwl``
6003 * ``_rotwr``
6004 * ``_lrotl``
6005 * ``_lrotr``
6006 * ``_subborrow_u32``
6007 * ``_subborrow_u64``
6009 Debugging the Compiler
6010 ======================
6012 Clang supports a number of pragma directives that help debugging the compiler itself.
6013 Syntax is the following: `#pragma clang __debug <command> <arguments>`.
6014 Note, all of debugging pragmas are subject to change.
6016 `dump`
6017 ------
6018 Accepts either a single identifier or an expression. When a single identifier is passed,
6019 the lookup results for the identifier are printed to `stderr`. When an expression is passed,
6020 the AST for the expression is printed to `stderr`. The expression is an unevaluated operand,
6021 so things like overload resolution and template instantiations are performed,
6022 but the expression has no runtime effects.
6023 Type- and value-dependent expressions are not supported yet.
6025 This facility is designed to aid with testing name lookup machinery.
6027 Predefined Macros
6028 =================
6030 `__GCC_DESTRUCTIVE_SIZE` and `__GCC_CONSTRUCTIVE_SIZE`
6031 ------------------------------------------------------
6032 Specify the mimum offset between two objects to avoid false sharing and the
6033 maximum size of contiguous memory to promote true sharing, respectively. These
6034 macros are predefined in all C and C++ language modes, but can be redefined on
6035 the command line with ``-D`` to specify different values as needed or can be
6036 undefined on the command line with ``-U`` to disable support for the feature.
6038 **Note: the values the macros expand to are not guaranteed to be stable. They
6039 are are affected by architectures and CPU tuning flags, can change between
6040 releases of Clang and will not match the values defined by other compilers such
6041 as GCC.**
6043 Compiling different TUs depending on these flags (including use of
6044 ``std::hardware_constructive_interference`` or
6045 ``std::hardware_destructive_interference``)  with different compilers, macro
6046 definitions, or architecture flags will lead to ODR violations and should be
6047 avoided.
6049 ``#embed`` Parameters
6050 =====================
6052 ``clang::offset``
6053 -----------------
6054 The ``clang::offset`` embed parameter may appear zero or one time in the
6055 embed parameter sequence. Its preprocessor argument clause shall be present and
6056 have the form:
6058 ..code-block: text
6060   ( constant-expression )
6062 and shall be an integer constant expression. The integer constant expression
6063 shall not evaluate to a value less than 0. The token ``defined`` shall not
6064 appear within the constant expression.
6066 The offset will be used when reading the contents of the embedded resource to
6067 specify the starting offset to begin embedding from. The resources is treated
6068 as being empty if the specified offset is larger than the number of bytes in
6069 the resource. The offset will be applied *before* any ``limit`` parameters are
6070 applied.
6072 Union and aggregate initialization in C
6073 =======================================
6075 In C23 (N2900), when an object is initialized from initializer ``= {}``, all
6076 elements of arrays, all members of structs, and the first members of unions are
6077 empty-initialized recursively. In addition, all padding bits are initialized to
6078 zero.
6080 Clang guarantees the following behaviors:
6082 * ``1:`` Clang supports initializer ``= {}`` mentioned above in all C
6083   standards.
6085 * ``2:`` When unions are initialized from initializer ``= {}``, bytes outside
6086   of the first members of unions are also initialized to zero.
6088 * ``3:`` When unions, structures and arrays are initialized from initializer
6089   ``= { initializer-list }``, all members not explicitly initialized in
6090   the initializer list are empty-initialized recursively. In addition, all
6091   padding bits are initialized to zero.
6093 Currently, the above extension only applies to C source code, not C++.
6096 Empty Objects in C
6097 ==================
6098 The declaration of a structure or union type which has no named members is
6099 undefined behavior (C23 and earlier) or implementation-defined behavior (C2y).
6100 Clang allows the declaration of a structure or union type with no named members
6101 in all C language modes. `sizeof` for such a type returns `0`, which is
6102 different behavior than in C++ (where the size of such an object is typically
6103 `1`).
6106 Qualified function types in C
6107 =============================
6108 Declaring a function with a qualified type in C is undefined behavior (C23 and
6109 earlier) or implementation-defined behavior (C2y). Clang allows a function type
6110 to be specified with the ``const`` and ``volatile`` qualifiers, but ignores the
6111 qualifications.
6113 .. code-block:: c
6115    typedef int f(void);
6116    const volatile f func; // Qualifier on function type has no effect.
6119 Note, Clang does not allow an ``_Atomic`` function type because
6120 of explicit constraints against atomically qualified (arrays and) function
6121 types.