1=========================
2Clang Language Extensions
3=========================
4
5.. contents::
6   :local:
7   :depth: 1
8
9.. toctree::
10   :hidden:
11
12   ObjectiveCLiterals
13   BlockLanguageSpec
14   Block-ABI-Apple
15   AutomaticReferenceCounting
16   MatrixTypes
17
18Introduction
19============
20
21This document describes the language extensions provided by Clang.  In addition
22to the language extensions listed here, Clang aims to support a broad range of
23GCC extensions.  Please see the `GCC manual
24<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
25these extensions.
26
27.. _langext-feature_check:
28
29Feature Checking Macros
30=======================
31
32Language extensions can be very useful, but only if you know you can depend on
33them.  In order to allow fine-grain features checks, we support three builtin
34function-like macros.  This allows you to directly test for a feature in your
35code without having to resort to something like autoconf or fragile "compiler
36version checks".
37
38``__has_builtin``
39-----------------
40
41This function-like macro takes a single identifier argument that is the name of
42a builtin function, a builtin pseudo-function (taking one or more type
43arguments), or a builtin template.
44It evaluates to 1 if the builtin is supported or 0 if not.
45It can be used like this:
46
47.. code-block:: c++
48
49  #ifndef __has_builtin         // Optional of course.
50    #define __has_builtin(x) 0  // Compatibility with non-clang compilers.
51  #endif
52
53  ...
54  #if __has_builtin(__builtin_trap)
55    __builtin_trap();
56  #else
57    abort();
58  #endif
59  ...
60
61.. note::
62
63  Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin
64  pseudo-functions.
65
66  ``__has_builtin`` should not be used to detect support for a builtin macro;
67  use ``#ifdef`` instead.
68
69.. _langext-__has_feature-__has_extension:
70
71``__has_feature`` and ``__has_extension``
72-----------------------------------------
73
74These function-like macros take a single identifier argument that is the name
75of a feature.  ``__has_feature`` evaluates to 1 if the feature is both
76supported by Clang and standardized in the current language standard or 0 if
77not (but see :ref:`below <langext-has-feature-back-compat>`), while
78``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
79current language (either as a language extension or a standard language
80feature) or 0 if not.  They can be used like this:
81
82.. code-block:: c++
83
84  #ifndef __has_feature         // Optional of course.
85    #define __has_feature(x) 0  // Compatibility with non-clang compilers.
86  #endif
87  #ifndef __has_extension
88    #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
89  #endif
90
91  ...
92  #if __has_feature(cxx_rvalue_references)
93  // This code will only be compiled with the -std=c++11 and -std=gnu++11
94  // options, because rvalue references are only standardized in C++11.
95  #endif
96
97  #if __has_extension(cxx_rvalue_references)
98  // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
99  // and -std=gnu++98 options, because rvalue references are supported as a
100  // language extension in C++98.
101  #endif
102
103.. _langext-has-feature-back-compat:
104
105For backward compatibility, ``__has_feature`` can also be used to test
106for support for non-standardized features, i.e. features not prefixed ``c_``,
107``cxx_`` or ``objc_``.
108
109Another use of ``__has_feature`` is to check for compiler features not related
110to the language standard, such as e.g. :doc:`AddressSanitizer
111<AddressSanitizer>`.
112
113If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
114to ``__has_feature``.
115
116The feature tag is described along with the language feature below.
117
118The feature name or extension name can also be specified with a preceding and
119following ``__`` (double underscore) to avoid interference from a macro with
120the same name.  For instance, ``__cxx_rvalue_references__`` can be used instead
121of ``cxx_rvalue_references``.
122
123``__has_cpp_attribute``
124-----------------------
125
126This function-like macro is available in C++20 by default, and is provided as an
127extension in earlier language standards. It takes a single argument that is the
128name of a double-square-bracket-style attribute. The argument can either be a
129single identifier or a scoped identifier. If the attribute is supported, a
130nonzero value is returned. If the attribute is a standards-based attribute, this
131macro returns a nonzero value based on the year and month in which the attribute
132was voted into the working draft. See `WG21 SD-6
133<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
134for the list of values returned for standards-based attributes. If the attribute
135is not supported by the current compilation target, this macro evaluates to 0.
136It can be used like this:
137
138.. code-block:: c++
139
140  #ifndef __has_cpp_attribute         // For backwards compatibility
141    #define __has_cpp_attribute(x) 0
142  #endif
143
144  ...
145  #if __has_cpp_attribute(clang::fallthrough)
146  #define FALLTHROUGH [[clang::fallthrough]]
147  #else
148  #define FALLTHROUGH
149  #endif
150  ...
151
152The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
153the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
154of these namespaces can be specified with a preceding and following ``__``
155(double underscore) to avoid interference from a macro with the same name. For
156instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
157
158``__has_c_attribute``
159---------------------
160
161This function-like macro takes a single argument that is the name of an
162attribute exposed with the double square-bracket syntax in C mode. The argument
163can either be a single identifier or a scoped identifier. If the attribute is
164supported, a nonzero value is returned. If the attribute is not supported by the
165current compilation target, this macro evaluates to 0. It can be used like this:
166
167.. code-block:: c
168
169  #ifndef __has_c_attribute         // Optional of course.
170    #define __has_c_attribute(x) 0  // Compatibility with non-clang compilers.
171  #endif
172
173  ...
174  #if __has_c_attribute(fallthrough)
175    #define FALLTHROUGH [[fallthrough]]
176  #else
177    #define FALLTHROUGH
178  #endif
179  ...
180
181The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
182the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
183of these namespaces can be specified with a preceding and following ``__``
184(double underscore) to avoid interference from a macro with the same name. For
185instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
186
187``__has_attribute``
188-------------------
189
190This function-like macro takes a single identifier argument that is the name of
191a GNU-style attribute.  It evaluates to 1 if the attribute is supported by the
192current compilation target, or 0 if not.  It can be used like this:
193
194.. code-block:: c++
195
196  #ifndef __has_attribute         // Optional of course.
197    #define __has_attribute(x) 0  // Compatibility with non-clang compilers.
198  #endif
199
200  ...
201  #if __has_attribute(always_inline)
202  #define ALWAYS_INLINE __attribute__((always_inline))
203  #else
204  #define ALWAYS_INLINE
205  #endif
206  ...
207
208The attribute name can also be specified with a preceding and following ``__``
209(double underscore) to avoid interference from a macro with the same name.  For
210instance, ``__always_inline__`` can be used instead of ``always_inline``.
211
212
213``__has_declspec_attribute``
214----------------------------
215
216This function-like macro takes a single identifier argument that is the name of
217an attribute implemented as a Microsoft-style ``__declspec`` attribute.  It
218evaluates to 1 if the attribute is supported by the current compilation target,
219or 0 if not.  It can be used like this:
220
221.. code-block:: c++
222
223  #ifndef __has_declspec_attribute         // Optional of course.
224    #define __has_declspec_attribute(x) 0  // Compatibility with non-clang compilers.
225  #endif
226
227  ...
228  #if __has_declspec_attribute(dllexport)
229  #define DLLEXPORT __declspec(dllexport)
230  #else
231  #define DLLEXPORT
232  #endif
233  ...
234
235The attribute name can also be specified with a preceding and following ``__``
236(double underscore) to avoid interference from a macro with the same name.  For
237instance, ``__dllexport__`` can be used instead of ``dllexport``.
238
239``__is_identifier``
240-------------------
241
242This function-like macro takes a single identifier argument that might be either
243a reserved word or a regular identifier. It evaluates to 1 if the argument is just
244a regular identifier and not a reserved word, in the sense that it can then be
245used as the name of a user-defined function or variable. Otherwise it evaluates
246to 0.  It can be used like this:
247
248.. code-block:: c++
249
250  ...
251  #ifdef __is_identifier          // Compatibility with non-clang compilers.
252    #if __is_identifier(__wchar_t)
253      typedef wchar_t __wchar_t;
254    #endif
255  #endif
256
257  __wchar_t WideCharacter;
258  ...
259
260Include File Checking Macros
261============================
262
263Not all developments systems have the same include files.  The
264:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
265you to check for the existence of an include file before doing a possibly
266failing ``#include`` directive.  Include file checking macros must be used
267as expressions in ``#if`` or ``#elif`` preprocessing directives.
268
269.. _langext-__has_include:
270
271``__has_include``
272-----------------
273
274This function-like macro takes a single file name string argument that is the
275name of an include file.  It evaluates to 1 if the file can be found using the
276include paths, or 0 otherwise:
277
278.. code-block:: c++
279
280  // Note the two possible file name string formats.
281  #if __has_include("myinclude.h") && __has_include(<stdint.h>)
282  # include "myinclude.h"
283  #endif
284
285To test for this feature, use ``#if defined(__has_include)``:
286
287.. code-block:: c++
288
289  // To avoid problem with non-clang compilers not having this macro.
290  #if defined(__has_include)
291  #if __has_include("myinclude.h")
292  # include "myinclude.h"
293  #endif
294  #endif
295
296.. _langext-__has_include_next:
297
298``__has_include_next``
299----------------------
300
301This function-like macro takes a single file name string argument that is the
302name of an include file.  It is like ``__has_include`` except that it looks for
303the second instance of the given file found in the include paths.  It evaluates
304to 1 if the second instance of the file can be found using the include paths,
305or 0 otherwise:
306
307.. code-block:: c++
308
309  // Note the two possible file name string formats.
310  #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
311  # include_next "myinclude.h"
312  #endif
313
314  // To avoid problem with non-clang compilers not having this macro.
315  #if defined(__has_include_next)
316  #if __has_include_next("myinclude.h")
317  # include_next "myinclude.h"
318  #endif
319  #endif
320
321Note that ``__has_include_next``, like the GNU extension ``#include_next``
322directive, is intended for use in headers only, and will issue a warning if
323used in the top-level compilation file.  A warning will also be issued if an
324absolute path is used in the file argument.
325
326``__has_warning``
327-----------------
328
329This function-like macro takes a string literal that represents a command line
330option for a warning and returns true if that is a valid warning option.
331
332.. code-block:: c++
333
334  #if __has_warning("-Wformat")
335  ...
336  #endif
337
338.. _languageextensions-builtin-macros:
339
340Builtin Macros
341==============
342
343``__BASE_FILE__``
344  Defined to a string that contains the name of the main input file passed to
345  Clang.
346
347``__FILE_NAME__``
348  Clang-specific extension that functions similar to ``__FILE__`` but only
349  renders the last path component (the filename) instead of an invocation
350  dependent full path to that file.
351
352``__COUNTER__``
353  Defined to an integer value that starts at zero and is incremented each time
354  the ``__COUNTER__`` macro is expanded.
355
356``__INCLUDE_LEVEL__``
357  Defined to an integral value that is the include depth of the file currently
358  being translated.  For the main file, this value is zero.
359
360``__TIMESTAMP__``
361  Defined to the date and time of the last modification of the current source
362  file.
363
364``__clang__``
365  Defined when compiling with Clang
366
367``__clang_major__``
368  Defined to the major marketing version number of Clang (e.g., the 2 in
369  2.0.1).  Note that marketing version numbers should not be used to check for
370  language features, as different vendors use different numbering schemes.
371  Instead, use the :ref:`langext-feature_check`.
372
373``__clang_minor__``
374  Defined to the minor version number of Clang (e.g., the 0 in 2.0.1).  Note
375  that marketing version numbers should not be used to check for language
376  features, as different vendors use different numbering schemes.  Instead, use
377  the :ref:`langext-feature_check`.
378
379``__clang_patchlevel__``
380  Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
381
382``__clang_version__``
383  Defined to a string that captures the Clang marketing version, including the
384  Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
385
386``__clang_literal_encoding__``
387  Defined to a narrow string literal that represents the current encoding of
388  narrow string literals, e.g., ``"hello"``. This macro typically expands to
389  "UTF-8" (but may change in the future if the
390  ``-fexec-charset="Encoding-Name"`` option is implemented.)
391
392``__clang_wide_literal_encoding__``
393  Defined to a narrow string literal that represents the current encoding of
394  wide string literals, e.g., ``L"hello"``. This macro typically expands to
395  "UTF-16" or "UTF-32" (but may change in the future if the
396  ``-fwide-exec-charset="Encoding-Name"`` option is implemented.)
397
398.. _langext-vectors:
399
400Vectors and Extended Vectors
401============================
402
403Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
404
405OpenCL vector types are created using the ``ext_vector_type`` attribute.  It
406supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL.  An example
407is:
408
409.. code-block:: c++
410
411  typedef float float4 __attribute__((ext_vector_type(4)));
412  typedef float float2 __attribute__((ext_vector_type(2)));
413
414  float4 foo(float2 a, float2 b) {
415    float4 c;
416    c.xz = a;
417    c.yw = b;
418    return c;
419  }
420
421Query for this feature with ``__has_attribute(ext_vector_type)``.
422
423Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
424and functions.  For example:
425
426.. code-block:: c++
427
428  vector float foo(vector int a) {
429    vector int b;
430    b = vec_add(a, a) + a;
431    return (vector float)b;
432  }
433
434NEON vector types are created using ``neon_vector_type`` and
435``neon_polyvector_type`` attributes.  For example:
436
437.. code-block:: c++
438
439  typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
440  typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
441
442  int8x8_t foo(int8x8_t a) {
443    int8x8_t v;
444    v = a;
445    return v;
446  }
447
448Vector Literals
449---------------
450
451Vector literals can be used to create vectors from a set of scalars, or
452vectors.  Either parentheses or braces form can be used.  In the parentheses
453form the number of literal values specified must be one, i.e. referring to a
454scalar value, or must match the size of the vector type being created.  If a
455single scalar literal value is specified, the scalar literal value will be
456replicated to all the components of the vector type.  In the brackets form any
457number of literals can be specified.  For example:
458
459.. code-block:: c++
460
461  typedef int v4si __attribute__((__vector_size__(16)));
462  typedef float float4 __attribute__((ext_vector_type(4)));
463  typedef float float2 __attribute__((ext_vector_type(2)));
464
465  v4si vsi = (v4si){1, 2, 3, 4};
466  float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
467  vector int vi1 = (vector int)(1);    // vi1 will be (1, 1, 1, 1).
468  vector int vi2 = (vector int){1};    // vi2 will be (1, 0, 0, 0).
469  vector int vi3 = (vector int)(1, 2); // error
470  vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
471  vector int vi5 = (vector int)(1, 2, 3, 4);
472  float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
473
474Vector Operations
475-----------------
476
477The table below shows the support for each operation by vector extension.  A
478dash indicates that an operation is not accepted according to a corresponding
479specification.
480
481============================== ======= ======= ============= =======
482         Operator              OpenCL  AltiVec     GCC        NEON
483============================== ======= ======= ============= =======
484[]                               yes     yes       yes         --
485unary operators +, --            yes     yes       yes         --
486++, -- --                        yes     yes       yes         --
487+,--,*,/,%                       yes     yes       yes         --
488bitwise operators &,|,^,~        yes     yes       yes         --
489>>,<<                            yes     yes       yes         --
490!, &&, ||                        yes     --        yes         --
491==, !=, >, <, >=, <=             yes     yes       yes         --
492=                                yes     yes       yes         yes
493?: [#]_                          yes     --        yes         --
494sizeof                           yes     yes       yes         yes
495C-style cast                     yes     yes       yes         no
496reinterpret_cast                 yes     no        yes         no
497static_cast                      yes     no        yes         no
498const_cast                       no      no        no          no
499============================== ======= ======= ============= =======
500
501See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
502
503.. [#] ternary operator(?:) has different behaviors depending on condition
504  operand's vector type. If the condition is a GNU vector (i.e. __vector_size__),
505  it's only available in C++ and uses normal bool conversions (that is, != 0).
506  If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.
507  And it selects base on signedness of the condition operands (OpenCL v1.1 s6.3.9).
508
509Vector Builtins
510---------------
511
512**Note: The implementation of vector builtins is work-in-progress and incomplete.**
513
514In addition to the operators mentioned above, Clang provides a set of builtins
515to perform additional operations on certain scalar and vector types.
516
517Let ``T`` be one of the following types:
518
519* an integer type (as in C2x 6.2.5p19), but excluding enumerated types and _Bool
520* the standard floating types float or double
521* a half-precision floating point type, if one is supported on the target
522* a vector type.
523
524For scalar types, consider the operation applied to a vector with a single element.
525
526*Elementwise Builtins*
527
528Each builtin returns a vector equivalent to applying the specified operation
529elementwise to the input.
530
531Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = ±infinity
532
533=========================================== ================================================================ =========================================
534         Name                                Operation                                                        Supported element types
535=========================================== ================================================================ =========================================
536 T __builtin_elementwise_abs(T x)            return the absolute value of a number x; the absolute value of   signed integer and floating point types
537                                             the most negative integer remains the most negative integer
538 T __builtin_elementwise_ceil(T x)           return the smallest integral value greater than or equal to x    floating point types
539 T __builtin_elementwise_floor(T x)          return the largest integral value less than or equal to x        floating point types
540 T __builtin_elementwise_roundeven(T x)      round x to the nearest integer value in floating point format,   floating point types
541                                             rounding halfway cases to even (that is, to the nearest value
542                                             that is an even integer), regardless of the current rounding
543                                             direction.
544 T__builtin_elementwise_trunc(T x)           return the integral value nearest to but no larger in            floating point types
545                                             magnitude than x
546 T __builtin_elementwise_max(T x, T y)       return x or y, whichever is larger                               integer and floating point types
547 T __builtin_elementwise_min(T x, T y)       return x or y, whichever is smaller                              integer and floating point types
548 T __builtin_elementwise_add_sat(T x, T y)   return the sum of x and y, clamped to the range of               integer types
549                                             representable values for the signed/unsigned integer type.
550 T __builtin_elementwise_sub_sat(T x, T y)   return the difference of x and y, clamped to the range of        integer types
551                                             representable values for the signed/unsigned integer type.
552=========================================== ================================================================ =========================================
553
554
555*Reduction Builtins*
556
557Each builtin returns a scalar equivalent to applying the specified
558operation(x, y) as recursive even-odd pairwise reduction to all vector
559elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping
560even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with
561``i in [0, Number of elements / 2)``. If the numbers of elements is not a
562power of 2, the vector is widened with neutral elements for the reduction
563at the end to the next power of 2.
564
565Example:
566
567.. code-block:: c++
568
569    __builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0])
570                                           = (e3 + e2) + (e1 + e0)
571
572
573Let ``VT`` be a vector type and ``ET`` the element type of ``VT``.
574
575======================================= ================================================================ ==================================
576         Name                            Operation                                                        Supported element types
577======================================= ================================================================ ==================================
578 ET __builtin_reduce_max(VT a)           return x or y, whichever is larger; If exactly one argument is   integer and floating point types
579                                         a NaN, return the other argument. If both arguments are NaNs,
580                                         fmax() return a NaN.
581 ET __builtin_reduce_min(VT a)           return x or y, whichever is smaller; If exactly one argument     integer and floating point types
582                                         is a NaN, return the other argument. If both arguments are
583                                         NaNs, fmax() return a NaN.
584 ET __builtin_reduce_add(VT a)           \+                                                               integer and floating point types
585 ET __builtin_reduce_and(VT a)           &                                                                integer types
586 ET __builtin_reduce_or(VT a)            \|                                                               integer types
587 ET __builtin_reduce_xor(VT a)           ^                                                                integer types
588======================================= ================================================================ ==================================
589
590Matrix Types
591============
592
593Clang provides an extension for matrix types, which is currently being
594implemented. See :ref:`the draft specification <matrixtypes>` for more details.
595
596For example, the code below uses the matrix types extension to multiply two 4x4
597float matrices and add the result to a third 4x4 matrix.
598
599.. code-block:: c++
600
601  typedef float m4x4_t __attribute__((matrix_type(4, 4)));
602
603  m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) {
604    return a + b * c;
605  }
606
607The matrix type extension also supports operations on a matrix and a scalar.
608
609.. code-block:: c++
610
611  typedef float m4x4_t __attribute__((matrix_type(4, 4)));
612
613  m4x4_t f(m4x4_t a) {
614    return (a + 23) * 12;
615  }
616
617The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix.
618
619.. code-block:: c++
620
621  typedef float m4x4_t __attribute__((matrix_type(4, 4)));
622
623  m4x4_t f(m4x4_t a) {
624    a = a / 3.0;
625    return a;
626  }
627
628The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices
629and on a matrix and a scalar, provided their types are consistent.
630
631.. code-block:: c++
632
633  typedef float m4x4_t __attribute__((matrix_type(4, 4)));
634
635  m4x4_t f(m4x4_t a, m4x4_t b) {
636    a += b;
637    a -= b;
638    a *= b;
639    a += 23;
640    a -= 12;
641    return a;
642  }
643
644The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed.
645
646.. code-block:: c++
647
648  typedef int ix5x5 __attribute__((matrix_type(5, 5)));
649  typedef float fx5x5 __attribute__((matrix_type(5, 5)));
650
651  fx5x5 f1(ix5x5 i, fx5x5 f) {
652    return (fx5x5) i;
653  }
654
655
656  template <typename X>
657  using matrix_4_4 = X __attribute__((matrix_type(4, 4)));
658
659  void f2() {
660    matrix_5_5<double> d;
661    matrix_5_5<int> i;
662    i = (matrix_5_5<int>)d;
663    i = static_cast<matrix_5_5<int>>(d);
664  }
665
666Half-Precision Floating Point
667=============================
668
669Clang supports three half-precision (16-bit) floating point types: ``__fp16``,
670``_Float16`` and ``__bf16``.  These types are supported in all language modes.
671
672``__fp16`` is supported on every target, as it is purely a storage format; see below.
673``_Float16`` is currently only supported on the following targets, with further
674targets pending ABI standardization:
675
676* 32-bit ARM
677* 64-bit ARM (AArch64)
678* AMDGPU
679* SPIR
680* X86 (Only available under feature AVX512-FP16)
681
682``_Float16`` will be supported on more targets as they define ABIs for it.
683
684``__bf16`` is purely a storage format; it is currently only supported on the following targets:
685* 32-bit ARM
686* 64-bit ARM (AArch64)
687
688The ``__bf16`` type is only available when supported in hardware.
689
690``__fp16`` is a storage and interchange format only.  This means that values of
691``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic
692operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``.
693The behavior of ``__fp16`` is specified by the ARM C Language Extensions (`ACLE <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053d/IHI0053D_acle_2_1.pdf>`_).
694Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
695alternative format.
696
697``_Float16`` is an interchange floating-point type.  This means that, just like arithmetic on
698``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the
699``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
700``_Float16``.  The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
701("Floating-point extensions for C").  As with ``__fp16``, Clang uses the ``binary16``
702format from IEEE 754-2008 for ``_Float16``.
703
704``_Float16`` arithmetic will be performed using native half-precision support
705when available on the target (e.g. on ARMv8.2a); otherwise it will be performed
706at a higher precision (currently always ``float``) and then truncated down to
707``_Float16``.  Note that C and C++ allow intermediate floating-point operands
708of an expression to be computed with greater precision than is expressible in
709their type, so Clang may avoid intermediate truncations in certain cases; this may
710lead to results that are inconsistent with native arithmetic.
711
712It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
713as it has been defined by the C standards committee and has behavior that is
714more familiar to most programmers.
715
716Because ``__fp16`` operands are always immediately promoted to ``float``, the
717common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
718arithmetic conversions is ``float``.
719
720A literal can be given ``_Float16`` type using the suffix ``f16``. For example,
721``3.14f16``.
722
723Because default argument promotion only applies to the standard floating-point
724types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
725or untyped arguments.  As a consequence, some caution must be taken when using
726certain library facilities with ``_Float16``; for example, there is no ``printf`` format
727specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
728``double`` when passed to ``printf``, so the programmer must explicitly cast it to
729``double`` before using it with an ``%f`` or similar specifier.
730
731Messages on ``deprecated`` and ``unavailable`` Attributes
732=========================================================
733
734An optional string message can be added to the ``deprecated`` and
735``unavailable`` attributes.  For example:
736
737.. code-block:: c++
738
739  void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
740
741If the deprecated or unavailable declaration is used, the message will be
742incorporated into the appropriate diagnostic:
743
744.. code-block:: none
745
746  harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
747        [-Wdeprecated-declarations]
748    explode();
749    ^
750
751Query for this feature with
752``__has_extension(attribute_deprecated_with_message)`` and
753``__has_extension(attribute_unavailable_with_message)``.
754
755Attributes on Enumerators
756=========================
757
758Clang allows attributes to be written on individual enumerators.  This allows
759enumerators to be deprecated, made unavailable, etc.  The attribute must appear
760after the enumerator name and before any initializer, like so:
761
762.. code-block:: c++
763
764  enum OperationMode {
765    OM_Invalid,
766    OM_Normal,
767    OM_Terrified __attribute__((deprecated)),
768    OM_AbortOnError __attribute__((deprecated)) = 4
769  };
770
771Attributes on the ``enum`` declaration do not apply to individual enumerators.
772
773Query for this feature with ``__has_extension(enumerator_attributes)``.
774
775C++11 Attributes on using-declarations
776======================================
777
778Clang allows C++-style ``[[]]`` attributes to be written on using-declarations.
779For instance:
780
781.. code-block:: c++
782
783  [[clang::using_if_exists]] using foo::bar;
784  using foo::baz [[clang::using_if_exists]];
785
786You can test for support for this extension with
787``__has_extension(cxx_attributes_on_using_declarations)``.
788
789'User-Specified' System Frameworks
790==================================
791
792Clang provides a mechanism by which frameworks can be built in such a way that
793they will always be treated as being "system frameworks", even if they are not
794present in a system framework directory.  This can be useful to system
795framework developers who want to be able to test building other applications
796with development builds of their framework, including the manner in which the
797compiler changes warning behavior for system headers.
798
799Framework developers can opt-in to this mechanism by creating a
800"``.system_framework``" file at the top-level of their framework.  That is, the
801framework should have contents like:
802
803.. code-block:: none
804
805  .../TestFramework.framework
806  .../TestFramework.framework/.system_framework
807  .../TestFramework.framework/Headers
808  .../TestFramework.framework/Headers/TestFramework.h
809  ...
810
811Clang will treat the presence of this file as an indicator that the framework
812should be treated as a system framework, regardless of how it was found in the
813framework search path.  For consistency, we recommend that such files never be
814included in installed versions of the framework.
815
816Checks for Standard Language Features
817=====================================
818
819The ``__has_feature`` macro can be used to query if certain standard language
820features are enabled.  The ``__has_extension`` macro can be used to query if
821language features are available as an extension when compiling for a standard
822which does not provide them.  The features which can be tested are listed here.
823
824Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
825These are macros with names of the form ``__cpp_<feature_name>``, and are
826intended to be a portable way to query the supported features of the compiler.
827See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
828information on the version of SD-6 supported by each Clang release, and the
829macros provided by that revision of the recommendations.
830
831C++98
832-----
833
834The features listed below are part of the C++98 standard.  These features are
835enabled by default when compiling C++ code.
836
837C++ exceptions
838^^^^^^^^^^^^^^
839
840Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
841enabled.  For example, compiling code with ``-fno-exceptions`` disables C++
842exceptions.
843
844C++ RTTI
845^^^^^^^^
846
847Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled.  For
848example, compiling code with ``-fno-rtti`` disables the use of RTTI.
849
850C++11
851-----
852
853The features listed below are part of the C++11 standard.  As a result, all
854these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
855when compiling C++ code.
856
857C++11 SFINAE includes access control
858^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
859
860Use ``__has_feature(cxx_access_control_sfinae)`` or
861``__has_extension(cxx_access_control_sfinae)`` to determine whether
862access-control errors (e.g., calling a private constructor) are considered to
863be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
864<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
865
866C++11 alias templates
867^^^^^^^^^^^^^^^^^^^^^
868
869Use ``__has_feature(cxx_alias_templates)`` or
870``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
871alias declarations and alias templates is enabled.
872
873C++11 alignment specifiers
874^^^^^^^^^^^^^^^^^^^^^^^^^^
875
876Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
877determine if support for alignment specifiers using ``alignas`` is enabled.
878
879Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
880determine if support for the ``alignof`` keyword is enabled.
881
882C++11 attributes
883^^^^^^^^^^^^^^^^
884
885Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
886determine if support for attribute parsing with C++11's square bracket notation
887is enabled.
888
889C++11 generalized constant expressions
890^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
891
892Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
893constant expressions (e.g., ``constexpr``) is enabled.
894
895C++11 ``decltype()``
896^^^^^^^^^^^^^^^^^^^^
897
898Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
899determine if support for the ``decltype()`` specifier is enabled.  C++11's
900``decltype`` does not require type-completeness of a function call expression.
901Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
902``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
903support for this feature is enabled.
904
905C++11 default template arguments in function templates
906^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
907
908Use ``__has_feature(cxx_default_function_template_args)`` or
909``__has_extension(cxx_default_function_template_args)`` to determine if support
910for default template arguments in function templates is enabled.
911
912C++11 ``default``\ ed functions
913^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
914
915Use ``__has_feature(cxx_defaulted_functions)`` or
916``__has_extension(cxx_defaulted_functions)`` to determine if support for
917defaulted function definitions (with ``= default``) is enabled.
918
919C++11 delegating constructors
920^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
921
922Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
923delegating constructors is enabled.
924
925C++11 ``deleted`` functions
926^^^^^^^^^^^^^^^^^^^^^^^^^^^
927
928Use ``__has_feature(cxx_deleted_functions)`` or
929``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
930function definitions (with ``= delete``) is enabled.
931
932C++11 explicit conversion functions
933^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
934
935Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
936``explicit`` conversion functions is enabled.
937
938C++11 generalized initializers
939^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
940
941Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
942generalized initializers (using braced lists and ``std::initializer_list``) is
943enabled.
944
945C++11 implicit move constructors/assignment operators
946^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
947
948Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
949generate move constructors and move assignment operators where needed.
950
951C++11 inheriting constructors
952^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
953
954Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
955inheriting constructors is enabled.
956
957C++11 inline namespaces
958^^^^^^^^^^^^^^^^^^^^^^^
959
960Use ``__has_feature(cxx_inline_namespaces)`` or
961``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
962namespaces is enabled.
963
964C++11 lambdas
965^^^^^^^^^^^^^
966
967Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
968determine if support for lambdas is enabled.
969
970C++11 local and unnamed types as template arguments
971^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
972
973Use ``__has_feature(cxx_local_type_template_args)`` or
974``__has_extension(cxx_local_type_template_args)`` to determine if support for
975local and unnamed types as template arguments is enabled.
976
977C++11 noexcept
978^^^^^^^^^^^^^^
979
980Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
981determine if support for noexcept exception specifications is enabled.
982
983C++11 in-class non-static data member initialization
984^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
985
986Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
987initialization of non-static data members is enabled.
988
989C++11 ``nullptr``
990^^^^^^^^^^^^^^^^^
991
992Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
993determine if support for ``nullptr`` is enabled.
994
995C++11 ``override control``
996^^^^^^^^^^^^^^^^^^^^^^^^^^
997
998Use ``__has_feature(cxx_override_control)`` or
999``__has_extension(cxx_override_control)`` to determine if support for the
1000override control keywords is enabled.
1001
1002C++11 reference-qualified functions
1003^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1004
1005Use ``__has_feature(cxx_reference_qualified_functions)`` or
1006``__has_extension(cxx_reference_qualified_functions)`` to determine if support
1007for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
1008applied to ``*this``) is enabled.
1009
1010C++11 range-based ``for`` loop
1011^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1012
1013Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
1014determine if support for the range-based for loop is enabled.
1015
1016C++11 raw string literals
1017^^^^^^^^^^^^^^^^^^^^^^^^^
1018
1019Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
1020string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
1021
1022C++11 rvalue references
1023^^^^^^^^^^^^^^^^^^^^^^^
1024
1025Use ``__has_feature(cxx_rvalue_references)`` or
1026``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
1027references is enabled.
1028
1029C++11 ``static_assert()``
1030^^^^^^^^^^^^^^^^^^^^^^^^^
1031
1032Use ``__has_feature(cxx_static_assert)`` or
1033``__has_extension(cxx_static_assert)`` to determine if support for compile-time
1034assertions using ``static_assert`` is enabled.
1035
1036C++11 ``thread_local``
1037^^^^^^^^^^^^^^^^^^^^^^
1038
1039Use ``__has_feature(cxx_thread_local)`` to determine if support for
1040``thread_local`` variables is enabled.
1041
1042C++11 type inference
1043^^^^^^^^^^^^^^^^^^^^
1044
1045Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
1046determine C++11 type inference is supported using the ``auto`` specifier.  If
1047this is disabled, ``auto`` will instead be a storage class specifier, as in C
1048or C++98.
1049
1050C++11 strongly typed enumerations
1051^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1052
1053Use ``__has_feature(cxx_strong_enums)`` or
1054``__has_extension(cxx_strong_enums)`` to determine if support for strongly
1055typed, scoped enumerations is enabled.
1056
1057C++11 trailing return type
1058^^^^^^^^^^^^^^^^^^^^^^^^^^
1059
1060Use ``__has_feature(cxx_trailing_return)`` or
1061``__has_extension(cxx_trailing_return)`` to determine if support for the
1062alternate function declaration syntax with trailing return type is enabled.
1063
1064C++11 Unicode string literals
1065^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1066
1067Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
1068string literals is enabled.
1069
1070C++11 unrestricted unions
1071^^^^^^^^^^^^^^^^^^^^^^^^^
1072
1073Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
1074unrestricted unions is enabled.
1075
1076C++11 user-defined literals
1077^^^^^^^^^^^^^^^^^^^^^^^^^^^
1078
1079Use ``__has_feature(cxx_user_literals)`` to determine if support for
1080user-defined literals is enabled.
1081
1082C++11 variadic templates
1083^^^^^^^^^^^^^^^^^^^^^^^^
1084
1085Use ``__has_feature(cxx_variadic_templates)`` or
1086``__has_extension(cxx_variadic_templates)`` to determine if support for
1087variadic templates is enabled.
1088
1089C++14
1090-----
1091
1092The features listed below are part of the C++14 standard.  As a result, all
1093these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
1094when compiling C++ code.
1095
1096C++14 binary literals
1097^^^^^^^^^^^^^^^^^^^^^
1098
1099Use ``__has_feature(cxx_binary_literals)`` or
1100``__has_extension(cxx_binary_literals)`` to determine whether
1101binary literals (for instance, ``0b10010``) are recognized. Clang supports this
1102feature as an extension in all language modes.
1103
1104C++14 contextual conversions
1105^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1106
1107Use ``__has_feature(cxx_contextual_conversions)`` or
1108``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
1109are used when performing an implicit conversion for an array bound in a
1110*new-expression*, the operand of a *delete-expression*, an integral constant
1111expression, or a condition in a ``switch`` statement.
1112
1113C++14 decltype(auto)
1114^^^^^^^^^^^^^^^^^^^^
1115
1116Use ``__has_feature(cxx_decltype_auto)`` or
1117``__has_extension(cxx_decltype_auto)`` to determine if support
1118for the ``decltype(auto)`` placeholder type is enabled.
1119
1120C++14 default initializers for aggregates
1121^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1122
1123Use ``__has_feature(cxx_aggregate_nsdmi)`` or
1124``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
1125for default initializers in aggregate members is enabled.
1126
1127C++14 digit separators
1128^^^^^^^^^^^^^^^^^^^^^^
1129
1130Use ``__cpp_digit_separators`` to determine if support for digit separators
1131using single quotes (for instance, ``10'000``) is enabled. At this time, there
1132is no corresponding ``__has_feature`` name
1133
1134C++14 generalized lambda capture
1135^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1136
1137Use ``__has_feature(cxx_init_captures)`` or
1138``__has_extension(cxx_init_captures)`` to determine if support for
1139lambda captures with explicit initializers is enabled
1140(for instance, ``[n(0)] { return ++n; }``).
1141
1142C++14 generic lambdas
1143^^^^^^^^^^^^^^^^^^^^^
1144
1145Use ``__has_feature(cxx_generic_lambdas)`` or
1146``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
1147(polymorphic) lambdas is enabled
1148(for instance, ``[] (auto x) { return x + 1; }``).
1149
1150C++14 relaxed constexpr
1151^^^^^^^^^^^^^^^^^^^^^^^
1152
1153Use ``__has_feature(cxx_relaxed_constexpr)`` or
1154``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
1155declarations, local variable modification, and control flow constructs
1156are permitted in ``constexpr`` functions.
1157
1158C++14 return type deduction
1159^^^^^^^^^^^^^^^^^^^^^^^^^^^
1160
1161Use ``__has_feature(cxx_return_type_deduction)`` or
1162``__has_extension(cxx_return_type_deduction)`` to determine if support
1163for return type deduction for functions (using ``auto`` as a return type)
1164is enabled.
1165
1166C++14 runtime-sized arrays
1167^^^^^^^^^^^^^^^^^^^^^^^^^^
1168
1169Use ``__has_feature(cxx_runtime_array)`` or
1170``__has_extension(cxx_runtime_array)`` to determine if support
1171for arrays of runtime bound (a restricted form of variable-length arrays)
1172is enabled.
1173Clang's implementation of this feature is incomplete.
1174
1175C++14 variable templates
1176^^^^^^^^^^^^^^^^^^^^^^^^
1177
1178Use ``__has_feature(cxx_variable_templates)`` or
1179``__has_extension(cxx_variable_templates)`` to determine if support for
1180templated variable declarations is enabled.
1181
1182C11
1183---
1184
1185The features listed below are part of the C11 standard.  As a result, all these
1186features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
1187compiling C code.  Additionally, because these features are all
1188backward-compatible, they are available as extensions in all language modes.
1189
1190C11 alignment specifiers
1191^^^^^^^^^^^^^^^^^^^^^^^^
1192
1193Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
1194if support for alignment specifiers using ``_Alignas`` is enabled.
1195
1196Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
1197if support for the ``_Alignof`` keyword is enabled.
1198
1199C11 atomic operations
1200^^^^^^^^^^^^^^^^^^^^^
1201
1202Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
1203if support for atomic types using ``_Atomic`` is enabled.  Clang also provides
1204:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
1205the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
1206``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
1207is available.
1208
1209Clang will use the system's ``<stdatomic.h>`` header when one is available, and
1210will otherwise use its own. When using its own, implementations of the atomic
1211operations are provided as macros. In the cases where C11 also requires a real
1212function, this header provides only the declaration of that function (along
1213with a shadowing macro implementation), and you must link to a library which
1214provides a definition of the function if you use it instead of the macro.
1215
1216C11 generic selections
1217^^^^^^^^^^^^^^^^^^^^^^
1218
1219Use ``__has_feature(c_generic_selections)`` or
1220``__has_extension(c_generic_selections)`` to determine if support for generic
1221selections is enabled.
1222
1223As an extension, the C11 generic selection expression is available in all
1224languages supported by Clang.  The syntax is the same as that given in the C11
1225standard.
1226
1227In C, type compatibility is decided according to the rules given in the
1228appropriate standard, but in C++, which lacks the type compatibility rules used
1229in C, types are considered compatible only if they are equivalent.
1230
1231C11 ``_Static_assert()``
1232^^^^^^^^^^^^^^^^^^^^^^^^
1233
1234Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
1235to determine if support for compile-time assertions using ``_Static_assert`` is
1236enabled.
1237
1238C11 ``_Thread_local``
1239^^^^^^^^^^^^^^^^^^^^^
1240
1241Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
1242to determine if support for ``_Thread_local`` variables is enabled.
1243
1244Modules
1245-------
1246
1247Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1248For example, compiling code with ``-fmodules`` enables the use of Modules.
1249
1250More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
1251
1252Type Trait Primitives
1253=====================
1254
1255Type trait primitives are special builtin constant expressions that can be used
1256by the standard C++ library to facilitate or simplify the implementation of
1257user-facing type traits in the <type_traits> header.
1258
1259They are not intended to be used directly by user code because they are
1260implementation-defined and subject to change -- as such they're tied closely to
1261the supported set of system headers, currently:
1262
1263* LLVM's own libc++
1264* GNU libstdc++
1265* The Microsoft standard C++ library
1266
1267Clang supports the `GNU C++ type traits
1268<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
1269`Microsoft Visual C++ type traits
1270<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,
1271as well as nearly all of the
1272`Embarcadero C++ type traits
1273<http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.
1274
1275The following type trait primitives are supported by Clang. Those traits marked
1276(C++) provide implementations for type traits specified by the C++ standard;
1277``__X(...)`` has the same semantics and constraints as the corresponding
1278``std::X_t<...>`` or ``std::X_v<...>`` type trait.
1279
1280* ``__array_rank(type)`` (Embarcadero):
1281  Returns the number of levels of array in the type ``type``:
1282  ``0`` if ``type`` is not an array type, and
1283  ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.
1284* ``__array_extent(type, dim)`` (Embarcadero):
1285  The ``dim``'th array bound in the type ``type``, or ``0`` if
1286  ``dim >= __array_rank(type)``.
1287* ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero):
1288  Deprecated, use ``__is_nothrow_assignable`` instead.
1289* ``__has_nothrow_move_assign`` (GNU, Microsoft):
1290  Deprecated, use ``__is_nothrow_assignable`` instead.
1291* ``__has_nothrow_copy`` (GNU, Microsoft):
1292  Deprecated, use ``__is_nothrow_constructible`` instead.
1293* ``__has_nothrow_constructor`` (GNU, Microsoft):
1294  Deprecated, use ``__is_nothrow_constructible`` instead.
1295* ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero):
1296  Deprecated, use ``__is_trivially_assignable`` instead.
1297* ``__has_trivial_move_assign`` (GNU, Microsoft):
1298  Deprecated, use ``__is_trivially_assignable`` instead.
1299* ``__has_trivial_copy`` (GNU, Microsoft):
1300  Deprecated, use ``__is_trivially_constructible`` instead.
1301* ``__has_trivial_constructor`` (GNU, Microsoft):
1302  Deprecated, use ``__is_trivially_constructible`` instead.
1303* ``__has_trivial_move_constructor`` (GNU, Microsoft):
1304  Deprecated, use ``__is_trivially_constructible`` instead.
1305* ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero):
1306  Deprecated, use ``__is_trivially_destructible`` instead.
1307* ``__has_unique_object_representations`` (C++, GNU)
1308* ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero)
1309* ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero)
1310* ``__is_aggregate`` (C++, GNU, Microsoft)
1311* ``__is_arithmetic`` (C++, Embarcadero)
1312* ``__is_array`` (C++, Embarcadero)
1313* ``__is_assignable`` (C++, MSVC 2015)
1314* ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero)
1315* ``__is_class`` (C++, GNU, Microsoft, Embarcadero)
1316* ``__is_complete_type(type)`` (Embarcadero):
1317  Return ``true`` if ``type`` is a complete type.
1318  Warning: this trait is dangerous because it can return different values at
1319  different points in the same program.
1320* ``__is_compound`` (C++, Embarcadero)
1321* ``__is_const`` (C++, Embarcadero)
1322* ``__is_constructible`` (C++, MSVC 2013)
1323* ``__is_convertible`` (C++, Embarcadero)
1324* ``__is_convertible_to`` (Microsoft):
1325  Synonym for ``__is_convertible``.
1326* ``__is_destructible`` (C++, MSVC 2013):
1327  Only available in ``-fms-extensions`` mode.
1328* ``__is_empty`` (C++, GNU, Microsoft, Embarcadero)
1329* ``__is_enum`` (C++, GNU, Microsoft, Embarcadero)
1330* ``__is_final`` (C++, GNU, Microsoft)
1331* ``__is_floating_point`` (C++, Embarcadero)
1332* ``__is_function`` (C++, Embarcadero)
1333* ``__is_fundamental`` (C++, Embarcadero)
1334* ``__is_integral`` (C++, Embarcadero)
1335* ``__is_interface_class`` (Microsoft):
1336  Returns ``false``, even for types defined with ``__interface``.
1337* ``__is_literal`` (Clang):
1338  Synonym for ``__is_literal_type``.
1339* ``__is_literal_type`` (C++, GNU, Microsoft):
1340  Note, the corresponding standard trait was deprecated in C++17
1341  and removed in C++20.
1342* ``__is_lvalue_reference`` (C++, Embarcadero)
1343* ``__is_member_object_pointer`` (C++, Embarcadero)
1344* ``__is_member_function_pointer`` (C++, Embarcadero)
1345* ``__is_member_pointer`` (C++, Embarcadero)
1346* ``__is_nothrow_assignable`` (C++, MSVC 2013)
1347* ``__is_nothrow_constructible`` (C++, MSVC 2013)
1348* ``__is_nothrow_destructible`` (C++, MSVC 2013)
1349  Only available in ``-fms-extensions`` mode.
1350* ``__is_object`` (C++, Embarcadero)
1351* ``__is_pod`` (C++, GNU, Microsoft, Embarcadero):
1352  Note, the corresponding standard trait was deprecated in C++20.
1353* ``__is_pointer`` (C++, Embarcadero)
1354* ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero)
1355* ``__is_reference`` (C++, Embarcadero)
1356* ``__is_rvalue_reference`` (C++, Embarcadero)
1357* ``__is_same`` (C++, Embarcadero)
1358* ``__is_same_as`` (GCC): Synonym for ``__is_same``.
1359* ``__is_scalar`` (C++, Embarcadero)
1360* ``__is_sealed`` (Microsoft):
1361  Synonym for ``__is_final``.
1362* ``__is_signed`` (C++, Embarcadero):
1363  Returns false for enumeration types, and returns true for floating-point
1364  types. Note, before Clang 10, returned true for enumeration types if the
1365  underlying type was signed, and returned false for floating-point types.
1366* ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero)
1367* ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero)
1368* ``__is_trivially_assignable`` (C++, GNU, Microsoft)
1369* ``__is_trivially_constructible`` (C++, GNU, Microsoft)
1370* ``__is_trivially_copyable`` (C++, GNU, Microsoft)
1371* ``__is_trivially_destructible`` (C++, MSVC 2013)
1372* ``__is_trivially_relocatable`` (Clang): Returns true if moving an object
1373  of the given type, and then destroying the source object, is known to be
1374  functionally equivalent to copying the underlying bytes and then dropping the
1375  source object on the floor. This is true of trivial types and types which
1376  were made trivially relocatable via the ``clang::trivial_abi`` attribute.
1377* ``__is_union`` (C++, GNU, Microsoft, Embarcadero)
1378* ``__is_unsigned`` (C++, Embarcadero):
1379  Returns false for enumeration types. Note, before Clang 13, returned true for
1380  enumeration types if the underlying type was unsigned.
1381* ``__is_void`` (C++, Embarcadero)
1382* ``__is_volatile`` (C++, Embarcadero)
1383* ``__reference_binds_to_temporary(T, U)`` (Clang):  Determines whether a
1384  reference of type ``T`` bound to an expression of type ``U`` would bind to a
1385  materialized temporary object. If ``T`` is not a reference type the result
1386  is false. Note this trait will also return false when the initialization of
1387  ``T`` from ``U`` is ill-formed.
1388* ``__underlying_type`` (C++, GNU, Microsoft)
1389
1390In addition, the following expression traits are supported:
1391
1392* ``__is_lvalue_expr(e)`` (Embarcadero):
1393  Returns true if ``e`` is an lvalue expression.
1394  Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.
1395* ``__is_rvalue_expr(e)`` (Embarcadero):
1396  Returns true if ``e`` is a prvalue expression.
1397  Deprecated, use ``!__is_reference(decltype((e)))`` instead.
1398
1399There are multiple ways to detect support for a type trait ``__X`` in the
1400compiler, depending on the oldest version of Clang you wish to support.
1401
1402* From Clang 10 onwards, ``__has_builtin(__X)`` can be used.
1403* From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.
1404* From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports
1405  the following traits:
1406
1407  * ``__has_nothrow_assign``
1408  * ``__has_nothrow_copy``
1409  * ``__has_nothrow_constructor``
1410  * ``__has_trivial_assign``
1411  * ``__has_trivial_copy``
1412  * ``__has_trivial_constructor``
1413  * ``__has_trivial_destructor``
1414  * ``__has_virtual_destructor``
1415  * ``__is_abstract``
1416  * ``__is_base_of``
1417  * ``__is_class``
1418  * ``__is_constructible``
1419  * ``__is_convertible_to``
1420  * ``__is_empty``
1421  * ``__is_enum``
1422  * ``__is_final``
1423  * ``__is_literal``
1424  * ``__is_standard_layout``
1425  * ``__is_pod``
1426  * ``__is_polymorphic``
1427  * ``__is_sealed``
1428  * ``__is_trivial``
1429  * ``__is_trivially_assignable``
1430  * ``__is_trivially_constructible``
1431  * ``__is_trivially_copyable``
1432  * ``__is_union``
1433  * ``__underlying_type``
1434
1435A simplistic usage example as might be seen in standard C++ headers follows:
1436
1437.. code-block:: c++
1438
1439  #if __has_builtin(__is_convertible_to)
1440  template<typename From, typename To>
1441  struct is_convertible_to {
1442    static const bool value = __is_convertible_to(From, To);
1443  };
1444  #else
1445  // Emulate type trait for compatibility with other compilers.
1446  #endif
1447
1448Blocks
1449======
1450
1451The syntax and high level language feature description is in
1452:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1453the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
1454
1455Query for this feature with ``__has_extension(blocks)``.
1456
1457ASM Goto with Output Constraints
1458================================
1459
1460In addition to the functionality provided by `GCC's extended
1461assembly <https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html>`_, clang
1462supports output constraints with the `goto` form.
1463
1464The goto form of GCC's extended assembly allows the programmer to branch to a C
1465label from within an inline assembly block. Clang extends this behavior by
1466allowing the programmer to use output constraints:
1467
1468.. code-block:: c++
1469
1470  int foo(int x) {
1471      int y;
1472      asm goto("# %0 %1 %l2" : "=r"(y) : "r"(x) : : err);
1473      return y;
1474    err:
1475      return -1;
1476  }
1477
1478It's important to note that outputs are valid only on the "fallthrough" branch.
1479Using outputs on an indirect branch may result in undefined behavior. For
1480example, in the function above, use of the value assigned to `y` in the `err`
1481block is undefined behavior.
1482
1483When using tied-outputs (i.e. outputs that are inputs and outputs, not just
1484outputs) with the `+r` constraint, there is a hidden input that's created
1485before the label, so numeric references to operands must account for that.
1486
1487.. code-block:: c++
1488
1489  int foo(int x) {
1490      // %0 and %1 both refer to x
1491      // %l2 refers to err
1492      asm goto("# %0 %1 %l2" : "+r"(x) : : : err);
1493      return x;
1494    err:
1495      return -1;
1496  }
1497
1498This was changed to match GCC in clang-13; for better portability, symbolic
1499references can be used instead of numeric references.
1500
1501.. code-block:: c++
1502
1503  int foo(int x) {
1504      asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err);
1505      return x;
1506    err:
1507      return -1;
1508  }
1509
1510Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.
1511
1512Objective-C Features
1513====================
1514
1515Related result types
1516--------------------
1517
1518According to Cocoa conventions, Objective-C methods with certain names
1519("``init``", "``alloc``", etc.) always return objects that are an instance of
1520the receiving class's type.  Such methods are said to have a "related result
1521type", meaning that a message send to one of these methods will have the same
1522static type as an instance of the receiver class.  For example, given the
1523following classes:
1524
1525.. code-block:: objc
1526
1527  @interface NSObject
1528  + (id)alloc;
1529  - (id)init;
1530  @end
1531
1532  @interface NSArray : NSObject
1533  @end
1534
1535and this common initialization pattern
1536
1537.. code-block:: objc
1538
1539  NSArray *array = [[NSArray alloc] init];
1540
1541the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1542``alloc`` implicitly has a related result type.  Similarly, the type of the
1543expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1544related result type and its receiver is known to have the type ``NSArray *``.
1545If neither ``alloc`` nor ``init`` had a related result type, the expressions
1546would have had type ``id``, as declared in the method signature.
1547
1548A method with a related result type can be declared by using the type
1549``instancetype`` as its result type.  ``instancetype`` is a contextual keyword
1550that is only permitted in the result type of an Objective-C method, e.g.
1551
1552.. code-block:: objc
1553
1554  @interface A
1555  + (instancetype)constructAnA;
1556  @end
1557
1558The related result type can also be inferred for some methods.  To determine
1559whether a method has an inferred related result type, the first word in the
1560camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1561and the method will have a related result type if its return type is compatible
1562with the type of its class and if:
1563
1564* the first word is "``alloc``" or "``new``", and the method is a class method,
1565  or
1566
1567* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1568  and the method is an instance method.
1569
1570If a method with a related result type is overridden by a subclass method, the
1571subclass method must also return a type that is compatible with the subclass
1572type.  For example:
1573
1574.. code-block:: objc
1575
1576  @interface NSString : NSObject
1577  - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1578  @end
1579
1580Related result types only affect the type of a message send or property access
1581via the given method.  In all other respects, a method with a related result
1582type is treated the same way as method that returns ``id``.
1583
1584Use ``__has_feature(objc_instancetype)`` to determine whether the
1585``instancetype`` contextual keyword is available.
1586
1587Automatic reference counting
1588----------------------------
1589
1590Clang provides support for :doc:`automated reference counting
1591<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
1592for manual ``retain``/``release``/``autorelease`` message sends.  There are three
1593feature macros associated with automatic reference counting:
1594``__has_feature(objc_arc)`` indicates the availability of automated reference
1595counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1596automated reference counting also includes support for ``__weak`` pointers to
1597Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
1598are allowed to have fields that are pointers to Objective-C objects managed by
1599automatic reference counting.
1600
1601.. _objc-weak:
1602
1603Weak references
1604---------------
1605
1606Clang supports ARC-style weak and unsafe references in Objective-C even
1607outside of ARC mode.  Weak references must be explicitly enabled with
1608the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
1609to test whether they are enabled.  Unsafe references are enabled
1610unconditionally.  ARC-style weak and unsafe references cannot be used
1611when Objective-C garbage collection is enabled.
1612
1613Except as noted below, the language rules for the ``__weak`` and
1614``__unsafe_unretained`` qualifiers (and the ``weak`` and
1615``unsafe_unretained`` property attributes) are just as laid out
1616in the :doc:`ARC specification <AutomaticReferenceCounting>`.
1617In particular, note that some classes do not support forming weak
1618references to their instances, and note that special care must be
1619taken when storing weak references in memory where initialization
1620and deinitialization are outside the responsibility of the compiler
1621(such as in ``malloc``-ed memory).
1622
1623Loading from a ``__weak`` variable always implicitly retains the
1624loaded value.  In non-ARC modes, this retain is normally balanced
1625by an implicit autorelease.  This autorelease can be suppressed
1626by performing the load in the receiver position of a ``-retain``
1627message send (e.g. ``[weakReference retain]``); note that this performs
1628only a single retain (the retain done when primitively loading from
1629the weak reference).
1630
1631For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
1632default behavior of variables and therefore is not needed.  However,
1633it does have an effect on the semantics of block captures: normally,
1634copying a block which captures an Objective-C object or block pointer
1635causes the captured pointer to be retained or copied, respectively,
1636but that behavior is suppressed when the captured variable is qualified
1637with ``__unsafe_unretained``.
1638
1639Note that the ``__weak`` qualifier formerly meant the GC qualifier in
1640all non-ARC modes and was silently ignored outside of GC modes.  It now
1641means the ARC-style qualifier in all non-GC modes and is no longer
1642allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
1643It is expected that ``-fobjc-weak`` will eventually be enabled by default
1644in all non-GC Objective-C modes.
1645
1646.. _objc-fixed-enum:
1647
1648Enumerations with a fixed underlying type
1649-----------------------------------------
1650
1651Clang provides support for C++11 enumerations with a fixed underlying type
1652within Objective-C.  For example, one can write an enumeration type as:
1653
1654.. code-block:: c++
1655
1656  typedef enum : unsigned char { Red, Green, Blue } Color;
1657
1658This specifies that the underlying type, which is used to store the enumeration
1659value, is ``unsigned char``.
1660
1661Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1662underlying types is available in Objective-C.
1663
1664Interoperability with C++11 lambdas
1665-----------------------------------
1666
1667Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1668permitting a lambda to be implicitly converted to a block pointer with the
1669corresponding signature.  For example, consider an API such as ``NSArray``'s
1670array-sorting method:
1671
1672.. code-block:: objc
1673
1674  - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1675
1676``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1677(^)(id, id)``, and parameters of this type are generally provided with block
1678literals as arguments.  However, one can also use a C++11 lambda so long as it
1679provides the same signature (in this case, accepting two parameters of type
1680``id`` and returning an ``NSComparisonResult``):
1681
1682.. code-block:: objc
1683
1684  NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1685                     @"String 02"];
1686  const NSStringCompareOptions comparisonOptions
1687    = NSCaseInsensitiveSearch | NSNumericSearch |
1688      NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1689  NSLocale *currentLocale = [NSLocale currentLocale];
1690  NSArray *sorted
1691    = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1692               NSRange string1Range = NSMakeRange(0, [s1 length]);
1693               return [s1 compare:s2 options:comparisonOptions
1694               range:string1Range locale:currentLocale];
1695       }];
1696  NSLog(@"sorted: %@", sorted);
1697
1698This code relies on an implicit conversion from the type of the lambda
1699expression (an unnamed, local class type called the *closure type*) to the
1700corresponding block pointer type.  The conversion itself is expressed by a
1701conversion operator in that closure type that produces a block pointer with the
1702same signature as the lambda itself, e.g.,
1703
1704.. code-block:: objc
1705
1706  operator NSComparisonResult (^)(id, id)() const;
1707
1708This conversion function returns a new block that simply forwards the two
1709parameters to the lambda object (which it captures by copy), then returns the
1710result.  The returned block is first copied (with ``Block_copy``) and then
1711autoreleased.  As an optimization, if a lambda expression is immediately
1712converted to a block pointer (as in the first example, above), then the block
1713is not copied and autoreleased: rather, it is given the same lifetime as a
1714block literal written at that point in the program, which avoids the overhead
1715of copying a block to the heap in the common case.
1716
1717The conversion from a lambda to a block pointer is only available in
1718Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1719management (autorelease).
1720
1721Object Literals and Subscripting
1722--------------------------------
1723
1724Clang provides support for :doc:`Object Literals and Subscripting
1725<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
1726programming patterns, makes programs more concise, and improves the safety of
1727container creation.  There are several feature macros associated with object
1728literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1729availability of array literals; ``__has_feature(objc_dictionary_literals)``
1730tests the availability of dictionary literals;
1731``__has_feature(objc_subscripting)`` tests the availability of object
1732subscripting.
1733
1734Objective-C Autosynthesis of Properties
1735---------------------------------------
1736
1737Clang provides support for autosynthesis of declared properties.  Using this
1738feature, clang provides default synthesis of those properties not declared
1739@dynamic and not having user provided backing getter and setter methods.
1740``__has_feature(objc_default_synthesize_properties)`` checks for availability
1741of this feature in version of clang being used.
1742
1743.. _langext-objc-retain-release:
1744
1745Objective-C retaining behavior attributes
1746-----------------------------------------
1747
1748In Objective-C, functions and methods are generally assumed to follow the
1749`Cocoa Memory Management
1750<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1751conventions for ownership of object arguments and
1752return values. However, there are exceptions, and so Clang provides attributes
1753to allow these exceptions to be documented. This are used by ARC and the
1754`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
1755better described using the ``objc_method_family`` attribute instead.
1756
1757**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1758``ns_returns_autoreleased``, ``cf_returns_retained``, and
1759``cf_returns_not_retained`` attributes can be placed on methods and functions
1760that return Objective-C or CoreFoundation objects. They are commonly placed at
1761the end of a function prototype or method declaration:
1762
1763.. code-block:: objc
1764
1765  id foo() __attribute__((ns_returns_retained));
1766
1767  - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1768
1769The ``*_returns_retained`` attributes specify that the returned object has a +1
1770retain count.  The ``*_returns_not_retained`` attributes specify that the return
1771object has a +0 retain count, even if the normal convention for its selector
1772would be +1.  ``ns_returns_autoreleased`` specifies that the returned object is
1773+0, but is guaranteed to live at least as long as the next flush of an
1774autorelease pool.
1775
1776**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1777an parameter declaration; they specify that the argument is expected to have a
1778+1 retain count, which will be balanced in some way by the function or method.
1779The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1780method; it specifies that the method expects its ``self`` parameter to have a
1781+1 retain count, which it will balance in some way.
1782
1783.. code-block:: objc
1784
1785  void foo(__attribute__((ns_consumed)) NSString *string);
1786
1787  - (void) bar __attribute__((ns_consumes_self));
1788  - (void) baz:(id) __attribute__((ns_consumed)) x;
1789
1790Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1791<https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1792
1793Query for these features with ``__has_attribute(ns_consumed)``,
1794``__has_attribute(ns_returns_retained)``, etc.
1795
1796Objective-C @available
1797----------------------
1798
1799It is possible to use the newest SDK but still build a program that can run on
1800older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
1801``-miphoneos-version-min=``.
1802
1803Before LLVM 5.0, when calling a function that exists only in the OS that's
1804newer than the target OS (as determined by the minimum deployment version),
1805programmers had to carefully check if the function exists at runtime, using
1806null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
1807and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
1808Objective-C methods.  If such a check was missed, the program would compile
1809fine, run fine on newer systems, but crash on older systems.
1810
1811As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
1812<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
1813with the new ``@available()`` keyword to assist with this issue.
1814When a method that's introduced in the OS newer than the target OS is called, a
1815-Wunguarded-availability warning is emitted if that call is not guarded:
1816
1817.. code-block:: objc
1818
1819  void my_fun(NSSomeClass* var) {
1820    // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
1821    // built with -mmacosx-version-min=10.11, then this unconditional call
1822    // will emit a -Wunguarded-availability warning:
1823    [var fancyNewMethod];
1824  }
1825
1826To fix the warning and to avoid the crash on macOS 10.11, wrap it in
1827``if(@available())``:
1828
1829.. code-block:: objc
1830
1831  void my_fun(NSSomeClass* var) {
1832    if (@available(macOS 10.12, *)) {
1833      [var fancyNewMethod];
1834    } else {
1835      // Put fallback behavior for old macOS versions (and for non-mac
1836      // platforms) here.
1837    }
1838  }
1839
1840The ``*`` is required and means that platforms not explicitly listed will take
1841the true branch, and the compiler will emit ``-Wunguarded-availability``
1842warnings for unlisted platforms based on those platform's deployment target.
1843More than one platform can be listed in ``@available()``:
1844
1845.. code-block:: objc
1846
1847  void my_fun(NSSomeClass* var) {
1848    if (@available(macOS 10.12, iOS 10, *)) {
1849      [var fancyNewMethod];
1850    }
1851  }
1852
1853If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
1854on 10.12, then add an `availability attribute
1855<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
1856which will also suppress the warning and require that calls to my_fun() are
1857checked:
1858
1859.. code-block:: objc
1860
1861  API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
1862    [var fancyNewMethod];  // Now ok.
1863  }
1864
1865``@available()`` is only available in Objective-C code.  To use the feature
1866in C and C++ code, use the ``__builtin_available()`` spelling instead.
1867
1868If existing code uses null checks or ``-respondsToSelector:``, it should
1869be changed to use ``@available()`` (or ``__builtin_available``) instead.
1870
1871``-Wunguarded-availability`` is disabled by default, but
1872``-Wunguarded-availability-new``, which only emits this warning for APIs
1873that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
1874tvOS >= 11, is enabled by default.
1875
1876.. _langext-overloading:
1877
1878Objective-C++ ABI: protocol-qualifier mangling of parameters
1879------------------------------------------------------------
1880
1881Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
1882type is a qualified-``id`` (e.g., ``id<Foo>``).  This mangling allows such
1883parameters to be differentiated from those with the regular unqualified ``id``
1884type.
1885
1886This was a non-backward compatible mangling change to the ABI.  This change
1887allows proper overloading, and also prevents mangling conflicts with template
1888parameters of protocol-qualified type.
1889
1890Query the presence of this new mangling with
1891``__has_feature(objc_protocol_qualifier_mangling)``.
1892
1893Initializer lists for complex numbers in C
1894==========================================
1895
1896clang supports an extension which allows the following in C:
1897
1898.. code-block:: c++
1899
1900  #include <math.h>
1901  #include <complex.h>
1902  complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1903
1904This construct is useful because there is no way to separately initialize the
1905real and imaginary parts of a complex variable in standard C, given that clang
1906does not support ``_Imaginary``.  (Clang also supports the ``__real__`` and
1907``__imag__`` extensions from gcc, which help in some cases, but are not usable
1908in static initializers.)
1909
1910Note that this extension does not allow eliding the braces; the meaning of the
1911following two lines is different:
1912
1913.. code-block:: c++
1914
1915  complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1916  complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1917
1918This extension also works in C++ mode, as far as that goes, but does not apply
1919to the C++ ``std::complex``.  (In C++11, list initialization allows the same
1920syntax to be used with ``std::complex`` with the same meaning.)
1921
1922For GCC compatibility, ``__builtin_complex(re, im)`` can also be used to
1923construct a complex number from the given real and imaginary components.
1924
1925OpenCL Features
1926===============
1927
1928Clang supports internal OpenCL extensions documented below.
1929
1930``__cl_clang_bitfields``
1931--------------------------------
1932
1933With this extension it is possible to enable bitfields in structs
1934or unions using the OpenCL extension pragma mechanism detailed in
1935`the OpenCL Extension Specification, section 1.2
1936<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
1937
1938Use of bitfields in OpenCL kernels can result in reduced portability as struct
1939layout is not guaranteed to be consistent when compiled by different compilers.
1940If structs with bitfields are used as kernel function parameters, it can result
1941in incorrect functionality when the layout is different between the host and
1942device code.
1943
1944**Example of Use**:
1945
1946.. code-block:: c++
1947
1948  #pragma OPENCL EXTENSION __cl_clang_bitfields : enable
1949  struct with_bitfield {
1950    unsigned int i : 5; // compiled - no diagnostic generated
1951  };
1952
1953  #pragma OPENCL EXTENSION __cl_clang_bitfields : disable
1954  struct without_bitfield {
1955    unsigned int i : 5; // error - bitfields are not supported
1956  };
1957
1958``__cl_clang_function_pointers``
1959--------------------------------
1960
1961With this extension it is possible to enable various language features that
1962are relying on function pointers using regular OpenCL extension pragma
1963mechanism detailed in `the OpenCL Extension Specification,
1964section 1.2
1965<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
1966
1967In C++ for OpenCL this also enables:
1968
1969- Use of member function pointers;
1970
1971- Unrestricted use of references to functions;
1972
1973- Virtual member functions.
1974
1975Such functionality is not conformant and does not guarantee to compile
1976correctly in any circumstances. It can be used if:
1977
1978- the kernel source does not contain call expressions to (member-) function
1979  pointers, or virtual functions. For example this extension can be used in
1980  metaprogramming algorithms to be able to specify/detect types generically.
1981
1982- the generated kernel binary does not contain indirect calls because they
1983  are eliminated using compiler optimizations e.g. devirtualization.
1984
1985- the selected target supports the function pointer like functionality e.g.
1986  most CPU targets.
1987
1988**Example of Use**:
1989
1990.. code-block:: c++
1991
1992  #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable
1993  void foo()
1994  {
1995    void (*fp)(); // compiled - no diagnostic generated
1996  }
1997
1998  #pragma OPENCL EXTENSION __cl_clang_function_pointers : disable
1999  void bar()
2000  {
2001    void (*fp)(); // error - pointers to function are not allowed
2002  }
2003
2004``__cl_clang_variadic_functions``
2005---------------------------------
2006
2007With this extension it is possible to enable variadic arguments in functions
2008using regular OpenCL extension pragma mechanism detailed in `the OpenCL
2009Extension Specification, section 1.2
2010<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2011
2012This is not conformant behavior and it can only be used portably when the
2013functions with variadic prototypes do not get generated in binary e.g. the
2014variadic prototype is used to specify a function type with any number of
2015arguments in metaprogramming algorithms in C++ for OpenCL.
2016
2017This extensions can also be used when the kernel code is intended for targets
2018supporting the variadic arguments e.g. majority of CPU targets.
2019
2020**Example of Use**:
2021
2022.. code-block:: c++
2023
2024  #pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable
2025  void foo(int a, ...); // compiled - no diagnostic generated
2026
2027  #pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable
2028  void bar(int a, ...); // error - variadic prototype is not allowed
2029
2030``__cl_clang_non_portable_kernel_param_types``
2031----------------------------------------------
2032
2033With this extension it is possible to enable the use of some restricted types
2034in kernel parameters specified in `C++ for OpenCL v1.0 s2.4
2035<https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_.
2036The restrictions can be relaxed using regular OpenCL extension pragma mechanism
2037detailed in `the OpenCL Extension Specification, section 1.2
2038<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2039
2040This is not a conformant behavior and it can only be used when the
2041kernel arguments are not accessed on the host side or the data layout/size
2042between the host and device is known to be compatible.
2043
2044**Example of Use**:
2045
2046.. code-block:: c++
2047
2048  // Plain Old Data type.
2049  struct Pod {
2050    int a;
2051    int b;
2052  };
2053
2054  // Not POD type because of the constructor.
2055  // Standard layout type because there is only one access control.
2056  struct OnlySL {
2057    int a;
2058    int b;
2059    NotPod() : a(0), b(0) {}
2060  };
2061
2062  // Not standard layout type because of two different access controls.
2063  struct NotSL {
2064    int a;
2065  private:
2066    int b;
2067  }
2068
2069  kernel void kernel_main(
2070    Pod a,
2071  #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable
2072    OnlySL b,
2073    global NotSL *c,
2074  #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable
2075    global OnlySL *d,
2076  );
2077
2078Remove address space builtin function
2079-------------------------------------
2080
2081``__remove_address_space`` allows to derive types in C++ for OpenCL
2082that have address space qualifiers removed. This utility only affects
2083address space qualifiers, therefore, other type qualifiers such as
2084``const`` or ``volatile`` remain unchanged.
2085
2086**Example of Use**:
2087
2088.. code-block:: c++
2089
2090  template<typename T>
2091  void foo(T *par){
2092    T var1; // error - local function variable with global address space
2093    __private T var2; // error - conflicting address space qualifiers
2094    __private __remove_address_space<T>::type var3; // var3 is __private int
2095  }
2096
2097  void bar(){
2098    __global int* ptr;
2099    foo(ptr);
2100  }
2101
2102Legacy 1.x atomics with generic address space
2103---------------------------------------------
2104
2105Clang allows use of atomic functions from the OpenCL 1.x standards
2106with the generic address space pointer in C++ for OpenCL mode.
2107
2108This is a non-portable feature and might not be supported by all
2109targets.
2110
2111**Example of Use**:
2112
2113.. code-block:: c++
2114
2115  void foo(__generic volatile unsigned int* a) {
2116    atomic_add(a, 1);
2117  }
2118
2119Builtin Functions
2120=================
2121
2122Clang supports a number of builtin library functions with the same syntax as
2123GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
2124``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
2125``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc.  In addition to
2126the GCC builtins, Clang supports a number of builtins that GCC does not, which
2127are listed here.
2128
2129Please note that Clang does not and will not support all of the GCC builtins
2130for vector operations.  Instead of using builtins, you should use the functions
2131defined in target-specific header files like ``<xmmintrin.h>``, which define
2132portable wrappers for these.  Many of the Clang versions of these functions are
2133implemented directly in terms of :ref:`extended vector support
2134<langext-vectors>` instead of builtins, in order to reduce the number of
2135builtins that we need to implement.
2136
2137``__builtin_alloca``
2138--------------------
2139
2140``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory
2141is automatically freed upon function termination.
2142
2143**Syntax**:
2144
2145.. code-block:: c++
2146
2147  __builtin_alloca(size_t n)
2148
2149**Example of Use**:
2150
2151.. code-block:: c++
2152
2153  void init(float* data, size_t nbelems);
2154  void process(float* data, size_t nbelems);
2155  int foo(size_t n) {
2156    auto mem = (float*)__builtin_alloca(n * sizeof(float));
2157    init(mem, n);
2158    process(mem, n);
2159    /* mem is automatically freed at this point */
2160  }
2161
2162**Description**:
2163
2164``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory
2165on the stack. This amount is subject to stack allocation limits.
2166
2167Query for this feature with ``__has_builtin(__builtin_alloca)``.
2168
2169``__builtin_alloca_with_align``
2170-------------------------------
2171
2172``__builtin_alloca_with_align`` is used to dynamically allocate memory on the
2173stack while controlling its alignment. Memory is automatically freed upon
2174function termination.
2175
2176
2177**Syntax**:
2178
2179.. code-block:: c++
2180
2181  __builtin_alloca_with_align(size_t n, size_t align)
2182
2183**Example of Use**:
2184
2185.. code-block:: c++
2186
2187  void init(float* data, size_t nbelems);
2188  void process(float* data, size_t nbelems);
2189  int foo(size_t n) {
2190    auto mem = (float*)__builtin_alloca_with_align(
2191                        n * sizeof(float),
2192                        CHAR_BIT * alignof(float));
2193    init(mem, n);
2194    process(mem, n);
2195    /* mem is automatically freed at this point */
2196  }
2197
2198**Description**:
2199
2200``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory
2201on the stack. It is similar to ``__builtin_alloca`` but accepts a second
2202argument whose value is the alignment constraint, as a power of 2 in *bits*.
2203
2204Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``.
2205
2206.. _langext-__builtin_assume:
2207
2208``__builtin_assume``
2209--------------------
2210
2211``__builtin_assume`` is used to provide the optimizer with a boolean
2212invariant that is defined to be true.
2213
2214**Syntax**:
2215
2216.. code-block:: c++
2217
2218    __builtin_assume(bool)
2219
2220**Example of Use**:
2221
2222.. code-block:: c++
2223
2224  int foo(int x) {
2225      __builtin_assume(x != 0);
2226      // The optimizer may short-circuit this check using the invariant.
2227      if (x == 0)
2228            return do_something();
2229      return do_something_else();
2230  }
2231
2232**Description**:
2233
2234The boolean argument to this function is defined to be true. The optimizer may
2235analyze the form of the expression provided as the argument and deduce from
2236that information used to optimize the program. If the condition is violated
2237during execution, the behavior is undefined. The argument itself is
2238
2239Query for this feature with ``__has_builtin(__builtin_assume)``.
2240
2241``__builtin_call_with_static_chain``
2242------------------------------------
2243
2244``__builtin_call_with_static_chain`` is used to perform a static call while
2245setting updating the static chain register.
2246
2247**Syntax**:
2248
2249.. code-block:: c++
2250
2251  T __builtin_call_with_static_chain(T expr, void* ptr)
2252
2253**Example of Use**:
2254
2255.. code-block:: c++
2256
2257  auto v = __builtin_call_with_static_chain(foo(3), foo);
2258
2259**Description**:
2260
2261This builtin returns ``expr`` after checking that ``expr`` is a non-member
2262static call expression. The call to that expression is made while using ``ptr``
2263as a function pointer stored in a dedicated register to implement *static chain*
2264calling convention, as used by some language to implement closures or nested
2265functions.
2266
2267Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``.
2268
2269``__builtin_readcyclecounter``
2270------------------------------
2271
2272``__builtin_readcyclecounter`` is used to access the cycle counter register (or
2273a similar low-latency, high-accuracy clock) on those targets that support it.
2274
2275**Syntax**:
2276
2277.. code-block:: c++
2278
2279  __builtin_readcyclecounter()
2280
2281**Example of Use**:
2282
2283.. code-block:: c++
2284
2285  unsigned long long t0 = __builtin_readcyclecounter();
2286  do_something();
2287  unsigned long long t1 = __builtin_readcyclecounter();
2288  unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
2289
2290**Description**:
2291
2292The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
2293which may be either global or process/thread-specific depending on the target.
2294As the backing counters often overflow quickly (on the order of seconds) this
2295should only be used for timing small intervals.  When not supported by the
2296target, the return value is always zero.  This builtin takes no arguments and
2297produces an unsigned long long result.
2298
2299Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
2300that even if present, its use may depend on run-time privilege or other OS
2301controlled state.
2302
2303``__builtin_dump_struct``
2304-------------------------
2305
2306**Syntax**:
2307
2308.. code-block:: c++
2309
2310     __builtin_dump_struct(&some_struct, &some_printf_func);
2311
2312**Examples**:
2313
2314.. code-block:: c++
2315
2316     struct S {
2317       int x, y;
2318       float f;
2319       struct T {
2320         int i;
2321       } t;
2322     };
2323
2324     void func(struct S *s) {
2325       __builtin_dump_struct(s, &printf);
2326     }
2327
2328Example output:
2329
2330.. code-block:: none
2331
2332     struct S {
2333     int i : 100
2334     int j : 42
2335     float f : 3.14159
2336     struct T t : struct T {
2337         int i : 1997
2338         }
2339     }
2340
2341**Description**:
2342
2343The '``__builtin_dump_struct``' function is used to print the fields of a simple
2344structure and their values for debugging purposes. The builtin accepts a pointer
2345to a structure to dump the fields of, and a pointer to a formatted output
2346function whose signature must be: ``int (*)(const char *, ...)`` and must
2347support the format specifiers used by ``printf()``.
2348
2349.. _langext-__builtin_shufflevector:
2350
2351``__builtin_shufflevector``
2352---------------------------
2353
2354``__builtin_shufflevector`` is used to express generic vector
2355permutation/shuffle/swizzle operations.  This builtin is also very important
2356for the implementation of various target-specific header files like
2357``<xmmintrin.h>``.
2358
2359**Syntax**:
2360
2361.. code-block:: c++
2362
2363  __builtin_shufflevector(vec1, vec2, index1, index2, ...)
2364
2365**Examples**:
2366
2367.. code-block:: c++
2368
2369  // identity operation - return 4-element vector v1.
2370  __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
2371
2372  // "Splat" element 0 of V1 into a 4-element result.
2373  __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
2374
2375  // Reverse 4-element vector V1.
2376  __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
2377
2378  // Concatenate every other element of 4-element vectors V1 and V2.
2379  __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
2380
2381  // Concatenate every other element of 8-element vectors V1 and V2.
2382  __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
2383
2384  // Shuffle v1 with some elements being undefined
2385  __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
2386
2387**Description**:
2388
2389The first two arguments to ``__builtin_shufflevector`` are vectors that have
2390the same element type.  The remaining arguments are a list of integers that
2391specify the elements indices of the first two vectors that should be extracted
2392and returned in a new vector.  These element indices are numbered sequentially
2393starting with the first vector, continuing into the second vector.  Thus, if
2394``vec1`` is a 4-element vector, index 5 would refer to the second element of
2395``vec2``. An index of -1 can be used to indicate that the corresponding element
2396in the returned vector is a don't care and can be optimized by the backend.
2397
2398The result of ``__builtin_shufflevector`` is a vector with the same element
2399type as ``vec1``/``vec2`` but that has an element count equal to the number of
2400indices specified.
2401
2402Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
2403
2404.. _langext-__builtin_convertvector:
2405
2406``__builtin_convertvector``
2407---------------------------
2408
2409``__builtin_convertvector`` is used to express generic vector
2410type-conversion operations. The input vector and the output vector
2411type must have the same number of elements.
2412
2413**Syntax**:
2414
2415.. code-block:: c++
2416
2417  __builtin_convertvector(src_vec, dst_vec_type)
2418
2419**Examples**:
2420
2421.. code-block:: c++
2422
2423  typedef double vector4double __attribute__((__vector_size__(32)));
2424  typedef float  vector4float  __attribute__((__vector_size__(16)));
2425  typedef short  vector4short  __attribute__((__vector_size__(8)));
2426  vector4float vf; vector4short vs;
2427
2428  // convert from a vector of 4 floats to a vector of 4 doubles.
2429  __builtin_convertvector(vf, vector4double)
2430  // equivalent to:
2431  (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
2432
2433  // convert from a vector of 4 shorts to a vector of 4 floats.
2434  __builtin_convertvector(vs, vector4float)
2435  // equivalent to:
2436  (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
2437
2438**Description**:
2439
2440The first argument to ``__builtin_convertvector`` is a vector, and the second
2441argument is a vector type with the same number of elements as the first
2442argument.
2443
2444The result of ``__builtin_convertvector`` is a vector with the same element
2445type as the second argument, with a value defined in terms of the action of a
2446C-style cast applied to each element of the first argument.
2447
2448Query for this feature with ``__has_builtin(__builtin_convertvector)``.
2449
2450``__builtin_bitreverse``
2451------------------------
2452
2453* ``__builtin_bitreverse8``
2454* ``__builtin_bitreverse16``
2455* ``__builtin_bitreverse32``
2456* ``__builtin_bitreverse64``
2457
2458**Syntax**:
2459
2460.. code-block:: c++
2461
2462     __builtin_bitreverse32(x)
2463
2464**Examples**:
2465
2466.. code-block:: c++
2467
2468      uint8_t rev_x = __builtin_bitreverse8(x);
2469      uint16_t rev_x = __builtin_bitreverse16(x);
2470      uint32_t rev_y = __builtin_bitreverse32(y);
2471      uint64_t rev_z = __builtin_bitreverse64(z);
2472
2473**Description**:
2474
2475The '``__builtin_bitreverse``' family of builtins is used to reverse
2476the bitpattern of an integer value; for example ``0b10110110`` becomes
2477``0b01101101``. These builtins can be used within constant expressions.
2478
2479``__builtin_rotateleft``
2480------------------------
2481
2482* ``__builtin_rotateleft8``
2483* ``__builtin_rotateleft16``
2484* ``__builtin_rotateleft32``
2485* ``__builtin_rotateleft64``
2486
2487**Syntax**:
2488
2489.. code-block:: c++
2490
2491     __builtin_rotateleft32(x, y)
2492
2493**Examples**:
2494
2495.. code-block:: c++
2496
2497      uint8_t rot_x = __builtin_rotateleft8(x, y);
2498      uint16_t rot_x = __builtin_rotateleft16(x, y);
2499      uint32_t rot_x = __builtin_rotateleft32(x, y);
2500      uint64_t rot_x = __builtin_rotateleft64(x, y);
2501
2502**Description**:
2503
2504The '``__builtin_rotateleft``' family of builtins is used to rotate
2505the bits in the first argument by the amount in the second argument.
2506For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
2507The shift value is treated as an unsigned amount modulo the size of
2508the arguments. Both arguments and the result have the bitwidth specified
2509by the name of the builtin. These builtins can be used within constant
2510expressions.
2511
2512``__builtin_rotateright``
2513-------------------------
2514
2515* ``__builtin_rotateright8``
2516* ``__builtin_rotateright16``
2517* ``__builtin_rotateright32``
2518* ``__builtin_rotateright64``
2519
2520**Syntax**:
2521
2522.. code-block:: c++
2523
2524     __builtin_rotateright32(x, y)
2525
2526**Examples**:
2527
2528.. code-block:: c++
2529
2530      uint8_t rot_x = __builtin_rotateright8(x, y);
2531      uint16_t rot_x = __builtin_rotateright16(x, y);
2532      uint32_t rot_x = __builtin_rotateright32(x, y);
2533      uint64_t rot_x = __builtin_rotateright64(x, y);
2534
2535**Description**:
2536
2537The '``__builtin_rotateright``' family of builtins is used to rotate
2538the bits in the first argument by the amount in the second argument.
2539For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
2540The shift value is treated as an unsigned amount modulo the size of
2541the arguments. Both arguments and the result have the bitwidth specified
2542by the name of the builtin. These builtins can be used within constant
2543expressions.
2544
2545``__builtin_unreachable``
2546-------------------------
2547
2548``__builtin_unreachable`` is used to indicate that a specific point in the
2549program cannot be reached, even if the compiler might otherwise think it can.
2550This is useful to improve optimization and eliminates certain warnings.  For
2551example, without the ``__builtin_unreachable`` in the example below, the
2552compiler assumes that the inline asm can fall through and prints a "function
2553declared '``noreturn``' should not return" warning.
2554
2555**Syntax**:
2556
2557.. code-block:: c++
2558
2559    __builtin_unreachable()
2560
2561**Example of use**:
2562
2563.. code-block:: c++
2564
2565  void myabort(void) __attribute__((noreturn));
2566  void myabort(void) {
2567    asm("int3");
2568    __builtin_unreachable();
2569  }
2570
2571**Description**:
2572
2573The ``__builtin_unreachable()`` builtin has completely undefined behavior.
2574Since it has undefined behavior, it is a statement that it is never reached and
2575the optimizer can take advantage of this to produce better code.  This builtin
2576takes no arguments and produces a void result.
2577
2578Query for this feature with ``__has_builtin(__builtin_unreachable)``.
2579
2580``__builtin_unpredictable``
2581---------------------------
2582
2583``__builtin_unpredictable`` is used to indicate that a branch condition is
2584unpredictable by hardware mechanisms such as branch prediction logic.
2585
2586**Syntax**:
2587
2588.. code-block:: c++
2589
2590    __builtin_unpredictable(long long)
2591
2592**Example of use**:
2593
2594.. code-block:: c++
2595
2596  if (__builtin_unpredictable(x > 0)) {
2597     foo();
2598  }
2599
2600**Description**:
2601
2602The ``__builtin_unpredictable()`` builtin is expected to be used with control
2603flow conditions such as in ``if`` and ``switch`` statements.
2604
2605Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
2606
2607
2608``__builtin_expect``
2609--------------------
2610
2611``__builtin_expect`` is used to indicate that the value of an expression is
2612anticipated to be the same as a statically known result.
2613
2614**Syntax**:
2615
2616.. code-block:: c++
2617
2618    long __builtin_expect(long expr, long val)
2619
2620**Example of use**:
2621
2622.. code-block:: c++
2623
2624  if (__builtin_expect(x, 0)) {
2625     bar();
2626  }
2627
2628**Description**:
2629
2630The ``__builtin_expect()`` builtin is typically used with control flow
2631conditions such as in ``if`` and ``switch`` statements to help branch
2632prediction. It means that its first argument ``expr`` is expected to take the
2633value of its second argument ``val``. It always returns ``expr``.
2634
2635Query for this feature with ``__has_builtin(__builtin_expect)``.
2636
2637``__builtin_expect_with_probability``
2638-------------------------------------
2639
2640``__builtin_expect_with_probability`` is similar to ``__builtin_expect`` but it
2641takes a probability as third argument.
2642
2643**Syntax**:
2644
2645.. code-block:: c++
2646
2647    long __builtin_expect_with_probability(long expr, long val, double p)
2648
2649**Example of use**:
2650
2651.. code-block:: c++
2652
2653  if (__builtin_expect_with_probability(x, 0, .3)) {
2654     bar();
2655  }
2656
2657**Description**:
2658
2659The ``__builtin_expect_with_probability()`` builtin is typically used with
2660control flow conditions such as in ``if`` and ``switch`` statements to help
2661branch prediction. It means that its first argument ``expr`` is expected to take
2662the value of its second argument ``val`` with probability ``p``. ``p`` must be
2663within ``[0.0 ; 1.0]`` bounds. This builtin always returns the value of ``expr``.
2664
2665Query for this feature with ``__has_builtin(__builtin_expect_with_probability)``.
2666
2667``__builtin_prefetch``
2668----------------------
2669
2670``__builtin_prefetch`` is used to communicate with the cache handler to bring
2671data into the cache before it gets used.
2672
2673**Syntax**:
2674
2675.. code-block:: c++
2676
2677    void __builtin_prefetch(const void *addr, int rw=0, int locality=3)
2678
2679**Example of use**:
2680
2681.. code-block:: c++
2682
2683    __builtin_prefetch(a + i);
2684
2685**Description**:
2686
2687The ``__builtin_prefetch(addr, rw, locality)`` builtin is expected to be used to
2688avoid cache misses when the developper has a good understanding of which data
2689are going to be used next. ``addr`` is the address that needs to be brought into
2690the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and ``1``
2691for *write*. In case of *read write* access, ``1`` is to be used. ``locality``
2692indicates the expected persistance of data in cache, from ``0`` which means that
2693data can be discarded from cache after its next use to ``3`` which means that
2694data is going to be reused a lot once in cache. ``1`` and ``2`` provide
2695intermediate behavior between these two extremes.
2696
2697Query for this feature with ``__has_builtin(__builtin_prefetch)``.
2698
2699``__sync_swap``
2700---------------
2701
2702``__sync_swap`` is used to atomically swap integers or pointers in memory.
2703
2704**Syntax**:
2705
2706.. code-block:: c++
2707
2708  type __sync_swap(type *ptr, type value, ...)
2709
2710**Example of Use**:
2711
2712.. code-block:: c++
2713
2714  int old_value = __sync_swap(&value, new_value);
2715
2716**Description**:
2717
2718The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
2719atomic intrinsics to allow code to atomically swap the current value with the
2720new value.  More importantly, it helps developers write more efficient and
2721correct code by avoiding expensive loops around
2722``__sync_bool_compare_and_swap()`` or relying on the platform specific
2723implementation details of ``__sync_lock_test_and_set()``.  The
2724``__sync_swap()`` builtin is a full barrier.
2725
2726``__builtin_addressof``
2727-----------------------
2728
2729``__builtin_addressof`` performs the functionality of the built-in ``&``
2730operator, ignoring any ``operator&`` overload.  This is useful in constant
2731expressions in C++11, where there is no other way to take the address of an
2732object that overloads ``operator&``.
2733
2734**Example of use**:
2735
2736.. code-block:: c++
2737
2738  template<typename T> constexpr T *addressof(T &value) {
2739    return __builtin_addressof(value);
2740  }
2741
2742``__builtin_function_start``
2743-----------------------------
2744
2745``__builtin_function_start`` returns the address of a function body.
2746
2747**Syntax**:
2748
2749.. code-block:: c++
2750
2751  void *__builtin_function_start(function)
2752
2753**Example of use**:
2754
2755.. code-block:: c++
2756
2757  void a() {}
2758  void *p = __builtin_function_start(a);
2759
2760  class A {
2761  public:
2762    void a(int n);
2763    void a();
2764  };
2765
2766  void A::a(int n) {}
2767  void A::a() {}
2768
2769  void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a);
2770  void *pa2 = __builtin_function_start((void(A::*)()) &A::a);
2771
2772**Description**:
2773
2774The ``__builtin_function_start`` builtin accepts an argument that can be
2775constant-evaluated to a function, and returns the address of the function
2776body.  This builtin is not supported on all targets.
2777
2778The returned pointer may differ from the normally taken function address
2779and is not safe to call.  For example, with ``-fsanitize=cfi``, taking a
2780function address produces a callable pointer to a CFI jump table, while
2781``__builtin_function_start`` returns an address that fails
2782:doc:`cfi-icall<ControlFlowIntegrity>` checks.
2783
2784``__builtin_operator_new`` and ``__builtin_operator_delete``
2785------------------------------------------------------------
2786
2787A call to ``__builtin_operator_new(args)`` is exactly the same as a call to
2788``::operator new(args)``, except that it allows certain optimizations
2789that the C++ standard does not permit for a direct function call to
2790``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
2791merging allocations), and that the call is required to resolve to a
2792`replaceable global allocation function
2793<https://en.cppreference.com/w/cpp/memory/new/operator_new>`_.
2794
2795Likewise, ``__builtin_operator_delete`` is exactly the same as a call to
2796``::operator delete(args)``, except that it permits optimizations
2797and that the call is required to resolve to a
2798`replaceable global deallocation function
2799<https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_.
2800
2801These builtins are intended for use in the implementation of ``std::allocator``
2802and other similar allocation libraries, and are only available in C++.
2803
2804Query for this feature with ``__has_builtin(__builtin_operator_new)`` or
2805``__has_builtin(__builtin_operator_delete)``:
2806
2807  * If the value is at least ``201802L``, the builtins behave as described above.
2808
2809  * If the value is non-zero, the builtins may not support calling arbitrary
2810    replaceable global (de)allocation functions, but do support calling at least
2811    ``::operator new(size_t)`` and ``::operator delete(void*)``.
2812
2813``__builtin_preserve_access_index``
2814-----------------------------------
2815
2816``__builtin_preserve_access_index`` specifies a code section where
2817array subscript access and structure/union member access are relocatable
2818under bpf compile-once run-everywhere framework. Debuginfo (typically
2819with ``-g``) is needed, otherwise, the compiler will exit with an error.
2820The return type for the intrinsic is the same as the type of the
2821argument.
2822
2823**Syntax**:
2824
2825.. code-block:: c
2826
2827  type __builtin_preserve_access_index(type arg)
2828
2829**Example of Use**:
2830
2831.. code-block:: c
2832
2833  struct t {
2834    int i;
2835    int j;
2836    union {
2837      int a;
2838      int b;
2839    } c[4];
2840  };
2841  struct t *v = ...;
2842  int *pb =__builtin_preserve_access_index(&v->c[3].b);
2843  __builtin_preserve_access_index(v->j);
2844
2845``__builtin_debugtrap``
2846-----------------------
2847
2848``__builtin_debugtrap`` causes the program to stop its execution in such a way that a debugger can catch it.
2849
2850**Syntax**:
2851
2852.. code-block:: c++
2853
2854    __builtin_debugtrap()
2855
2856**Description**
2857
2858``__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.
2859
2860Query for this feature with ``__has_builtin(__builtin_debugtrap)``.
2861
2862
2863``__builtin_trap``
2864------------------
2865
2866``__builtin_trap`` causes the program to stop its execution abnormally.
2867
2868**Syntax**:
2869
2870.. code-block:: c++
2871
2872    __builtin_trap()
2873
2874**Description**
2875
2876``__builtin_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.
2877
2878Query for this feature with ``__has_builtin(__builtin_trap)``.
2879
2880
2881``__builtin_sycl_unique_stable_name``
2882-------------------------------------
2883
2884``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and
2885produces a string literal containing a unique name for the type that is stable
2886across split compilations, mainly to support SYCL/Data Parallel C++ language.
2887
2888In cases where the split compilation needs to share a unique token for a type
2889across the boundary (such as in an offloading situation), this name can be used
2890for lookup purposes, such as in the SYCL Integration Header.
2891
2892The value of this builtin is computed entirely at compile time, so it can be
2893used in constant expressions. This value encodes lambda functions based on a
2894stable numbering order in which they appear in their local declaration contexts.
2895Once this builtin is evaluated in a constexpr context, it is erroneous to use
2896it in an instantiation which changes its value.
2897
2898In order to produce the unique name, the current implementation of the bultin
2899uses Itanium mangling even if the host compilation uses a different name
2900mangling scheme at runtime. The mangler marks all the lambdas required to name
2901the SYCL kernel and emits a stable local ordering of the respective lambdas.
2902The resulting pattern is demanglable.  When non-lambda types are passed to the
2903builtin, the mangler emits their usual pattern without any special treatment.
2904
2905**Syntax**:
2906
2907.. code-block:: c
2908
2909  // Computes a unique stable name for the given type.
2910  constexpr const char * __builtin_sycl_unique_stable_name( type-id );
2911
2912Multiprecision Arithmetic Builtins
2913----------------------------------
2914
2915Clang provides a set of builtins which expose multiprecision arithmetic in a
2916manner amenable to C. They all have the following form:
2917
2918.. code-block:: c
2919
2920  unsigned x = ..., y = ..., carryin = ..., carryout;
2921  unsigned sum = __builtin_addc(x, y, carryin, &carryout);
2922
2923Thus one can form a multiprecision addition chain in the following manner:
2924
2925.. code-block:: c
2926
2927  unsigned *x, *y, *z, carryin=0, carryout;
2928  z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
2929  carryin = carryout;
2930  z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
2931  carryin = carryout;
2932  z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
2933  carryin = carryout;
2934  z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
2935
2936The complete list of builtins are:
2937
2938.. code-block:: c
2939
2940  unsigned char      __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
2941  unsigned short     __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
2942  unsigned           __builtin_addc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
2943  unsigned long      __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
2944  unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
2945  unsigned char      __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
2946  unsigned short     __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
2947  unsigned           __builtin_subc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
2948  unsigned long      __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
2949  unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
2950
2951Checked Arithmetic Builtins
2952---------------------------
2953
2954Clang provides a set of builtins that implement checked arithmetic for security
2955critical applications in a manner that is fast and easily expressible in C. As
2956an example of their usage:
2957
2958.. code-block:: c
2959
2960  errorcode_t security_critical_application(...) {
2961    unsigned x, y, result;
2962    ...
2963    if (__builtin_mul_overflow(x, y, &result))
2964      return kErrorCodeHackers;
2965    ...
2966    use_multiply(result);
2967    ...
2968  }
2969
2970Clang provides the following checked arithmetic builtins:
2971
2972.. code-block:: c
2973
2974  bool __builtin_add_overflow   (type1 x, type2 y, type3 *sum);
2975  bool __builtin_sub_overflow   (type1 x, type2 y, type3 *diff);
2976  bool __builtin_mul_overflow   (type1 x, type2 y, type3 *prod);
2977  bool __builtin_uadd_overflow  (unsigned x, unsigned y, unsigned *sum);
2978  bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
2979  bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
2980  bool __builtin_usub_overflow  (unsigned x, unsigned y, unsigned *diff);
2981  bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
2982  bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
2983  bool __builtin_umul_overflow  (unsigned x, unsigned y, unsigned *prod);
2984  bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
2985  bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
2986  bool __builtin_sadd_overflow  (int x, int y, int *sum);
2987  bool __builtin_saddl_overflow (long x, long y, long *sum);
2988  bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
2989  bool __builtin_ssub_overflow  (int x, int y, int *diff);
2990  bool __builtin_ssubl_overflow (long x, long y, long *diff);
2991  bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
2992  bool __builtin_smul_overflow  (int x, int y, int *prod);
2993  bool __builtin_smull_overflow (long x, long y, long *prod);
2994  bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
2995
2996Each builtin performs the specified mathematical operation on the
2997first two arguments and stores the result in the third argument.  If
2998possible, the result will be equal to mathematically-correct result
2999and the builtin will return 0.  Otherwise, the builtin will return
30001 and the result will be equal to the unique value that is equivalent
3001to the mathematically-correct result modulo two raised to the *k*
3002power, where *k* is the number of bits in the result type.  The
3003behavior of these builtins is well-defined for all argument values.
3004
3005The first three builtins work generically for operands of any integer type,
3006including boolean types.  The operands need not have the same type as each
3007other, or as the result.  The other builtins may implicitly promote or
3008convert their operands before performing the operation.
3009
3010Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
3011
3012Floating point builtins
3013---------------------------------------
3014
3015``__builtin_canonicalize``
3016--------------------------
3017
3018.. code-block:: c
3019
3020   double __builtin_canonicalize(double);
3021   float __builtin_canonicalizef(float);
3022   long double__builtin_canonicalizel(long double);
3023
3024Returns the platform specific canonical encoding of a floating point
3025number. This canonicalization is useful for implementing certain
3026numeric primitives such as frexp. See `LLVM canonicalize intrinsic
3027<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
3028more information on the semantics.
3029
3030String builtins
3031---------------
3032
3033Clang provides constant expression evaluation support for builtins forms of
3034the following functions from the C standard library headers
3035``<string.h>`` and ``<wchar.h>``:
3036
3037* ``memchr``
3038* ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``)
3039* ``strchr``
3040* ``strcmp``
3041* ``strlen``
3042* ``strncmp``
3043* ``wcschr``
3044* ``wcscmp``
3045* ``wcslen``
3046* ``wcsncmp``
3047* ``wmemchr``
3048* ``wmemcmp``
3049
3050In each case, the builtin form has the name of the C library function prefixed
3051by ``__builtin_``. Example:
3052
3053.. code-block:: c
3054
3055  void *p = __builtin_memchr("foobar", 'b', 5);
3056
3057In addition to the above, one further builtin is provided:
3058
3059.. code-block:: c
3060
3061  char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
3062
3063``__builtin_char_memchr(a, b, c)`` is identical to
3064``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
3065constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
3066is disallowed in general).
3067
3068Constant evaluation support for the ``__builtin_mem*`` functions is provided
3069only for arrays of ``char``, ``signed char``, ``unsigned char``, or ``char8_t``,
3070despite these functions accepting an argument of type ``const void*``.
3071
3072Support for constant expression evaluation for the above builtins can be detected
3073with ``__has_feature(cxx_constexpr_string_builtins)``.
3074
3075Memory builtins
3076---------------
3077
3078Clang provides constant expression evaluation support for builtin forms of the
3079following functions from the C standard library headers
3080``<string.h>`` and ``<wchar.h>``:
3081
3082* ``memcpy``
3083* ``memmove``
3084* ``wmemcpy``
3085* ``wmemmove``
3086
3087In each case, the builtin form has the name of the C library function prefixed
3088by ``__builtin_``.
3089
3090Constant evaluation support is only provided when the source and destination
3091are pointers to arrays with the same trivially copyable element type, and the
3092given size is an exact multiple of the element size that is no greater than
3093the number of elements accessible through the source and destination operands.
3094
3095Guaranteed inlined copy
3096^^^^^^^^^^^^^^^^^^^^^^^
3097
3098.. code-block:: c
3099
3100  void __builtin_memcpy_inline(void *dst, const void *src, size_t size);
3101
3102
3103``__builtin_memcpy_inline`` has been designed as a building block for efficient
3104``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also
3105guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline
3106<https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic
3107for more information.
3108
3109This is useful to implement a custom version of ``memcpy``, implement a
3110``libc`` memcpy or work around the absence of a ``libc``.
3111
3112Note that the `size` argument must be a compile time constant.
3113
3114Note that this intrinsic cannot yet be called in a ``constexpr`` context.
3115
3116
3117Atomic Min/Max builtins with memory ordering
3118--------------------------------------------
3119
3120There are two atomic builtins with min/max in-memory comparison and swap.
3121The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
3122
3123* ``__atomic_fetch_min``
3124* ``__atomic_fetch_max``
3125
3126The builtins work with signed and unsigned integers and require to specify memory ordering.
3127The return value is the original value that was stored in memory before comparison.
3128
3129Example:
3130
3131.. code-block:: c
3132
3133  unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
3134
3135The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
3136``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
3137``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
3138
3139In terms or aquire-release ordering barriers these two operations are always
3140considered as operations with *load-store* semantics, even when the original value
3141is not actually modified after comparison.
3142
3143.. _langext-__c11_atomic:
3144
3145__c11_atomic builtins
3146---------------------
3147
3148Clang provides a set of builtins which are intended to be used to implement
3149C11's ``<stdatomic.h>`` header.  These builtins provide the semantics of the
3150``_explicit`` form of the corresponding C11 operation, and are named with a
3151``__c11_`` prefix.  The supported operations, and the differences from
3152the corresponding C11 operations, are:
3153
3154* ``__c11_atomic_init``
3155* ``__c11_atomic_thread_fence``
3156* ``__c11_atomic_signal_fence``
3157* ``__c11_atomic_is_lock_free`` (The argument is the size of the
3158  ``_Atomic(...)`` object, instead of its address)
3159* ``__c11_atomic_store``
3160* ``__c11_atomic_load``
3161* ``__c11_atomic_exchange``
3162* ``__c11_atomic_compare_exchange_strong``
3163* ``__c11_atomic_compare_exchange_weak``
3164* ``__c11_atomic_fetch_add``
3165* ``__c11_atomic_fetch_sub``
3166* ``__c11_atomic_fetch_and``
3167* ``__c11_atomic_fetch_or``
3168* ``__c11_atomic_fetch_xor``
3169* ``__c11_atomic_fetch_nand`` (Nand is not presented in ``<stdatomic.h>``)
3170* ``__c11_atomic_fetch_max``
3171* ``__c11_atomic_fetch_min``
3172
3173The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
3174``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
3175provided, with values corresponding to the enumerators of C11's
3176``memory_order`` enumeration.
3177
3178(Note that Clang additionally provides GCC-compatible ``__atomic_*``
3179builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
3180atomic builtins are an explicit form of the corresponding OpenCL 2.0
3181builtin function, and are named with a ``__opencl_`` prefix. The macros
3182``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
3183``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
3184and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
3185corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
3186
3187Low-level ARM exclusive memory builtins
3188---------------------------------------
3189
3190Clang provides overloaded builtins giving direct access to the three key ARM
3191instructions for implementing atomic operations.
3192
3193.. code-block:: c
3194
3195  T __builtin_arm_ldrex(const volatile T *addr);
3196  T __builtin_arm_ldaex(const volatile T *addr);
3197  int __builtin_arm_strex(T val, volatile T *addr);
3198  int __builtin_arm_stlex(T val, volatile T *addr);
3199  void __builtin_arm_clrex(void);
3200
3201The types ``T`` currently supported are:
3202
3203* Integer types with width at most 64 bits (or 128 bits on AArch64).
3204* Floating-point types
3205* Pointer types.
3206
3207Note that the compiler does not guarantee it will not insert stores which clear
3208the exclusive monitor in between an ``ldrex`` type operation and its paired
3209``strex``. In practice this is only usually a risk when the extra store is on
3210the same cache line as the variable being modified and Clang will only insert
3211stack stores on its own, so it is best not to use these operations on variables
3212with automatic storage duration.
3213
3214Also, loads and stores may be implicit in code written between the ``ldrex`` and
3215``strex``. Clang will not necessarily mitigate the effects of these either, so
3216care should be exercised.
3217
3218For these reasons the higher level atomic primitives should be preferred where
3219possible.
3220
3221Non-temporal load/store builtins
3222--------------------------------
3223
3224Clang provides overloaded builtins allowing generation of non-temporal memory
3225accesses.
3226
3227.. code-block:: c
3228
3229  T __builtin_nontemporal_load(T *addr);
3230  void __builtin_nontemporal_store(T value, T *addr);
3231
3232The types ``T`` currently supported are:
3233
3234* Integer types.
3235* Floating-point types.
3236* Vector types.
3237
3238Note that the compiler does not guarantee that non-temporal loads or stores
3239will be used.
3240
3241C++ Coroutines support builtins
3242--------------------------------
3243
3244.. warning::
3245  This is a work in progress. Compatibility across Clang/LLVM releases is not
3246  guaranteed.
3247
3248Clang provides experimental builtins to support C++ Coroutines as defined by
3249https://wg21.link/P0057. The following four are intended to be used by the
3250standard library to implement the ``std::coroutine_handle`` type.
3251
3252**Syntax**:
3253
3254.. code-block:: c
3255
3256  void  __builtin_coro_resume(void *addr);
3257  void  __builtin_coro_destroy(void *addr);
3258  bool  __builtin_coro_done(void *addr);
3259  void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
3260
3261**Example of use**:
3262
3263.. code-block:: c++
3264
3265  template <> struct coroutine_handle<void> {
3266    void resume() const { __builtin_coro_resume(ptr); }
3267    void destroy() const { __builtin_coro_destroy(ptr); }
3268    bool done() const { return __builtin_coro_done(ptr); }
3269    // ...
3270  protected:
3271    void *ptr;
3272  };
3273
3274  template <typename Promise> struct coroutine_handle : coroutine_handle<> {
3275    // ...
3276    Promise &promise() const {
3277      return *reinterpret_cast<Promise *>(
3278        __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
3279    }
3280    static coroutine_handle from_promise(Promise &promise) {
3281      coroutine_handle p;
3282      p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
3283                                                      /*from-promise=*/true);
3284      return p;
3285    }
3286  };
3287
3288
3289Other coroutine builtins are either for internal clang use or for use during
3290development of the coroutine feature. See `Coroutines in LLVM
3291<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
3292more information on their semantics. Note that builtins matching the intrinsics
3293that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
3294llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
3295an appropriate value during the emission.
3296
3297**Syntax**:
3298
3299.. code-block:: c
3300
3301  size_t __builtin_coro_size()
3302  void  *__builtin_coro_frame()
3303  void  *__builtin_coro_free(void *coro_frame)
3304
3305  void  *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
3306  bool   __builtin_coro_alloc()
3307  void  *__builtin_coro_begin(void *memory)
3308  void   __builtin_coro_end(void *coro_frame, bool unwind)
3309  char   __builtin_coro_suspend(bool final)
3310
3311Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
3312automatically will insert one if the first argument to `llvm.coro.suspend` is
3313token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
3314as the first argument to the intrinsic.
3315
3316Source location builtins
3317------------------------
3318
3319Clang provides experimental builtins to support C++ standard library implementation
3320of ``std::experimental::source_location`` as specified in  http://wg21.link/N4600.
3321With the exception of ``__builtin_COLUMN``, these builtins are also implemented by
3322GCC.
3323
3324**Syntax**:
3325
3326.. code-block:: c
3327
3328  const char *__builtin_FILE();
3329  const char *__builtin_FUNCTION();
3330  unsigned    __builtin_LINE();
3331  unsigned    __builtin_COLUMN(); // Clang only
3332
3333**Example of use**:
3334
3335.. code-block:: c++
3336
3337  void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
3338                 const char* file = __builtin_FILE(),
3339                 const char* function = __builtin_FUNCTION()) {
3340    if (pred) return;
3341    printf("%s:%d assertion failed in function %s\n", file, line, function);
3342    std::abort();
3343  }
3344
3345  struct MyAggregateType {
3346    int x;
3347    int line = __builtin_LINE(); // captures line where aggregate initialization occurs
3348  };
3349  static_assert(MyAggregateType{42}.line == __LINE__);
3350
3351  struct MyClassType {
3352    int line = __builtin_LINE(); // captures line of the constructor used during initialization
3353    constexpr MyClassType(int) { assert(line == __LINE__); }
3354  };
3355
3356**Description**:
3357
3358The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, and ``__builtin_FILE`` return
3359the values, at the "invocation point", for ``__LINE__``, ``__FUNCTION__``, and
3360``__FILE__`` respectively. These builtins are constant expressions.
3361
3362When the builtins appear as part of a default function argument the invocation
3363point is the location of the caller. When the builtins appear as part of a
3364default member initializer, the invocation point is the location of the
3365constructor or aggregate initialization used to create the object. Otherwise
3366the invocation point is the same as the location of the builtin.
3367
3368When the invocation point of ``__builtin_FUNCTION`` is not a function scope the
3369empty string is returned.
3370
3371Alignment builtins
3372------------------
3373Clang provides builtins to support checking and adjusting alignment of
3374pointers and integers.
3375These builtins can be used to avoid relying on implementation-defined behavior
3376of arithmetic on integers derived from pointers.
3377Additionally, these builtins retain type information and, unlike bitwise
3378arithmetic, they can perform semantic checking on the alignment value.
3379
3380**Syntax**:
3381
3382.. code-block:: c
3383
3384  Type __builtin_align_up(Type value, size_t alignment);
3385  Type __builtin_align_down(Type value, size_t alignment);
3386  bool __builtin_is_aligned(Type value, size_t alignment);
3387
3388
3389**Example of use**:
3390
3391.. code-block:: c++
3392
3393  char* global_alloc_buffer;
3394  void* my_aligned_allocator(size_t alloc_size, size_t alignment) {
3395    char* result = __builtin_align_up(global_alloc_buffer, alignment);
3396    // result now contains the value of global_alloc_buffer rounded up to the
3397    // next multiple of alignment.
3398    global_alloc_buffer = result + alloc_size;
3399    return result;
3400  }
3401
3402  void* get_start_of_page(void* ptr) {
3403    return __builtin_align_down(ptr, PAGE_SIZE);
3404  }
3405
3406  void example(char* buffer) {
3407     if (__builtin_is_aligned(buffer, 64)) {
3408       do_fast_aligned_copy(buffer);
3409     } else {
3410       do_unaligned_copy(buffer);
3411     }
3412  }
3413
3414  // In addition to pointers, the builtins can also be used on integer types
3415  // and are evaluatable inside constant expressions.
3416  static_assert(__builtin_align_up(123, 64) == 128, "");
3417  static_assert(__builtin_align_down(123u, 64) == 64u, "");
3418  static_assert(!__builtin_is_aligned(123, 64), "");
3419
3420
3421**Description**:
3422
3423The builtins ``__builtin_align_up``, ``__builtin_align_down``, return their
3424first argument aligned up/down to the next multiple of the second argument.
3425If the value is already sufficiently aligned, it is returned unchanged.
3426The builtin ``__builtin_is_aligned`` returns whether the first argument is
3427aligned to a multiple of the second argument.
3428All of these builtins expect the alignment to be expressed as a number of bytes.
3429
3430These builtins can be used for all integer types as well as (non-function)
3431pointer types. For pointer types, these builtins operate in terms of the integer
3432address of the pointer and return a new pointer of the same type (including
3433qualifiers such as ``const``) with an adjusted address.
3434When aligning pointers up or down, the resulting value must be within the same
3435underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]).
3436This means that arbitrary integer values stored in pointer-type variables must
3437not be passed to these builtins. For those use cases, the builtins can still be
3438used, but the operation must be performed on the pointer cast to ``uintptr_t``.
3439
3440If Clang can determine that the alignment is not a power of two at compile time,
3441it will result in a compilation failure. If the alignment argument is not a
3442power of two at run time, the behavior of these builtins is undefined.
3443
3444Non-standard C++11 Attributes
3445=============================
3446
3447Clang's non-standard C++11 attributes live in the ``clang`` attribute
3448namespace.
3449
3450Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
3451are accepted with the ``__attribute__((foo))`` syntax are also accepted as
3452``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
3453(see the list of `GCC function attributes
3454<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
3455attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
3456`GCC type attributes
3457<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
3458implementation, these attributes must appertain to the *declarator-id* in a
3459declaration, which means they must go either at the start of the declaration or
3460immediately after the name being declared.
3461
3462For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
3463also applies the GNU ``noreturn`` attribute to ``f``.
3464
3465.. code-block:: c++
3466
3467  [[gnu::unused]] int a, f [[gnu::noreturn]] ();
3468
3469Target-Specific Extensions
3470==========================
3471
3472Clang supports some language features conditionally on some targets.
3473
3474ARM/AArch64 Language Extensions
3475-------------------------------
3476
3477Memory Barrier Intrinsics
3478^^^^^^^^^^^^^^^^^^^^^^^^^
3479Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
3480in the `ARM C Language Extensions Release 2.0
3481<http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
3482Note that these intrinsics are implemented as motion barriers that block
3483reordering of memory accesses and side effect instructions. Other instructions
3484like simple arithmetic may be reordered around the intrinsic. If you expect to
3485have no reordering at all, use inline assembly instead.
3486
3487X86/X86-64 Language Extensions
3488------------------------------
3489
3490The X86 backend has these language extensions:
3491
3492Memory references to specified segments
3493^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3494
3495Annotating a pointer with address space #256 causes it to be code generated
3496relative to the X86 GS segment register, address space #257 causes it to be
3497relative to the X86 FS segment, and address space #258 causes it to be
3498relative to the X86 SS segment.  Note that this is a very very low-level
3499feature that should only be used if you know what you're doing (for example in
3500an OS kernel).
3501
3502Here is an example:
3503
3504.. code-block:: c++
3505
3506  #define GS_RELATIVE __attribute__((address_space(256)))
3507  int foo(int GS_RELATIVE *P) {
3508    return *P;
3509  }
3510
3511Which compiles to (on X86-32):
3512
3513.. code-block:: gas
3514
3515  _foo:
3516          movl    4(%esp), %eax
3517          movl    %gs:(%eax), %eax
3518          ret
3519
3520You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for
3521the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``
3522indicate their support.
3523
3524PowerPC Language Extensions
3525---------------------------
3526
3527Set the Floating Point Rounding Mode
3528^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3529PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
3530the floating point rounding mode. This function will use the least significant
3531two bits of integer argument to set the floating point rounding mode.
3532
3533.. code-block:: c++
3534
3535  double __builtin_setrnd(int mode);
3536
3537The effective values for mode are:
3538
3539    - 0 - round to nearest
3540    - 1 - round to zero
3541    - 2 - round to +infinity
3542    - 3 - round to -infinity
3543
3544Note that the mode argument will modulo 4, so if the integer argument is greater
3545than 3, it will only use the least significant two bits of the mode.
3546Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
3547
3548PowerPC cache builtins
3549^^^^^^^^^^^^^^^^^^^^^^
3550
3551The PowerPC architecture specifies instructions implementing cache operations.
3552Clang provides builtins that give direct programmer access to these cache
3553instructions.
3554
3555Currently the following builtins are implemented in clang:
3556
3557``__builtin_dcbf`` copies the contents of a modified block from the data cache
3558to main memory and flushes the copy from the data cache.
3559
3560**Syntax**:
3561
3562.. code-block:: c
3563
3564  void __dcbf(const void* addr); /* Data Cache Block Flush */
3565
3566**Example of Use**:
3567
3568.. code-block:: c
3569
3570  int a = 1;
3571  __builtin_dcbf (&a);
3572
3573Extensions for Static Analysis
3574==============================
3575
3576Clang supports additional attributes that are useful for documenting program
3577invariants and rules for static analysis tools, such as the `Clang Static
3578Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
3579in the analyzer's `list of source-level annotations
3580<https://clang-analyzer.llvm.org/annotations.html>`_.
3581
3582
3583Extensions for Dynamic Analysis
3584===============================
3585
3586Use ``__has_feature(address_sanitizer)`` to check if the code is being built
3587with :doc:`AddressSanitizer`.
3588
3589Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
3590with :doc:`ThreadSanitizer`.
3591
3592Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
3593with :doc:`MemorySanitizer`.
3594
3595Use ``__has_feature(dataflow_sanitizer)`` to check if the code is being built
3596with :doc:`DataFlowSanitizer`.
3597
3598Use ``__has_feature(safe_stack)`` to check if the code is being built
3599with :doc:`SafeStack`.
3600
3601
3602Extensions for selectively disabling optimization
3603=================================================
3604
3605Clang provides a mechanism for selectively disabling optimizations in functions
3606and methods.
3607
3608To disable optimizations in a single function definition, the GNU-style or C++11
3609non-standard attribute ``optnone`` can be used.
3610
3611.. code-block:: c++
3612
3613  // The following functions will not be optimized.
3614  // GNU-style attribute
3615  __attribute__((optnone)) int foo() {
3616    // ... code
3617  }
3618  // C++11 attribute
3619  [[clang::optnone]] int bar() {
3620    // ... code
3621  }
3622
3623To facilitate disabling optimization for a range of function definitions, a
3624range-based pragma is provided. Its syntax is ``#pragma clang optimize``
3625followed by ``off`` or ``on``.
3626
3627All function definitions in the region between an ``off`` and the following
3628``on`` will be decorated with the ``optnone`` attribute unless doing so would
3629conflict with explicit attributes already present on the function (e.g. the
3630ones that control inlining).
3631
3632.. code-block:: c++
3633
3634  #pragma clang optimize off
3635  // This function will be decorated with optnone.
3636  int foo() {
3637    // ... code
3638  }
3639
3640  // optnone conflicts with always_inline, so bar() will not be decorated.
3641  __attribute__((always_inline)) int bar() {
3642    // ... code
3643  }
3644  #pragma clang optimize on
3645
3646If no ``on`` is found to close an ``off`` region, the end of the region is the
3647end of the compilation unit.
3648
3649Note that a stray ``#pragma clang optimize on`` does not selectively enable
3650additional optimizations when compiling at low optimization levels. This feature
3651can only be used to selectively disable optimizations.
3652
3653The pragma has an effect on functions only at the point of their definition; for
3654function templates, this means that the state of the pragma at the point of an
3655instantiation is not necessarily relevant. Consider the following example:
3656
3657.. code-block:: c++
3658
3659  template<typename T> T twice(T t) {
3660    return 2 * t;
3661  }
3662
3663  #pragma clang optimize off
3664  template<typename T> T thrice(T t) {
3665    return 3 * t;
3666  }
3667
3668  int container(int a, int b) {
3669    return twice(a) + thrice(b);
3670  }
3671  #pragma clang optimize on
3672
3673In this example, the definition of the template function ``twice`` is outside
3674the pragma region, whereas the definition of ``thrice`` is inside the region.
3675The ``container`` function is also in the region and will not be optimized, but
3676it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
3677these two instantiations, ``twice`` will be optimized (because its definition
3678was outside the region) and ``thrice`` will not be optimized.
3679
3680Extensions for loop hint optimizations
3681======================================
3682
3683The ``#pragma clang loop`` directive is used to specify hints for optimizing the
3684subsequent for, while, do-while, or c++11 range-based for loop. The directive
3685provides options for vectorization, interleaving, predication, unrolling and
3686distribution. Loop hints can be specified before any loop and will be ignored if
3687the optimization is not safe to apply.
3688
3689There are loop hints that control transformations (e.g. vectorization, loop
3690unrolling) and there are loop hints that set transformation options (e.g.
3691``vectorize_width``, ``unroll_count``).  Pragmas setting transformation options
3692imply the transformation is enabled, as if it was enabled via the corresponding
3693transformation pragma (e.g. ``vectorize(enable)``). If the transformation is
3694disabled  (e.g. ``vectorize(disable)``), that takes precedence over
3695transformations option pragmas implying that transformation.
3696
3697Vectorization, Interleaving, and Predication
3698--------------------------------------------
3699
3700A vectorized loop performs multiple iterations of the original loop
3701in parallel using vector instructions. The instruction set of the target
3702processor determines which vector instructions are available and their vector
3703widths. This restricts the types of loops that can be vectorized. The vectorizer
3704automatically determines if the loop is safe and profitable to vectorize. A
3705vector instruction cost model is used to select the vector width.
3706
3707Interleaving multiple loop iterations allows modern processors to further
3708improve instruction-level parallelism (ILP) using advanced hardware features,
3709such as multiple execution units and out-of-order execution. The vectorizer uses
3710a cost model that depends on the register pressure and generated code size to
3711select the interleaving count.
3712
3713Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
3714by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
3715manually enable vectorization or interleaving.
3716
3717.. code-block:: c++
3718
3719  #pragma clang loop vectorize(enable)
3720  #pragma clang loop interleave(enable)
3721  for(...) {
3722    ...
3723  }
3724
3725The vector width is specified by
3726``vectorize_width(_value_[, fixed|scalable])``, where _value_ is a positive
3727integer and the type of vectorization can be specified with an optional
3728second parameter. The default for the second parameter is 'fixed' and
3729refers to fixed width vectorization, whereas 'scalable' indicates the
3730compiler should use scalable vectors instead. Another use of vectorize_width
3731is ``vectorize_width(fixed|scalable)`` where the user can hint at the type
3732of vectorization to use without specifying the exact width. In both variants
3733of the pragma the vectorizer may decide to fall back on fixed width
3734vectorization if the target does not support scalable vectors.
3735
3736The interleave count is specified by ``interleave_count(_value_)``, where
3737_value_ is a positive integer. This is useful for specifying the optimal
3738width/count of the set of target architectures supported by your application.
3739
3740.. code-block:: c++
3741
3742  #pragma clang loop vectorize_width(2)
3743  #pragma clang loop interleave_count(2)
3744  for(...) {
3745    ...
3746  }
3747
3748Specifying a width/count of 1 disables the optimization, and is equivalent to
3749``vectorize(disable)`` or ``interleave(disable)``.
3750
3751Vector predication is enabled by ``vectorize_predicate(enable)``, for example:
3752
3753.. code-block:: c++
3754
3755  #pragma clang loop vectorize(enable)
3756  #pragma clang loop vectorize_predicate(enable)
3757  for(...) {
3758    ...
3759  }
3760
3761This predicates (masks) all instructions in the loop, which allows the scalar
3762remainder loop (the tail) to be folded into the main vectorized loop. This
3763might be more efficient when vector predication is efficiently supported by the
3764target platform.
3765
3766Loop Unrolling
3767--------------
3768
3769Unrolling a loop reduces the loop control overhead and exposes more
3770opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
3771eliminates the loop and replaces it with an enumerated sequence of loop
3772iterations. Full unrolling is only possible if the loop trip count is known at
3773compile time. Partial unrolling replicates the loop body within the loop and
3774reduces the trip count.
3775
3776If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
3777loop if the trip count is known at compile time. If the fully unrolled code size
3778is greater than an internal limit the loop will be partially unrolled up to this
3779limit. If the trip count is not known at compile time the loop will be partially
3780unrolled with a heuristically chosen unroll factor.
3781
3782.. code-block:: c++
3783
3784  #pragma clang loop unroll(enable)
3785  for(...) {
3786    ...
3787  }
3788
3789If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
3790loop if the trip count is known at compile time identically to
3791``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
3792if the loop count is not known at compile time.
3793
3794.. code-block:: c++
3795
3796  #pragma clang loop unroll(full)
3797  for(...) {
3798    ...
3799  }
3800
3801The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
3802_value_ is a positive integer. If this value is greater than the trip count the
3803loop will be fully unrolled. Otherwise the loop is partially unrolled subject
3804to the same code size limit as with ``unroll(enable)``.
3805
3806.. code-block:: c++
3807
3808  #pragma clang loop unroll_count(8)
3809  for(...) {
3810    ...
3811  }
3812
3813Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
3814
3815Loop unroll parameters can be controlled by options
3816`-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`.
3817
3818Loop Distribution
3819-----------------
3820
3821Loop Distribution allows splitting a loop into multiple loops.  This is
3822beneficial for example when the entire loop cannot be vectorized but some of the
3823resulting loops can.
3824
3825If ``distribute(enable))`` is specified and the loop has memory dependencies
3826that inhibit vectorization, the compiler will attempt to isolate the offending
3827operations into a new loop.  This optimization is not enabled by default, only
3828loops marked with the pragma are considered.
3829
3830.. code-block:: c++
3831
3832  #pragma clang loop distribute(enable)
3833  for (i = 0; i < N; ++i) {
3834    S1: A[i + 1] = A[i] + B[i];
3835    S2: C[i] = D[i] * E[i];
3836  }
3837
3838This loop will be split into two loops between statements S1 and S2.  The
3839second loop containing S2 will be vectorized.
3840
3841Loop Distribution is currently not enabled by default in the optimizer because
3842it can hurt performance in some cases.  For example, instruction-level
3843parallelism could be reduced by sequentializing the execution of the
3844statements S1 and S2 above.
3845
3846If Loop Distribution is turned on globally with
3847``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
3848be used the disable it on a per-loop basis.
3849
3850Additional Information
3851----------------------
3852
3853For convenience multiple loop hints can be specified on a single line.
3854
3855.. code-block:: c++
3856
3857  #pragma clang loop vectorize_width(4) interleave_count(8)
3858  for(...) {
3859    ...
3860  }
3861
3862If an optimization cannot be applied any hints that apply to it will be ignored.
3863For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
3864proven safe to vectorize. To identify and diagnose optimization issues use
3865`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
3866user guide for details.
3867
3868Extensions to specify floating-point flags
3869====================================================
3870
3871The ``#pragma clang fp`` pragma allows floating-point options to be specified
3872for a section of the source code. This pragma can only appear at file scope or
3873at the start of a compound statement (excluding comments). When using within a
3874compound statement, the pragma is active within the scope of the compound
3875statement.
3876
3877Currently, the following settings can be controlled with this pragma:
3878
3879``#pragma clang fp reassociate`` allows control over the reassociation
3880of floating point expressions. When enabled, this pragma allows the expression
3881``x + (y + z)`` to be reassociated as ``(x + y) + z``.
3882Reassociation can also occur across multiple statements.
3883This pragma can be used to disable reassociation when it is otherwise
3884enabled for the translation unit with the ``-fassociative-math`` flag.
3885The pragma can take two values: ``on`` and ``off``.
3886
3887.. code-block:: c++
3888
3889  float f(float x, float y, float z)
3890  {
3891    // Enable floating point reassociation across statements
3892    #pragma clang fp reassociate(on)
3893    float t = x + y;
3894    float v = t + z;
3895  }
3896
3897
3898``#pragma clang fp contract`` specifies whether the compiler should
3899contract a multiply and an addition (or subtraction) into a fused FMA
3900operation when supported by the target.
3901
3902The pragma can take three values: ``on``, ``fast`` and ``off``.  The ``on``
3903option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
3904fusion as specified the language standard.  The ``fast`` option allows fusion
3905in cases when the language standard does not make this possible (e.g. across
3906statements in C).
3907
3908.. code-block:: c++
3909
3910  for(...) {
3911    #pragma clang fp contract(fast)
3912    a = b[i] * c[i];
3913    d[i] += a;
3914  }
3915
3916
3917The pragma can also be used with ``off`` which turns FP contraction off for a
3918section of the code. This can be useful when fast contraction is otherwise
3919enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag.
3920Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and
3921addition across statements regardless of any controlling pragmas.
3922
3923``#pragma clang fp exceptions`` specifies floating point exception behavior. It
3924may take one the the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of
3925these values is same as for `constrained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics>`_.
3926
3927.. code-block:: c++
3928
3929  {
3930    // Preserve floating point exceptions
3931    #pragma clang fp exceptions(strict)
3932    z = x + y;
3933    if (fetestexcept(FE_OVERFLOW))
3934	  ...
3935  }
3936
3937A ``#pragma clang fp`` pragma may contain any number of options:
3938
3939.. code-block:: c++
3940
3941  void func(float *dest, float a, float b) {
3942    #pragma clang fp exceptions(maytrap) contract(fast) reassociate(on)
3943    ...
3944  }
3945
3946``#pragma clang fp eval_method`` allows floating-point behavior to be specified
3947for a section of the source code. This pragma can appear at file or namespace
3948scope, or at the start of a compound statement (excluding comments).
3949The pragma is active within the scope of the compound statement.
3950
3951When ``pragma clang fp eval_method(source)`` is enabled, the section of code
3952governed by the pragma behaves as though the command-line option
3953``-ffp-eval-method=source`` is enabled. Rounds intermediate results to
3954source-defined precision.
3955
3956When ``pragma clang fp eval_method(double)`` is enabled, the section of code
3957governed by the pragma behaves as though the command-line option
3958``-ffp-eval-method=double`` is enabled. Rounds intermediate results to
3959``double`` precision.
3960
3961When ``pragma clang fp eval_method(extended)`` is enabled, the section of code
3962governed by the pragma behaves as though the command-line option
3963``-ffp-eval-method=extended`` is enabled. Rounds intermediate results to
3964target-dependent ``long double`` precision. In Win32 programming, for instance,
3965the long double data type maps to the double, 64-bit precision data type.
3966
3967The full syntax this pragma supports is
3968``#pragma clang fp eval_method(source|double|extended)``.
3969
3970.. code-block:: c++
3971
3972  for(...) {
3973    // The compiler will use long double as the floating-point evaluation
3974    // method.
3975    #pragma clang fp eval_method(extended)
3976    a = b[i] * c[i] + e;
3977  }
3978
3979The ``#pragma float_control`` pragma allows precise floating-point
3980semantics and floating-point exception behavior to be specified
3981for a section of the source code. This pragma can only appear at file or
3982namespace scope, within a language linkage specification or at the start of a
3983compound statement (excluding comments). When used within a compound statement,
3984the pragma is active within the scope of the compound statement.  This pragma
3985is modeled after a Microsoft pragma with the same spelling and syntax.  For
3986pragmas specified at file or namespace scope, or within a language linkage
3987specification, a stack is supported so that the ``pragma float_control``
3988settings can be pushed or popped.
3989
3990When ``pragma float_control(precise, on)`` is enabled, the section of code
3991governed by the pragma uses precise floating point semantics, effectively
3992``-ffast-math`` is disabled and ``-ffp-contract=on``
3993(fused multiply add) is enabled.
3994
3995When ``pragma float_control(except, on)`` is enabled, the section of code
3996governed by the pragma behaves as though the command-line option
3997``-ffp-exception-behavior=strict`` is enabled,
3998when ``pragma float_control(except, off)`` is enabled, the section of code
3999governed by the pragma behaves as though the command-line option
4000``-ffp-exception-behavior=ignore`` is enabled.
4001
4002The full syntax this pragma supports is
4003``float_control(except|precise, on|off [, push])`` and
4004``float_control(push|pop)``.
4005The ``push`` and ``pop`` forms, including using ``push`` as the optional
4006third argument, can only occur at file scope.
4007
4008.. code-block:: c++
4009
4010  for(...) {
4011    // This block will be compiled with -fno-fast-math and -ffp-contract=on
4012    #pragma float_control(precise, on)
4013    a = b[i] * c[i] + e;
4014  }
4015
4016Specifying an attribute for multiple declarations (#pragma clang attribute)
4017===========================================================================
4018
4019The ``#pragma clang attribute`` directive can be used to apply an attribute to
4020multiple declarations. The ``#pragma clang attribute push`` variation of the
4021directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
4022can be added to. The ``#pragma clang attribute (...)`` variation adds an
4023attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
4024the scope. You can also use ``#pragma clang attribute push (...)``, which is a
4025shorthand for when you want to add one attribute to a new scope. Multiple push
4026directives can be nested inside each other.
4027
4028The attributes that are used in the ``#pragma clang attribute`` directives
4029can be written using the GNU-style syntax:
4030
4031.. code-block:: c++
4032
4033  #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
4034
4035  void function(); // The function now has the annotate("custom") attribute
4036
4037  #pragma clang attribute pop
4038
4039The attributes can also be written using the C++11 style syntax:
4040
4041.. code-block:: c++
4042
4043  #pragma clang attribute push ([[noreturn]], apply_to = function)
4044
4045  void function(); // The function now has the [[noreturn]] attribute
4046
4047  #pragma clang attribute pop
4048
4049The ``__declspec`` style syntax is also supported:
4050
4051.. code-block:: c++
4052
4053  #pragma clang attribute push (__declspec(dllexport), apply_to = function)
4054
4055  void function(); // The function now has the __declspec(dllexport) attribute
4056
4057  #pragma clang attribute pop
4058
4059A single push directive accepts only one attribute regardless of the syntax
4060used.
4061
4062Because multiple push directives can be nested, if you're writing a macro that
4063expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
4064required) to add a namespace to your push/pop directives. A pop directive with a
4065namespace will pop the innermost push that has that same namespace. This will
4066ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
4067that an ``pop`` without a namespace will pop the innermost ``push`` without a
4068namespace. ``push``es with a namespace can only be popped by ``pop`` with the
4069same namespace. For instance:
4070
4071.. code-block:: c++
4072
4073   #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
4074   #define ASSUME_NORETURN_END   _Pragma("clang attribute AssumeNoreturn.pop")
4075
4076   #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
4077   #define ASSUME_UNAVAILABLE_END   _Pragma("clang attribute Unavailable.pop")
4078
4079
4080   ASSUME_NORETURN_BEGIN
4081   ASSUME_UNAVAILABLE_BEGIN
4082   void function(); // function has [[noreturn]] and __attribute__((unavailable))
4083   ASSUME_NORETURN_END
4084   void other_function(); // function has __attribute__((unavailable))
4085   ASSUME_UNAVAILABLE_END
4086
4087Without the namespaces on the macros, ``other_function`` will be annotated with
4088``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
4089a contrived example, but its very possible for this kind of situation to appear
4090in real code if the pragmas are spread out across a large file. You can test if
4091your version of clang supports namespaces on ``#pragma clang attribute`` with
4092``__has_extension(pragma_clang_attribute_namespaces)``.
4093
4094Subject Match Rules
4095-------------------
4096
4097The set of declarations that receive a single attribute from the attribute stack
4098depends on the subject match rules that were specified in the pragma. Subject
4099match rules are specified after the attribute. The compiler expects an
4100identifier that corresponds to the subject set specifier. The ``apply_to``
4101specifier is currently the only supported subject set specifier. It allows you
4102to specify match rules that form a subset of the attribute's allowed subject
4103set, i.e. the compiler doesn't require all of the attribute's subjects. For
4104example, an attribute like ``[[nodiscard]]`` whose subject set includes
4105``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
4106least one of these rules after ``apply_to``:
4107
4108.. code-block:: c++
4109
4110  #pragma clang attribute push([[nodiscard]], apply_to = enum)
4111
4112  enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
4113
4114  struct Record1 { }; // The struct will *not* receive [[nodiscard]]
4115
4116  #pragma clang attribute pop
4117
4118  #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
4119
4120  enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
4121
4122  struct Record2 { }; // The struct *will* receive [[nodiscard]]
4123
4124  #pragma clang attribute pop
4125
4126  // This is an error, since [[nodiscard]] can't be applied to namespaces:
4127  #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
4128
4129  #pragma clang attribute pop
4130
4131Multiple match rules can be specified using the ``any`` match rule, as shown
4132in the example above. The ``any`` rule applies attributes to all declarations
4133that are matched by at least one of the rules in the ``any``. It doesn't nest
4134and can't be used inside the other match rules. Redundant match rules or rules
4135that conflict with one another should not be used inside of ``any``. Failing to
4136specify a rule within the ``any`` rule results in an error.
4137
4138Clang supports the following match rules:
4139
4140- ``function``: Can be used to apply attributes to functions. This includes C++
4141  member functions, static functions, operators, and constructors/destructors.
4142
4143- ``function(is_member)``: Can be used to apply attributes to C++ member
4144  functions. This includes members like static functions, operators, and
4145  constructors/destructors.
4146
4147- ``hasType(functionType)``: Can be used to apply attributes to functions, C++
4148  member functions, and variables/fields whose type is a function pointer. It
4149  does not apply attributes to Objective-C methods or blocks.
4150
4151- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
4152  and C++11 type aliases.
4153
4154- ``record``: Can be used to apply attributes to ``struct``, ``class``, and
4155  ``union`` declarations.
4156
4157- ``record(unless(is_union))``: Can be used to apply attributes only to
4158  ``struct`` and ``class`` declarations.
4159
4160- ``enum``: Can be be used to apply attributes to enumeration declarations.
4161
4162- ``enum_constant``: Can be used to apply attributes to enumerators.
4163
4164- ``variable``: Can be used to apply attributes to variables, including
4165  local variables, parameters, global variables, and static member variables.
4166  It does not apply attributes to instance member variables or Objective-C
4167  ivars.
4168
4169- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
4170  variables only.
4171
4172- ``variable(is_global)``: Can be used to apply attributes to global variables
4173  only.
4174
4175- ``variable(is_local)``: Can be used to apply attributes to local variables
4176  only.
4177
4178- ``variable(is_parameter)``: Can be used to apply attributes to parameters
4179  only.
4180
4181- ``variable(unless(is_parameter))``: Can be used to apply attributes to all
4182  the variables that are not parameters.
4183
4184- ``field``: Can be used to apply attributes to non-static member variables
4185  in a record. This includes Objective-C ivars.
4186
4187- ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
4188
4189- ``objc_interface``: Can be used to apply attributes to ``@interface``
4190  declarations.
4191
4192- ``objc_protocol``: Can be used to apply attributes to ``@protocol``
4193  declarations.
4194
4195- ``objc_category``: Can be used to apply attributes to category declarations,
4196  including class extensions.
4197
4198- ``objc_method``: Can be used to apply attributes to Objective-C methods,
4199  including instance and class methods. Implicit methods like implicit property
4200  getters and setters do not receive the attribute.
4201
4202- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
4203  instance methods.
4204
4205- ``objc_property``: Can be used to apply attributes to ``@property``
4206  declarations.
4207
4208- ``block``: Can be used to apply attributes to block declarations. This does
4209  not include variables/fields of block pointer type.
4210
4211The use of ``unless`` in match rules is currently restricted to a strict set of
4212sub-rules that are used by the supported attributes. That means that even though
4213``variable(unless(is_parameter))`` is a valid match rule,
4214``variable(unless(is_thread_local))`` is not.
4215
4216Supported Attributes
4217--------------------
4218
4219Not all attributes can be used with the ``#pragma clang attribute`` directive.
4220Notably, statement attributes like ``[[fallthrough]]`` or type attributes
4221like ``address_space`` aren't supported by this directive. You can determine
4222whether or not an attribute is supported by the pragma by referring to the
4223:doc:`individual documentation for that attribute <AttributeReference>`.
4224
4225The attributes are applied to all matching declarations individually, even when
4226the attribute is semantically incorrect. The attributes that aren't applied to
4227any declaration are not verified semantically.
4228
4229Specifying section names for global objects (#pragma clang section)
4230===================================================================
4231
4232The ``#pragma clang section`` directive provides a means to assign section-names
4233to global variables, functions and static variables.
4234
4235The section names can be specified as:
4236
4237.. code-block:: c++
4238
4239  #pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText"
4240
4241The section names can be reverted back to default name by supplying an empty
4242string to the section kind, for example:
4243
4244.. code-block:: c++
4245
4246  #pragma clang section bss="" data="" text="" rodata="" relro=""
4247
4248The ``#pragma clang section`` directive obeys the following rules:
4249
4250* The pragma applies to all global variable, statics and function declarations
4251  from the pragma to the end of the translation unit.
4252
4253* The pragma clang section is enabled automatically, without need of any flags.
4254
4255* This feature is only defined to work sensibly for ELF targets.
4256
4257* If section name is specified through _attribute_((section("myname"))), then
4258  the attribute name gains precedence.
4259
4260* Global variables that are initialized to zero will be placed in the named
4261  bss section, if one is present.
4262
4263* The ``#pragma clang section`` directive does not does try to infer section-kind
4264  from the name. For example, naming a section "``.bss.mySec``" does NOT mean
4265  it will be a bss section name.
4266
4267* The decision about which section-kind applies to each global is taken in the back-end.
4268  Once the section-kind is known, appropriate section name, as specified by the user using
4269  ``#pragma clang section`` directive, is applied to that global.
4270
4271Specifying Linker Options on ELF Targets
4272========================================
4273
4274The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
4275The second parameter is the library name (without the traditional Unix prefix of
4276``lib``).  This allows you to provide an implicit link of dependent libraries.
4277
4278Evaluating Object Size Dynamically
4279==================================
4280
4281Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are
4282the same as GCC's ``__builtin_object_size`` (which Clang also supports), but
4283``__builtin_dynamic_object_size`` can evaluate the object's size at runtime.
4284``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement
4285for ``__builtin_object_size`` in libraries that support it.
4286
4287For instance, here is a program that ``__builtin_dynamic_object_size`` will make
4288safer:
4289
4290.. code-block:: c
4291
4292  void copy_into_buffer(size_t size) {
4293    char* buffer = malloc(size);
4294    strlcpy(buffer, "some string", strlen("some string"));
4295    // Previous line preprocesses to:
4296    // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
4297  }
4298
4299Since the size of ``buffer`` can't be known at compile time, Clang will fold
4300``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
4301as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
4302``size``, providing some extra runtime safety.
4303
4304Deprecating Macros
4305==================
4306
4307Clang supports the pragma ``#pragma clang deprecated``, which can be used to
4308provide deprecation warnings for macro uses. For example:
4309
4310.. code-block:: c
4311
4312   #define MIN(x, y) x < y ? x : y
4313   #pragma clang deprecated(MIN, "use std::min instead")
4314
4315   void min(int a, int b) {
4316     return MIN(a, b); // warning: MIN is deprecated: use std::min instead
4317   }
4318
4319``#pragma clang deprecated`` should be preferred for this purpose over
4320``#pragma GCC warning`` because the warning can be controlled with
4321``-Wdeprecated``.
4322
4323Restricted Expansion Macros
4324===========================
4325
4326Clang supports the pragma ``#pragma clang restrict_expansion``, which can be
4327used restrict macro expansion in headers. This can be valuable when providing
4328headers with ABI stability requirements. Any expansion of the annotated macro
4329processed by the preprocessor after the ``#pragma`` annotation will log a
4330warning. Redefining the macro or undefining the macro will not be diagnosed, nor
4331will expansion of the macro within the main source file. For example:
4332
4333.. code-block:: c
4334
4335   #define TARGET_ARM 1
4336   #pragma clang restrict_expansion(TARGET_ARM, "<reason>")
4337
4338   /// Foo.h
4339   struct Foo {
4340   #if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason>
4341     uint32_t X;
4342   #else
4343     uint64_t X;
4344   #endif
4345   };
4346
4347   /// main.c
4348   #include "foo.h"
4349   #if TARGET_ARM // No warning in main source file
4350   X_TYPE uint32_t
4351   #else
4352   X_TYPE uint64_t
4353   #endif
4354
4355This warning is controlled by ``-Wpedantic-macros``.
4356
4357Final Macros
4358============
4359
4360Clang supports the pragma ``#pragma clang final``, which can be used to
4361mark macros as final, meaning they cannot be undef'd or re-defined. For example:
4362
4363.. code-block:: c
4364
4365   #define FINAL_MACRO 1
4366   #pragma clang final(FINAL_MACRO)
4367
4368   #define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined
4369   #undef FINAL_MACRO  // warning: FINAL_MACRO is marked final and should not be undefined
4370
4371This is useful for enforcing system-provided macros that should not be altered
4372in user headers or code. This is controlled by ``-Wpedantic-macros``. Final
4373macros will always warn on redefinition, including situations with identical
4374bodies and in system headers.
4375
4376Line Control
4377============
4378
4379Clang supports an extension for source line control, which takes the
4380form of a preprocessor directive starting with an unsigned integral
4381constant. In addition to the standard ``#line`` directive, this form
4382allows control of an include stack and header file type, which is used
4383in issuing diagnostics. These lines are emitted in preprocessed
4384output.
4385
4386.. code-block:: c
4387
4388   # <line:number> <filename:string> <header-type:numbers>
4389
4390The filename is optional, and if unspecified indicates no change in
4391source filename. The header-type is an optional, whitespace-delimited,
4392sequence of magic numbers as follows.
4393
4394* ``1:`` Push the current source file name onto the include stack and
4395  enter a new file.
4396
4397* ``2``: Pop the include stack and return to the specified file. If
4398  the filename is ``""``, the name popped from the include stack is
4399  used. Otherwise there is no requirement that the specified filename
4400  matches the current source when originally pushed.
4401
4402* ``3``: Enter a system-header region. System headers often contain
4403  implementation-specific source that would normally emit a diagnostic.
4404
4405* ``4``: Enter an implicit ``extern "C"`` region. This is not required on
4406  modern systems where system headers are C++-aware.
4407
4408At most a single ``1`` or ``2`` can be present, and values must be in
4409ascending order.
4410
4411Examples are:
4412
4413.. code-block:: c
4414
4415   # 57 // Advance (or return) to line 57 of the current source file
4416   # 57 "frob" // Set to line 57 of "frob"
4417   # 1 "foo.h" 1 // Enter "foo.h" at line 1
4418   # 59 "main.c" 2 // Leave current include and return to "main.c"
4419   # 1 "/usr/include/stdio.h" 1 3 // Enter a system header
4420   # 60 "" 2 // return to "main.c"
4421   # 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
4422
4423Extended Integer Types
4424======================
4425
4426Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
4427and in C++. This type was previously implemented in Clang with the same
4428semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
4429favor of the standard type.
4430
4431Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
4432so this type should not yet be used in interfaces that require ABI stability.
4433
4434Intrinsics Support within Constant Expressions
4435==============================================
4436
4437The following builtin intrinsics can be used in constant expressions:
4438
4439* ``__builtin_bitreverse8``
4440* ``__builtin_bitreverse16``
4441* ``__builtin_bitreverse32``
4442* ``__builtin_bitreverse64``
4443* ``__builtin_bswap16``
4444* ``__builtin_bswap32``
4445* ``__builtin_bswap64``
4446* ``__builtin_clrsb``
4447* ``__builtin_clrsbl``
4448* ``__builtin_clrsbll``
4449* ``__builtin_clz``
4450* ``__builtin_clzl``
4451* ``__builtin_clzll``
4452* ``__builtin_clzs``
4453* ``__builtin_ctz``
4454* ``__builtin_ctzl``
4455* ``__builtin_ctzll``
4456* ``__builtin_ctzs``
4457* ``__builtin_ffs``
4458* ``__builtin_ffsl``
4459* ``__builtin_ffsll``
4460* ``__builtin_fpclassify``
4461* ``__builtin_inf``
4462* ``__builtin_isinf``
4463* ``__builtin_isinf_sign``
4464* ``__builtin_isfinite``
4465* ``__builtin_isnan``
4466* ``__builtin_isnormal``
4467* ``__builtin_nan``
4468* ``__builtin_nans``
4469* ``__builtin_parity``
4470* ``__builtin_parityl``
4471* ``__builtin_parityll``
4472* ``__builtin_popcount``
4473* ``__builtin_popcountl``
4474* ``__builtin_popcountll``
4475* ``__builtin_rotateleft8``
4476* ``__builtin_rotateleft16``
4477* ``__builtin_rotateleft32``
4478* ``__builtin_rotateleft64``
4479* ``__builtin_rotateright8``
4480* ``__builtin_rotateright16``
4481* ``__builtin_rotateright32``
4482* ``__builtin_rotateright64``
4483
4484The following x86-specific intrinsics can be used in constant expressions:
4485
4486* ``_bit_scan_forward``
4487* ``_bit_scan_reverse``
4488* ``__bsfd``
4489* ``__bsfq``
4490* ``__bsrd``
4491* ``__bsrq``
4492* ``__bswap``
4493* ``__bswapd``
4494* ``__bswap64``
4495* ``__bswapq``
4496* ``_castf32_u32``
4497* ``_castf64_u64``
4498* ``_castu32_f32``
4499* ``_castu64_f64``
4500* ``_mm_popcnt_u32``
4501* ``_mm_popcnt_u64``
4502* ``_popcnt32``
4503* ``_popcnt64``
4504* ``__popcntd``
4505* ``__popcntq``
4506* ``__rolb``
4507* ``__rolw``
4508* ``__rold``
4509* ``__rolq``
4510* ``__rorb``
4511* ``__rorw``
4512* ``__rord``
4513* ``__rorq``
4514* ``_rotl``
4515* ``_rotr``
4516* ``_rotwl``
4517* ``_rotwr``
4518* ``_lrotl``
4519* ``_lrotr``
4520