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