Lines Matching +full:tests +full:/ +full:files +full:/ +full:good +full:- +full:0 +full:- +full:empty +full:. +full:xz

5 .. contents::
9 .. toctree::
14 Block-ABI-Apple
21 This document describes the language extensions provided by Clang. In addition
23 GCC extensions. Please see the `GCC manual
24 <https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
25 these extensions.
27 .. _langext-feature_check:
33 them. In order to allow fine-grain features checks, we support three builtin
34 function-like macros. This allows you to directly test for a feature in your
36 version checks".
39 -----------------
41 This function-like macro takes a single identifier argument that is the name of
42 a builtin function, a builtin pseudo-function (taking one or more type
43 arguments), or a builtin template.
44 It evaluates to 1 if the builtin is supported or 0 if not.
47 .. code-block:: c++
49 #ifndef __has_builtin // Optional of course.
50 #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
53 ...
59 ...
61 .. note::
64 pseudo-functions.
67 use ``#ifdef`` instead.
69 .. _langext-__has_feature-__has_extension:
72 -----------------------------------------
74 These function-like macros take a single identifier argument that is the name
75 of a feature. ``__has_feature`` evaluates to 1 if the feature is both
76 supported by Clang and standardized in the current language standard or 0 if
77 not (but see :ref:`below <langext-has-feature-back-compat>`), while
80 feature) or 0 if not. They can be used like this:
82 .. code-block:: c++
84 #ifndef __has_feature // Optional of course.
85 #define __has_feature(x) 0 // Compatibility with non-clang compilers.
88 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
91 ...
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.
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.
103 .. _langext-has-feature-back-compat:
106 for support for non-standardized features, i.e. features not prefixed ``c_``,
107 ``cxx_`` or ``objc_``.
110 to the language standard, such as e.g. :doc:`AddressSanitizer
111 <AddressSanitizer>`.
113 If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
114 to ``__has_feature``.
116 The feature tag is described along with the language feature below.
120 the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
121 of ``cxx_rvalue_references``.
124 -----------------------
126 This function-like macro is available in C++20 by default, and is provided as an
127 extension in earlier language standards. It takes a single argument that is the
128 name of a double-square-bracket-style attribute. The argument can either be a
129 single identifier or a scoped identifier. If the attribute is supported, a
130 nonzero value is returned. If the attribute is a standards-based attribute, this
132 was voted into the working draft. See `WG21 SD-6
133 <https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
134 for the list of values returned for standards-based attributes. If the attribute
135 is not supported by the current compilation target, this macro evaluates to 0.
138 .. code-block:: c++
140 #ifndef __has_cpp_attribute // For backwards compatibility
141 #define __has_cpp_attribute(x) 0
144 ...
150 ...
153 the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
155 (double underscore) to avoid interference from a macro with the same name. For
156 instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
159 ---------------------
161 This function-like macro takes a single argument that is the name of an
162 attribute exposed with the double square-bracket syntax in C mode. The argument
163 can either be a single identifier or a scoped identifier. If the attribute is
164 supported, a nonzero value is returned. If the attribute is not supported by the
165 current compilation target, this macro evaluates to 0. It can be used like this:
167 .. code-block:: c
169 #ifndef __has_c_attribute // Optional of course.
170 #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers.
173 ...
179 ...
182 the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
184 (double underscore) to avoid interference from a macro with the same name. For
185 instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
188 -------------------
190 This function-like macro takes a single identifier argument that is the name of
191 a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
192 current compilation target, or 0 if not. It can be used like this:
194 .. code-block:: c++
196 #ifndef __has_attribute // Optional of course.
197 #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
200 ...
206 ...
209 (double underscore) to avoid interference from a macro with the same name. For
210 instance, ``__always_inline__`` can be used instead of ``always_inline``.
214 ----------------------------
216 This function-like macro takes a single identifier argument that is the name of
217 an attribute implemented as a Microsoft-style ``__declspec`` attribute. It
219 or 0 if not. It can be used like this:
221 .. code-block:: c++
223 #ifndef __has_declspec_attribute // Optional of course.
224 #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers.
227 ...
233 ...
236 (double underscore) to avoid interference from a macro with the same name. For
237 instance, ``__dllexport__`` can be used instead of ``dllexport``.
240 -------------------
242 This function-like macro takes a single identifier argument that might be either
243 a reserved word or a regular identifier. It evaluates to 1 if the argument is just
245 used as the name of a user-defined function or variable. Otherwise it evaluates
246 to 0. It can be used like this:
248 .. code-block:: c++
250 ...
251 #ifdef __is_identifier // Compatibility with non-clang compilers.
258 ...
263 Not all developments systems have the same include files. The
264 :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
266 failing ``#include`` directive. Include file checking macros must be used
267 as expressions in ``#if`` or ``#elif`` preprocessing directives.
269 .. _langext-__has_include:
272 -----------------
274 This function-like macro takes a single file name string argument that is the
275 name of an include file. It evaluates to 1 if the file can be found using the
276 include paths, or 0 otherwise:
278 .. code-block:: c++
280 // Note the two possible file name string formats.
281 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
282 # include "myinclude.h"
287 .. code-block:: c++
289 // To avoid problem with non-clang compilers not having this macro.
291 #if __has_include("myinclude.h")
292 # include "myinclude.h"
296 .. _langext-__has_include_next:
299 ----------------------
301 This function-like macro takes a single file name string argument that is the
302 name of an include file. It is like ``__has_include`` except that it looks for
303 the second instance of the given file found in the include paths. It evaluates
305 or 0 otherwise:
307 .. code-block:: c++
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"
314 // To avoid problem with non-clang compilers not having this macro.
316 #if __has_include_next("myinclude.h")
317 # include_next "myinclude.h"
323 used in the top-level compilation file. A warning will also be issued if an
324 absolute path is used in the file argument.
327 -----------------
329 This function-like macro takes a string literal that represents a command line
330 option for a warning and returns true if that is a valid warning option.
332 .. code-block:: c++
334 #if __has_warning("-Wformat")
335 ...
338 .. _languageextensions-builtin-macros:
345 Clang.
348 Clang-specific extension that functions similar to ``__FILE__`` but only
350 dependent full path to that file.
354 the ``__COUNTER__`` macro is expanded.
358 being translated. For the main file, this value is zero.
362 file.
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`.
374 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
376 features, as different vendors use different numbering schemes. Instead, use
377 the :ref:`langext-feature_check`.
380 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
384 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
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.)
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.)
398 .. _langext-vectors:
403 Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
405 OpenCL vector types are created using the ``ext_vector_type`` attribute. It
406 supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
409 .. code-block:: c++
416 c.xz = a;
417 c.yw = b;
421 Query for this feature with ``__has_attribute(ext_vector_type)``.
423 Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
424 and functions. For example:
426 .. code-block:: c++
435 ``neon_polyvector_type`` attributes. For example:
437 .. code-block:: c++
449 ---------------
452 vectors. Either parentheses or braces form can be used. In the parentheses
453 form the number of literal values specified must be one, i.e. referring to a
454 scalar value, or must match the size of the vector type being created. If a
456 replicated to all the components of the vector type. In the brackets form any
457 number of literals can be specified. For example:
459 .. code-block:: c++
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).
475 -----------------
477 The table below shows the support for each operation by vector extension. A
479 specification.
484 [] yes yes yes --
485 unary operators +, -- yes yes yes --
486 ++, -- -- yes yes yes --
487 +,--,*,/,% yes yes yes --
488 bitwise operators &,|,^,~ yes yes yes --
489 >>,<< yes yes yes --
490 !, &&, || yes -- yes --
491 ==, !=, >, <, >=, <= yes yes yes --
493 ?: [#]_ yes -- yes --
495 C-style cast yes yes yes no
501 See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
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).
513 implemented. See :ref:`the draft specification <matrixtypes>` for more details.
516 float matrices and add the result to a third 4x4 matrix.
518 .. code-block:: c++
527 Half-Precision Floating Point
530 Clang supports three half-precision (16-bit) floating point types: ``__fp16``,
531 ``_Float16`` and ``__bf16``. These types are supported in all language modes.
533 ``__fp16`` is supported on every target, as it is purely a storage format; see below.
537 * 32-bit ARM
538 * 64-bit ARM (AArch64)
542 ``_Float16`` will be supported on more targets as they define ABIs for it.
545 * 32-bit ARM
546 * 64-bit ARM (AArch64)
548 The ``__bf16`` type is only available when supported in hardware.
550 ``__fp16`` is a storage and interchange format only. This means that values of
552 operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``.
553 …M C Language Extensions (`ACLE <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053d/IHI0053D…
554 Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
555 alternative format.
557 ``_Float16`` is an interchange floating-point type. This means that, just like arithmetic on
559 ``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
560 ``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
561 ("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16``
562 format from IEEE 754-2008 for ``_Float16``.
564 ``_Float16`` arithmetic will be performed using native half-precision support
565 when available on the target (e.g. on ARMv8.2a); otherwise it will be performed
567 ``_Float16``. Note that C and C++ allow intermediate floating-point operands
570 lead to results that are inconsistent with native arithmetic.
574 more familiar to most programmers.
578 arithmetic conversions is ``float``.
580 A literal can be given ``_Float16`` type using the suffix ``f16``. For example,
581 ``3.14f16``.
583 Because default argument promotion only applies to the standard floating-point
585 or untyped arguments. As a consequence, some caution must be taken when using
589 ``double`` before using it with an ``%f`` or similar specifier.
595 ``unavailable`` attributes. For example:
597 .. code-block:: c++
604 .. code-block:: none
606 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
607 [-Wdeprecated-declarations]
613 ``__has_extension(attribute_unavailable_with_message)``.
618 Clang allows attributes to be written on individual enumerators. This allows
619 enumerators to be deprecated, made unavailable, etc. The attribute must appear
622 .. code-block:: c++
631 Attributes on the ``enum`` declaration do not apply to individual enumerators.
633 Query for this feature with ``__has_extension(enumerator_attributes)``.
635 'User-Specified' System Frameworks
640 present in a system framework directory. This can be useful to system
643 compiler changes warning behavior for system headers.
645 Framework developers can opt-in to this mechanism by creating a
646 "``.system_framework``" file at the top-level of their framework. That is, the
649 .. code-block:: none
651 .../TestFramework.framework
652 .../TestFramework.framework/.system_framework
653 .../TestFramework.framework/Headers
654 .../TestFramework.framework/Headers/TestFramework.h
655 ...
659 framework search path. For consistency, we recommend that such files never be
660 included in installed versions of the framework.
666 features are enabled. The ``__has_extension`` macro can be used to query if
668 which does not provide them. The features which can be tested are listed here.
670 Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
672 intended to be a portable way to query the supported features of the compiler.
673 See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
674 information on the version of SD-6 supported by each Clang release, and the
675 macros provided by that revision of the recommendations.
678 -----
680 The features listed below are part of the C++98 standard. These features are
681 enabled by default when compiling C++ code.
687 enabled. For example, compiling code with ``-fno-exceptions`` disables C++
688 exceptions.
693 Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
694 example, compiling code with ``-fno-rtti`` disables the use of RTTI.
697 -----
699 The features listed below are part of the C++11 standard. As a result, all
700 these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
701 when compiling C++ code.
708 access-control errors (e.g., calling a private constructor) are considered to
710 <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
717 alias declarations and alias templates is enabled.
723 determine if support for alignment specifiers using ``alignas`` is enabled.
726 determine if support for the ``alignof`` keyword is enabled.
733 is enabled.
739 constant expressions (e.g., ``constexpr``) is enabled.
745 determine if support for the ``decltype()`` specifier is enabled. C++11's
746 ``decltype`` does not require type-completeness of a function call expression.
749 support for this feature is enabled.
756 for default template arguments in function templates is enabled.
763 defaulted function definitions (with ``= default``) is enabled.
769 delegating constructors is enabled.
776 function definitions (with ``= delete``) is enabled.
782 ``explicit`` conversion functions is enabled.
789 enabled.
791 C++11 implicit move constructors/assignment operators
795 generate move constructors and move assignment operators where needed.
801 inheriting constructors is enabled.
808 namespaces is enabled.
814 determine if support for lambdas is enabled.
821 local and unnamed types as template arguments is enabled.
827 determine if support for noexcept exception specifications is enabled.
829 C++11 in-class non-static data member initialization
832 Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
833 initialization of non-static data members is enabled.
839 determine if support for ``nullptr`` is enabled.
846 override control keywords is enabled.
848 C++11 reference-qualified functions
853 for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
854 applied to ``*this``) is enabled.
856 C++11 range-based ``for`` loop
860 determine if support for the range-based for loop is enabled.
866 string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
873 references is enabled.
879 ``__has_extension(cxx_static_assert)`` to determine if support for compile-time
880 assertions using ``static_assert`` is enabled.
886 ``thread_local`` variables is enabled.
892 determine C++11 type inference is supported using the ``auto`` specifier. If
894 or C++98.
901 typed, scoped enumerations is enabled.
908 alternate function declaration syntax with trailing return type is enabled.
914 string literals is enabled.
920 unrestricted unions is enabled.
922 C++11 user-defined literals
926 user-defined literals is enabled.
933 variadic templates is enabled.
936 -----
938 The features listed below are part of the C++14 standard. As a result, all
939 these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
940 when compiling C++ code.
947 binary literals (for instance, ``0b10010``) are recognized. Clang supports this
948 feature as an extension in all language modes.
956 *new-expression*, the operand of a *delete-expression*, an integral constant
957 expression, or a condition in a ``switch`` statement.
964 for the ``decltype(auto)`` placeholder type is enabled.
971 for default initializers in aggregate members is enabled.
977 using single quotes (for instance, ``10'000``) is enabled. At this time, there
986 (for instance, ``[n(0)] { return ++n; }``).
994 (for instance, ``[] (auto x) { return x + 1; }``).
1002 are permitted in ``constexpr`` functions.
1010 is enabled.
1012 C++14 runtime-sized arrays
1017 for arrays of runtime bound (a restricted form of variable-length arrays)
1018 is enabled.
1019 Clang's implementation of this feature is incomplete.
1026 templated variable declarations is enabled.
1029 ---
1031 The features listed below are part of the C11 standard. As a result, all these
1032 features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
1033 compiling C code. Additionally, because these features are all
1034 backward-compatible, they are available as extensions in all language modes.
1040 if support for alignment specifiers using ``_Alignas`` is enabled.
1043 if support for the ``_Alignof`` keyword is enabled.
1049 if support for atomic types using ``_Atomic`` is enabled. Clang also provides
1050 :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
1051 the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
1052 ``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
1053 is available.
1055 Clang will use the system's ``<stdatomic.h>`` header when one is available, and
1056 will otherwise use its own. When using its own, implementations of the atomic
1057 operations are provided as macros. In the cases where C11 also requires a real
1060 provides a definition of the function if you use it instead of the macro.
1067 selections is enabled.
1070 languages supported by Clang. The syntax is the same as that given in the C11
1071 standard.
1075 in C, types are considered compatible only if they are equivalent.
1081 to determine if support for compile-time assertions using ``_Static_assert`` is
1082 enabled.
1088 to determine if support for ``_Thread_local`` variables is enabled.
1091 -------
1093 Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1094 For example, compiling code with ``-fmodules`` enables the use of Modules.
1096 More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
1103 user-facing type traits in the <type_traits> header.
1106 implementation-defined and subject to change -- as such they're tied closely to
1114 <https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
1116 <https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,
1119 <http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.
1121 The following type trait primitives are supported by Clang. Those traits marked
1123 ``__X(...)`` has the same semantics and constraints as the corresponding
1124 ``std::X_t<...>`` or ``std::X_v<...>`` type trait.
1128 ``0`` if ``type`` is not an array type, and
1129 ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.
1131 The ``dim``'th array bound in the type ``type``, or ``0`` if
1132 ``dim >= __array_rank(type)``.
1134 Deprecated, use ``__is_nothrow_assignable`` instead.
1136 Deprecated, use ``__is_nothrow_assignable`` instead.
1138 Deprecated, use ``__is_nothrow_constructible`` instead.
1140 Deprecated, use ``__is_nothrow_constructible`` instead.
1142 Deprecated, use ``__is_trivially_assignable`` instead.
1144 Deprecated, use ``__is_trivially_assignable`` instead.
1146 Deprecated, use ``__is_trivially_constructible`` instead.
1148 Deprecated, use ``__is_trivially_constructible`` instead.
1150 Deprecated, use ``__is_trivially_constructible`` instead.
1152 Deprecated, use ``__is_trivially_destructible`` instead.
1163 Return ``true`` if ``type`` is a complete type.
1165 different points in the same program.
1171 Synonym for ``__is_convertible``.
1173 Only available in ``-fms-extensions`` mode.
1182 Returns ``false``, even for types defined with ``__interface``.
1184 Synonym for ``__is_literal_type``.
1187 and removed in C++20.
1195 Only available in ``-fms-extensions`` mode.
1198 Note, the corresponding standard trait was deprecated in C++20.
1204 * ``__is_same_as`` (GCC): Synonym for ``__is_same``.
1207 Synonym for ``__is_final``.
1209 Returns false for enumeration types, and returns true for floating-point
1210 types. Note, before Clang 10, returned true for enumeration types if the
1211 underlying type was signed, and returned false for floating-point types.
1220 Returns false for enumeration types. Note, before Clang 13, returned true for
1221 enumeration types if the underlying type was unsigned.
1226 materialized temporary object. If ``T`` is not a reference type the result
1227 is false. Note this trait will also return false when the initialization of
1228 ``T`` from ``U`` is ill-formed.
1234 Returns true if ``e`` is an lvalue expression.
1235 Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.
1237 Returns true if ``e`` is a prvalue expression.
1238 Deprecated, use ``!__is_reference(decltype((e)))`` instead.
1241 compiler, depending on the oldest version of Clang you wish to support.
1243 * From Clang 10 onwards, ``__has_builtin(__X)`` can be used.
1244 * From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.
1278 .. code-block:: c++
1286 // Emulate type trait for compatibility with other compilers.
1293 :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1294 the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
1296 Query for this feature with ``__has_extension(blocks)``.
1302 assembly <https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html>`_, clang
1303 supports output constraints with the `goto` form.
1306 label from within an inline assembly block. Clang extends this behavior by
1309 .. code-block:: c++
1313 asm goto("# %0 %1 %l2" : "=r"(y) : "r"(x) : : err);
1316 return -1;
1319 It's important to note that outputs are valid only on the "fallthrough" branch.
1320 Using outputs on an indirect branch may result in undefined behavior. For
1322 block is undefined behavior.
1324 Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.
1326 Objective-C Features
1330 --------------------
1332 According to Cocoa conventions, Objective-C methods with certain names
1333 ("``init``", "``alloc``", etc.) always return objects that are an instance of
1334 the receiving class's type. Such methods are said to have a "related result
1336 static type as an instance of the receiver class. For example, given the
1339 .. code-block:: objc
1343 - (id)init;
1351 .. code-block:: objc
1356 ``alloc`` implicitly has a related result type. Similarly, the type of the
1358 related result type and its receiver is known to have the type ``NSArray *``.
1360 would have had type ``id``, as declared in the method signature.
1363 ``instancetype`` as its result type. ``instancetype`` is a contextual keyword
1364 that is only permitted in the result type of an Objective-C method, e.g.
1366 .. code-block:: objc
1372 The related result type can also be inferred for some methods. To determine
1374 camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1382 and the method is an instance method.
1386 type. For example:
1388 .. code-block:: objc
1391 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1395 via the given method. In all other respects, a method with a related result
1396 type is treated the same way as method that returns ``id``.
1399 ``instancetype`` contextual keyword is available.
1402 ----------------------------
1405 <AutomaticReferenceCounting>` in Objective-C, which eliminates the need
1406 for manual ``retain``/``release``/``autorelease`` message sends. There are three
1411 Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
1412 are allowed to have fields that are pointers to Objective-C objects managed by
1413 automatic reference counting.
1415 .. _objc-weak:
1418 ---------------
1420 Clang supports ARC-style weak and unsafe references in Objective-C even
1421 outside of ARC mode. Weak references must be explicitly enabled with
1422 the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
1423 to test whether they are enabled. Unsafe references are enabled
1424 unconditionally. ARC-style weak and unsafe references cannot be used
1425 when Objective-C garbage collection is enabled.
1430 in the :doc:`ARC specification <AutomaticReferenceCounting>`.
1435 (such as in ``malloc``-ed memory).
1438 loaded value. In non-ARC modes, this retain is normally balanced
1439 by an implicit autorelease. This autorelease can be suppressed
1440 by performing the load in the receiver position of a ``-retain``
1441 message send (e.g. ``[weakReference retain]``); note that this performs
1443 the weak reference).
1445 For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
1446 default behavior of variables and therefore is not needed. However,
1448 copying a block which captures an Objective-C object or block pointer
1451 with ``__unsafe_unretained``.
1454 all non-ARC modes and was silently ignored outside of GC modes. It now
1455 means the ARC-style qualifier in all non-GC modes and is no longer
1456 allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
1457 It is expected that ``-fobjc-weak`` will eventually be enabled by default
1458 in all non-GC Objective-C modes.
1460 .. _objc-fixed-enum:
1463 -----------------------------------------
1466 within Objective-C. For example, one can write an enumeration type as:
1468 .. code-block:: c++
1473 value, is ``unsigned char``.
1476 underlying types is available in Objective-C.
1479 -----------------------------------
1481 Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1483 corresponding signature. For example, consider an API such as ``NSArray``'s
1484 array-sorting method:
1486 .. code-block:: objc
1488 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1492 literals as arguments. However, one can also use a C++11 lambda so long as it
1496 .. code-block:: objc
1505 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1506 NSRange string1Range = NSMakeRange(0, [s1 length]);
1514 corresponding block pointer type. The conversion itself is expressed by a
1516 same signature as the lambda itself, e.g.,
1518 .. code-block:: objc
1524 result. The returned block is first copied (with ``Block_copy``) and then
1525 autoreleased. As an optimization, if a lambda expression is immediately
1529 of copying a block to the heap in the common case.
1532 Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1533 management (autorelease).
1536 --------------------------------
1539 <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
1541 container creation. There are several feature macros associated with object
1542 literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1544 tests the availability of dictionary literals;
1545 ``__has_feature(objc_subscripting)`` tests the availability of object
1546 subscripting.
1548 Objective-C Autosynthesis of Properties
1549 ---------------------------------------
1551 Clang provides support for autosynthesis of declared properties. Using this
1553 @dynamic and not having user provided backing getter and setter methods.
1555 of this feature in version of clang being used.
1557 .. _langext-objc-retain-release:
1559 Objective-C retaining behavior attributes
1560 -----------------------------------------
1562 In Objective-C, functions and methods are generally assumed to follow the
1564 <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRule…
1566 return values. However, there are exceptions, and so Clang provides attributes
1567 to allow these exceptions to be documented. This are used by ARC and the
1568 `static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
1569 better described using the ``objc_method_family`` attribute instead.
1574 that return Objective-C or CoreFoundation objects. They are commonly placed at
1577 .. code-block:: objc
1581 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1584 retain count. The ``*_returns_not_retained`` attributes specify that the return
1585 object has a +0 retain count, even if the normal convention for its selector
1586 would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1587 +0, but is guaranteed to live at least as long as the next flush of an
1588 autorelease pool.
1592 +1 retain count, which will be balanced in some way by the function or method.
1593 The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1595 +1 retain count, which it will balance in some way.
1597 .. code-block:: objc
1601 - (void) bar __attribute__((ns_consumes_self));
1602 - (void) baz:(id) __attribute__((ns_consumed)) x;
1605 <https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1608 ``__has_attribute(ns_returns_retained)``, etc.
1610 Objective-C @available
1611 ----------------------
1614 older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
1615 ``-miphoneos-version-min=``.
1620 null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
1621 and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
1622 Objective-C methods. If such a check was missed, the program would compile
1623 fine, run fine on newer systems, but crash on older systems.
1625 As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
1626 <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
1627 with the new ``@available()`` keyword to assist with this issue.
1629 -Wunguarded-availability warning is emitted if that call is not guarded:
1631 .. code-block:: objc
1634 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
1635 // built with -mmacosx-version-min=10.11, then this unconditional call
1636 // will emit a -Wunguarded-availability warning:
1643 .. code-block:: objc
1649 // Put fallback behavior for old macOS versions (and for non-mac
1650 // platforms) here.
1655 the true branch, and the compiler will emit ``-Wunguarded-availability``
1656 warnings for unlisted platforms based on those platform's deployment target.
1659 .. code-block:: objc
1669 <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
1673 .. code-block:: objc
1676 [var fancyNewMethod]; // Now ok.
1679 ``@available()`` is only available in Objective-C code. To use the feature
1680 in C and C++ code, use the ``__builtin_available()`` spelling instead.
1682 If existing code uses null checks or ``-respondsToSelector:``, it should
1683 be changed to use ``@available()`` (or ``__builtin_available``) instead.
1685 ``-Wunguarded-availability`` is disabled by default, but
1686 ``-Wunguarded-availability-new``, which only emits this warning for APIs
1688 tvOS >= 11, is enabled by default.
1690 .. _langext-overloading:
1692 Objective-C++ ABI: protocol-qualifier mangling of parameters
1693 ------------------------------------------------------------
1696 type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
1698 type.
1700 This was a non-backward compatible mangling change to the ABI. This change
1702 parameters of protocol-qualified type.
1705 ``__has_feature(objc_protocol_qualifier_mangling)``.
1712 .. code-block:: c++
1714 #include <math.h>
1715 #include <complex.h>
1716 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1720 does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1722 in static initializers.)
1727 .. code-block:: c++
1729 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1730 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1733 to the C++ ``std::complex``. (In C++11, list initialization allows the same
1734 syntax to be used with ``std::complex`` with the same meaning.)
1737 construct a complex number from the given real and imaginary components.
1742 Clang supports internal OpenCL extensions documented below.
1745 --------------------------------
1751 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview…
1755 - Use of member function pointers;
1757 - Unrestricted use of references to functions;
1759 - Virtual member functions.
1762 correctly in any circumstances. It can be used if:
1764 - the kernel source does not contain call expressions to (member-) function
1765 pointers, or virtual functions. For example this extension can be used in
1766 metaprogramming algorithms to be able to specify/detect types generically.
1768 - the generated kernel binary does not contain indirect calls because they
1769 are eliminated using compiler optimizations e.g. devirtualization.
1771 - the selected target supports the function pointer like functionality e.g.
1772 most CPU targets.
1776 .. code-block:: c++
1781 void (*fp)(); // compiled - no diagnostic generated
1787 void (*fp)(); // error - pointers to function are not allowed
1791 ---------------------------------
1796 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview…
1799 functions with variadic prototypes do not get generated in binary e.g. the
1801 arguments in metaprogramming algorithms in C++ for OpenCL.
1804 supporting the variadic arguments e.g. majority of CPU targets.
1808 .. code-block:: c++
1811 void foo(int a, ...); // compiled - no diagnostic generated
1814 void bar(int a, ...); // error - variadic prototype is not allowed
1817 ----------------------------------------------
1820 in kernel parameters specified in `C++ for OpenCL v1.0 s2.4
1821 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_.
1824 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview…
1827 kernel arguments are not accessed on the host side or the data layout/size
1828 between the host and device is known to be compatible.
1832 .. code-block:: c++
1834 // Plain Old Data type.
1840 // Not POD type because of the constructor.
1841 // Standard layout type because there is only one access control.
1845 NotPod() : a(0), b(0) {}
1848 // Not standard layout type because of two different access controls.
1864 Legacy 1.x atomics with generic address space
1865 ---------------------------------------------
1867 Clang allows use of atomic functions from the OpenCL 1.x standards
1868 with the generic address space pointer in C++ for OpenCL mode.
1870 This is a non-portable feature and might not be supported by all
1871 targets.
1875 .. code-block:: c++
1887 ``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to
1889 are listed here.
1892 for vector operations. Instead of using builtins, you should use the functions
1893 defined in target-specific header files like ``<xmmintrin.h>``, which define
1894 portable wrappers for these. Many of the Clang versions of these functions are
1896 <langext-vectors>` instead of builtins, in order to reduce the number of
1897 builtins that we need to implement.
1899 .. _langext-__builtin_assume:
1902 ------------------------------
1905 invariant that is defined to be true.
1909 .. code-block:: c++
1915 .. code-block:: c++
1918 __builtin_assume(x != 0);
1920 // The optimizer may short-circuit this check using the invariant.
1921 if (x == 0)
1929 The boolean argument to this function is defined to be true. The optimizer may
1931 that information used to optimize the program. If the condition is violated
1932 during execution, the behavior is undefined. The argument itself is never
1933 evaluated, so any side effects of the expression will be discarded.
1935 Query for this feature with ``__has_builtin(__builtin_assume)``.
1938 ------------------------------
1941 a similar low-latency, high-accuracy clock) on those targets that support it.
1945 .. code-block:: c++
1951 .. code-block:: c++
1956 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1961 which may be either global or process/thread-specific depending on the target.
1963 should only be used for timing small intervals. When not supported by the
1964 target, the return value is always zero. This builtin takes no arguments and
1965 produces an unsigned long long result.
1967 Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
1968 that even if present, its use may depend on run-time privilege or other OS
1969 controlled state.
1972 -------------------------
1976 .. code-block:: c++
1982 .. code-block:: c++
1998 .. code-block:: none
2012 structure and their values for debugging purposes. The builtin accepts a pointer
2014 function whose signature must be: ``int (*)(const char *, ...)`` and must
2015 support the format specifiers used by ``printf()``.
2017 .. _langext-__builtin_shufflevector:
2020 ---------------------------
2023 permutation/shuffle/swizzle operations. This builtin is also very important
2024 for the implementation of various target-specific header files like
2025 ``<xmmintrin.h>``.
2029 .. code-block:: c++
2031 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
2035 .. code-block:: c++
2037 // identity operation - return 4-element vector v1.
2038 __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
2040 // "Splat" element 0 of V1 into a 4-element result.
2041 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
2043 // Reverse 4-element vector V1.
2044 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
2046 // Concatenate every other element of 4-element vectors V1 and V2.
2047 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
2049 // Concatenate every other element of 8-element vectors V1 and V2.
2050 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
2052 // Shuffle v1 with some elements being undefined
2053 __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
2058 the same element type. The remaining arguments are a list of integers that
2060 and returned in a new vector. These element indices are numbered sequentially
2061 starting with the first vector, continuing into the second vector. Thus, if
2062 ``vec1`` is a 4-element vector, index 5 would refer to the second element of
2063 ``vec2``. An index of -1 can be used to indicate that the corresponding element
2064 in the returned vector is a don't care and can be optimized by the backend.
2067 type as ``vec1``/``vec2`` but that has an element count equal to the number of
2068 indices specified.
2070 Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
2072 .. _langext-__builtin_convertvector:
2075 ---------------------------
2078 type-conversion operations. The input vector and the output vector
2079 type must have the same number of elements.
2083 .. code-block:: c++
2089 .. code-block:: c++
2096 // convert from a vector of 4 floats to a vector of 4 doubles.
2098 // equivalent to:
2099 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
2101 // convert from a vector of 4 shorts to a vector of 4 floats.
2103 // equivalent to:
2104 (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
2110 argument.
2114 C-style cast applied to each element of the first argument.
2116 Query for this feature with ``__has_builtin(__builtin_convertvector)``.
2119 ------------------------
2128 .. code-block:: c++
2134 .. code-block:: c++
2144 the bitpattern of an integer value; for example ``0b10110110`` becomes
2145 ``0b01101101``. These builtins can be used within constant expressions.
2148 ------------------------
2157 .. code-block:: c++
2163 .. code-block:: c++
2173 the bits in the first argument by the amount in the second argument.
2174 For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
2176 the arguments. Both arguments and the result have the bitwidth specified
2177 by the name of the builtin. These builtins can be used within constant
2178 expressions.
2181 -------------------------
2190 .. code-block:: c++
2196 .. code-block:: c++
2206 the bits in the first argument by the amount in the second argument.
2207 For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
2209 the arguments. Both arguments and the result have the bitwidth specified
2210 by the name of the builtin. These builtins can be used within constant
2211 expressions.
2214 -------------------------
2217 program cannot be reached, even if the compiler might otherwise think it can.
2218 This is useful to improve optimization and eliminates certain warnings. For
2221 declared '``noreturn``' should not return" warning.
2225 .. code-block:: c++
2231 .. code-block:: c++
2241 The ``__builtin_unreachable()`` builtin has completely undefined behavior.
2243 the optimizer can take advantage of this to produce better code. This builtin
2244 takes no arguments and produces a void result.
2246 Query for this feature with ``__has_builtin(__builtin_unreachable)``.
2249 ---------------------------
2252 unpredictable by hardware mechanisms such as branch prediction logic.
2256 .. code-block:: c++
2262 .. code-block:: c++
2264 if (__builtin_unpredictable(x > 0)) {
2271 flow conditions such as in ``if`` and ``switch`` statements.
2273 Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
2276 ---------------
2278 ``__sync_swap`` is used to atomically swap integers or pointers in memory.
2282 .. code-block:: c++
2284 type __sync_swap(type *ptr, type value, ...)
2288 .. code-block:: c++
2296 new value. More importantly, it helps developers write more efficient and
2299 implementation details of ``__sync_lock_test_and_set()``. The
2300 ``__sync_swap()`` builtin is a full barrier.
2303 -----------------------
2305 ``__builtin_addressof`` performs the functionality of the built-in ``&``
2306 operator, ignoring any ``operator&`` overload. This is useful in constant
2308 object that overloads ``operator&``.
2312 .. code-block:: c++
2319 ------------------------------------------------------------
2324 ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
2327 <https://en.cppreference.com/w/cpp/memory/new/operator_new>`_.
2333 <https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_.
2336 and other similar allocation libraries, and are only available in C++.
2341 * If the value is at least ``201802L``, the builtins behave as described above.
2343 * If the value is non-zero, the builtins may not support calling arbitrary
2345 ``::operator new(size_t)`` and ``::operator delete(void*)``.
2348 -----------------------------------
2351 array subscript access and structure/union member access are relocatable
2352 under bpf compile-once run-everywhere framework. Debuginfo (typically
2353 with ``-g``) is needed, otherwise, the compiler will exit with an error.
2355 argument.
2359 .. code-block:: c
2365 .. code-block:: c
2375 struct t *v = ...;
2376 int *pb =__builtin_preserve_access_index(&v->c[3].b);
2377 __builtin_preserve_access_index(v->j);
2380 ----------------------------------
2383 manner amenable to C. They all have the following form:
2385 .. code-block:: c
2387 unsigned x = ..., y = ..., carryin = ..., carryout;
2392 .. code-block:: c
2394 unsigned *x, *y, *z, carryin=0, carryout;
2395 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
2405 .. code-block:: c
2419 ---------------------------
2422 critical applications in a manner that is fast and easily expressible in C. As
2425 .. code-block:: c
2427 errorcode_t security_critical_application(...) {
2429 ...
2432 ...
2434 ...
2439 .. code-block:: c
2464 first two arguments and stores the result in the third argument. If
2465 possible, the result will be equal to mathematically-correct result
2466 and the builtin will return 0. Otherwise, the builtin will return
2468 to the mathematically-correct result modulo two raised to the *k*
2469 power, where *k* is the number of bits in the result type. The
2470 behavior of these builtins is well-defined for all argument values.
2473 including boolean types. The operands need not have the same type as each
2474 other, or as the result. The other builtins may implicitly promote or
2475 convert their operands before performing the operation.
2477 Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
2480 ---------------------------------------
2483 --------------------------
2485 .. code-block:: c
2492 number. This canonicalization is useful for implementing certain
2493 numeric primitives such as frexp. See `LLVM canonicalize intrinsic
2494 <https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
2495 more information on the semantics.
2498 ---------------
2502 ``<string.h>`` and ``<wchar.h>``:
2505 * ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``)
2518 by ``__builtin_``. Example:
2520 .. code-block:: c
2526 .. code-block:: c
2533 is disallowed in general).
2537 despite these functions accepting an argument of type ``const void*``.
2540 with ``__has_feature(cxx_constexpr_string_builtins)``.
2543 ---------------
2547 ``<string.h>`` and ``<wchar.h>``:
2555 by ``__builtin_``.
2560 the number of elements accessible through the source and destination operands.
2565 .. code-block:: c
2571 ``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also
2572 guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline
2573 <https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic
2574 for more information.
2577 ``libc`` memcpy or work around the absence of a ``libc``.
2579 Note that the `size` argument must be a compile time constant.
2581 Note that this intrinsic cannot yet be called in a ``constexpr`` context.
2584 Atomic Min/Max builtins with memory ordering
2585 --------------------------------------------
2587 There are two atomic builtins with min/max in-memory comparison and swap.
2588 The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
2593 The builtins work with signed and unsigned integers and require to specify memory ordering.
2594 The return value is the original value that was stored in memory before comparison.
2598 .. code-block:: c
2604 ``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
2606 In terms or aquire-release ordering barriers these two operations are always
2607 considered as operations with *load-store* semantics, even when the original value
2608 is not actually modified after comparison.
2610 .. _langext-__c11_atomic:
2613 ---------------------
2616 C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
2618 ``__c11_`` prefix. The supported operations, and the differences from
2625 ``_Atomic(...)`` object, instead of its address)
2642 ``memory_order`` enumeration.
2644 (Note that Clang additionally provides GCC-compatible ``__atomic_*``
2645 builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
2647 builtin function, and are named with a ``__opencl_`` prefix. The macros
2651 corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
2653 Low-level ARM exclusive memory builtins
2654 ---------------------------------------
2657 instructions for implementing atomic operations.
2659 .. code-block:: c
2669 * Integer types with width at most 64 bits (or 128 bits on AArch64).
2670 * Floating-point types
2671 * Pointer types.
2675 ``strex``. In practice this is only usually a risk when the extra store is on
2678 with automatic storage duration.
2681 ``strex``. Clang will not necessarily mitigate the effects of these either, so
2682 care should be exercised.
2685 possible.
2687 Non-temporal load/store builtins
2688 --------------------------------
2690 Clang provides overloaded builtins allowing generation of non-temporal memory
2691 accesses.
2693 .. code-block:: c
2700 * Integer types.
2701 * Floating-point types.
2702 * Vector types.
2704 Note that the compiler does not guarantee that non-temporal loads or stores
2705 will be used.
2708 --------------------------------
2710 .. warning::
2711 This is a work in progress. Compatibility across Clang/LLVM releases is not
2712 guaranteed.
2715 https://wg21.link/P0057. The following four are intended to be used by the
2716 standard library to implement `std::experimental::coroutine_handle` type.
2720 .. code-block:: c
2729 .. code-block:: c++
2735 // ...
2741 // ...
2744 __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
2748 p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
2749 /*from-promise=*/true);
2756 development of the coroutine feature. See `Coroutines in LLVM
2757 <https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
2758 more information on their semantics. Note that builtins matching the intrinsics
2759 that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
2760 llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
2761 an appropriate value during the emission.
2765 .. code-block:: c
2778 Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
2779 automatically will insert one if the first argument to `llvm.coro.suspend` is
2780 token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
2781 as the first argument to the intrinsic.
2784 ------------------------
2787 of ``std::experimental::source_location`` as specified in http://wg21.link/N4600.
2789 GCC.
2793 .. code-block:: c
2798 unsigned __builtin_COLUMN(); // Clang only
2802 .. code-block:: c++
2804 void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
2814 int line = __builtin_LINE(); // captures line where aggregate initialization occurs
2816 static_assert(MyAggregateType{42}.line == __LINE__);
2819 int line = __builtin_LINE(); // captures line of the constructor used during initialization
2827 ``__FILE__`` respectively. These builtins are constant expressions.
2830 point is the location of the caller. When the builtins appear as part of a
2832 constructor or aggregate initialization used to create the object. Otherwise
2833 the invocation point is the same as the location of the builtin.
2836 empty string is returned.
2839 ------------------
2841 pointers and integers.
2842 These builtins can be used to avoid relying on implementation-defined behavior
2843 of arithmetic on integers derived from pointers.
2845 arithmetic, they can perform semantic checking on the alignment value.
2849 .. code-block:: c
2858 .. code-block:: c++
2863 // result now contains the value of global_alloc_buffer rounded up to the
2864 // next multiple of alignment.
2881 // In addition to pointers, the builtins can also be used on integer types
2882 // and are evaluatable inside constant expressions.
2891 first argument aligned up/down to the next multiple of the second argument.
2892 If the value is already sufficiently aligned, it is returned unchanged.
2894 aligned to a multiple of the second argument.
2895 All of these builtins expect the alignment to be expressed as a number of bytes.
2897 These builtins can be used for all integer types as well as (non-function)
2898 pointer types. For pointer types, these builtins operate in terms of the integer
2900 qualifiers such as ``const``) with an adjusted address.
2902 underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]).
2903 This means that arbitrary integer values stored in pointer-type variables must
2904 not be passed to these builtins. For those use cases, the builtins can still be
2905 used, but the operation must be performed on the pointer cast to ``uintptr_t``.
2908 it will result in a compilation failure. If the alignment argument is not a
2909 power of two at run time, the behavior of these builtins is undefined.
2911 Non-standard C++11 Attributes
2914 Clang's non-standard C++11 attributes live in the ``clang`` attribute
2915 namespace.
2917 Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
2919 ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
2921 <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
2922 attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
2924 <https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
2925 implementation, these attributes must appertain to the *declarator-id* in a
2927 immediately after the name being declared.
2930 also applies the GNU ``noreturn`` attribute to ``f``.
2932 .. code-block:: c++
2936 Target-Specific Extensions
2939 Clang supports some language features conditionally on some targets.
2941 ARM/AArch64 Language Extensions
2942 -------------------------------
2948 <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
2950 reordering of memory accesses and side effect instructions. Other instructions
2951 like simple arithmetic may be reordered around the intrinsic. If you expect to
2952 have no reordering at all, use inline assembly instead.
2954 X86/X86-64 Language Extensions
2955 ------------------------------
2965 relative to the X86 SS segment. Note that this is a very very low-level
2967 an OS kernel).
2971 .. code-block:: c++
2978 Which compiles to (on X86-32):
2980 .. code-block:: gas
2988 the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``
2989 indicate their support.
2992 ------------------------------
2996 PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
2997 the floating point rounding mode. This function will use the least significant
2998 two bits of integer argument to set the floating point rounding mode.
3000 .. code-block:: c++
3006 - 0 - round to nearest
3007 - 1 - round to zero
3008 - 2 - round to +infinity
3009 - 3 - round to -infinity
3012 than 3, it will only use the least significant two bits of the mode.
3013 Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
3018 The PowerPC architecture specifies instructions implementing cache operations.
3020 instructions.
3025 to main memory and flushes the copy from the data cache.
3029 .. code-block:: c
3031 void __dcbf(const void* addr); /* Data Cache Block Flush */
3035 .. code-block:: c
3045 Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
3046 in the analyzer's `list of source-level annotations
3047 <https://clang-analyzer.llvm.org/annotations.html>`_.
3054 with :doc:`AddressSanitizer`.
3057 with :doc:`ThreadSanitizer`.
3060 with :doc:`MemorySanitizer`.
3063 with :doc:`SafeStack`.
3070 and methods.
3072 To disable optimizations in a single function definition, the GNU-style or C++11
3073 non-standard attribute ``optnone`` can be used.
3075 .. code-block:: c++
3077 // The following functions will not be optimized.
3078 // GNU-style attribute
3080 // ... code
3082 // C++11 attribute
3084 // ... code
3088 range-based pragma is provided. Its syntax is ``#pragma clang optimize``
3089 followed by ``off`` or ``on``.
3093 conflict with explicit attributes already present on the function (e.g. the
3094 ones that control inlining).
3096 .. code-block:: c++
3099 // This function will be decorated with optnone.
3101 // ... code
3104 // optnone conflicts with always_inline, so bar() will not be decorated.
3106 // ... code
3111 end of the compilation unit.
3114 additional optimizations when compiling at low optimization levels. This feature
3115 can only be used to selectively disable optimizations.
3119 instantiation is not necessarily relevant. Consider the following example:
3121 .. code-block:: c++
3138 the pragma region, whereas the definition of ``thrice`` is inside the region.
3142 was outside the region) and ``thrice`` will not be optimized.
3148 subsequent for, while, do-while, or c++11 range-based for loop. The directive
3150 distribution. Loop hints can be specified before any loop and will be ignored if
3151 the optimization is not safe to apply.
3153 There are loop hints that control transformations (e.g. vectorization, loop
3154 unrolling) and there are loop hints that set transformation options (e.g.
3155 ``vectorize_width``, ``unroll_count``). Pragmas setting transformation options
3157 transformation pragma (e.g. ``vectorize(enable)``). If the transformation is
3158 disabled (e.g. ``vectorize(disable)``), that takes precedence over
3159 transformations option pragmas implying that transformation.
3162 --------------------------------------------
3165 in parallel using vector instructions. The instruction set of the target
3167 widths. This restricts the types of loops that can be vectorized. The vectorizer
3168 automatically determines if the loop is safe and profitable to vectorize. A
3169 vector instruction cost model is used to select the vector width.
3172 improve instruction-level parallelism (ILP) using advanced hardware features,
3173 such as multiple execution units and out-of-order execution. The vectorizer uses
3175 select the interleaving count.
3178 by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
3179 manually enable vectorization or interleaving.
3181 .. code-block:: c++
3185 for(...) {
3186 ...
3192 second parameter. The default for the second parameter is 'fixed' and
3194 compiler should use scalable vectors instead. Another use of vectorize_width
3196 of vectorization to use without specifying the exact width. In both variants
3198 vectorization if the target does not support scalable vectors.
3201 _value_ is a positive integer. This is useful for specifying the optimal
3202 width/count of the set of target architectures supported by your application.
3204 .. code-block:: c++
3208 for(...) {
3209 ...
3212 Specifying a width/count of 1 disables the optimization, and is equivalent to
3213 ``vectorize(disable)`` or ``interleave(disable)``.
3217 .. code-block:: c++
3221 for(...) {
3222 ...
3226 remainder loop (the tail) to be folded into the main vectorized loop. This
3228 target platform.
3231 --------------
3234 opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
3236 iterations. Full unrolling is only possible if the loop trip count is known at
3237 compile time. Partial unrolling replicates the loop body within the loop and
3238 reduces the trip count.
3241 loop if the trip count is known at compile time. If the fully unrolled code size
3243 limit. If the trip count is not known at compile time the loop will be partially
3244 unrolled with a heuristically chosen unroll factor.
3246 .. code-block:: c++
3249 for(...) {
3250 ...
3255 ``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
3256 if the loop count is not known at compile time.
3258 .. code-block:: c++
3261 for(...) {
3262 ...
3266 _value_ is a positive integer. If this value is greater than the trip count the
3267 loop will be fully unrolled. Otherwise the loop is partially unrolled subject
3268 to the same code size limit as with ``unroll(enable)``.
3270 .. code-block:: c++
3273 for(...) {
3274 ...
3277 Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
3280 -----------------
3282 Loop Distribution allows splitting a loop into multiple loops. This is
3284 resulting loops can.
3288 operations into a new loop. This optimization is not enabled by default, only
3289 loops marked with the pragma are considered.
3291 .. code-block:: c++
3294 for (i = 0; i < N; ++i) {
3299 This loop will be split into two loops between statements S1 and S2. The
3300 second loop containing S2 will be vectorized.
3303 it can hurt performance in some cases. For example, instruction-level
3305 statements S1 and S2 above.
3308 ``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
3309 be used the disable it on a per-loop basis.
3312 ----------------------
3314 For convenience multiple loop hints can be specified on a single line.
3316 .. code-block:: c++
3319 for(...) {
3320 ...
3323 If an optimization cannot be applied any hints that apply to it will be ignored.
3325 proven safe to vectorize. To identify and diagnose optimization issues use
3326 `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
3327 user guide for details.
3329 Extensions to specify floating-point flags
3332 The ``#pragma clang fp`` pragma allows floating-point options to be specified
3333 for a section of the source code. This pragma can only appear at file scope or
3334 at the start of a compound statement (excluding comments). When using within a
3336 statement.
3341 of floating point expressions. When enabled, this pragma allows the expression
3342 ``x + (y + z)`` to be reassociated as ``(x + y) + z``.
3343 Reassociation can also occur across multiple statements.
3345 enabled for the translation unit with the ``-fassociative-math`` flag.
3346 The pragma can take two values: ``on`` and ``off``.
3348 .. code-block:: c++
3352 // Enable floating point reassociation across statements
3361 operation when supported by the target.
3363 The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on``
3365 fusion as specified the language standard. The ``fast`` option allows fusion
3366 in cases when the language standard does not make this possible (e.g. across
3367 statements in C).
3369 .. code-block:: c++
3371 for(...) {
3379 section of the code. This can be useful when fast contraction is otherwise
3380 enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag.
3381 Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and
3382 addition across statements regardless of any controlling pragmas.
3384 ``#pragma clang fp exceptions`` specifies floating point exception behavior. It
3385 may take one the the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of
3386 …strained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-i…
3388 .. code-block:: c++
3391 // Preserve floating point exceptions
3395 ...
3400 .. code-block:: c++
3404 ...
3408 The ``#pragma float_control`` pragma allows precise floating-point
3409 semantics and floating-point exception behavior to be specified
3410 for a section of the source code. This pragma can only appear at file scope or
3411 at the start of a compound statement (excluding comments). When using within a
3413 statement. This pragma is modeled after a Microsoft pragma with the
3414 same spelling and syntax. For pragmas specified at file scope, a stack
3415 is supported so that the ``pragma float_control`` settings can be pushed or popped.
3419 ``-ffast-math`` is disabled and ``-ffp-contract=on``
3420 (fused multiply add) is enabled.
3423 by the pragma behaves as though the command-line option
3424 ``-ffp-exception-behavior=strict`` is enabled,
3426 governed by the pragma behaves as though the command-line option
3427 ``-ffp-exception-behavior=ignore`` is enabled.
3431 ``float_control(push|pop)``.
3433 third argument, can only occur at file scope.
3435 .. code-block:: c++
3437 for(...) {
3438 // This block will be compiled with -fno-fast-math and -ffp-contract=on
3447 multiple declarations. The ``#pragma clang attribute push`` variation of the
3449 can be added to. The ``#pragma clang attribute (...)`` variation adds an
3451 the scope. You can also use ``#pragma clang attribute push (...)``, which is a
3452 shorthand for when you want to add one attribute to a new scope. Multiple push
3453 directives can be nested inside each other.
3456 can be written using the GNU-style syntax:
3458 .. code-block:: c++
3462 void function(); // The function now has the annotate("custom") attribute
3468 .. code-block:: c++
3472 void function(); // The function now has the [[noreturn]] attribute
3478 .. code-block:: c++
3482 void function(); // The function now has the __declspec(dllexport) attribute
3487 used.
3490 expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
3491 required) to add a namespace to your push/pop directives. A pop directive with a
3492 namespace will pop the innermost push that has that same namespace. This will
3493 ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
3495 namespace. ``push``es with a namespace can only be popped by ``pop`` with the
3496 same namespace. For instance:
3498 .. code-block:: c++
3500 …#define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to…
3501 #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop")
3503 …#define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavail…
3504 #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop")
3509 void function(); // function has [[noreturn]] and __attribute__((unavailable))
3511 void other_function(); // function has __attribute__((unavailable))
3515 ``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
3517 in real code if the pragmas are spread out across a large file. You can test if
3519 ``__has_extension(pragma_clang_attribute_namespaces)``.
3522 -------------------
3525 depends on the subject match rules that were specified in the pragma. Subject
3526 match rules are specified after the attribute. The compiler expects an
3527 identifier that corresponds to the subject set specifier. The ``apply_to``
3528 specifier is currently the only supported subject set specifier. It allows you
3530 set, i.e. the compiler doesn't require all of the attribute's subjects. For
3535 .. code-block:: c++
3539 enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
3541 struct Record1 { }; // The struct will *not* receive [[nodiscard]]
3547 enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
3549 struct Record2 { }; // The struct *will* receive [[nodiscard]]
3553 // This is an error, since [[nodiscard]] can't be applied to namespaces:
3559 in the example above. The ``any`` rule applies attributes to all declarations
3560 that are matched by at least one of the rules in the ``any``. It doesn't nest
3561 and can't be used inside the other match rules. Redundant match rules or rules
3562 that conflict with one another should not be used inside of ``any``.
3566 - ``function``: Can be used to apply attributes to functions. This includes C++
3567 member functions, static functions, operators, and constructors/destructors.
3569 - ``function(is_member)``: Can be used to apply attributes to C++ member
3570 functions. This includes members like static functions, operators, and
3571 constructors/destructors.
3573 - ``hasType(functionType)``: Can be used to apply attributes to functions, C++
3574 member functions, and variables/fields whose type is a function pointer. It
3575 does not apply attributes to Objective-C methods or blocks.
3577 - ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
3578 and C++11 type aliases.
3580 - ``record``: Can be used to apply attributes to ``struct``, ``class``, and
3581 ``union`` declarations.
3583 - ``record(unless(is_union))``: Can be used to apply attributes only to
3584 ``struct`` and ``class`` declarations.
3586 - ``enum``: Can be be used to apply attributes to enumeration declarations.
3588 - ``enum_constant``: Can be used to apply attributes to enumerators.
3590 - ``variable``: Can be used to apply attributes to variables, including
3591 local variables, parameters, global variables, and static member variables.
3592 It does not apply attributes to instance member variables or Objective-C
3593 ivars.
3595 - ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
3596 variables only.
3598 - ``variable(is_global)``: Can be used to apply attributes to global variables
3599 only.
3601 - ``variable(is_local)``: Can be used to apply attributes to local variables
3602 only.
3604 - ``variable(is_parameter)``: Can be used to apply attributes to parameters
3605 only.
3607 - ``variable(unless(is_parameter))``: Can be used to apply attributes to all
3608 the variables that are not parameters.
3610 - ``field``: Can be used to apply attributes to non-static member variables
3611 in a record. This includes Objective-C ivars.
3613 - ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
3615 - ``objc_interface``: Can be used to apply attributes to ``@interface``
3616 declarations.
3618 - ``objc_protocol``: Can be used to apply attributes to ``@protocol``
3619 declarations.
3621 - ``objc_category``: Can be used to apply attributes to category declarations,
3622 including class extensions.
3624 - ``objc_method``: Can be used to apply attributes to Objective-C methods,
3625 including instance and class methods. Implicit methods like implicit property
3626 getters and setters do not receive the attribute.
3628 - ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
3629 instance methods.
3631 - ``objc_property``: Can be used to apply attributes to ``@property``
3632 declarations.
3634 - ``block``: Can be used to apply attributes to block declarations. This does
3635 not include variables/fields of block pointer type.
3638 sub-rules that are used by the supported attributes. That means that even though
3640 ``variable(unless(is_thread_local))`` is not.
3643 --------------------
3645 Not all attributes can be used with the ``#pragma clang attribute`` directive.
3647 like ``address_space`` aren't supported by this directive. You can determine
3649 :doc:`individual documentation for that attribute <AttributeReference>`.
3652 the attribute is semantically incorrect. The attributes that aren't applied to
3653 any declaration are not verified semantically.
3658 The ``#pragma clang section`` directive provides a means to assign section-names
3659 to global variables, functions and static variables.
3663 .. code-block:: c++
3667 The section names can be reverted back to default name by supplying an empty
3670 .. code-block:: c++
3677 from the pragma to the end of the translation unit.
3679 * The pragma clang section is enabled automatically, without need of any flags.
3681 * This feature is only defined to work sensibly for ELF targets.
3684 the attribute name gains precedence.
3687 bss section, if one is present.
3689 * The ``#pragma clang section`` directive does not does try to infer section-kind
3690 from the name. For example, naming a section "``.bss.mySec``" does NOT mean
3691 it will be a bss section name.
3693 * The decision about which section-kind applies to each global is taken in the back-end.
3694 Once the section-kind is known, appropriate section name, as specified by the user using
3695 ``#pragma clang section`` directive, is applied to that global.
3700 The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
3702 ``lib``). This allows you to provide an implicit link of dependent libraries.
3709 ``__builtin_dynamic_object_size`` can evaluate the object's size at runtime.
3710 ``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement
3711 for ``__builtin_object_size`` in libraries that support it.
3716 .. code-block:: c
3721 // Previous line preprocesses to:
3722// __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buf…
3726 ``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
3727 as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
3728 ``size``, providing some extra runtime safety.
3735 the type, including the sign bit. The keyword ``_ExtInt`` is a type specifier, thus
3736 it can be used in any place a type can, including as a non-type-template-parameter,
3737 as the type of a bitfield, and as the underlying type of an enumeration.
3740 ``signed``/``unsigned`` keywords. If no sign specifier is used or if the ``signed``
3742 negative values.
3746 both signed and unsigned types. Both a signed and unsigned extended integer of the
3747 same ``N`` value will have the same number of bits in its representation. Many
3748 architectures don't have a way of representing non power-of-2 integers, so these
3749 architectures emulate these types using larger integers. In these cases, they are
3750 expected to follow the 'as-if' rule and do math 'as-if' they were done at the
3751 specified number of bits.
3755 standard integer conversion ranks. An extended integer type has a greater rank than
3756 any integer type with less precision. However, they have lower rank than any
3757 of the built in or other integer types (such as __int128). Usual arithmetic conversions
3758 also work the same, where the smaller ranked integer is converted to the larger.
3760 The one exception to the C rules for integers for these types is Integer Promotion.
3761 Unary +, -, and ~ operators typically will promote operands to ``int``. Doing these
3763 integer types aren't subject to the integer promotion rules in these cases.
3765 In languages (such as OpenCL) that define shift by-out-of-range behavior as a mask,
3766 non-power-of-two versions of these types use an unsigned remainder operation to constrain
3767 the value to the proper range, preventing undefined behavior.
3769 Extended integer types are aligned to the next greatest power-of-2 up to 64 bits.
3771 bits aligned to this calculated alignment. This permits the use of these types in
3772 allocated arrays using common ``sizeof(Array)/sizeof(ElementType)`` pattern.
3775 that are powers-of-2 greater than 8 bit are accepted.
3777 Extended integer types align with existing calling conventions. They have the same size
3778 and alignment as the smallest basic type that can contain them. Types that are larger
3780 treated as struct of register size chunks. They number of chunks are the smallest
3781 number that can contain the types which does not necessarily mean a power-of-2 size.
3833 The following x86-specific intrinsics can be used in constant expressions: