blob: 50630490aae904efcf694f18ab8bdc215c16ea0c [file] [log] [blame]
Sean Silva3872b462012-12-12 23:44:55 +00001=========================
2Clang Language Extensions
3=========================
4
5.. contents::
6 :local:
Sean Silva55d3f942013-01-02 21:09:58 +00007 :depth: 1
Sean Silva3872b462012-12-12 23:44:55 +00008
Sean Silvaa0c392d2013-01-02 21:03:11 +00009.. toctree::
10 :hidden:
11
12 ObjectiveCLiterals
13 BlockLanguageSpec
14 AutomaticReferenceCounting
15
Sean Silva3872b462012-12-12 23:44:55 +000016Introduction
17============
18
19This document describes the language extensions provided by Clang. In addition
20to the language extensions listed here, Clang aims to support a broad range of
21GCC extensions. Please see the `GCC manual
22<http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
23these extensions.
24
25.. _langext-feature_check:
26
27Feature Checking Macros
28=======================
29
30Language extensions can be very useful, but only if you know you can depend on
31them. In order to allow fine-grain features checks, we support three builtin
32function-like macros. This allows you to directly test for a feature in your
33code without having to resort to something like autoconf or fragile "compiler
34version checks".
35
36``__has_builtin``
37-----------------
38
39This function-like macro takes a single identifier argument that is the name of
40a builtin function. It evaluates to 1 if the builtin is supported or 0 if not.
41It can be used like this:
42
43.. code-block:: c++
44
45 #ifndef __has_builtin // Optional of course.
46 #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
47 #endif
48
49 ...
50 #if __has_builtin(__builtin_trap)
51 __builtin_trap();
52 #else
53 abort();
54 #endif
55 ...
56
57.. _langext-__has_feature-__has_extension:
58
59``__has_feature`` and ``__has_extension``
60-----------------------------------------
61
62These function-like macros take a single identifier argument that is the name
63of a feature. ``__has_feature`` evaluates to 1 if the feature is both
64supported by Clang and standardized in the current language standard or 0 if
65not (but see :ref:`below <langext-has-feature-back-compat>`), while
66``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
67current language (either as a language extension or a standard language
68feature) or 0 if not. They can be used like this:
69
70.. code-block:: c++
71
72 #ifndef __has_feature // Optional of course.
73 #define __has_feature(x) 0 // Compatibility with non-clang compilers.
74 #endif
75 #ifndef __has_extension
76 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
77 #endif
78
79 ...
80 #if __has_feature(cxx_rvalue_references)
81 // This code will only be compiled with the -std=c++11 and -std=gnu++11
82 // options, because rvalue references are only standardized in C++11.
83 #endif
84
85 #if __has_extension(cxx_rvalue_references)
86 // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
87 // and -std=gnu++98 options, because rvalue references are supported as a
88 // language extension in C++98.
89 #endif
90
91.. _langext-has-feature-back-compat:
92
93For backwards compatibility reasons, ``__has_feature`` can also be used to test
94for support for non-standardized features, i.e. features not prefixed ``c_``,
95``cxx_`` or ``objc_``.
96
97Another use of ``__has_feature`` is to check for compiler features not related
Sean Silva159cc9e2013-01-02 13:07:47 +000098to the language standard, such as e.g. :doc:`AddressSanitizer
99<AddressSanitizer>`.
Sean Silva3872b462012-12-12 23:44:55 +0000100
101If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
102to ``__has_feature``.
103
104The feature tag is described along with the language feature below.
105
106The feature name or extension name can also be specified with a preceding and
107following ``__`` (double underscore) to avoid interference from a macro with
108the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
109of ``cxx_rvalue_references``.
110
111``__has_attribute``
112-------------------
113
114This function-like macro takes a single identifier argument that is the name of
115an attribute. It evaluates to 1 if the attribute is supported or 0 if not. It
116can be used like this:
117
118.. code-block:: c++
119
120 #ifndef __has_attribute // Optional of course.
121 #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
122 #endif
123
124 ...
125 #if __has_attribute(always_inline)
126 #define ALWAYS_INLINE __attribute__((always_inline))
127 #else
128 #define ALWAYS_INLINE
129 #endif
130 ...
131
132The attribute name can also be specified with a preceding and following ``__``
133(double underscore) to avoid interference from a macro with the same name. For
134instance, ``__always_inline__`` can be used instead of ``always_inline``.
135
136Include File Checking Macros
137============================
138
139Not all developments systems have the same include files. The
140:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
141you to check for the existence of an include file before doing a possibly
142failing ``#include`` directive.
143
144.. _langext-__has_include:
145
146``__has_include``
147-----------------
148
149This function-like macro takes a single file name string argument that is the
150name of an include file. It evaluates to 1 if the file can be found using the
151include paths, or 0 otherwise:
152
153.. code-block:: c++
154
155 // Note the two possible file name string formats.
156 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
157 # include "myinclude.h"
158 #endif
159
160 // To avoid problem with non-clang compilers not having this macro.
161 #if defined(__has_include) && __has_include("myinclude.h")
162 # include "myinclude.h"
163 #endif
164
165To test for this feature, use ``#if defined(__has_include)``.
166
167.. _langext-__has_include_next:
168
169``__has_include_next``
170----------------------
171
172This function-like macro takes a single file name string argument that is the
173name of an include file. It is like ``__has_include`` except that it looks for
174the second instance of the given file found in the include paths. It evaluates
175to 1 if the second instance of the file can be found using the include paths,
176or 0 otherwise:
177
178.. code-block:: c++
179
180 // Note the two possible file name string formats.
181 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
182 # include_next "myinclude.h"
183 #endif
184
185 // To avoid problem with non-clang compilers not having this macro.
186 #if defined(__has_include_next) && __has_include_next("myinclude.h")
187 # include_next "myinclude.h"
188 #endif
189
190Note that ``__has_include_next``, like the GNU extension ``#include_next``
191directive, is intended for use in headers only, and will issue a warning if
192used in the top-level compilation file. A warning will also be issued if an
193absolute path is used in the file argument.
194
195``__has_warning``
196-----------------
197
198This function-like macro takes a string literal that represents a command line
199option for a warning and returns true if that is a valid warning option.
200
201.. code-block:: c++
202
203 #if __has_warning("-Wformat")
204 ...
205 #endif
206
207Builtin Macros
208==============
209
210``__BASE_FILE__``
211 Defined to a string that contains the name of the main input file passed to
212 Clang.
213
214``__COUNTER__``
215 Defined to an integer value that starts at zero and is incremented each time
216 the ``__COUNTER__`` macro is expanded.
217
218``__INCLUDE_LEVEL__``
219 Defined to an integral value that is the include depth of the file currently
220 being translated. For the main file, this value is zero.
221
222``__TIMESTAMP__``
223 Defined to the date and time of the last modification of the current source
224 file.
225
226``__clang__``
227 Defined when compiling with Clang
228
229``__clang_major__``
230 Defined to the major marketing version number of Clang (e.g., the 2 in
231 2.0.1). Note that marketing version numbers should not be used to check for
232 language features, as different vendors use different numbering schemes.
233 Instead, use the :ref:`langext-feature_check`.
234
235``__clang_minor__``
236 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
237 that marketing version numbers should not be used to check for language
238 features, as different vendors use different numbering schemes. Instead, use
239 the :ref:`langext-feature_check`.
240
241``__clang_patchlevel__``
242 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
243
244``__clang_version__``
245 Defined to a string that captures the Clang marketing version, including the
246 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
247
248.. _langext-vectors:
249
250Vectors and Extended Vectors
251============================
252
253Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
254
255OpenCL vector types are created using ``ext_vector_type`` attribute. It
256support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
257is:
258
259.. code-block:: c++
260
261 typedef float float4 __attribute__((ext_vector_type(4)));
262 typedef float float2 __attribute__((ext_vector_type(2)));
263
264 float4 foo(float2 a, float2 b) {
265 float4 c;
266 c.xz = a;
267 c.yw = b;
268 return c;
269 }
270
271Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
272
273Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax
274and functions. For example:
275
276.. code-block:: c++
277
278 vector float foo(vector int a) {
279 vector int b;
280 b = vec_add(a, a) + a;
281 return (vector float)b;
282 }
283
284NEON vector types are created using ``neon_vector_type`` and
285``neon_polyvector_type`` attributes. For example:
286
287.. code-block:: c++
288
289 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
290 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
291
292 int8x8_t foo(int8x8_t a) {
293 int8x8_t v;
294 v = a;
295 return v;
296 }
297
298Vector Literals
299---------------
300
301Vector literals can be used to create vectors from a set of scalars, or
302vectors. Either parentheses or braces form can be used. In the parentheses
303form the number of literal values specified must be one, i.e. referring to a
304scalar value, or must match the size of the vector type being created. If a
305single scalar literal value is specified, the scalar literal value will be
306replicated to all the components of the vector type. In the brackets form any
307number of literals can be specified. For example:
308
309.. code-block:: c++
310
311 typedef int v4si __attribute__((__vector_size__(16)));
312 typedef float float4 __attribute__((ext_vector_type(4)));
313 typedef float float2 __attribute__((ext_vector_type(2)));
314
315 v4si vsi = (v4si){1, 2, 3, 4};
316 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
317 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
318 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
319 vector int vi3 = (vector int)(1, 2); // error
320 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
321 vector int vi5 = (vector int)(1, 2, 3, 4);
322 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
323
324Vector Operations
325-----------------
326
327The table below shows the support for each operation by vector extension. A
328dash indicates that an operation is not accepted according to a corresponding
329specification.
330
331============================== ====== ======= === ====
332 Opeator OpenCL AltiVec GCC NEON
333============================== ====== ======= === ====
334[] yes yes yes --
335unary operators +, -- yes yes yes --
336++, -- -- yes yes yes --
337+,--,*,/,% yes yes yes --
338bitwise operators &,|,^,~ yes yes yes --
339>>,<< yes yes yes --
340!, &&, || no -- -- --
341==, !=, >, <, >=, <= yes yes -- --
342= yes yes yes yes
343:? yes -- -- --
344sizeof yes yes yes yes
345============================== ====== ======= === ====
346
347See also :ref:`langext-__builtin_shufflevector`.
348
349Messages on ``deprecated`` and ``unavailable`` Attributes
350=========================================================
351
352An optional string message can be added to the ``deprecated`` and
353``unavailable`` attributes. For example:
354
355.. code-block:: c++
356
357 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
358
359If the deprecated or unavailable declaration is used, the message will be
360incorporated into the appropriate diagnostic:
361
362.. code-block:: c++
363
364 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
365 [-Wdeprecated-declarations]
366 explode();
367 ^
368
369Query for this feature with
370``__has_extension(attribute_deprecated_with_message)`` and
371``__has_extension(attribute_unavailable_with_message)``.
372
373Attributes on Enumerators
374=========================
375
376Clang allows attributes to be written on individual enumerators. This allows
377enumerators to be deprecated, made unavailable, etc. The attribute must appear
378after the enumerator name and before any initializer, like so:
379
380.. code-block:: c++
381
382 enum OperationMode {
383 OM_Invalid,
384 OM_Normal,
385 OM_Terrified __attribute__((deprecated)),
386 OM_AbortOnError __attribute__((deprecated)) = 4
387 };
388
389Attributes on the ``enum`` declaration do not apply to individual enumerators.
390
391Query for this feature with ``__has_extension(enumerator_attributes)``.
392
393'User-Specified' System Frameworks
394==================================
395
396Clang provides a mechanism by which frameworks can be built in such a way that
397they will always be treated as being "system frameworks", even if they are not
398present in a system framework directory. This can be useful to system
399framework developers who want to be able to test building other applications
400with development builds of their framework, including the manner in which the
401compiler changes warning behavior for system headers.
402
403Framework developers can opt-in to this mechanism by creating a
404"``.system_framework``" file at the top-level of their framework. That is, the
405framework should have contents like:
406
407.. code-block:: none
408
409 .../TestFramework.framework
410 .../TestFramework.framework/.system_framework
411 .../TestFramework.framework/Headers
412 .../TestFramework.framework/Headers/TestFramework.h
413 ...
414
415Clang will treat the presence of this file as an indicator that the framework
416should be treated as a system framework, regardless of how it was found in the
417framework search path. For consistency, we recommend that such files never be
418included in installed versions of the framework.
419
420Availability attribute
421======================
422
423Clang introduces the ``availability`` attribute, which can be placed on
424declarations to describe the lifecycle of that declaration relative to
425operating system versions. Consider the function declaration for a
426hypothetical function ``f``:
427
428.. code-block:: c++
429
430 void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
431
432The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
433deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
434is used by Clang to determine when it is safe to use ``f``: for example, if
435Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
436succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
437succeeds but Clang emits a warning specifying that the function is deprecated.
438Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
439fails because ``f()`` is no longer available.
440
441The availablility attribute is a comma-separated list starting with the
442platform name and then including clauses specifying important milestones in the
443declaration's lifetime (in any order) along with additional information. Those
444clauses can be:
445
446introduced=\ *version*
447 The first version in which this declaration was introduced.
448
449deprecated=\ *version*
450 The first version in which this declaration was deprecated, meaning that
451 users should migrate away from this API.
452
453obsoleted=\ *version*
454 The first version in which this declaration was obsoleted, meaning that it
455 was removed completely and can no longer be used.
456
457unavailable
458 This declaration is never available on this platform.
459
460message=\ *string-literal*
461 Additional message text that Clang will provide when emitting a warning or
462 error about use of a deprecated or obsoleted declaration. Useful to direct
463 users to replacement APIs.
464
465Multiple availability attributes can be placed on a declaration, which may
466correspond to different platforms. Only the availability attribute with the
467platform corresponding to the target platform will be used; any others will be
468ignored. If no availability attribute specifies availability for the current
469target platform, the availability attributes are ignored. Supported platforms
470are:
471
472``ios``
473 Apple's iOS operating system. The minimum deployment target is specified by
474 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
475 command-line arguments.
476
477``macosx``
478 Apple's Mac OS X operating system. The minimum deployment target is
479 specified by the ``-mmacosx-version-min=*version*`` command-line argument.
480
481A declaration can be used even when deploying back to a platform version prior
482to when the declaration was introduced. When this happens, the declaration is
483`weakly linked
484<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
485as if the ``weak_import`` attribute were added to the declaration. A
486weakly-linked declaration may or may not be present a run-time, and a program
487can determine whether the declaration is present by checking whether the
488address of that declaration is non-NULL.
489
490Checks for Standard Language Features
491=====================================
492
493The ``__has_feature`` macro can be used to query if certain standard language
494features are enabled. The ``__has_extension`` macro can be used to query if
495language features are available as an extension when compiling for a standard
496which does not provide them. The features which can be tested are listed here.
497
498C++98
499-----
500
501The features listed below are part of the C++98 standard. These features are
502enabled by default when compiling C++ code.
503
504C++ exceptions
505^^^^^^^^^^^^^^
506
507Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
508enabled. For example, compiling code with ``-fno-exceptions`` disables C++
509exceptions.
510
511C++ RTTI
512^^^^^^^^
513
514Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
515example, compiling code with ``-fno-rtti`` disables the use of RTTI.
516
517C++11
518-----
519
520The features listed below are part of the C++11 standard. As a result, all
521these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
522when compiling C++ code.
523
524C++11 SFINAE includes access control
525^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
526
527Use ``__has_feature(cxx_access_control_sfinae)`` or
528``__has_extension(cxx_access_control_sfinae)`` to determine whether
529access-control errors (e.g., calling a private constructor) are considered to
530be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
531<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
532
533C++11 alias templates
534^^^^^^^^^^^^^^^^^^^^^
535
536Use ``__has_feature(cxx_alias_templates)`` or
537``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
538alias declarations and alias templates is enabled.
539
540C++11 alignment specifiers
541^^^^^^^^^^^^^^^^^^^^^^^^^^
542
543Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
544determine if support for alignment specifiers using ``alignas`` is enabled.
545
546C++11 attributes
547^^^^^^^^^^^^^^^^
548
549Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
550determine if support for attribute parsing with C++11's square bracket notation
551is enabled.
552
553C++11 generalized constant expressions
554^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
555
556Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
557constant expressions (e.g., ``constexpr``) is enabled.
558
559C++11 ``decltype()``
560^^^^^^^^^^^^^^^^^^^^
561
562Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
563determine if support for the ``decltype()`` specifier is enabled. C++11's
564``decltype`` does not require type-completeness of a function call expression.
565Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
566``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
567support for this feature is enabled.
568
569C++11 default template arguments in function templates
570^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
571
572Use ``__has_feature(cxx_default_function_template_args)`` or
573``__has_extension(cxx_default_function_template_args)`` to determine if support
574for default template arguments in function templates is enabled.
575
576C++11 ``default``\ ed functions
577^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
578
579Use ``__has_feature(cxx_defaulted_functions)`` or
580``__has_extension(cxx_defaulted_functions)`` to determine if support for
581defaulted function definitions (with ``= default``) is enabled.
582
583C++11 delegating constructors
584^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
585
586Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
587delegating constructors is enabled.
588
589C++11 ``deleted`` functions
590^^^^^^^^^^^^^^^^^^^^^^^^^^^
591
592Use ``__has_feature(cxx_deleted_functions)`` or
593``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
594function definitions (with ``= delete``) is enabled.
595
596C++11 explicit conversion functions
597^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
598
599Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
600``explicit`` conversion functions is enabled.
601
602C++11 generalized initializers
603^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
604
605Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
606generalized initializers (using braced lists and ``std::initializer_list``) is
607enabled.
608
609C++11 implicit move constructors/assignment operators
610^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
611
612Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
613generate move constructors and move assignment operators where needed.
614
615C++11 inheriting constructors
616^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
617
618Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
619inheriting constructors is enabled. Clang does not currently implement this
620feature.
621
622C++11 inline namespaces
623^^^^^^^^^^^^^^^^^^^^^^^
624
625Use ``__has_feature(cxx_inline_namespaces)`` or
626``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
627namespaces is enabled.
628
629C++11 lambdas
630^^^^^^^^^^^^^
631
632Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
633determine if support for lambdas is enabled.
634
635C++11 local and unnamed types as template arguments
636^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
637
638Use ``__has_feature(cxx_local_type_template_args)`` or
639``__has_extension(cxx_local_type_template_args)`` to determine if support for
640local and unnamed types as template arguments is enabled.
641
642C++11 noexcept
643^^^^^^^^^^^^^^
644
645Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
646determine if support for noexcept exception specifications is enabled.
647
648C++11 in-class non-static data member initialization
649^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
650
651Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
652initialization of non-static data members is enabled.
653
654C++11 ``nullptr``
655^^^^^^^^^^^^^^^^^
656
657Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
658determine if support for ``nullptr`` is enabled.
659
660C++11 ``override control``
661^^^^^^^^^^^^^^^^^^^^^^^^^^
662
663Use ``__has_feature(cxx_override_control)`` or
664``__has_extension(cxx_override_control)`` to determine if support for the
665override control keywords is enabled.
666
667C++11 reference-qualified functions
668^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
669
670Use ``__has_feature(cxx_reference_qualified_functions)`` or
671``__has_extension(cxx_reference_qualified_functions)`` to determine if support
672for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
673applied to ``*this``) is enabled.
674
675C++11 range-based ``for`` loop
676^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
677
678Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
679determine if support for the range-based for loop is enabled.
680
681C++11 raw string literals
682^^^^^^^^^^^^^^^^^^^^^^^^^
683
684Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
685string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
686
687C++11 rvalue references
688^^^^^^^^^^^^^^^^^^^^^^^
689
690Use ``__has_feature(cxx_rvalue_references)`` or
691``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
692references is enabled.
693
694C++11 ``static_assert()``
695^^^^^^^^^^^^^^^^^^^^^^^^^
696
697Use ``__has_feature(cxx_static_assert)`` or
698``__has_extension(cxx_static_assert)`` to determine if support for compile-time
699assertions using ``static_assert`` is enabled.
700
701C++11 type inference
702^^^^^^^^^^^^^^^^^^^^
703
704Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
705determine C++11 type inference is supported using the ``auto`` specifier. If
706this is disabled, ``auto`` will instead be a storage class specifier, as in C
707or C++98.
708
709C++11 strongly typed enumerations
710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
711
712Use ``__has_feature(cxx_strong_enums)`` or
713``__has_extension(cxx_strong_enums)`` to determine if support for strongly
714typed, scoped enumerations is enabled.
715
716C++11 trailing return type
717^^^^^^^^^^^^^^^^^^^^^^^^^^
718
719Use ``__has_feature(cxx_trailing_return)`` or
720``__has_extension(cxx_trailing_return)`` to determine if support for the
721alternate function declaration syntax with trailing return type is enabled.
722
723C++11 Unicode string literals
724^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
725
726Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
727string literals is enabled.
728
729C++11 unrestricted unions
730^^^^^^^^^^^^^^^^^^^^^^^^^
731
732Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
733unrestricted unions is enabled.
734
735C++11 user-defined literals
736^^^^^^^^^^^^^^^^^^^^^^^^^^^
737
738Use ``__has_feature(cxx_user_literals)`` to determine if support for
739user-defined literals is enabled.
740
741C++11 variadic templates
742^^^^^^^^^^^^^^^^^^^^^^^^
743
744Use ``__has_feature(cxx_variadic_templates)`` or
745``__has_extension(cxx_variadic_templates)`` to determine if support for
746variadic templates is enabled.
747
748C11
749---
750
751The features listed below are part of the C11 standard. As a result, all these
752features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
753compiling C code. Additionally, because these features are all
754backward-compatible, they are available as extensions in all language modes.
755
756C11 alignment specifiers
757^^^^^^^^^^^^^^^^^^^^^^^^
758
759Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
760if support for alignment specifiers using ``_Alignas`` is enabled.
761
762C11 atomic operations
763^^^^^^^^^^^^^^^^^^^^^
764
765Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
766if support for atomic types using ``_Atomic`` is enabled. Clang also provides
767:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
768the ``<stdatomic.h>`` operations on ``_Atomic`` types.
769
770C11 generic selections
771^^^^^^^^^^^^^^^^^^^^^^
772
773Use ``__has_feature(c_generic_selections)`` or
774``__has_extension(c_generic_selections)`` to determine if support for generic
775selections is enabled.
776
777As an extension, the C11 generic selection expression is available in all
778languages supported by Clang. The syntax is the same as that given in the C11
779standard.
780
781In C, type compatibility is decided according to the rules given in the
782appropriate standard, but in C++, which lacks the type compatibility rules used
783in C, types are considered compatible only if they are equivalent.
784
785C11 ``_Static_assert()``
786^^^^^^^^^^^^^^^^^^^^^^^^
787
788Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
789to determine if support for compile-time assertions using ``_Static_assert`` is
790enabled.
791
792Checks for Type Traits
793======================
794
795Clang supports the `GNU C++ type traits
796<http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
797`Microsoft Visual C++ Type traits
798<http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. For each
799supported type trait ``__X``, ``__has_extension(X)`` indicates the presence of
800the type trait. For example:
801
802.. code-block:: c++
803
804 #if __has_extension(is_convertible_to)
805 template<typename From, typename To>
806 struct is_convertible_to {
807 static const bool value = __is_convertible_to(From, To);
808 };
809 #else
810 // Emulate type trait
811 #endif
812
813The following type traits are supported by Clang:
814
815* ``__has_nothrow_assign`` (GNU, Microsoft)
816* ``__has_nothrow_copy`` (GNU, Microsoft)
817* ``__has_nothrow_constructor`` (GNU, Microsoft)
818* ``__has_trivial_assign`` (GNU, Microsoft)
819* ``__has_trivial_copy`` (GNU, Microsoft)
820* ``__has_trivial_constructor`` (GNU, Microsoft)
821* ``__has_trivial_destructor`` (GNU, Microsoft)
822* ``__has_virtual_destructor`` (GNU, Microsoft)
823* ``__is_abstract`` (GNU, Microsoft)
824* ``__is_base_of`` (GNU, Microsoft)
825* ``__is_class`` (GNU, Microsoft)
826* ``__is_convertible_to`` (Microsoft)
827* ``__is_empty`` (GNU, Microsoft)
828* ``__is_enum`` (GNU, Microsoft)
829* ``__is_interface_class`` (Microsoft)
830* ``__is_pod`` (GNU, Microsoft)
831* ``__is_polymorphic`` (GNU, Microsoft)
832* ``__is_union`` (GNU, Microsoft)
833* ``__is_literal(type)``: Determines whether the given type is a literal type
834* ``__is_final``: Determines whether the given type is declared with a
835 ``final`` class-virt-specifier.
836* ``__underlying_type(type)``: Retrieves the underlying type for a given
837 ``enum`` type. This trait is required to implement the C++11 standard
838 library.
839* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
840 of type ``totype`` can be assigned to from a value of type ``fromtype`` such
841 that no non-trivial functions are called as part of that assignment. This
842 trait is required to implement the C++11 standard library.
843* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
844 value of type ``type`` can be direct-initialized with arguments of types
845 ``argtypes...`` such that no non-trivial functions are called as part of
846 that initialization. This trait is required to implement the C++11 standard
847 library.
848
849Blocks
850======
851
852The syntax and high level language feature description is in
Dmitri Gribenko7b00b842012-12-20 20:51:59 +0000853:doc:`BlockLanguageSpec`. Implementation and ABI details for the clang
854implementation are in `Block-ABI-Apple.txt <Block-ABI-Apple.txt>`_.
Sean Silva3872b462012-12-12 23:44:55 +0000855
856Query for this feature with ``__has_extension(blocks)``.
857
858Objective-C Features
859====================
860
861Related result types
862--------------------
863
864According to Cocoa conventions, Objective-C methods with certain names
865("``init``", "``alloc``", etc.) always return objects that are an instance of
866the receiving class's type. Such methods are said to have a "related result
867type", meaning that a message send to one of these methods will have the same
868static type as an instance of the receiver class. For example, given the
869following classes:
870
871.. code-block:: objc
872
873 @interface NSObject
874 + (id)alloc;
875 - (id)init;
876 @end
877
878 @interface NSArray : NSObject
879 @end
880
881and this common initialization pattern
882
883.. code-block:: objc
884
885 NSArray *array = [[NSArray alloc] init];
886
887the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
888``alloc`` implicitly has a related result type. Similarly, the type of the
889expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
890related result type and its receiver is known to have the type ``NSArray *``.
891If neither ``alloc`` nor ``init`` had a related result type, the expressions
892would have had type ``id``, as declared in the method signature.
893
894A method with a related result type can be declared by using the type
895``instancetype`` as its result type. ``instancetype`` is a contextual keyword
896that is only permitted in the result type of an Objective-C method, e.g.
897
898.. code-block:: objc
899
900 @interface A
901 + (instancetype)constructAnA;
902 @end
903
904The related result type can also be inferred for some methods. To determine
905whether a method has an inferred related result type, the first word in the
906camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
907and the method will have a related result type if its return type is compatible
908with the type of its class and if:
909
910* the first word is "``alloc``" or "``new``", and the method is a class method,
911 or
912
913* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
914 and the method is an instance method.
915
916If a method with a related result type is overridden by a subclass method, the
917subclass method must also return a type that is compatible with the subclass
918type. For example:
919
920.. code-block:: objc
921
922 @interface NSString : NSObject
923 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
924 @end
925
926Related result types only affect the type of a message send or property access
927via the given method. In all other respects, a method with a related result
928type is treated the same way as method that returns ``id``.
929
930Use ``__has_feature(objc_instancetype)`` to determine whether the
931``instancetype`` contextual keyword is available.
932
933Automatic reference counting
934----------------------------
935
Sean Silva159cc9e2013-01-02 13:07:47 +0000936Clang provides support for :doc:`automated reference counting
937<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
Sean Silva3872b462012-12-12 23:44:55 +0000938for manual ``retain``/``release``/``autorelease`` message sends. There are two
939feature macros associated with automatic reference counting:
940``__has_feature(objc_arc)`` indicates the availability of automated reference
941counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
942automated reference counting also includes support for ``__weak`` pointers to
943Objective-C objects.
944
Sean Silva159cc9e2013-01-02 13:07:47 +0000945.. _objc-fixed-enum:
946
Sean Silva3872b462012-12-12 23:44:55 +0000947Enumerations with a fixed underlying type
948-----------------------------------------
949
950Clang provides support for C++11 enumerations with a fixed underlying type
951within Objective-C. For example, one can write an enumeration type as:
952
953.. code-block:: c++
954
955 typedef enum : unsigned char { Red, Green, Blue } Color;
956
957This specifies that the underlying type, which is used to store the enumeration
958value, is ``unsigned char``.
959
960Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
961underlying types is available in Objective-C.
962
963Interoperability with C++11 lambdas
964-----------------------------------
965
966Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
967permitting a lambda to be implicitly converted to a block pointer with the
968corresponding signature. For example, consider an API such as ``NSArray``'s
969array-sorting method:
970
971.. code-block:: objc
972
973 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
974
975``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
976(^)(id, id)``, and parameters of this type are generally provided with block
977literals as arguments. However, one can also use a C++11 lambda so long as it
978provides the same signature (in this case, accepting two parameters of type
979``id`` and returning an ``NSComparisonResult``):
980
981.. code-block:: objc
982
983 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
984 @"String 02"];
985 const NSStringCompareOptions comparisonOptions
986 = NSCaseInsensitiveSearch | NSNumericSearch |
987 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
988 NSLocale *currentLocale = [NSLocale currentLocale];
989 NSArray *sorted
990 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
991 NSRange string1Range = NSMakeRange(0, [s1 length]);
992 return [s1 compare:s2 options:comparisonOptions
993 range:string1Range locale:currentLocale];
994 }];
995 NSLog(@"sorted: %@", sorted);
996
997This code relies on an implicit conversion from the type of the lambda
998expression (an unnamed, local class type called the *closure type*) to the
999corresponding block pointer type. The conversion itself is expressed by a
1000conversion operator in that closure type that produces a block pointer with the
1001same signature as the lambda itself, e.g.,
1002
1003.. code-block:: objc
1004
1005 operator NSComparisonResult (^)(id, id)() const;
1006
1007This conversion function returns a new block that simply forwards the two
1008parameters to the lambda object (which it captures by copy), then returns the
1009result. The returned block is first copied (with ``Block_copy``) and then
1010autoreleased. As an optimization, if a lambda expression is immediately
1011converted to a block pointer (as in the first example, above), then the block
1012is not copied and autoreleased: rather, it is given the same lifetime as a
1013block literal written at that point in the program, which avoids the overhead
1014of copying a block to the heap in the common case.
1015
1016The conversion from a lambda to a block pointer is only available in
1017Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1018management (autorelease).
1019
1020Object Literals and Subscripting
1021--------------------------------
1022
Sean Silva159cc9e2013-01-02 13:07:47 +00001023Clang provides support for :doc:`Object Literals and Subscripting
1024<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
Sean Silva3872b462012-12-12 23:44:55 +00001025programming patterns, makes programs more concise, and improves the safety of
1026container creation. There are several feature macros associated with object
1027literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1028availability of array literals; ``__has_feature(objc_dictionary_literals)``
1029tests the availability of dictionary literals;
1030``__has_feature(objc_subscripting)`` tests the availability of object
1031subscripting.
1032
1033Objective-C Autosynthesis of Properties
1034---------------------------------------
1035
1036Clang provides support for autosynthesis of declared properties. Using this
1037feature, clang provides default synthesis of those properties not declared
1038@dynamic and not having user provided backing getter and setter methods.
1039``__has_feature(objc_default_synthesize_properties)`` checks for availability
1040of this feature in version of clang being used.
1041
Jordan Rose3115f5b62012-12-15 00:37:01 +00001042.. _langext-objc_method_family:
1043
1044The ``objc_method_family`` attribute
1045------------------------------------
1046
1047Many methods in Objective-C have conventional meanings determined by their
1048selectors. It is sometimes useful to be able to mark a method as having a
1049particular conventional meaning despite not having the right selector, or as
1050not having the conventional meaning that its selector would suggest. For these
1051use cases, we provide an attribute to specifically describe the "method family"
1052that a method belongs to.
1053
1054**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
1055``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
1056attribute can only be placed at the end of a method declaration:
1057
1058.. code-block:: objc
1059
1060 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
1061
1062Users who do not wish to change the conventional meaning of a method, and who
1063merely want to document its non-standard retain and release semantics, should
1064use the :ref:`retaining behavior attributes <langext-objc-retain-release>`
1065described below.
1066
1067Query for this feature with ``__has_attribute(objc_method_family)``.
1068
1069.. _langext-objc-retain-release:
1070
1071Objective-C retaining behavior attributes
1072-----------------------------------------
1073
1074In Objective-C, functions and methods are generally assumed to follow the
1075`Cocoa Memory Management
1076<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1077conventions for ownership of object arguments and
1078return values. However, there are exceptions, and so Clang provides attributes
1079to allow these exceptions to be documented. This are used by ARC and the
1080`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
1081better described using the :ref:`objc_method_family
1082<langext-objc_method_family>` attribute instead.
1083
1084**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1085``ns_returns_autoreleased``, ``cf_returns_retained``, and
1086``cf_returns_not_retained`` attributes can be placed on methods and functions
1087that return Objective-C or CoreFoundation objects. They are commonly placed at
1088the end of a function prototype or method declaration:
1089
1090.. code-block:: objc
1091
1092 id foo() __attribute__((ns_returns_retained));
1093
1094 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1095
1096The ``*_returns_retained`` attributes specify that the returned object has a +1
1097retain count. The ``*_returns_not_retained`` attributes specify that the return
1098object has a +0 retain count, even if the normal convention for its selector
1099would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1100+0, but is guaranteed to live at least as long as the next flush of an
1101autorelease pool.
1102
1103**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1104an parameter declaration; they specify that the argument is expected to have a
1105+1 retain count, which will be balanced in some way by the function or method.
1106The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1107method; it specifies that the method expects its ``self`` parameter to have a
1108+1 retain count, which it will balance in some way.
1109
1110.. code-block:: objc
1111
1112 void foo(__attribute__((ns_consumed)) NSString *string);
1113
1114 - (void) bar __attribute__((ns_consumes_self));
1115 - (void) baz:(id) __attribute__((ns_consumed)) x;
1116
1117Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1118<http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1119
1120Query for these features with ``__has_attribute(ns_consumed)``,
1121``__has_attribute(ns_returns_retained)``, etc.
1122
1123
Sean Silva3872b462012-12-12 23:44:55 +00001124Function Overloading in C
1125=========================
1126
1127Clang provides support for C++ function overloading in C. Function overloading
1128in C is introduced using the ``overloadable`` attribute. For example, one
1129might provide several overloaded versions of a ``tgsin`` function that invokes
1130the appropriate standard function computing the sine of a value with ``float``,
1131``double``, or ``long double`` precision:
1132
1133.. code-block:: c
1134
1135 #include <math.h>
1136 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
1137 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
1138 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
1139
1140Given these declarations, one can call ``tgsin`` with a ``float`` value to
1141receive a ``float`` result, with a ``double`` to receive a ``double`` result,
1142etc. Function overloading in C follows the rules of C++ function overloading
1143to pick the best overload given the call arguments, with a few C-specific
1144semantics:
1145
1146* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
1147 floating-point promotion (per C99) rather than as a floating-point conversion
1148 (as in C++).
1149
1150* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
1151 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
1152 compatible types.
1153
1154* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
1155 and ``U`` are compatible types. This conversion is given "conversion" rank.
1156
1157The declaration of ``overloadable`` functions is restricted to function
1158declarations and definitions. Most importantly, if any function with a given
1159name is given the ``overloadable`` attribute, then all function declarations
1160and definitions with that name (and in that scope) must have the
1161``overloadable`` attribute. This rule even applies to redeclarations of
1162functions whose original declaration had the ``overloadable`` attribute, e.g.,
1163
1164.. code-block:: c
1165
1166 int f(int) __attribute__((overloadable));
1167 float f(float); // error: declaration of "f" must have the "overloadable" attribute
1168
1169 int g(int) __attribute__((overloadable));
1170 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
1171
1172Functions marked ``overloadable`` must have prototypes. Therefore, the
1173following code is ill-formed:
1174
1175.. code-block:: c
1176
1177 int h() __attribute__((overloadable)); // error: h does not have a prototype
1178
1179However, ``overloadable`` functions are allowed to use a ellipsis even if there
1180are no named parameters (as is permitted in C++). This feature is particularly
1181useful when combined with the ``unavailable`` attribute:
1182
1183.. code-block:: c++
1184
1185 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
1186
1187Functions declared with the ``overloadable`` attribute have their names mangled
1188according to the same rules as C++ function names. For example, the three
1189``tgsin`` functions in our motivating example get the mangled names
1190``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
1191caveats to this use of name mangling:
1192
1193* Future versions of Clang may change the name mangling of functions overloaded
1194 in C, so you should not depend on an specific mangling. To be completely
1195 safe, we strongly urge the use of ``static inline`` with ``overloadable``
1196 functions.
1197
1198* The ``overloadable`` attribute has almost no meaning when used in C++,
1199 because names will already be mangled and functions are already overloadable.
1200 However, when an ``overloadable`` function occurs within an ``extern "C"``
1201 linkage specification, it's name *will* be mangled in the same way as it
1202 would in C.
1203
1204Query for this feature with ``__has_extension(attribute_overloadable)``.
1205
1206Initializer lists for complex numbers in C
1207==========================================
1208
1209clang supports an extension which allows the following in C:
1210
1211.. code-block:: c++
1212
1213 #include <math.h>
1214 #include <complex.h>
1215 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1216
1217This construct is useful because there is no way to separately initialize the
1218real and imaginary parts of a complex variable in standard C, given that clang
1219does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1220``__imag__`` extensions from gcc, which help in some cases, but are not usable
1221in static initializers.)
1222
1223Note that this extension does not allow eliding the braces; the meaning of the
1224following two lines is different:
1225
1226.. code-block:: c++
1227
1228 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1229 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1230
1231This extension also works in C++ mode, as far as that goes, but does not apply
1232to the C++ ``std::complex``. (In C++11, list initialization allows the same
1233syntax to be used with ``std::complex`` with the same meaning.)
1234
1235Builtin Functions
1236=================
1237
1238Clang supports a number of builtin library functions with the same syntax as
1239GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1240``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
1241``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports
1242a number of builtins that GCC does not, which are listed here.
1243
1244Please note that Clang does not and will not support all of the GCC builtins
1245for vector operations. Instead of using builtins, you should use the functions
1246defined in target-specific header files like ``<xmmintrin.h>``, which define
1247portable wrappers for these. Many of the Clang versions of these functions are
1248implemented directly in terms of :ref:`extended vector support
1249<langext-vectors>` instead of builtins, in order to reduce the number of
1250builtins that we need to implement.
1251
1252``__builtin_readcyclecounter``
1253------------------------------
1254
1255``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1256a similar low-latency, high-accuracy clock) on those targets that support it.
1257
1258**Syntax**:
1259
1260.. code-block:: c++
1261
1262 __builtin_readcyclecounter()
1263
1264**Example of Use**:
1265
1266.. code-block:: c++
1267
1268 unsigned long long t0 = __builtin_readcyclecounter();
1269 do_something();
1270 unsigned long long t1 = __builtin_readcyclecounter();
1271 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1272
1273**Description**:
1274
1275The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1276which may be either global or process/thread-specific depending on the target.
1277As the backing counters often overflow quickly (on the order of seconds) this
1278should only be used for timing small intervals. When not supported by the
1279target, the return value is always zero. This builtin takes no arguments and
1280produces an unsigned long long result.
1281
1282Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``.
1283
1284.. _langext-__builtin_shufflevector:
1285
1286``__builtin_shufflevector``
1287---------------------------
1288
1289``__builtin_shufflevector`` is used to express generic vector
1290permutation/shuffle/swizzle operations. This builtin is also very important
1291for the implementation of various target-specific header files like
1292``<xmmintrin.h>``.
1293
1294**Syntax**:
1295
1296.. code-block:: c++
1297
1298 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1299
1300**Examples**:
1301
1302.. code-block:: c++
1303
1304 // Identity operation - return 4-element vector V1.
1305 __builtin_shufflevector(V1, V1, 0, 1, 2, 3)
1306
1307 // "Splat" element 0 of V1 into a 4-element result.
1308 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1309
1310 // Reverse 4-element vector V1.
1311 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1312
1313 // Concatenate every other element of 4-element vectors V1 and V2.
1314 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1315
1316 // Concatenate every other element of 8-element vectors V1 and V2.
1317 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1318
1319**Description**:
1320
1321The first two arguments to ``__builtin_shufflevector`` are vectors that have
1322the same element type. The remaining arguments are a list of integers that
1323specify the elements indices of the first two vectors that should be extracted
1324and returned in a new vector. These element indices are numbered sequentially
1325starting with the first vector, continuing into the second vector. Thus, if
1326``vec1`` is a 4-element vector, index 5 would refer to the second element of
1327``vec2``.
1328
1329The result of ``__builtin_shufflevector`` is a vector with the same element
1330type as ``vec1``/``vec2`` but that has an element count equal to the number of
1331indices specified.
1332
1333Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1334
1335``__builtin_unreachable``
1336-------------------------
1337
1338``__builtin_unreachable`` is used to indicate that a specific point in the
1339program cannot be reached, even if the compiler might otherwise think it can.
1340This is useful to improve optimization and eliminates certain warnings. For
1341example, without the ``__builtin_unreachable`` in the example below, the
1342compiler assumes that the inline asm can fall through and prints a "function
1343declared '``noreturn``' should not return" warning.
1344
1345**Syntax**:
1346
1347.. code-block:: c++
1348
1349 __builtin_unreachable()
1350
1351**Example of use**:
1352
1353.. code-block:: c++
1354
1355 void myabort(void) __attribute__((noreturn));
1356 void myabort(void) {
1357 asm("int3");
1358 __builtin_unreachable();
1359 }
1360
1361**Description**:
1362
1363The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1364Since it has undefined behavior, it is a statement that it is never reached and
1365the optimizer can take advantage of this to produce better code. This builtin
1366takes no arguments and produces a void result.
1367
1368Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1369
1370``__sync_swap``
1371---------------
1372
1373``__sync_swap`` is used to atomically swap integers or pointers in memory.
1374
1375**Syntax**:
1376
1377.. code-block:: c++
1378
1379 type __sync_swap(type *ptr, type value, ...)
1380
1381**Example of Use**:
1382
1383.. code-block:: c++
1384
1385 int old_value = __sync_swap(&value, new_value);
1386
1387**Description**:
1388
1389The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1390atomic intrinsics to allow code to atomically swap the current value with the
1391new value. More importantly, it helps developers write more efficient and
1392correct code by avoiding expensive loops around
1393``__sync_bool_compare_and_swap()`` or relying on the platform specific
1394implementation details of ``__sync_lock_test_and_set()``. The
1395``__sync_swap()`` builtin is a full barrier.
1396
1397.. _langext-__c11_atomic:
1398
1399__c11_atomic builtins
1400---------------------
1401
1402Clang provides a set of builtins which are intended to be used to implement
1403C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
1404``_explicit`` form of the corresponding C11 operation, and are named with a
1405``__c11_`` prefix. The supported operations are:
1406
1407* ``__c11_atomic_init``
1408* ``__c11_atomic_thread_fence``
1409* ``__c11_atomic_signal_fence``
1410* ``__c11_atomic_is_lock_free``
1411* ``__c11_atomic_store``
1412* ``__c11_atomic_load``
1413* ``__c11_atomic_exchange``
1414* ``__c11_atomic_compare_exchange_strong``
1415* ``__c11_atomic_compare_exchange_weak``
1416* ``__c11_atomic_fetch_add``
1417* ``__c11_atomic_fetch_sub``
1418* ``__c11_atomic_fetch_and``
1419* ``__c11_atomic_fetch_or``
1420* ``__c11_atomic_fetch_xor``
1421
1422Non-standard C++11 Attributes
1423=============================
1424
1425Clang supports one non-standard C++11 attribute. It resides in the ``clang``
1426attribute namespace.
1427
1428The ``clang::fallthrough`` attribute
1429------------------------------------
1430
1431The ``clang::fallthrough`` attribute is used along with the
1432``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
1433between switch labels. It can only be applied to a null statement placed at a
1434point of execution between any statement and the next switch label. It is
1435common to mark these places with a specific comment, but this attribute is
1436meant to replace comments with a more strict annotation, which can be checked
1437by the compiler. This attribute doesn't change semantics of the code and can
1438be used wherever an intended fall-through occurs. It is designed to mimic
1439control-flow statements like ``break;``, so it can be placed in most places
1440where ``break;`` can, but only if there are no statements on the execution path
1441between it and the next switch label.
1442
1443Here is an example:
1444
1445.. code-block:: c++
1446
1447 // compile with -Wimplicit-fallthrough
1448 switch (n) {
1449 case 22:
1450 case 33: // no warning: no statements between case labels
1451 f();
1452 case 44: // warning: unannotated fall-through
1453 g();
1454 [[clang::fallthrough]];
1455 case 55: // no warning
1456 if (x) {
1457 h();
1458 break;
1459 }
1460 else {
1461 i();
1462 [[clang::fallthrough]];
1463 }
1464 case 66: // no warning
1465 p();
1466 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1467 // directly precede case label
1468 q();
1469 case 77: // warning: unannotated fall-through
1470 r();
1471 }
1472
1473Target-Specific Extensions
1474==========================
1475
1476Clang supports some language features conditionally on some targets.
1477
1478X86/X86-64 Language Extensions
1479------------------------------
1480
1481The X86 backend has these language extensions:
1482
1483Memory references off the GS segment
1484^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1485
1486Annotating a pointer with address space #256 causes it to be code generated
1487relative to the X86 GS segment register, and address space #257 causes it to be
1488relative to the X86 FS segment. Note that this is a very very low-level
1489feature that should only be used if you know what you're doing (for example in
1490an OS kernel).
1491
1492Here is an example:
1493
1494.. code-block:: c++
1495
1496 #define GS_RELATIVE __attribute__((address_space(256)))
1497 int foo(int GS_RELATIVE *P) {
1498 return *P;
1499 }
1500
1501Which compiles to (on X86-32):
1502
1503.. code-block:: gas
1504
1505 _foo:
1506 movl 4(%esp), %eax
1507 movl %gs:(%eax), %eax
1508 ret
1509
Jordan Rose3115f5b62012-12-15 00:37:01 +00001510Extensions for Static Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001511==============================
Sean Silva3872b462012-12-12 23:44:55 +00001512
1513Clang supports additional attributes that are useful for documenting program
Jordan Rose3115f5b62012-12-15 00:37:01 +00001514invariants and rules for static analysis tools, such as the `Clang Static
1515Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
1516in the analyzer's `list of source-level annotations
1517<http://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva3872b462012-12-12 23:44:55 +00001518
Sean Silva3872b462012-12-12 23:44:55 +00001519
Jordan Rose3115f5b62012-12-15 00:37:01 +00001520Extensions for Dynamic Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001521===============================
Sean Silva3872b462012-12-12 23:44:55 +00001522
1523.. _langext-address_sanitizer:
1524
1525AddressSanitizer
1526----------------
1527
1528Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001529with :doc:`AddressSanitizer`.
Sean Silva3872b462012-12-12 23:44:55 +00001530
1531Use ``__attribute__((no_address_safety_analysis))`` on a function declaration
1532to specify that address safety instrumentation (e.g. AddressSanitizer) should
1533not be applied to that function.
1534
1535Thread-Safety Annotation Checking
1536=================================
1537
1538Clang supports additional attributes for checking basic locking policies in
1539multithreaded programs. Clang currently parses the following list of
1540attributes, although **the implementation for these annotations is currently in
1541development.** For more details, see the `GCC implementation
1542<http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_.
1543
1544``no_thread_safety_analysis``
1545-----------------------------
1546
1547Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to
1548specify that the thread safety analysis should not be run on that function.
1549This attribute provides an escape hatch (e.g. for situations when it is
1550difficult to annotate the locking policy).
1551
1552``lockable``
1553------------
1554
1555Use ``__attribute__((lockable))`` on a class definition to specify that it has
1556a lockable type (e.g. a Mutex class). This annotation is primarily used to
1557check consistency.
1558
1559``scoped_lockable``
1560-------------------
1561
1562Use ``__attribute__((scoped_lockable))`` on a class definition to specify that
1563it has a "scoped" lockable type. Objects of this type will acquire the lock
1564upon construction and release it upon going out of scope. This annotation is
1565primarily used to check consistency.
1566
1567``guarded_var``
1568---------------
1569
1570Use ``__attribute__((guarded_var))`` on a variable declaration to specify that
1571the variable must be accessed while holding some lock.
1572
1573``pt_guarded_var``
1574------------------
1575
1576Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify
1577that the pointer must be dereferenced while holding some lock.
1578
1579``guarded_by(l)``
1580-----------------
1581
1582Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify
1583that the variable must be accessed while holding lock ``l``.
1584
1585``pt_guarded_by(l)``
1586--------------------
1587
1588Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify
1589that the pointer must be dereferenced while holding lock ``l``.
1590
1591``acquired_before(...)``
1592------------------------
1593
1594Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable
1595variable to specify that the lock must be acquired before all attribute
1596arguments. Arguments must be lockable type, and there must be at least one
1597argument.
1598
1599``acquired_after(...)``
1600-----------------------
1601
1602Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable
1603variable to specify that the lock must be acquired after all attribute
1604arguments. Arguments must be lockable type, and there must be at least one
1605argument.
1606
1607``exclusive_lock_function(...)``
1608--------------------------------
1609
1610Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
1611to specify that the function acquires all listed locks exclusively. This
1612attribute takes zero or more arguments: either of lockable type or integers
1613indexing into function parameters of lockable type. If no arguments are given,
1614the acquired lock is implicitly ``this`` of the enclosing object.
1615
1616``shared_lock_function(...)``
1617-----------------------------
1618
1619Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
1620specify that the function acquires all listed locks, although the locks may be
1621shared (e.g. read locks). This attribute takes zero or more arguments: either
1622of lockable type or integers indexing into function parameters of lockable
1623type. If no arguments are given, the acquired lock is implicitly ``this`` of
1624the enclosing object.
1625
1626``exclusive_trylock_function(...)``
1627-----------------------------------
1628
1629Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
1630to specify that the function will try (without blocking) to acquire all listed
1631locks exclusively. This attribute takes one or more arguments. The first
1632argument is an integer or boolean value specifying the return value of a
1633successful lock acquisition. The remaining arugments are either of lockable
1634type or integers indexing into function parameters of lockable type. If only
1635one argument is given, the acquired lock is implicitly ``this`` of the
1636enclosing object.
1637
1638``shared_trylock_function(...)``
1639--------------------------------
1640
1641Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
1642specify that the function will try (without blocking) to acquire all listed
1643locks, although the locks may be shared (e.g. read locks). This attribute
1644takes one or more arguments. The first argument is an integer or boolean value
1645specifying the return value of a successful lock acquisition. The remaining
1646arugments are either of lockable type or integers indexing into function
1647parameters of lockable type. If only one argument is given, the acquired lock
1648is implicitly ``this`` of the enclosing object.
1649
1650``unlock_function(...)``
1651------------------------
1652
1653Use ``__attribute__((unlock_function(...)))`` on a function declaration to
1654specify that the function release all listed locks. This attribute takes zero
1655or more arguments: either of lockable type or integers indexing into function
1656parameters of lockable type. If no arguments are given, the acquired lock is
1657implicitly ``this`` of the enclosing object.
1658
1659``lock_returned(l)``
1660--------------------
1661
1662Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify
1663that the function returns lock ``l`` (``l`` must be of lockable type). This
1664annotation is used to aid in resolving lock expressions.
1665
1666``locks_excluded(...)``
1667-----------------------
1668
1669Use ``__attribute__((locks_excluded(...)))`` on a function declaration to
1670specify that the function must not be called with the listed locks. Arguments
1671must be lockable type, and there must be at least one argument.
1672
1673``exclusive_locks_required(...)``
1674---------------------------------
1675
1676Use ``__attribute__((exclusive_locks_required(...)))`` on a function
1677declaration to specify that the function must be called while holding the
1678listed exclusive locks. Arguments must be lockable type, and there must be at
1679least one argument.
1680
1681``shared_locks_required(...)``
1682------------------------------
1683
1684Use ``__attribute__((shared_locks_required(...)))`` on a function declaration
1685to specify that the function must be called while holding the listed shared
1686locks. Arguments must be lockable type, and there must be at least one
1687argument.
1688
1689Type Safety Checking
1690====================
1691
1692Clang supports additional attributes to enable checking type safety properties
1693that can't be enforced by C type system. Usecases include:
1694
1695* MPI library implementations, where these attributes enable checking that
1696 buffer type matches the passed ``MPI_Datatype``;
1697* for HDF5 library there is a similar usecase as MPI;
1698* checking types of variadic functions' arguments for functions like
1699 ``fcntl()`` and ``ioctl()``.
1700
1701You can detect support for these attributes with ``__has_attribute()``. For
1702example:
1703
1704.. code-block:: c++
1705
1706 #if defined(__has_attribute)
1707 # if __has_attribute(argument_with_type_tag) && \
1708 __has_attribute(pointer_with_type_tag) && \
1709 __has_attribute(type_tag_for_datatype)
1710 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
1711 /* ... other macros ... */
1712 # endif
1713 #endif
1714
1715 #if !defined(ATTR_MPI_PWT)
1716 # define ATTR_MPI_PWT(buffer_idx, type_idx)
1717 #endif
1718
1719 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1720 ATTR_MPI_PWT(1,3);
1721
1722``argument_with_type_tag(...)``
1723-------------------------------
1724
1725Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
1726type_tag_idx)))`` on a function declaration to specify that the function
1727accepts a type tag that determines the type of some other argument.
1728``arg_kind`` is an identifier that should be used when annotating all
1729applicable type tags.
1730
1731This attribute is primarily useful for checking arguments of variadic functions
1732(``pointer_with_type_tag`` can be used in most of non-variadic cases).
1733
1734For example:
1735
1736.. code-block:: c++
1737
1738 int fcntl(int fd, int cmd, ...)
1739 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
1740
1741``pointer_with_type_tag(...)``
1742------------------------------
1743
1744Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
1745on a function declaration to specify that the function accepts a type tag that
1746determines the pointee type of some other pointer argument.
1747
1748For example:
1749
1750.. code-block:: c++
1751
1752 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1753 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
1754
1755``type_tag_for_datatype(...)``
1756------------------------------
1757
1758Clang supports annotating type tags of two forms.
1759
1760* **Type tag that is an expression containing a reference to some declared
1761 identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
1762 declaration with that identifier:
1763
1764 .. code-block:: c++
1765
1766 extern struct mpi_datatype mpi_datatype_int
1767 __attribute__(( type_tag_for_datatype(mpi,int) ));
1768 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
1769
1770* **Type tag that is an integral literal.** Introduce a ``static const``
1771 variable with a corresponding initializer value and attach
1772 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
1773 for example:
1774
1775 .. code-block:: c++
1776
1777 #define MPI_INT ((MPI_Datatype) 42)
1778 static const MPI_Datatype mpi_datatype_int
1779 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42
1780
1781The attribute also accepts an optional third argument that determines how the
1782expression is compared to the type tag. There are two supported flags:
1783
1784* ``layout_compatible`` will cause types to be compared according to
1785 layout-compatibility rules (C++11 [class.mem] p 17, 18). This is
1786 implemented to support annotating types like ``MPI_DOUBLE_INT``.
1787
1788 For example:
1789
1790 .. code-block:: c++
1791
1792 /* In mpi.h */
1793 struct internal_mpi_double_int { double d; int i; };
1794 extern struct mpi_datatype mpi_datatype_double_int
1795 __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
1796
1797 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
1798
1799 /* In user code */
1800 struct my_pair { double a; int b; };
1801 struct my_pair *buffer;
1802 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning
1803
1804 struct my_int_pair { int a; int b; }
1805 struct my_int_pair *buffer2;
1806 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element
1807 // type 'struct my_int_pair'
1808 // doesn't match specified MPI_Datatype
1809
1810* ``must_be_null`` specifies that the expression should be a null pointer
1811 constant, for example:
1812
1813 .. code-block:: c++
1814
1815 /* In mpi.h */
1816 extern struct mpi_datatype mpi_datatype_null
1817 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
1818
1819 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
1820
1821 /* In user code */
1822 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
1823 // was specified but buffer
1824 // is not a null pointer
1825