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
17Introduction
18============
19
20This document describes the language extensions provided by Clang.  In addition
21to the language extensions listed here, Clang aims to support a broad range of
22GCC extensions.  Please see the `GCC manual
23<http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
24these extensions.
25
26.. _langext-feature_check:
27
28Feature Checking Macros
29=======================
30
31Language extensions can be very useful, but only if you know you can depend on
32them.  In order to allow fine-grain features checks, we support three builtin
33function-like macros.  This allows you to directly test for a feature in your
34code without having to resort to something like autoconf or fragile "compiler
35version checks".
36
37``__has_builtin``
38-----------------
39
40This function-like macro takes a single identifier argument that is the name of
41a builtin function.  It evaluates to 1 if the builtin is supported or 0 if not.
42It can be used like this:
43
44.. code-block:: c++
45
46  #ifndef __has_builtin         // Optional of course.
47    #define __has_builtin(x) 0  // Compatibility with non-clang compilers.
48  #endif
49
50  ...
51  #if __has_builtin(__builtin_trap)
52    __builtin_trap();
53  #else
54    abort();
55  #endif
56  ...
57
58.. _langext-__has_feature-__has_extension:
59
60``__has_feature`` and ``__has_extension``
61-----------------------------------------
62
63These function-like macros take a single identifier argument that is the name
64of a feature.  ``__has_feature`` evaluates to 1 if the feature is both
65supported by Clang and standardized in the current language standard or 0 if
66not (but see :ref:`below <langext-has-feature-back-compat>`), while
67``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
68current language (either as a language extension or a standard language
69feature) or 0 if not.  They can be used like this:
70
71.. code-block:: c++
72
73  #ifndef __has_feature         // Optional of course.
74    #define __has_feature(x) 0  // Compatibility with non-clang compilers.
75  #endif
76  #ifndef __has_extension
77    #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
78  #endif
79
80  ...
81  #if __has_feature(cxx_rvalue_references)
82  // This code will only be compiled with the -std=c++11 and -std=gnu++11
83  // options, because rvalue references are only standardized in C++11.
84  #endif
85
86  #if __has_extension(cxx_rvalue_references)
87  // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
88  // and -std=gnu++98 options, because rvalue references are supported as a
89  // language extension in C++98.
90  #endif
91
92.. _langext-has-feature-back-compat:
93
94For backward compatibility, ``__has_feature`` can also be used to test
95for support for non-standardized features, i.e. features not prefixed ``c_``,
96``cxx_`` or ``objc_``.
97
98Another use of ``__has_feature`` is to check for compiler features not related
99to the language standard, such as e.g. :doc:`AddressSanitizer
100<AddressSanitizer>`.
101
102If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
103to ``__has_feature``.
104
105The feature tag is described along with the language feature below.
106
107The feature name or extension name can also be specified with a preceding and
108following ``__`` (double underscore) to avoid interference from a macro with
109the same name.  For instance, ``__cxx_rvalue_references__`` can be used instead
110of ``cxx_rvalue_references``.
111
112``__has_cpp_attribute``
113-----------------------
114
115This function-like macro is available in C++2a by default, and is provided as an
116extension in earlier language standards. It takes a single argument that is the
117name of a double-square-bracket-style attribute. The argument can either be a
118single identifier or a scoped identifier. If the attribute is supported, a
119nonzero value is returned. If the attribute is a standards-based attribute, this
120macro returns a nonzero value based on the year and month in which the attribute
121was voted into the working draft. See `WG21 SD-6
122<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
123for the list of values returned for standards-based attributes. If the attribute
124is not supported by the current compliation target, this macro evaluates to 0.
125It can be used like this:
126
127.. code-block:: c++
128
129  #ifndef __has_cpp_attribute         // For backwards compatibility
130    #define __has_cpp_attribute(x) 0
131  #endif
132
133  ...
134  #if __has_cpp_attribute(clang::fallthrough)
135  #define FALLTHROUGH [[clang::fallthrough]]
136  #else
137  #define FALLTHROUGH
138  #endif
139  ...
140
141The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
142the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
143of these namespaces can be specified with a preceding and following ``__``
144(double underscore) to avoid interference from a macro with the same name. For
145instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
146
147``__has_c_attribute``
148---------------------
149
150This function-like macro takes a single argument that is the name of an
151attribute exposed with the double square-bracket syntax in C mode. The argument
152can either be a single identifier or a scoped identifier. If the attribute is
153supported, a nonzero value is returned. If the attribute is not supported by the
154current compilation target, this macro evaluates to 0. It can be used like this:
155
156.. code-block:: c
157
158  #ifndef __has_c_attribute         // Optional of course.
159    #define __has_c_attribute(x) 0  // Compatibility with non-clang compilers.
160  #endif
161
162  ...
163  #if __has_c_attribute(fallthrough)
164    #define FALLTHROUGH [[fallthrough]]
165  #else
166    #define FALLTHROUGH
167  #endif
168  ...
169
170The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
171the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
172of these namespaces can be specified with a preceding and following ``__``
173(double underscore) to avoid interference from a macro with the same name. For
174instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
175
176``__has_attribute``
177-------------------
178
179This function-like macro takes a single identifier argument that is the name of
180a GNU-style attribute.  It evaluates to 1 if the attribute is supported by the
181current compilation target, or 0 if not.  It can be used like this:
182
183.. code-block:: c++
184
185  #ifndef __has_attribute         // Optional of course.
186    #define __has_attribute(x) 0  // Compatibility with non-clang compilers.
187  #endif
188
189  ...
190  #if __has_attribute(always_inline)
191  #define ALWAYS_INLINE __attribute__((always_inline))
192  #else
193  #define ALWAYS_INLINE
194  #endif
195  ...
196
197The attribute name can also be specified with a preceding and following ``__``
198(double underscore) to avoid interference from a macro with the same name.  For
199instance, ``__always_inline__`` can be used instead of ``always_inline``.
200
201
202``__has_declspec_attribute``
203----------------------------
204
205This function-like macro takes a single identifier argument that is the name of
206an attribute implemented as a Microsoft-style ``__declspec`` attribute.  It
207evaluates to 1 if the attribute is supported by the current compilation target,
208or 0 if not.  It can be used like this:
209
210.. code-block:: c++
211
212  #ifndef __has_declspec_attribute         // Optional of course.
213    #define __has_declspec_attribute(x) 0  // Compatibility with non-clang compilers.
214  #endif
215
216  ...
217  #if __has_declspec_attribute(dllexport)
218  #define DLLEXPORT __declspec(dllexport)
219  #else
220  #define DLLEXPORT
221  #endif
222  ...
223
224The attribute name can also be specified with a preceding and following ``__``
225(double underscore) to avoid interference from a macro with the same name.  For
226instance, ``__dllexport__`` can be used instead of ``dllexport``.
227
228``__is_identifier``
229-------------------
230
231This function-like macro takes a single identifier argument that might be either
232a reserved word or a regular identifier. It evaluates to 1 if the argument is just
233a regular identifier and not a reserved word, in the sense that it can then be
234used as the name of a user-defined function or variable. Otherwise it evaluates
235to 0.  It can be used like this:
236
237.. code-block:: c++
238
239  ...
240  #ifdef __is_identifier          // Compatibility with non-clang compilers.
241    #if __is_identifier(__wchar_t)
242      typedef wchar_t __wchar_t;
243    #endif
244  #endif
245
246  __wchar_t WideCharacter;
247  ...
248
249Include File Checking Macros
250============================
251
252Not all developments systems have the same include files.  The
253:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
254you to check for the existence of an include file before doing a possibly
255failing ``#include`` directive.  Include file checking macros must be used
256as expressions in ``#if`` or ``#elif`` preprocessing directives.
257
258.. _langext-__has_include:
259
260``__has_include``
261-----------------
262
263This function-like macro takes a single file name string argument that is the
264name of an include file.  It evaluates to 1 if the file can be found using the
265include paths, or 0 otherwise:
266
267.. code-block:: c++
268
269  // Note the two possible file name string formats.
270  #if __has_include("myinclude.h") && __has_include(<stdint.h>)
271  # include "myinclude.h"
272  #endif
273
274To test for this feature, use ``#if defined(__has_include)``:
275
276.. code-block:: c++
277
278  // To avoid problem with non-clang compilers not having this macro.
279  #if defined(__has_include)
280  #if __has_include("myinclude.h")
281  # include "myinclude.h"
282  #endif
283  #endif
284
285.. _langext-__has_include_next:
286
287``__has_include_next``
288----------------------
289
290This function-like macro takes a single file name string argument that is the
291name of an include file.  It is like ``__has_include`` except that it looks for
292the second instance of the given file found in the include paths.  It evaluates
293to 1 if the second instance of the file can be found using the include paths,
294or 0 otherwise:
295
296.. code-block:: c++
297
298  // Note the two possible file name string formats.
299  #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
300  # include_next "myinclude.h"
301  #endif
302
303  // To avoid problem with non-clang compilers not having this macro.
304  #if defined(__has_include_next)
305  #if __has_include_next("myinclude.h")
306  # include_next "myinclude.h"
307  #endif
308  #endif
309
310Note that ``__has_include_next``, like the GNU extension ``#include_next``
311directive, is intended for use in headers only, and will issue a warning if
312used in the top-level compilation file.  A warning will also be issued if an
313absolute path is used in the file argument.
314
315``__has_warning``
316-----------------
317
318This function-like macro takes a string literal that represents a command line
319option for a warning and returns true if that is a valid warning option.
320
321.. code-block:: c++
322
323  #if __has_warning("-Wformat")
324  ...
325  #endif
326
327Builtin Macros
328==============
329
330``__BASE_FILE__``
331  Defined to a string that contains the name of the main input file passed to
332  Clang.
333
334``__COUNTER__``
335  Defined to an integer value that starts at zero and is incremented each time
336  the ``__COUNTER__`` macro is expanded.
337
338``__INCLUDE_LEVEL__``
339  Defined to an integral value that is the include depth of the file currently
340  being translated.  For the main file, this value is zero.
341
342``__TIMESTAMP__``
343  Defined to the date and time of the last modification of the current source
344  file.
345
346``__clang__``
347  Defined when compiling with Clang
348
349``__clang_major__``
350  Defined to the major marketing version number of Clang (e.g., the 2 in
351  2.0.1).  Note that marketing version numbers should not be used to check for
352  language features, as different vendors use different numbering schemes.
353  Instead, use the :ref:`langext-feature_check`.
354
355``__clang_minor__``
356  Defined to the minor version number of Clang (e.g., the 0 in 2.0.1).  Note
357  that marketing version numbers should not be used to check for language
358  features, as different vendors use different numbering schemes.  Instead, use
359  the :ref:`langext-feature_check`.
360
361``__clang_patchlevel__``
362  Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
363
364``__clang_version__``
365  Defined to a string that captures the Clang marketing version, including the
366  Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
367
368.. _langext-vectors:
369
370Vectors and Extended Vectors
371============================
372
373Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
374
375OpenCL vector types are created using ``ext_vector_type`` attribute.  It
376support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL.  An example
377is:
378
379.. code-block:: c++
380
381  typedef float float4 __attribute__((ext_vector_type(4)));
382  typedef float float2 __attribute__((ext_vector_type(2)));
383
384  float4 foo(float2 a, float2 b) {
385    float4 c;
386    c.xz = a;
387    c.yw = b;
388    return c;
389  }
390
391Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
392
393Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
394and functions.  For example:
395
396.. code-block:: c++
397
398  vector float foo(vector int a) {
399    vector int b;
400    b = vec_add(a, a) + a;
401    return (vector float)b;
402  }
403
404NEON vector types are created using ``neon_vector_type`` and
405``neon_polyvector_type`` attributes.  For example:
406
407.. code-block:: c++
408
409  typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
410  typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
411
412  int8x8_t foo(int8x8_t a) {
413    int8x8_t v;
414    v = a;
415    return v;
416  }
417
418Vector Literals
419---------------
420
421Vector literals can be used to create vectors from a set of scalars, or
422vectors.  Either parentheses or braces form can be used.  In the parentheses
423form the number of literal values specified must be one, i.e. referring to a
424scalar value, or must match the size of the vector type being created.  If a
425single scalar literal value is specified, the scalar literal value will be
426replicated to all the components of the vector type.  In the brackets form any
427number of literals can be specified.  For example:
428
429.. code-block:: c++
430
431  typedef int v4si __attribute__((__vector_size__(16)));
432  typedef float float4 __attribute__((ext_vector_type(4)));
433  typedef float float2 __attribute__((ext_vector_type(2)));
434
435  v4si vsi = (v4si){1, 2, 3, 4};
436  float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
437  vector int vi1 = (vector int)(1);    // vi1 will be (1, 1, 1, 1).
438  vector int vi2 = (vector int){1};    // vi2 will be (1, 0, 0, 0).
439  vector int vi3 = (vector int)(1, 2); // error
440  vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
441  vector int vi5 = (vector int)(1, 2, 3, 4);
442  float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
443
444Vector Operations
445-----------------
446
447The table below shows the support for each operation by vector extension.  A
448dash indicates that an operation is not accepted according to a corresponding
449specification.
450
451============================== ======= ======= ======= =======
452         Operator              OpenCL  AltiVec   GCC    NEON
453============================== ======= ======= ======= =======
454[]                               yes     yes     yes     --
455unary operators +, --            yes     yes     yes     --
456++, -- --                        yes     yes     yes     --
457+,--,*,/,%                       yes     yes     yes     --
458bitwise operators &,|,^,~        yes     yes     yes     --
459>>,<<                            yes     yes     yes     --
460!, &&, ||                        yes     --      --      --
461==, !=, >, <, >=, <=             yes     yes     --      --
462=                                yes     yes     yes     yes
463:?                               yes     --      --      --
464sizeof                           yes     yes     yes     yes
465C-style cast                     yes     yes     yes     no
466reinterpret_cast                 yes     no      yes     no
467static_cast                      yes     no      yes     no
468const_cast                       no      no      no      no
469============================== ======= ======= ======= =======
470
471See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
472
473Half-Precision Floating Point
474=============================
475
476Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
477``_Float16``.  These types are supported in all language modes.
478
479``__fp16`` is supported on every target, as it is purely a storage format; see below.
480``_Float16`` is currently only supported on the following targets, with further
481targets pending ABI standardization:
482- 32-bit ARM
483- 64-bit ARM (AArch64)
484- SPIR
485``_Float16`` will be supported on more targets as they define ABIs for it.
486
487``__fp16`` is a storage and interchange format only.  This means that values of
488``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic
489operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``.
490The 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>`_).
491Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
492alternative format.
493
494``_Float16`` is an extended floating-point type.  This means that, just like arithmetic on
495``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the
496``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
497``_Float16``.  The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
498("Floating-point extensions for C").  As with ``__fp16``, Clang uses the ``binary16``
499format from IEEE 754-2008 for ``_Float16``.
500
501``_Float16`` arithmetic will be performed using native half-precision support
502when available on the target (e.g. on ARMv8.2a); otherwise it will be performed
503at a higher precision (currently always ``float``) and then truncated down to
504``_Float16``.  Note that C and C++ allow intermediate floating-point operands
505of an expression to be computed with greater precision than is expressible in
506their type, so Clang may avoid intermediate truncations in certain cases; this may
507lead to results that are inconsistent with native arithmetic.
508
509It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
510as it has been defined by the C standards committee and has behavior that is
511more familiar to most programmers.
512
513Because ``__fp16`` operands are always immediately promoted to ``float``, the
514common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
515arithmetic conversions is ``float``.
516
517A literal can be given ``_Float16`` type using the suffix ``f16``; for example:
518```
5193.14f16
520```
521
522Because default argument promotion only applies to the standard floating-point
523types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
524or untyped arguments.  As a consequence, some caution must be taken when using
525certain library facilities with ``_Float16``; for example, there is no ``printf`` format
526specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
527``double`` when passed to ``printf``, so the programmer must explicitly cast it to
528``double`` before using it with an ``%f`` or similar specifier.
529
530Messages on ``deprecated`` and ``unavailable`` Attributes
531=========================================================
532
533An optional string message can be added to the ``deprecated`` and
534``unavailable`` attributes.  For example:
535
536.. code-block:: c++
537
538  void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
539
540If the deprecated or unavailable declaration is used, the message will be
541incorporated into the appropriate diagnostic:
542
543.. code-block:: none
544
545  harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
546        [-Wdeprecated-declarations]
547    explode();
548    ^
549
550Query for this feature with
551``__has_extension(attribute_deprecated_with_message)`` and
552``__has_extension(attribute_unavailable_with_message)``.
553
554Attributes on Enumerators
555=========================
556
557Clang allows attributes to be written on individual enumerators.  This allows
558enumerators to be deprecated, made unavailable, etc.  The attribute must appear
559after the enumerator name and before any initializer, like so:
560
561.. code-block:: c++
562
563  enum OperationMode {
564    OM_Invalid,
565    OM_Normal,
566    OM_Terrified __attribute__((deprecated)),
567    OM_AbortOnError __attribute__((deprecated)) = 4
568  };
569
570Attributes on the ``enum`` declaration do not apply to individual enumerators.
571
572Query for this feature with ``__has_extension(enumerator_attributes)``.
573
574'User-Specified' System Frameworks
575==================================
576
577Clang provides a mechanism by which frameworks can be built in such a way that
578they will always be treated as being "system frameworks", even if they are not
579present in a system framework directory.  This can be useful to system
580framework developers who want to be able to test building other applications
581with development builds of their framework, including the manner in which the
582compiler changes warning behavior for system headers.
583
584Framework developers can opt-in to this mechanism by creating a
585"``.system_framework``" file at the top-level of their framework.  That is, the
586framework should have contents like:
587
588.. code-block:: none
589
590  .../TestFramework.framework
591  .../TestFramework.framework/.system_framework
592  .../TestFramework.framework/Headers
593  .../TestFramework.framework/Headers/TestFramework.h
594  ...
595
596Clang will treat the presence of this file as an indicator that the framework
597should be treated as a system framework, regardless of how it was found in the
598framework search path.  For consistency, we recommend that such files never be
599included in installed versions of the framework.
600
601Checks for Standard Language Features
602=====================================
603
604The ``__has_feature`` macro can be used to query if certain standard language
605features are enabled.  The ``__has_extension`` macro can be used to query if
606language features are available as an extension when compiling for a standard
607which does not provide them.  The features which can be tested are listed here.
608
609Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
610These are macros with names of the form ``__cpp_<feature_name>``, and are
611intended to be a portable way to query the supported features of the compiler.
612See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
613information on the version of SD-6 supported by each Clang release, and the
614macros provided by that revision of the recommendations.
615
616C++98
617-----
618
619The features listed below are part of the C++98 standard.  These features are
620enabled by default when compiling C++ code.
621
622C++ exceptions
623^^^^^^^^^^^^^^
624
625Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
626enabled.  For example, compiling code with ``-fno-exceptions`` disables C++
627exceptions.
628
629C++ RTTI
630^^^^^^^^
631
632Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled.  For
633example, compiling code with ``-fno-rtti`` disables the use of RTTI.
634
635C++11
636-----
637
638The features listed below are part of the C++11 standard.  As a result, all
639these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
640when compiling C++ code.
641
642C++11 SFINAE includes access control
643^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
644
645Use ``__has_feature(cxx_access_control_sfinae)`` or
646``__has_extension(cxx_access_control_sfinae)`` to determine whether
647access-control errors (e.g., calling a private constructor) are considered to
648be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
649<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
650
651C++11 alias templates
652^^^^^^^^^^^^^^^^^^^^^
653
654Use ``__has_feature(cxx_alias_templates)`` or
655``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
656alias declarations and alias templates is enabled.
657
658C++11 alignment specifiers
659^^^^^^^^^^^^^^^^^^^^^^^^^^
660
661Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
662determine if support for alignment specifiers using ``alignas`` is enabled.
663
664Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
665determine if support for the ``alignof`` keyword is enabled.
666
667C++11 attributes
668^^^^^^^^^^^^^^^^
669
670Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
671determine if support for attribute parsing with C++11's square bracket notation
672is enabled.
673
674C++11 generalized constant expressions
675^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
676
677Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
678constant expressions (e.g., ``constexpr``) is enabled.
679
680C++11 ``decltype()``
681^^^^^^^^^^^^^^^^^^^^
682
683Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
684determine if support for the ``decltype()`` specifier is enabled.  C++11's
685``decltype`` does not require type-completeness of a function call expression.
686Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
687``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
688support for this feature is enabled.
689
690C++11 default template arguments in function templates
691^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
692
693Use ``__has_feature(cxx_default_function_template_args)`` or
694``__has_extension(cxx_default_function_template_args)`` to determine if support
695for default template arguments in function templates is enabled.
696
697C++11 ``default``\ ed functions
698^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
699
700Use ``__has_feature(cxx_defaulted_functions)`` or
701``__has_extension(cxx_defaulted_functions)`` to determine if support for
702defaulted function definitions (with ``= default``) is enabled.
703
704C++11 delegating constructors
705^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
706
707Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
708delegating constructors is enabled.
709
710C++11 ``deleted`` functions
711^^^^^^^^^^^^^^^^^^^^^^^^^^^
712
713Use ``__has_feature(cxx_deleted_functions)`` or
714``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
715function definitions (with ``= delete``) is enabled.
716
717C++11 explicit conversion functions
718^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
719
720Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
721``explicit`` conversion functions is enabled.
722
723C++11 generalized initializers
724^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
725
726Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
727generalized initializers (using braced lists and ``std::initializer_list``) is
728enabled.
729
730C++11 implicit move constructors/assignment operators
731^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
732
733Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
734generate move constructors and move assignment operators where needed.
735
736C++11 inheriting constructors
737^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
738
739Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
740inheriting constructors is enabled.
741
742C++11 inline namespaces
743^^^^^^^^^^^^^^^^^^^^^^^
744
745Use ``__has_feature(cxx_inline_namespaces)`` or
746``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
747namespaces is enabled.
748
749C++11 lambdas
750^^^^^^^^^^^^^
751
752Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
753determine if support for lambdas is enabled.
754
755C++11 local and unnamed types as template arguments
756^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
757
758Use ``__has_feature(cxx_local_type_template_args)`` or
759``__has_extension(cxx_local_type_template_args)`` to determine if support for
760local and unnamed types as template arguments is enabled.
761
762C++11 noexcept
763^^^^^^^^^^^^^^
764
765Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
766determine if support for noexcept exception specifications is enabled.
767
768C++11 in-class non-static data member initialization
769^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
770
771Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
772initialization of non-static data members is enabled.
773
774C++11 ``nullptr``
775^^^^^^^^^^^^^^^^^
776
777Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
778determine if support for ``nullptr`` is enabled.
779
780C++11 ``override control``
781^^^^^^^^^^^^^^^^^^^^^^^^^^
782
783Use ``__has_feature(cxx_override_control)`` or
784``__has_extension(cxx_override_control)`` to determine if support for the
785override control keywords is enabled.
786
787C++11 reference-qualified functions
788^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
789
790Use ``__has_feature(cxx_reference_qualified_functions)`` or
791``__has_extension(cxx_reference_qualified_functions)`` to determine if support
792for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
793applied to ``*this``) is enabled.
794
795C++11 range-based ``for`` loop
796^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
797
798Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
799determine if support for the range-based for loop is enabled.
800
801C++11 raw string literals
802^^^^^^^^^^^^^^^^^^^^^^^^^
803
804Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
805string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
806
807C++11 rvalue references
808^^^^^^^^^^^^^^^^^^^^^^^
809
810Use ``__has_feature(cxx_rvalue_references)`` or
811``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
812references is enabled.
813
814C++11 ``static_assert()``
815^^^^^^^^^^^^^^^^^^^^^^^^^
816
817Use ``__has_feature(cxx_static_assert)`` or
818``__has_extension(cxx_static_assert)`` to determine if support for compile-time
819assertions using ``static_assert`` is enabled.
820
821C++11 ``thread_local``
822^^^^^^^^^^^^^^^^^^^^^^
823
824Use ``__has_feature(cxx_thread_local)`` to determine if support for
825``thread_local`` variables is enabled.
826
827C++11 type inference
828^^^^^^^^^^^^^^^^^^^^
829
830Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
831determine C++11 type inference is supported using the ``auto`` specifier.  If
832this is disabled, ``auto`` will instead be a storage class specifier, as in C
833or C++98.
834
835C++11 strongly typed enumerations
836^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
837
838Use ``__has_feature(cxx_strong_enums)`` or
839``__has_extension(cxx_strong_enums)`` to determine if support for strongly
840typed, scoped enumerations is enabled.
841
842C++11 trailing return type
843^^^^^^^^^^^^^^^^^^^^^^^^^^
844
845Use ``__has_feature(cxx_trailing_return)`` or
846``__has_extension(cxx_trailing_return)`` to determine if support for the
847alternate function declaration syntax with trailing return type is enabled.
848
849C++11 Unicode string literals
850^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
851
852Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
853string literals is enabled.
854
855C++11 unrestricted unions
856^^^^^^^^^^^^^^^^^^^^^^^^^
857
858Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
859unrestricted unions is enabled.
860
861C++11 user-defined literals
862^^^^^^^^^^^^^^^^^^^^^^^^^^^
863
864Use ``__has_feature(cxx_user_literals)`` to determine if support for
865user-defined literals is enabled.
866
867C++11 variadic templates
868^^^^^^^^^^^^^^^^^^^^^^^^
869
870Use ``__has_feature(cxx_variadic_templates)`` or
871``__has_extension(cxx_variadic_templates)`` to determine if support for
872variadic templates is enabled.
873
874C++14
875-----
876
877The features listed below are part of the C++14 standard.  As a result, all
878these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
879when compiling C++ code.
880
881C++14 binary literals
882^^^^^^^^^^^^^^^^^^^^^
883
884Use ``__has_feature(cxx_binary_literals)`` or
885``__has_extension(cxx_binary_literals)`` to determine whether
886binary literals (for instance, ``0b10010``) are recognized. Clang supports this
887feature as an extension in all language modes.
888
889C++14 contextual conversions
890^^^^^^^^^^^^^^^^^^^^^^^^^^^^
891
892Use ``__has_feature(cxx_contextual_conversions)`` or
893``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
894are used when performing an implicit conversion for an array bound in a
895*new-expression*, the operand of a *delete-expression*, an integral constant
896expression, or a condition in a ``switch`` statement.
897
898C++14 decltype(auto)
899^^^^^^^^^^^^^^^^^^^^
900
901Use ``__has_feature(cxx_decltype_auto)`` or
902``__has_extension(cxx_decltype_auto)`` to determine if support
903for the ``decltype(auto)`` placeholder type is enabled.
904
905C++14 default initializers for aggregates
906^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
907
908Use ``__has_feature(cxx_aggregate_nsdmi)`` or
909``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
910for default initializers in aggregate members is enabled.
911
912C++14 digit separators
913^^^^^^^^^^^^^^^^^^^^^^
914
915Use ``__cpp_digit_separators`` to determine if support for digit separators
916using single quotes (for instance, ``10'000``) is enabled. At this time, there
917is no corresponding ``__has_feature`` name
918
919C++14 generalized lambda capture
920^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
921
922Use ``__has_feature(cxx_init_captures)`` or
923``__has_extension(cxx_init_captures)`` to determine if support for
924lambda captures with explicit initializers is enabled
925(for instance, ``[n(0)] { return ++n; }``).
926
927C++14 generic lambdas
928^^^^^^^^^^^^^^^^^^^^^
929
930Use ``__has_feature(cxx_generic_lambdas)`` or
931``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
932(polymorphic) lambdas is enabled
933(for instance, ``[] (auto x) { return x + 1; }``).
934
935C++14 relaxed constexpr
936^^^^^^^^^^^^^^^^^^^^^^^
937
938Use ``__has_feature(cxx_relaxed_constexpr)`` or
939``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
940declarations, local variable modification, and control flow constructs
941are permitted in ``constexpr`` functions.
942
943C++14 return type deduction
944^^^^^^^^^^^^^^^^^^^^^^^^^^^
945
946Use ``__has_feature(cxx_return_type_deduction)`` or
947``__has_extension(cxx_return_type_deduction)`` to determine if support
948for return type deduction for functions (using ``auto`` as a return type)
949is enabled.
950
951C++14 runtime-sized arrays
952^^^^^^^^^^^^^^^^^^^^^^^^^^
953
954Use ``__has_feature(cxx_runtime_array)`` or
955``__has_extension(cxx_runtime_array)`` to determine if support
956for arrays of runtime bound (a restricted form of variable-length arrays)
957is enabled.
958Clang's implementation of this feature is incomplete.
959
960C++14 variable templates
961^^^^^^^^^^^^^^^^^^^^^^^^
962
963Use ``__has_feature(cxx_variable_templates)`` or
964``__has_extension(cxx_variable_templates)`` to determine if support for
965templated variable declarations is enabled.
966
967C11
968---
969
970The features listed below are part of the C11 standard.  As a result, all these
971features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
972compiling C code.  Additionally, because these features are all
973backward-compatible, they are available as extensions in all language modes.
974
975C11 alignment specifiers
976^^^^^^^^^^^^^^^^^^^^^^^^
977
978Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
979if support for alignment specifiers using ``_Alignas`` is enabled.
980
981Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
982if support for the ``_Alignof`` keyword is enabled.
983
984C11 atomic operations
985^^^^^^^^^^^^^^^^^^^^^
986
987Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
988if support for atomic types using ``_Atomic`` is enabled.  Clang also provides
989:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
990the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
991``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
992is available.
993
994Clang will use the system's ``<stdatomic.h>`` header when one is available, and
995will otherwise use its own. When using its own, implementations of the atomic
996operations are provided as macros. In the cases where C11 also requires a real
997function, this header provides only the declaration of that function (along
998with a shadowing macro implementation), and you must link to a library which
999provides a definition of the function if you use it instead of the macro.
1000
1001C11 generic selections
1002^^^^^^^^^^^^^^^^^^^^^^
1003
1004Use ``__has_feature(c_generic_selections)`` or
1005``__has_extension(c_generic_selections)`` to determine if support for generic
1006selections is enabled.
1007
1008As an extension, the C11 generic selection expression is available in all
1009languages supported by Clang.  The syntax is the same as that given in the C11
1010standard.
1011
1012In C, type compatibility is decided according to the rules given in the
1013appropriate standard, but in C++, which lacks the type compatibility rules used
1014in C, types are considered compatible only if they are equivalent.
1015
1016C11 ``_Static_assert()``
1017^^^^^^^^^^^^^^^^^^^^^^^^
1018
1019Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
1020to determine if support for compile-time assertions using ``_Static_assert`` is
1021enabled.
1022
1023C11 ``_Thread_local``
1024^^^^^^^^^^^^^^^^^^^^^
1025
1026Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
1027to determine if support for ``_Thread_local`` variables is enabled.
1028
1029Modules
1030-------
1031
1032Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1033For example, compiling code with ``-fmodules`` enables the use of Modules.
1034
1035More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
1036
1037Checks for Type Trait Primitives
1038================================
1039
1040Type trait primitives are special builtin constant expressions that can be used
1041by the standard C++ library to facilitate or simplify the implementation of
1042user-facing type traits in the <type_traits> header.
1043
1044They are not intended to be used directly by user code because they are
1045implementation-defined and subject to change -- as such they're tied closely to
1046the supported set of system headers, currently:
1047
1048* LLVM's own libc++
1049* GNU libstdc++
1050* The Microsoft standard C++ library
1051
1052Clang supports the `GNU C++ type traits
1053<http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
1054`Microsoft Visual C++ Type traits
1055<http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_.
1056
1057Feature detection is supported only for some of the primitives at present. User
1058code should not use these checks because they bear no direct relation to the
1059actual set of type traits supported by the C++ standard library.
1060
1061For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the
1062type trait primitive in the compiler. A simplistic usage example as might be
1063seen in standard C++ headers follows:
1064
1065.. code-block:: c++
1066
1067  #if __has_extension(is_convertible_to)
1068  template<typename From, typename To>
1069  struct is_convertible_to {
1070    static const bool value = __is_convertible_to(From, To);
1071  };
1072  #else
1073  // Emulate type trait for compatibility with other compilers.
1074  #endif
1075
1076The following type trait primitives are supported by Clang:
1077
1078* ``__has_nothrow_assign`` (GNU, Microsoft)
1079* ``__has_nothrow_copy`` (GNU, Microsoft)
1080* ``__has_nothrow_constructor`` (GNU, Microsoft)
1081* ``__has_trivial_assign`` (GNU, Microsoft)
1082* ``__has_trivial_copy`` (GNU, Microsoft)
1083* ``__has_trivial_constructor`` (GNU, Microsoft)
1084* ``__has_trivial_destructor`` (GNU, Microsoft)
1085* ``__has_virtual_destructor`` (GNU, Microsoft)
1086* ``__is_abstract`` (GNU, Microsoft)
1087* ``__is_aggregate`` (GNU, Microsoft)
1088* ``__is_base_of`` (GNU, Microsoft)
1089* ``__is_class`` (GNU, Microsoft)
1090* ``__is_convertible_to`` (Microsoft)
1091* ``__is_empty`` (GNU, Microsoft)
1092* ``__is_enum`` (GNU, Microsoft)
1093* ``__is_interface_class`` (Microsoft)
1094* ``__is_pod`` (GNU, Microsoft)
1095* ``__is_polymorphic`` (GNU, Microsoft)
1096* ``__is_union`` (GNU, Microsoft)
1097* ``__is_literal(type)``: Determines whether the given type is a literal type
1098* ``__is_final``: Determines whether the given type is declared with a
1099  ``final`` class-virt-specifier.
1100* ``__underlying_type(type)``: Retrieves the underlying type for a given
1101  ``enum`` type.  This trait is required to implement the C++11 standard
1102  library.
1103* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
1104  of type ``totype`` can be assigned to from a value of type ``fromtype`` such
1105  that no non-trivial functions are called as part of that assignment.  This
1106  trait is required to implement the C++11 standard library.
1107* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
1108  value of type ``type`` can be direct-initialized with arguments of types
1109  ``argtypes...`` such that no non-trivial functions are called as part of
1110  that initialization.  This trait is required to implement the C++11 standard
1111  library.
1112* ``__is_destructible`` (MSVC 2013)
1113* ``__is_nothrow_destructible`` (MSVC 2013)
1114* ``__is_nothrow_assignable`` (MSVC 2013, clang)
1115* ``__is_constructible`` (MSVC 2013, clang)
1116* ``__is_nothrow_constructible`` (MSVC 2013, clang)
1117* ``__is_assignable`` (MSVC 2015, clang)
1118* ``__reference_binds_to_temporary(T, U)`` (Clang):  Determines whether a
1119  reference of type ``T`` bound to an expression of type ``U`` would bind to a
1120  materialized temporary object. If ``T`` is not a reference type the result
1121  is false. Note this trait will also return false when the initialization of
1122  ``T`` from ``U`` is ill-formed.
1123
1124Blocks
1125======
1126
1127The syntax and high level language feature description is in
1128:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1129the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
1130
1131Query for this feature with ``__has_extension(blocks)``.
1132
1133Objective-C Features
1134====================
1135
1136Related result types
1137--------------------
1138
1139According to Cocoa conventions, Objective-C methods with certain names
1140("``init``", "``alloc``", etc.) always return objects that are an instance of
1141the receiving class's type.  Such methods are said to have a "related result
1142type", meaning that a message send to one of these methods will have the same
1143static type as an instance of the receiver class.  For example, given the
1144following classes:
1145
1146.. code-block:: objc
1147
1148  @interface NSObject
1149  + (id)alloc;
1150  - (id)init;
1151  @end
1152
1153  @interface NSArray : NSObject
1154  @end
1155
1156and this common initialization pattern
1157
1158.. code-block:: objc
1159
1160  NSArray *array = [[NSArray alloc] init];
1161
1162the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1163``alloc`` implicitly has a related result type.  Similarly, the type of the
1164expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1165related result type and its receiver is known to have the type ``NSArray *``.
1166If neither ``alloc`` nor ``init`` had a related result type, the expressions
1167would have had type ``id``, as declared in the method signature.
1168
1169A method with a related result type can be declared by using the type
1170``instancetype`` as its result type.  ``instancetype`` is a contextual keyword
1171that is only permitted in the result type of an Objective-C method, e.g.
1172
1173.. code-block:: objc
1174
1175  @interface A
1176  + (instancetype)constructAnA;
1177  @end
1178
1179The related result type can also be inferred for some methods.  To determine
1180whether a method has an inferred related result type, the first word in the
1181camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1182and the method will have a related result type if its return type is compatible
1183with the type of its class and if:
1184
1185* the first word is "``alloc``" or "``new``", and the method is a class method,
1186  or
1187
1188* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1189  and the method is an instance method.
1190
1191If a method with a related result type is overridden by a subclass method, the
1192subclass method must also return a type that is compatible with the subclass
1193type.  For example:
1194
1195.. code-block:: objc
1196
1197  @interface NSString : NSObject
1198  - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1199  @end
1200
1201Related result types only affect the type of a message send or property access
1202via the given method.  In all other respects, a method with a related result
1203type is treated the same way as method that returns ``id``.
1204
1205Use ``__has_feature(objc_instancetype)`` to determine whether the
1206``instancetype`` contextual keyword is available.
1207
1208Automatic reference counting
1209----------------------------
1210
1211Clang provides support for :doc:`automated reference counting
1212<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
1213for manual ``retain``/``release``/``autorelease`` message sends.  There are three
1214feature macros associated with automatic reference counting:
1215``__has_feature(objc_arc)`` indicates the availability of automated reference
1216counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1217automated reference counting also includes support for ``__weak`` pointers to
1218Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
1219are allowed to have fields that are pointers to Objective-C objects managed by
1220automatic reference counting.
1221
1222.. _objc-weak:
1223
1224Weak references
1225---------------
1226
1227Clang supports ARC-style weak and unsafe references in Objective-C even
1228outside of ARC mode.  Weak references must be explicitly enabled with
1229the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
1230to test whether they are enabled.  Unsafe references are enabled
1231unconditionally.  ARC-style weak and unsafe references cannot be used
1232when Objective-C garbage collection is enabled.
1233
1234Except as noted below, the language rules for the ``__weak`` and
1235``__unsafe_unretained`` qualifiers (and the ``weak`` and
1236``unsafe_unretained`` property attributes) are just as laid out
1237in the :doc:`ARC specification <AutomaticReferenceCounting>`.
1238In particular, note that some classes do not support forming weak
1239references to their instances, and note that special care must be
1240taken when storing weak references in memory where initialization
1241and deinitialization are outside the responsibility of the compiler
1242(such as in ``malloc``-ed memory).
1243
1244Loading from a ``__weak`` variable always implicitly retains the
1245loaded value.  In non-ARC modes, this retain is normally balanced
1246by an implicit autorelease.  This autorelease can be suppressed
1247by performing the load in the receiver position of a ``-retain``
1248message send (e.g. ``[weakReference retain]``); note that this performs
1249only a single retain (the retain done when primitively loading from
1250the weak reference).
1251
1252For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
1253default behavior of variables and therefore is not needed.  However,
1254it does have an effect on the semantics of block captures: normally,
1255copying a block which captures an Objective-C object or block pointer
1256causes the captured pointer to be retained or copied, respectively,
1257but that behavior is suppressed when the captured variable is qualified
1258with ``__unsafe_unretained``.
1259
1260Note that the ``__weak`` qualifier formerly meant the GC qualifier in
1261all non-ARC modes and was silently ignored outside of GC modes.  It now
1262means the ARC-style qualifier in all non-GC modes and is no longer
1263allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
1264It is expected that ``-fobjc-weak`` will eventually be enabled by default
1265in all non-GC Objective-C modes.
1266
1267.. _objc-fixed-enum:
1268
1269Enumerations with a fixed underlying type
1270-----------------------------------------
1271
1272Clang provides support for C++11 enumerations with a fixed underlying type
1273within Objective-C.  For example, one can write an enumeration type as:
1274
1275.. code-block:: c++
1276
1277  typedef enum : unsigned char { Red, Green, Blue } Color;
1278
1279This specifies that the underlying type, which is used to store the enumeration
1280value, is ``unsigned char``.
1281
1282Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1283underlying types is available in Objective-C.
1284
1285Interoperability with C++11 lambdas
1286-----------------------------------
1287
1288Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1289permitting a lambda to be implicitly converted to a block pointer with the
1290corresponding signature.  For example, consider an API such as ``NSArray``'s
1291array-sorting method:
1292
1293.. code-block:: objc
1294
1295  - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1296
1297``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1298(^)(id, id)``, and parameters of this type are generally provided with block
1299literals as arguments.  However, one can also use a C++11 lambda so long as it
1300provides the same signature (in this case, accepting two parameters of type
1301``id`` and returning an ``NSComparisonResult``):
1302
1303.. code-block:: objc
1304
1305  NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1306                     @"String 02"];
1307  const NSStringCompareOptions comparisonOptions
1308    = NSCaseInsensitiveSearch | NSNumericSearch |
1309      NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1310  NSLocale *currentLocale = [NSLocale currentLocale];
1311  NSArray *sorted
1312    = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1313               NSRange string1Range = NSMakeRange(0, [s1 length]);
1314               return [s1 compare:s2 options:comparisonOptions
1315               range:string1Range locale:currentLocale];
1316       }];
1317  NSLog(@"sorted: %@", sorted);
1318
1319This code relies on an implicit conversion from the type of the lambda
1320expression (an unnamed, local class type called the *closure type*) to the
1321corresponding block pointer type.  The conversion itself is expressed by a
1322conversion operator in that closure type that produces a block pointer with the
1323same signature as the lambda itself, e.g.,
1324
1325.. code-block:: objc
1326
1327  operator NSComparisonResult (^)(id, id)() const;
1328
1329This conversion function returns a new block that simply forwards the two
1330parameters to the lambda object (which it captures by copy), then returns the
1331result.  The returned block is first copied (with ``Block_copy``) and then
1332autoreleased.  As an optimization, if a lambda expression is immediately
1333converted to a block pointer (as in the first example, above), then the block
1334is not copied and autoreleased: rather, it is given the same lifetime as a
1335block literal written at that point in the program, which avoids the overhead
1336of copying a block to the heap in the common case.
1337
1338The conversion from a lambda to a block pointer is only available in
1339Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1340management (autorelease).
1341
1342Object Literals and Subscripting
1343--------------------------------
1344
1345Clang provides support for :doc:`Object Literals and Subscripting
1346<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
1347programming patterns, makes programs more concise, and improves the safety of
1348container creation.  There are several feature macros associated with object
1349literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1350availability of array literals; ``__has_feature(objc_dictionary_literals)``
1351tests the availability of dictionary literals;
1352``__has_feature(objc_subscripting)`` tests the availability of object
1353subscripting.
1354
1355Objective-C Autosynthesis of Properties
1356---------------------------------------
1357
1358Clang provides support for autosynthesis of declared properties.  Using this
1359feature, clang provides default synthesis of those properties not declared
1360@dynamic and not having user provided backing getter and setter methods.
1361``__has_feature(objc_default_synthesize_properties)`` checks for availability
1362of this feature in version of clang being used.
1363
1364.. _langext-objc-retain-release:
1365
1366Objective-C retaining behavior attributes
1367-----------------------------------------
1368
1369In Objective-C, functions and methods are generally assumed to follow the
1370`Cocoa Memory Management
1371<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1372conventions for ownership of object arguments and
1373return values. However, there are exceptions, and so Clang provides attributes
1374to allow these exceptions to be documented. This are used by ARC and the
1375`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
1376better described using the ``objc_method_family`` attribute instead.
1377
1378**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1379``ns_returns_autoreleased``, ``cf_returns_retained``, and
1380``cf_returns_not_retained`` attributes can be placed on methods and functions
1381that return Objective-C or CoreFoundation objects. They are commonly placed at
1382the end of a function prototype or method declaration:
1383
1384.. code-block:: objc
1385
1386  id foo() __attribute__((ns_returns_retained));
1387
1388  - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1389
1390The ``*_returns_retained`` attributes specify that the returned object has a +1
1391retain count.  The ``*_returns_not_retained`` attributes specify that the return
1392object has a +0 retain count, even if the normal convention for its selector
1393would be +1.  ``ns_returns_autoreleased`` specifies that the returned object is
1394+0, but is guaranteed to live at least as long as the next flush of an
1395autorelease pool.
1396
1397**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1398an parameter declaration; they specify that the argument is expected to have a
1399+1 retain count, which will be balanced in some way by the function or method.
1400The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1401method; it specifies that the method expects its ``self`` parameter to have a
1402+1 retain count, which it will balance in some way.
1403
1404.. code-block:: objc
1405
1406  void foo(__attribute__((ns_consumed)) NSString *string);
1407
1408  - (void) bar __attribute__((ns_consumes_self));
1409  - (void) baz:(id) __attribute__((ns_consumed)) x;
1410
1411Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1412<https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1413
1414Query for these features with ``__has_attribute(ns_consumed)``,
1415``__has_attribute(ns_returns_retained)``, etc.
1416
1417Objective-C @available
1418----------------------
1419
1420It is possible to use the newest SDK but still build a program that can run on
1421older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
1422``-miphoneos-version-min=``.
1423
1424Before LLVM 5.0, when calling a function that exists only in the OS that's
1425newer than the target OS (as determined by the minimum deployment version),
1426programmers had to carefully check if the function exists at runtime, using
1427null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
1428and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
1429Objective-C methods.  If such a check was missed, the program would compile
1430fine, run fine on newer systems, but crash on older systems.
1431
1432As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
1433<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
1434with the new ``@available()`` keyword to assist with this issue.
1435When a method that's introduced in the OS newer than the target OS is called, a
1436-Wunguarded-availability warning is emitted if that call is not guarded:
1437
1438.. code-block:: objc
1439
1440  void my_fun(NSSomeClass* var) {
1441    // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
1442    // built with -mmacosx-version-min=10.11, then this unconditional call
1443    // will emit a -Wunguarded-availability warning:
1444    [var fancyNewMethod];
1445  }
1446
1447To fix the warning and to avoid the crash on macOS 10.11, wrap it in
1448``if(@available())``:
1449
1450.. code-block:: objc
1451
1452  void my_fun(NSSomeClass* var) {
1453    if (@available(macOS 10.12, *)) {
1454      [var fancyNewMethod];
1455    } else {
1456      // Put fallback behavior for old macOS versions (and for non-mac
1457      // platforms) here.
1458    }
1459  }
1460
1461The ``*`` is required and means that platforms not explicitly listed will take
1462the true branch, and the compiler will emit ``-Wunguarded-availability``
1463warnings for unlisted platforms based on those platform's deployment target.
1464More than one platform can be listed in ``@available()``:
1465
1466.. code-block:: objc
1467
1468  void my_fun(NSSomeClass* var) {
1469    if (@available(macOS 10.12, iOS 10, *)) {
1470      [var fancyNewMethod];
1471    }
1472  }
1473
1474If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
1475on 10.12, then add an `availability attribute
1476<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
1477which will also suppress the warning and require that calls to my_fun() are
1478checked:
1479
1480.. code-block:: objc
1481
1482  API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
1483    [var fancyNewMethod];  // Now ok.
1484  }
1485
1486``@available()`` is only available in Objective-C code.  To use the feature
1487in C and C++ code, use the ``__builtin_available()`` spelling instead.
1488
1489If existing code uses null checks or ``-respondsToSelector:``, it should
1490be changed to use ``@available()`` (or ``__builtin_available``) instead.
1491
1492``-Wunguarded-availability`` is disabled by default, but
1493``-Wunguarded-availability-new``, which only emits this warning for APIs
1494that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
1495tvOS >= 11, is enabled by default.
1496
1497.. _langext-overloading:
1498
1499Objective-C++ ABI: protocol-qualifier mangling of parameters
1500------------------------------------------------------------
1501
1502Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
1503type is a qualified-``id`` (e.g., ``id<Foo>``).  This mangling allows such
1504parameters to be differentiated from those with the regular unqualified ``id``
1505type.
1506
1507This was a non-backward compatible mangling change to the ABI.  This change
1508allows proper overloading, and also prevents mangling conflicts with template
1509parameters of protocol-qualified type.
1510
1511Query the presence of this new mangling with
1512``__has_feature(objc_protocol_qualifier_mangling)``.
1513
1514Initializer lists for complex numbers in C
1515==========================================
1516
1517clang supports an extension which allows the following in C:
1518
1519.. code-block:: c++
1520
1521  #include <math.h>
1522  #include <complex.h>
1523  complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1524
1525This construct is useful because there is no way to separately initialize the
1526real and imaginary parts of a complex variable in standard C, given that clang
1527does not support ``_Imaginary``.  (Clang also supports the ``__real__`` and
1528``__imag__`` extensions from gcc, which help in some cases, but are not usable
1529in static initializers.)
1530
1531Note that this extension does not allow eliding the braces; the meaning of the
1532following two lines is different:
1533
1534.. code-block:: c++
1535
1536  complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1537  complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1538
1539This extension also works in C++ mode, as far as that goes, but does not apply
1540to the C++ ``std::complex``.  (In C++11, list initialization allows the same
1541syntax to be used with ``std::complex`` with the same meaning.)
1542
1543Builtin Functions
1544=================
1545
1546Clang supports a number of builtin library functions with the same syntax as
1547GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1548``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
1549``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc.  In addition to
1550the GCC builtins, Clang supports a number of builtins that GCC does not, which
1551are listed here.
1552
1553Please note that Clang does not and will not support all of the GCC builtins
1554for vector operations.  Instead of using builtins, you should use the functions
1555defined in target-specific header files like ``<xmmintrin.h>``, which define
1556portable wrappers for these.  Many of the Clang versions of these functions are
1557implemented directly in terms of :ref:`extended vector support
1558<langext-vectors>` instead of builtins, in order to reduce the number of
1559builtins that we need to implement.
1560
1561``__builtin_assume``
1562------------------------------
1563
1564``__builtin_assume`` is used to provide the optimizer with a boolean
1565invariant that is defined to be true.
1566
1567**Syntax**:
1568
1569.. code-block:: c++
1570
1571  __builtin_assume(bool)
1572
1573**Example of Use**:
1574
1575.. code-block:: c++
1576
1577  int foo(int x) {
1578    __builtin_assume(x != 0);
1579
1580    // The optimizer may short-circuit this check using the invariant.
1581    if (x == 0)
1582      return do_something();
1583
1584    return do_something_else();
1585  }
1586
1587**Description**:
1588
1589The boolean argument to this function is defined to be true. The optimizer may
1590analyze the form of the expression provided as the argument and deduce from
1591that information used to optimize the program. If the condition is violated
1592during execution, the behavior is undefined. The argument itself is never
1593evaluated, so any side effects of the expression will be discarded.
1594
1595Query for this feature with ``__has_builtin(__builtin_assume)``.
1596
1597``__builtin_readcyclecounter``
1598------------------------------
1599
1600``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1601a similar low-latency, high-accuracy clock) on those targets that support it.
1602
1603**Syntax**:
1604
1605.. code-block:: c++
1606
1607  __builtin_readcyclecounter()
1608
1609**Example of Use**:
1610
1611.. code-block:: c++
1612
1613  unsigned long long t0 = __builtin_readcyclecounter();
1614  do_something();
1615  unsigned long long t1 = __builtin_readcyclecounter();
1616  unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1617
1618**Description**:
1619
1620The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1621which may be either global or process/thread-specific depending on the target.
1622As the backing counters often overflow quickly (on the order of seconds) this
1623should only be used for timing small intervals.  When not supported by the
1624target, the return value is always zero.  This builtin takes no arguments and
1625produces an unsigned long long result.
1626
1627Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
1628that even if present, its use may depend on run-time privilege or other OS
1629controlled state.
1630
1631.. _langext-__builtin_shufflevector:
1632
1633``__builtin_shufflevector``
1634---------------------------
1635
1636``__builtin_shufflevector`` is used to express generic vector
1637permutation/shuffle/swizzle operations.  This builtin is also very important
1638for the implementation of various target-specific header files like
1639``<xmmintrin.h>``.
1640
1641**Syntax**:
1642
1643.. code-block:: c++
1644
1645  __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1646
1647**Examples**:
1648
1649.. code-block:: c++
1650
1651  // identity operation - return 4-element vector v1.
1652  __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
1653
1654  // "Splat" element 0 of V1 into a 4-element result.
1655  __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1656
1657  // Reverse 4-element vector V1.
1658  __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1659
1660  // Concatenate every other element of 4-element vectors V1 and V2.
1661  __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1662
1663  // Concatenate every other element of 8-element vectors V1 and V2.
1664  __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1665
1666  // Shuffle v1 with some elements being undefined
1667  __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
1668
1669**Description**:
1670
1671The first two arguments to ``__builtin_shufflevector`` are vectors that have
1672the same element type.  The remaining arguments are a list of integers that
1673specify the elements indices of the first two vectors that should be extracted
1674and returned in a new vector.  These element indices are numbered sequentially
1675starting with the first vector, continuing into the second vector.  Thus, if
1676``vec1`` is a 4-element vector, index 5 would refer to the second element of
1677``vec2``. An index of -1 can be used to indicate that the corresponding element
1678in the returned vector is a don't care and can be optimized by the backend.
1679
1680The result of ``__builtin_shufflevector`` is a vector with the same element
1681type as ``vec1``/``vec2`` but that has an element count equal to the number of
1682indices specified.
1683
1684Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1685
1686.. _langext-__builtin_convertvector:
1687
1688``__builtin_convertvector``
1689---------------------------
1690
1691``__builtin_convertvector`` is used to express generic vector
1692type-conversion operations. The input vector and the output vector
1693type must have the same number of elements.
1694
1695**Syntax**:
1696
1697.. code-block:: c++
1698
1699  __builtin_convertvector(src_vec, dst_vec_type)
1700
1701**Examples**:
1702
1703.. code-block:: c++
1704
1705  typedef double vector4double __attribute__((__vector_size__(32)));
1706  typedef float  vector4float  __attribute__((__vector_size__(16)));
1707  typedef short  vector4short  __attribute__((__vector_size__(8)));
1708  vector4float vf; vector4short vs;
1709
1710  // convert from a vector of 4 floats to a vector of 4 doubles.
1711  __builtin_convertvector(vf, vector4double)
1712  // equivalent to:
1713  (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
1714
1715  // convert from a vector of 4 shorts to a vector of 4 floats.
1716  __builtin_convertvector(vs, vector4float)
1717  // equivalent to:
1718  (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
1719
1720**Description**:
1721
1722The first argument to ``__builtin_convertvector`` is a vector, and the second
1723argument is a vector type with the same number of elements as the first
1724argument.
1725
1726The result of ``__builtin_convertvector`` is a vector with the same element
1727type as the second argument, with a value defined in terms of the action of a
1728C-style cast applied to each element of the first argument.
1729
1730Query for this feature with ``__has_builtin(__builtin_convertvector)``.
1731
1732``__builtin_bitreverse``
1733------------------------
1734
1735* ``__builtin_bitreverse8``
1736* ``__builtin_bitreverse16``
1737* ``__builtin_bitreverse32``
1738* ``__builtin_bitreverse64``
1739
1740**Syntax**:
1741
1742.. code-block:: c++
1743
1744     __builtin_bitreverse32(x)
1745
1746**Examples**:
1747
1748.. code-block:: c++
1749
1750      uint8_t rev_x = __builtin_bitreverse8(x);
1751      uint16_t rev_x = __builtin_bitreverse16(x);
1752      uint32_t rev_y = __builtin_bitreverse32(y);
1753      uint64_t rev_z = __builtin_bitreverse64(z);
1754
1755**Description**:
1756
1757The '``__builtin_bitreverse``' family of builtins is used to reverse
1758the bitpattern of an integer value; for example ``0b10110110`` becomes
1759``0b01101101``.
1760
1761``__builtin_rotateleft``
1762------------------------
1763
1764* ``__builtin_rotateleft8``
1765* ``__builtin_rotateleft16``
1766* ``__builtin_rotateleft32``
1767* ``__builtin_rotateleft64``
1768
1769**Syntax**:
1770
1771.. code-block:: c++
1772
1773     __builtin_rotateleft32(x, y)
1774
1775**Examples**:
1776
1777.. code-block:: c++
1778
1779      uint8_t rot_x = __builtin_rotateleft8(x, y);
1780      uint16_t rot_x = __builtin_rotateleft16(x, y);
1781      uint32_t rot_x = __builtin_rotateleft32(x, y);
1782      uint64_t rot_x = __builtin_rotateleft64(x, y);
1783
1784**Description**:
1785
1786The '``__builtin_rotateleft``' family of builtins is used to rotate
1787the bits in the first argument by the amount in the second argument.
1788For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
1789The shift value is treated as an unsigned amount modulo the size of
1790the arguments. Both arguments and the result have the bitwidth specified
1791by the name of the builtin.
1792
1793``__builtin_rotateright``
1794_------------------------
1795
1796* ``__builtin_rotateright8``
1797* ``__builtin_rotateright16``
1798* ``__builtin_rotateright32``
1799* ``__builtin_rotateright64``
1800
1801**Syntax**:
1802
1803.. code-block:: c++
1804
1805     __builtin_rotateright32(x, y)
1806
1807**Examples**:
1808
1809.. code-block:: c++
1810
1811      uint8_t rot_x = __builtin_rotateright8(x, y);
1812      uint16_t rot_x = __builtin_rotateright16(x, y);
1813      uint32_t rot_x = __builtin_rotateright32(x, y);
1814      uint64_t rot_x = __builtin_rotateright64(x, y);
1815
1816**Description**:
1817
1818The '``__builtin_rotateright``' family of builtins is used to rotate
1819the bits in the first argument by the amount in the second argument.
1820For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
1821The shift value is treated as an unsigned amount modulo the size of
1822the arguments. Both arguments and the result have the bitwidth specified
1823by the name of the builtin.
1824
1825``__builtin_unreachable``
1826-------------------------
1827
1828``__builtin_unreachable`` is used to indicate that a specific point in the
1829program cannot be reached, even if the compiler might otherwise think it can.
1830This is useful to improve optimization and eliminates certain warnings.  For
1831example, without the ``__builtin_unreachable`` in the example below, the
1832compiler assumes that the inline asm can fall through and prints a "function
1833declared '``noreturn``' should not return" warning.
1834
1835**Syntax**:
1836
1837.. code-block:: c++
1838
1839    __builtin_unreachable()
1840
1841**Example of use**:
1842
1843.. code-block:: c++
1844
1845  void myabort(void) __attribute__((noreturn));
1846  void myabort(void) {
1847    asm("int3");
1848    __builtin_unreachable();
1849  }
1850
1851**Description**:
1852
1853The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1854Since it has undefined behavior, it is a statement that it is never reached and
1855the optimizer can take advantage of this to produce better code.  This builtin
1856takes no arguments and produces a void result.
1857
1858Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1859
1860``__builtin_unpredictable``
1861---------------------------
1862
1863``__builtin_unpredictable`` is used to indicate that a branch condition is
1864unpredictable by hardware mechanisms such as branch prediction logic.
1865
1866**Syntax**:
1867
1868.. code-block:: c++
1869
1870    __builtin_unpredictable(long long)
1871
1872**Example of use**:
1873
1874.. code-block:: c++
1875
1876  if (__builtin_unpredictable(x > 0)) {
1877     foo();
1878  }
1879
1880**Description**:
1881
1882The ``__builtin_unpredictable()`` builtin is expected to be used with control
1883flow conditions such as in ``if`` and ``switch`` statements.
1884
1885Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
1886
1887``__sync_swap``
1888---------------
1889
1890``__sync_swap`` is used to atomically swap integers or pointers in memory.
1891
1892**Syntax**:
1893
1894.. code-block:: c++
1895
1896  type __sync_swap(type *ptr, type value, ...)
1897
1898**Example of Use**:
1899
1900.. code-block:: c++
1901
1902  int old_value = __sync_swap(&value, new_value);
1903
1904**Description**:
1905
1906The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1907atomic intrinsics to allow code to atomically swap the current value with the
1908new value.  More importantly, it helps developers write more efficient and
1909correct code by avoiding expensive loops around
1910``__sync_bool_compare_and_swap()`` or relying on the platform specific
1911implementation details of ``__sync_lock_test_and_set()``.  The
1912``__sync_swap()`` builtin is a full barrier.
1913
1914``__builtin_addressof``
1915-----------------------
1916
1917``__builtin_addressof`` performs the functionality of the built-in ``&``
1918operator, ignoring any ``operator&`` overload.  This is useful in constant
1919expressions in C++11, where there is no other way to take the address of an
1920object that overloads ``operator&``.
1921
1922**Example of use**:
1923
1924.. code-block:: c++
1925
1926  template<typename T> constexpr T *addressof(T &value) {
1927    return __builtin_addressof(value);
1928  }
1929
1930``__builtin_operator_new`` and ``__builtin_operator_delete``
1931------------------------------------------------------------
1932
1933``__builtin_operator_new`` allocates memory just like a non-placement non-class
1934*new-expression*. This is exactly like directly calling the normal
1935non-placement ``::operator new``, except that it allows certain optimizations
1936that the C++ standard does not permit for a direct function call to
1937``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
1938merging allocations).
1939
1940Likewise, ``__builtin_operator_delete`` deallocates memory just like a
1941non-class *delete-expression*, and is exactly like directly calling the normal
1942``::operator delete``, except that it permits optimizations. Only the unsized
1943form of ``__builtin_operator_delete`` is currently available.
1944
1945These builtins are intended for use in the implementation of ``std::allocator``
1946and other similar allocation libraries, and are only available in C++.
1947
1948Multiprecision Arithmetic Builtins
1949----------------------------------
1950
1951Clang provides a set of builtins which expose multiprecision arithmetic in a
1952manner amenable to C. They all have the following form:
1953
1954.. code-block:: c
1955
1956  unsigned x = ..., y = ..., carryin = ..., carryout;
1957  unsigned sum = __builtin_addc(x, y, carryin, &carryout);
1958
1959Thus one can form a multiprecision addition chain in the following manner:
1960
1961.. code-block:: c
1962
1963  unsigned *x, *y, *z, carryin=0, carryout;
1964  z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
1965  carryin = carryout;
1966  z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
1967  carryin = carryout;
1968  z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
1969  carryin = carryout;
1970  z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
1971
1972The complete list of builtins are:
1973
1974.. code-block:: c
1975
1976  unsigned char      __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
1977  unsigned short     __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1978  unsigned           __builtin_addc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1979  unsigned long      __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1980  unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
1981  unsigned char      __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
1982  unsigned short     __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1983  unsigned           __builtin_subc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1984  unsigned long      __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1985  unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
1986
1987Checked Arithmetic Builtins
1988---------------------------
1989
1990Clang provides a set of builtins that implement checked arithmetic for security
1991critical applications in a manner that is fast and easily expressable in C. As
1992an example of their usage:
1993
1994.. code-block:: c
1995
1996  errorcode_t security_critical_application(...) {
1997    unsigned x, y, result;
1998    ...
1999    if (__builtin_mul_overflow(x, y, &result))
2000      return kErrorCodeHackers;
2001    ...
2002    use_multiply(result);
2003    ...
2004  }
2005
2006Clang provides the following checked arithmetic builtins:
2007
2008.. code-block:: c
2009
2010  bool __builtin_add_overflow   (type1 x, type2 y, type3 *sum);
2011  bool __builtin_sub_overflow   (type1 x, type2 y, type3 *diff);
2012  bool __builtin_mul_overflow   (type1 x, type2 y, type3 *prod);
2013  bool __builtin_uadd_overflow  (unsigned x, unsigned y, unsigned *sum);
2014  bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
2015  bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
2016  bool __builtin_usub_overflow  (unsigned x, unsigned y, unsigned *diff);
2017  bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
2018  bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
2019  bool __builtin_umul_overflow  (unsigned x, unsigned y, unsigned *prod);
2020  bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
2021  bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
2022  bool __builtin_sadd_overflow  (int x, int y, int *sum);
2023  bool __builtin_saddl_overflow (long x, long y, long *sum);
2024  bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
2025  bool __builtin_ssub_overflow  (int x, int y, int *diff);
2026  bool __builtin_ssubl_overflow (long x, long y, long *diff);
2027  bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
2028  bool __builtin_smul_overflow  (int x, int y, int *prod);
2029  bool __builtin_smull_overflow (long x, long y, long *prod);
2030  bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
2031
2032Each builtin performs the specified mathematical operation on the
2033first two arguments and stores the result in the third argument.  If
2034possible, the result will be equal to mathematically-correct result
2035and the builtin will return 0.  Otherwise, the builtin will return
20361 and the result will be equal to the unique value that is equivalent
2037to the mathematically-correct result modulo two raised to the *k*
2038power, where *k* is the number of bits in the result type.  The
2039behavior of these builtins is well-defined for all argument values.
2040
2041The first three builtins work generically for operands of any integer type,
2042including boolean types.  The operands need not have the same type as each
2043other, or as the result.  The other builtins may implicitly promote or
2044convert their operands before performing the operation.
2045
2046Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
2047
2048Floating point builtins
2049---------------------------------------
2050
2051``__builtin_canonicalize``
2052--------------------------
2053
2054.. code-block:: c
2055
2056   double __builtin_canonicalize(double);
2057   float __builtin_canonicalizef(float);
2058   long double__builtin_canonicalizel(long double);
2059
2060Returns the platform specific canonical encoding of a floating point
2061number. This canonicalization is useful for implementing certain
2062numeric primitives such as frexp. See `LLVM canonicalize intrinsic
2063<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
2064more information on the semantics.
2065
2066String builtins
2067---------------
2068
2069Clang provides constant expression evaluation support for builtins forms of
2070the following functions from the C standard library ``<string.h>`` header:
2071
2072* ``memchr``
2073* ``memcmp``
2074* ``strchr``
2075* ``strcmp``
2076* ``strlen``
2077* ``strncmp``
2078* ``wcschr``
2079* ``wcscmp``
2080* ``wcslen``
2081* ``wcsncmp``
2082* ``wmemchr``
2083* ``wmemcmp``
2084
2085In each case, the builtin form has the name of the C library function prefixed
2086by ``__builtin_``. Example:
2087
2088.. code-block:: c
2089
2090  void *p = __builtin_memchr("foobar", 'b', 5);
2091
2092In addition to the above, one further builtin is provided:
2093
2094.. code-block:: c
2095
2096  char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
2097
2098``__builtin_char_memchr(a, b, c)`` is identical to
2099``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
2100constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
2101is disallowed in general).
2102
2103Support for constant expression evaluation for the above builtins be detected
2104with ``__has_feature(cxx_constexpr_string_builtins)``.
2105
2106Atomic Min/Max builtins with memory ordering
2107--------------------------------------------
2108
2109There are two atomic builtins with min/max in-memory comparison and swap.
2110The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
2111
2112* ``__atomic_fetch_min``
2113* ``__atomic_fetch_max``
2114
2115The builtins work with signed and unsigned integers and require to specify memory ordering.
2116The return value is the original value that was stored in memory before comparison.
2117
2118Example:
2119
2120.. code-block:: c
2121
2122  unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
2123
2124The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
2125``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
2126``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
2127
2128In terms or aquire-release ordering barriers these two operations are always
2129considered as operations with *load-store* semantics, even when the original value
2130is not actually modified after comparison.
2131
2132.. _langext-__c11_atomic:
2133
2134__c11_atomic builtins
2135---------------------
2136
2137Clang provides a set of builtins which are intended to be used to implement
2138C11's ``<stdatomic.h>`` header.  These builtins provide the semantics of the
2139``_explicit`` form of the corresponding C11 operation, and are named with a
2140``__c11_`` prefix.  The supported operations, and the differences from
2141the corresponding C11 operations, are:
2142
2143* ``__c11_atomic_init``
2144* ``__c11_atomic_thread_fence``
2145* ``__c11_atomic_signal_fence``
2146* ``__c11_atomic_is_lock_free`` (The argument is the size of the
2147  ``_Atomic(...)`` object, instead of its address)
2148* ``__c11_atomic_store``
2149* ``__c11_atomic_load``
2150* ``__c11_atomic_exchange``
2151* ``__c11_atomic_compare_exchange_strong``
2152* ``__c11_atomic_compare_exchange_weak``
2153* ``__c11_atomic_fetch_add``
2154* ``__c11_atomic_fetch_sub``
2155* ``__c11_atomic_fetch_and``
2156* ``__c11_atomic_fetch_or``
2157* ``__c11_atomic_fetch_xor``
2158
2159The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
2160``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
2161provided, with values corresponding to the enumerators of C11's
2162``memory_order`` enumeration.
2163
2164(Note that Clang additionally provides GCC-compatible ``__atomic_*``
2165builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
2166atomic builtins are an explicit form of the corresponding OpenCL 2.0
2167builtin function, and are named with a ``__opencl_`` prefix. The macros
2168``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
2169``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
2170and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
2171corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
2172
2173Low-level ARM exclusive memory builtins
2174---------------------------------------
2175
2176Clang provides overloaded builtins giving direct access to the three key ARM
2177instructions for implementing atomic operations.
2178
2179.. code-block:: c
2180
2181  T __builtin_arm_ldrex(const volatile T *addr);
2182  T __builtin_arm_ldaex(const volatile T *addr);
2183  int __builtin_arm_strex(T val, volatile T *addr);
2184  int __builtin_arm_stlex(T val, volatile T *addr);
2185  void __builtin_arm_clrex(void);
2186
2187The types ``T`` currently supported are:
2188
2189* Integer types with width at most 64 bits (or 128 bits on AArch64).
2190* Floating-point types
2191* Pointer types.
2192
2193Note that the compiler does not guarantee it will not insert stores which clear
2194the exclusive monitor in between an ``ldrex`` type operation and its paired
2195``strex``. In practice this is only usually a risk when the extra store is on
2196the same cache line as the variable being modified and Clang will only insert
2197stack stores on its own, so it is best not to use these operations on variables
2198with automatic storage duration.
2199
2200Also, loads and stores may be implicit in code written between the ``ldrex`` and
2201``strex``. Clang will not necessarily mitigate the effects of these either, so
2202care should be exercised.
2203
2204For these reasons the higher level atomic primitives should be preferred where
2205possible.
2206
2207Non-temporal load/store builtins
2208--------------------------------
2209
2210Clang provides overloaded builtins allowing generation of non-temporal memory
2211accesses.
2212
2213.. code-block:: c
2214
2215  T __builtin_nontemporal_load(T *addr);
2216  void __builtin_nontemporal_store(T value, T *addr);
2217
2218The types ``T`` currently supported are:
2219
2220* Integer types.
2221* Floating-point types.
2222* Vector types.
2223
2224Note that the compiler does not guarantee that non-temporal loads or stores
2225will be used.
2226
2227C++ Coroutines support builtins
2228--------------------------------
2229
2230.. warning::
2231  This is a work in progress. Compatibility across Clang/LLVM releases is not
2232  guaranteed.
2233
2234Clang provides experimental builtins to support C++ Coroutines as defined by
2235http://wg21.link/P0057. The following four are intended to be used by the
2236standard library to implement `std::experimental::coroutine_handle` type.
2237
2238**Syntax**:
2239
2240.. code-block:: c
2241
2242  void  __builtin_coro_resume(void *addr);
2243  void  __builtin_coro_destroy(void *addr);
2244  bool  __builtin_coro_done(void *addr);
2245  void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
2246
2247**Example of use**:
2248
2249.. code-block:: c++
2250
2251  template <> struct coroutine_handle<void> {
2252    void resume() const { __builtin_coro_resume(ptr); }
2253    void destroy() const { __builtin_coro_destroy(ptr); }
2254    bool done() const { return __builtin_coro_done(ptr); }
2255    // ...
2256  protected:
2257    void *ptr;
2258  };
2259
2260  template <typename Promise> struct coroutine_handle : coroutine_handle<> {
2261    // ...
2262    Promise &promise() const {
2263      return *reinterpret_cast<Promise *>(
2264        __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
2265    }
2266    static coroutine_handle from_promise(Promise &promise) {
2267      coroutine_handle p;
2268      p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
2269                                                      /*from-promise=*/true);
2270      return p;
2271    }
2272  };
2273
2274
2275Other coroutine builtins are either for internal clang use or for use during
2276development of the coroutine feature. See `Coroutines in LLVM
2277<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
2278more information on their semantics. Note that builtins matching the intrinsics
2279that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
2280llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
2281an appropriate value during the emission.
2282
2283**Syntax**:
2284
2285.. code-block:: c
2286
2287  size_t __builtin_coro_size()
2288  void  *__builtin_coro_frame()
2289  void  *__builtin_coro_free(void *coro_frame)
2290
2291  void  *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
2292  bool   __builtin_coro_alloc()
2293  void  *__builtin_coro_begin(void *memory)
2294  void   __builtin_coro_end(void *coro_frame, bool unwind)
2295  char   __builtin_coro_suspend(bool final)
2296  bool   __builtin_coro_param(void *original, void *copy)
2297
2298Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
2299automatically will insert one if the first argument to `llvm.coro.suspend` is
2300token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
2301as the first argument to the intrinsic.
2302
2303Non-standard C++11 Attributes
2304=============================
2305
2306Clang's non-standard C++11 attributes live in the ``clang`` attribute
2307namespace.
2308
2309Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
2310are accepted with the ``__attribute__((foo))`` syntax are also accepted as
2311``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
2312(see the list of `GCC function attributes
2313<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
2314attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
2315`GCC type attributes
2316<http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
2317implementation, these attributes must appertain to the *declarator-id* in a
2318declaration, which means they must go either at the start of the declaration or
2319immediately after the name being declared.
2320
2321For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
2322also applies the GNU ``noreturn`` attribute to ``f``.
2323
2324.. code-block:: c++
2325
2326  [[gnu::unused]] int a, f [[gnu::noreturn]] ();
2327
2328Target-Specific Extensions
2329==========================
2330
2331Clang supports some language features conditionally on some targets.
2332
2333ARM/AArch64 Language Extensions
2334-------------------------------
2335
2336Memory Barrier Intrinsics
2337^^^^^^^^^^^^^^^^^^^^^^^^^
2338Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
2339in the `ARM C Language Extensions Release 2.0
2340<http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
2341Note that these intrinsics are implemented as motion barriers that block
2342reordering of memory accesses and side effect instructions. Other instructions
2343like simple arithmetic may be reordered around the intrinsic. If you expect to
2344have no reordering at all, use inline assembly instead.
2345
2346X86/X86-64 Language Extensions
2347------------------------------
2348
2349The X86 backend has these language extensions:
2350
2351Memory references to specified segments
2352^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2353
2354Annotating a pointer with address space #256 causes it to be code generated
2355relative to the X86 GS segment register, address space #257 causes it to be
2356relative to the X86 FS segment, and address space #258 causes it to be
2357relative to the X86 SS segment.  Note that this is a very very low-level
2358feature that should only be used if you know what you're doing (for example in
2359an OS kernel).
2360
2361Here is an example:
2362
2363.. code-block:: c++
2364
2365  #define GS_RELATIVE __attribute__((address_space(256)))
2366  int foo(int GS_RELATIVE *P) {
2367    return *P;
2368  }
2369
2370Which compiles to (on X86-32):
2371
2372.. code-block:: gas
2373
2374  _foo:
2375          movl    4(%esp), %eax
2376          movl    %gs:(%eax), %eax
2377          ret
2378
2379Extensions for Static Analysis
2380==============================
2381
2382Clang supports additional attributes that are useful for documenting program
2383invariants and rules for static analysis tools, such as the `Clang Static
2384Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
2385in the analyzer's `list of source-level annotations
2386<https://clang-analyzer.llvm.org/annotations.html>`_.
2387
2388
2389Extensions for Dynamic Analysis
2390===============================
2391
2392Use ``__has_feature(address_sanitizer)`` to check if the code is being built
2393with :doc:`AddressSanitizer`.
2394
2395Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
2396with :doc:`ThreadSanitizer`.
2397
2398Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
2399with :doc:`MemorySanitizer`.
2400
2401Use ``__has_feature(safe_stack)`` to check if the code is being built
2402with :doc:`SafeStack`.
2403
2404
2405Extensions for selectively disabling optimization
2406=================================================
2407
2408Clang provides a mechanism for selectively disabling optimizations in functions
2409and methods.
2410
2411To disable optimizations in a single function definition, the GNU-style or C++11
2412non-standard attribute ``optnone`` can be used.
2413
2414.. code-block:: c++
2415
2416  // The following functions will not be optimized.
2417  // GNU-style attribute
2418  __attribute__((optnone)) int foo() {
2419    // ... code
2420  }
2421  // C++11 attribute
2422  [[clang::optnone]] int bar() {
2423    // ... code
2424  }
2425
2426To facilitate disabling optimization for a range of function definitions, a
2427range-based pragma is provided. Its syntax is ``#pragma clang optimize``
2428followed by ``off`` or ``on``.
2429
2430All function definitions in the region between an ``off`` and the following
2431``on`` will be decorated with the ``optnone`` attribute unless doing so would
2432conflict with explicit attributes already present on the function (e.g. the
2433ones that control inlining).
2434
2435.. code-block:: c++
2436
2437  #pragma clang optimize off
2438  // This function will be decorated with optnone.
2439  int foo() {
2440    // ... code
2441  }
2442
2443  // optnone conflicts with always_inline, so bar() will not be decorated.
2444  __attribute__((always_inline)) int bar() {
2445    // ... code
2446  }
2447  #pragma clang optimize on
2448
2449If no ``on`` is found to close an ``off`` region, the end of the region is the
2450end of the compilation unit.
2451
2452Note that a stray ``#pragma clang optimize on`` does not selectively enable
2453additional optimizations when compiling at low optimization levels. This feature
2454can only be used to selectively disable optimizations.
2455
2456The pragma has an effect on functions only at the point of their definition; for
2457function templates, this means that the state of the pragma at the point of an
2458instantiation is not necessarily relevant. Consider the following example:
2459
2460.. code-block:: c++
2461
2462  template<typename T> T twice(T t) {
2463    return 2 * t;
2464  }
2465
2466  #pragma clang optimize off
2467  template<typename T> T thrice(T t) {
2468    return 3 * t;
2469  }
2470
2471  int container(int a, int b) {
2472    return twice(a) + thrice(b);
2473  }
2474  #pragma clang optimize on
2475
2476In this example, the definition of the template function ``twice`` is outside
2477the pragma region, whereas the definition of ``thrice`` is inside the region.
2478The ``container`` function is also in the region and will not be optimized, but
2479it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
2480these two instantiations, ``twice`` will be optimized (because its definition
2481was outside the region) and ``thrice`` will not be optimized.
2482
2483Extensions for loop hint optimizations
2484======================================
2485
2486The ``#pragma clang loop`` directive is used to specify hints for optimizing the
2487subsequent for, while, do-while, or c++11 range-based for loop. The directive
2488provides options for vectorization, interleaving, unrolling and
2489distribution. Loop hints can be specified before any loop and will be ignored if
2490the optimization is not safe to apply.
2491
2492Vectorization and Interleaving
2493------------------------------
2494
2495A vectorized loop performs multiple iterations of the original loop
2496in parallel using vector instructions. The instruction set of the target
2497processor determines which vector instructions are available and their vector
2498widths. This restricts the types of loops that can be vectorized. The vectorizer
2499automatically determines if the loop is safe and profitable to vectorize. A
2500vector instruction cost model is used to select the vector width.
2501
2502Interleaving multiple loop iterations allows modern processors to further
2503improve instruction-level parallelism (ILP) using advanced hardware features,
2504such as multiple execution units and out-of-order execution. The vectorizer uses
2505a cost model that depends on the register pressure and generated code size to
2506select the interleaving count.
2507
2508Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
2509by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
2510manually enable vectorization or interleaving.
2511
2512.. code-block:: c++
2513
2514  #pragma clang loop vectorize(enable)
2515  #pragma clang loop interleave(enable)
2516  for(...) {
2517    ...
2518  }
2519
2520The vector width is specified by ``vectorize_width(_value_)`` and the interleave
2521count is specified by ``interleave_count(_value_)``, where
2522_value_ is a positive integer. This is useful for specifying the optimal
2523width/count of the set of target architectures supported by your application.
2524
2525.. code-block:: c++
2526
2527  #pragma clang loop vectorize_width(2)
2528  #pragma clang loop interleave_count(2)
2529  for(...) {
2530    ...
2531  }
2532
2533Specifying a width/count of 1 disables the optimization, and is equivalent to
2534``vectorize(disable)`` or ``interleave(disable)``.
2535
2536Loop Unrolling
2537--------------
2538
2539Unrolling a loop reduces the loop control overhead and exposes more
2540opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
2541eliminates the loop and replaces it with an enumerated sequence of loop
2542iterations. Full unrolling is only possible if the loop trip count is known at
2543compile time. Partial unrolling replicates the loop body within the loop and
2544reduces the trip count.
2545
2546If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
2547loop if the trip count is known at compile time. If the fully unrolled code size
2548is greater than an internal limit the loop will be partially unrolled up to this
2549limit. If the trip count is not known at compile time the loop will be partially
2550unrolled with a heuristically chosen unroll factor.
2551
2552.. code-block:: c++
2553
2554  #pragma clang loop unroll(enable)
2555  for(...) {
2556    ...
2557  }
2558
2559If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
2560loop if the trip count is known at compile time identically to
2561``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
2562if the loop count is not known at compile time.
2563
2564.. code-block:: c++
2565
2566  #pragma clang loop unroll(full)
2567  for(...) {
2568    ...
2569  }
2570
2571The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
2572_value_ is a positive integer. If this value is greater than the trip count the
2573loop will be fully unrolled. Otherwise the loop is partially unrolled subject
2574to the same code size limit as with ``unroll(enable)``.
2575
2576.. code-block:: c++
2577
2578  #pragma clang loop unroll_count(8)
2579  for(...) {
2580    ...
2581  }
2582
2583Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
2584
2585Loop Distribution
2586-----------------
2587
2588Loop Distribution allows splitting a loop into multiple loops.  This is
2589beneficial for example when the entire loop cannot be vectorized but some of the
2590resulting loops can.
2591
2592If ``distribute(enable))`` is specified and the loop has memory dependencies
2593that inhibit vectorization, the compiler will attempt to isolate the offending
2594operations into a new loop.  This optimization is not enabled by default, only
2595loops marked with the pragma are considered.
2596
2597.. code-block:: c++
2598
2599  #pragma clang loop distribute(enable)
2600  for (i = 0; i < N; ++i) {
2601    S1: A[i + 1] = A[i] + B[i];
2602    S2: C[i] = D[i] * E[i];
2603  }
2604
2605This loop will be split into two loops between statements S1 and S2.  The
2606second loop containing S2 will be vectorized.
2607
2608Loop Distribution is currently not enabled by default in the optimizer because
2609it can hurt performance in some cases.  For example, instruction-level
2610parallelism could be reduced by sequentializing the execution of the
2611statements S1 and S2 above.
2612
2613If Loop Distribution is turned on globally with
2614``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
2615be used the disable it on a per-loop basis.
2616
2617Additional Information
2618----------------------
2619
2620For convenience multiple loop hints can be specified on a single line.
2621
2622.. code-block:: c++
2623
2624  #pragma clang loop vectorize_width(4) interleave_count(8)
2625  for(...) {
2626    ...
2627  }
2628
2629If an optimization cannot be applied any hints that apply to it will be ignored.
2630For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
2631proven safe to vectorize. To identify and diagnose optimization issues use
2632`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
2633user guide for details.
2634
2635Extensions to specify floating-point flags
2636====================================================
2637
2638The ``#pragma clang fp`` pragma allows floating-point options to be specified
2639for a section of the source code. This pragma can only appear at file scope or
2640at the start of a compound statement (excluding comments). When using within a
2641compound statement, the pragma is active within the scope of the compound
2642statement.
2643
2644Currently, only FP contraction can be controlled with the pragma. ``#pragma
2645clang fp contract`` specifies whether the compiler should contract a multiply
2646and an addition (or subtraction) into a fused FMA operation when supported by
2647the target.
2648
2649The pragma can take three values: ``on``, ``fast`` and ``off``.  The ``on``
2650option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
2651fusion as specified the language standard.  The ``fast`` option allows fusiong
2652in cases when the language standard does not make this possible (e.g. across
2653statements in C)
2654
2655.. code-block:: c++
2656
2657  for(...) {
2658    #pragma clang fp contract(fast)
2659    a = b[i] * c[i];
2660    d[i] += a;
2661  }
2662
2663
2664The pragma can also be used with ``off`` which turns FP contraction off for a
2665section of the code. This can be useful when fast contraction is otherwise
2666enabled for the translation unit with the ``-ffp-contract=fast`` flag.
2667
2668Specifying an attribute for multiple declarations (#pragma clang attribute)
2669===========================================================================
2670
2671The ``#pragma clang attribute`` directive can be used to apply an attribute to
2672multiple declarations. The ``#pragma clang attribute push`` variation of the
2673directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
2674can be added to. The ``#pragma clang attribute (...)`` variation adds an
2675attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
2676the scope. You can also use ``#pragma clang attribute push (...)``, which is a
2677shorthand for when you want to add one attribute to a new scope. Multiple push
2678directives can be nested inside each other.
2679
2680The attributes that are used in the ``#pragma clang attribute`` directives
2681can be written using the GNU-style syntax:
2682
2683.. code-block:: c++
2684
2685  #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
2686
2687  void function(); // The function now has the annotate("custom") attribute
2688
2689  #pragma clang attribute pop
2690
2691The attributes can also be written using the C++11 style syntax:
2692
2693.. code-block:: c++
2694
2695  #pragma clang attribute push ([[noreturn]], apply_to = function)
2696
2697  void function(); // The function now has the [[noreturn]] attribute
2698
2699  #pragma clang attribute pop
2700
2701The ``__declspec`` style syntax is also supported:
2702
2703.. code-block:: c++
2704
2705  #pragma clang attribute push (__declspec(dllexport), apply_to = function)
2706
2707  void function(); // The function now has the __declspec(dllexport) attribute
2708
2709  #pragma clang attribute pop
2710
2711A single push directive accepts only one attribute regardless of the syntax
2712used.
2713
2714Because multiple push directives can be nested, if you're writing a macro that
2715expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
2716required) to add a namespace to your push/pop directives. A pop directive with a
2717namespace will pop the innermost push that has that same namespace. This will
2718ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
2719that an ``pop`` without a namespace will pop the innermost ``push`` without a
2720namespace. ``push``es with a namespace can only be popped by ``pop`` with the
2721same namespace. For instance:
2722
2723.. code-block:: c++
2724
2725   #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
2726   #define ASSUME_NORETURN_END   _Pragma("clang attribute AssumeNoreturn.pop")
2727
2728   #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
2729   #define ASSUME_UNAVAILABLE_END   _Pragma("clang attribute Unavailable.pop")
2730
2731
2732   ASSUME_NORETURN_BEGIN
2733   ASSUME_UNAVAILABLE_BEGIN
2734   void function(); // function has [[noreturn]] and __attribute__((unavailable))
2735   ASSUME_NORETURN_END
2736   void other_function(); // function has __attribute__((unavailable))
2737   ASSUME_UNAVAILABLE_END
2738
2739Without the namespaces on the macros, ``other_function`` will be annotated with
2740``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
2741a contrived example, but its very possible for this kind of situation to appear
2742in real code if the pragmas are spread out across a large file. You can test if
2743your version of clang supports namespaces on ``#pragma clang attribute`` with
2744``__has_extension(pragma_clang_attribute_namespaces)``.
2745
2746Subject Match Rules
2747-------------------
2748
2749The set of declarations that receive a single attribute from the attribute stack
2750depends on the subject match rules that were specified in the pragma. Subject
2751match rules are specified after the attribute. The compiler expects an
2752identifier that corresponds to the subject set specifier. The ``apply_to``
2753specifier is currently the only supported subject set specifier. It allows you
2754to specify match rules that form a subset of the attribute's allowed subject
2755set, i.e. the compiler doesn't require all of the attribute's subjects. For
2756example, an attribute like ``[[nodiscard]]`` whose subject set includes
2757``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
2758least one of these rules after ``apply_to``:
2759
2760.. code-block:: c++
2761
2762  #pragma clang attribute push([[nodiscard]], apply_to = enum)
2763
2764  enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
2765
2766  struct Record1 { }; // The struct will *not* receive [[nodiscard]]
2767
2768  #pragma clang attribute pop
2769
2770  #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
2771
2772  enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
2773
2774  struct Record2 { }; // The struct *will* receive [[nodiscard]]
2775
2776  #pragma clang attribute pop
2777
2778  // This is an error, since [[nodiscard]] can't be applied to namespaces:
2779  #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
2780
2781  #pragma clang attribute pop
2782
2783Multiple match rules can be specified using the ``any`` match rule, as shown
2784in the example above. The ``any`` rule applies attributes to all declarations
2785that are matched by at least one of the rules in the ``any``. It doesn't nest
2786and can't be used inside the other match rules. Redundant match rules or rules
2787that conflict with one another should not be used inside of ``any``.
2788
2789Clang supports the following match rules:
2790
2791- ``function``: Can be used to apply attributes to functions. This includes C++
2792  member functions, static functions, operators, and constructors/destructors.
2793
2794- ``function(is_member)``: Can be used to apply attributes to C++ member
2795  functions. This includes members like static functions, operators, and
2796  constructors/destructors.
2797
2798- ``hasType(functionType)``: Can be used to apply attributes to functions, C++
2799  member functions, and variables/fields whose type is a function pointer. It
2800  does not apply attributes to Objective-C methods or blocks.
2801
2802- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
2803  and C++11 type aliases.
2804
2805- ``record``: Can be used to apply attributes to ``struct``, ``class``, and
2806  ``union`` declarations.
2807
2808- ``record(unless(is_union))``: Can be used to apply attributes only to
2809  ``struct`` and ``class`` declarations.
2810
2811- ``enum``: Can be be used to apply attributes to enumeration declarations.
2812
2813- ``enum_constant``: Can be used to apply attributes to enumerators.
2814
2815- ``variable``: Can be used to apply attributes to variables, including
2816  local variables, parameters, global variables, and static member variables.
2817  It does not apply attributes to instance member variables or Objective-C
2818  ivars.
2819
2820- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
2821  variables only.
2822
2823- ``variable(is_global)``: Can be used to apply attributes to global variables
2824  only.
2825
2826- ``variable(is_parameter)``: Can be used to apply attributes to parameters
2827  only.
2828
2829- ``variable(unless(is_parameter))``: Can be used to apply attributes to all
2830  the variables that are not parameters.
2831
2832- ``field``: Can be used to apply attributes to non-static member variables
2833  in a record. This includes Objective-C ivars.
2834
2835- ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
2836
2837- ``objc_interface``: Can be used to apply attributes to ``@interface``
2838  declarations.
2839
2840- ``objc_protocol``: Can be used to apply attributes to ``@protocol``
2841  declarations.
2842
2843- ``objc_category``: Can be used to apply attributes to category declarations,
2844  including class extensions.
2845
2846- ``objc_method``: Can be used to apply attributes to Objective-C methods,
2847  including instance and class methods. Implicit methods like implicit property
2848  getters and setters do not receive the attribute.
2849
2850- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
2851  instance methods.
2852
2853- ``objc_property``: Can be used to apply attributes to ``@property``
2854  declarations.
2855
2856- ``block``: Can be used to apply attributes to block declarations. This does
2857  not include variables/fields of block pointer type.
2858
2859The use of ``unless`` in match rules is currently restricted to a strict set of
2860sub-rules that are used by the supported attributes. That means that even though
2861``variable(unless(is_parameter))`` is a valid match rule,
2862``variable(unless(is_thread_local))`` is not.
2863
2864Supported Attributes
2865--------------------
2866
2867Not all attributes can be used with the ``#pragma clang attribute`` directive.
2868Notably, statement attributes like ``[[fallthrough]]`` or type attributes
2869like ``address_space`` aren't supported by this directive. You can determine
2870whether or not an attribute is supported by the pragma by referring to the
2871:doc:`individual documentation for that attribute <AttributeReference>`.
2872
2873The attributes are applied to all matching declarations individually, even when
2874the attribute is semantically incorrect. The attributes that aren't applied to
2875any declaration are not verified semantically.
2876
2877Specifying section names for global objects (#pragma clang section)
2878===================================================================
2879
2880The ``#pragma clang section`` directive provides a means to assign section-names
2881to global variables, functions and static variables.
2882
2883The section names can be specified as:
2884
2885.. code-block:: c++
2886
2887  #pragma clang section bss="myBSS" data="myData" rodata="myRodata" text="myText"
2888
2889The section names can be reverted back to default name by supplying an empty
2890string to the section kind, for example:
2891
2892.. code-block:: c++
2893
2894  #pragma clang section bss="" data="" text="" rodata=""
2895
2896The ``#pragma clang section`` directive obeys the following rules:
2897
2898* The pragma applies to all global variable, statics and function declarations
2899  from the pragma to the end of the translation unit.
2900
2901* The pragma clang section is enabled automatically, without need of any flags.
2902
2903* This feature is only defined to work sensibly for ELF targets.
2904
2905* If section name is specified through _attribute_((section("myname"))), then
2906  the attribute name gains precedence.
2907
2908* Global variables that are initialized to zero will be placed in the named
2909  bss section, if one is present.
2910
2911* The ``#pragma clang section`` directive does not does try to infer section-kind
2912  from the name. For example, naming a section "``.bss.mySec``" does NOT mean
2913  it will be a bss section name.
2914
2915* The decision about which section-kind applies to each global is taken in the back-end.
2916  Once the section-kind is known, appropriate section name, as specified by the user using
2917  ``#pragma clang section`` directive, is applied to that global.
2918
2919Specifying Linker Options on ELF Targets
2920========================================
2921
2922The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
2923The second parameter is the library name (without the traditional Unix prefix of
2924``lib``).  This allows you to provide an implicit link of dependent libraries.
2925