blob: c3e2c83d13018e7ffe93f829c1ddea60023275ce [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
90to the language standard, such as e.g. `AddressSanitizer
91<AddressSanitizer.html>`_.
92
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
928Clang provides support for `automated reference counting
929<AutomaticReferenceCounting.html>`_ in Objective-C, which eliminates the need
930for 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
937Enumerations with a fixed underlying type
938-----------------------------------------
939
940Clang provides support for C++11 enumerations with a fixed underlying type
941within Objective-C. For example, one can write an enumeration type as:
942
943.. code-block:: c++
944
945 typedef enum : unsigned char { Red, Green, Blue } Color;
946
947This specifies that the underlying type, which is used to store the enumeration
948value, is ``unsigned char``.
949
950Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
951underlying types is available in Objective-C.
952
953Interoperability with C++11 lambdas
954-----------------------------------
955
956Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
957permitting a lambda to be implicitly converted to a block pointer with the
958corresponding signature. For example, consider an API such as ``NSArray``'s
959array-sorting method:
960
961.. code-block:: objc
962
963 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
964
965``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
966(^)(id, id)``, and parameters of this type are generally provided with block
967literals as arguments. However, one can also use a C++11 lambda so long as it
968provides the same signature (in this case, accepting two parameters of type
969``id`` and returning an ``NSComparisonResult``):
970
971.. code-block:: objc
972
973 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
974 @"String 02"];
975 const NSStringCompareOptions comparisonOptions
976 = NSCaseInsensitiveSearch | NSNumericSearch |
977 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
978 NSLocale *currentLocale = [NSLocale currentLocale];
979 NSArray *sorted
980 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
981 NSRange string1Range = NSMakeRange(0, [s1 length]);
982 return [s1 compare:s2 options:comparisonOptions
983 range:string1Range locale:currentLocale];
984 }];
985 NSLog(@"sorted: %@", sorted);
986
987This code relies on an implicit conversion from the type of the lambda
988expression (an unnamed, local class type called the *closure type*) to the
989corresponding block pointer type. The conversion itself is expressed by a
990conversion operator in that closure type that produces a block pointer with the
991same signature as the lambda itself, e.g.,
992
993.. code-block:: objc
994
995 operator NSComparisonResult (^)(id, id)() const;
996
997This conversion function returns a new block that simply forwards the two
998parameters to the lambda object (which it captures by copy), then returns the
999result. The returned block is first copied (with ``Block_copy``) and then
1000autoreleased. As an optimization, if a lambda expression is immediately
1001converted to a block pointer (as in the first example, above), then the block
1002is not copied and autoreleased: rather, it is given the same lifetime as a
1003block literal written at that point in the program, which avoids the overhead
1004of copying a block to the heap in the common case.
1005
1006The conversion from a lambda to a block pointer is only available in
1007Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1008management (autorelease).
1009
1010Object Literals and Subscripting
1011--------------------------------
1012
1013Clang provides support for `Object Literals and Subscripting
1014<ObjectiveCLiterals.html>`_ in Objective-C, which simplifies common Objective-C
1015programming patterns, makes programs more concise, and improves the safety of
1016container creation. There are several feature macros associated with object
1017literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1018availability of array literals; ``__has_feature(objc_dictionary_literals)``
1019tests the availability of dictionary literals;
1020``__has_feature(objc_subscripting)`` tests the availability of object
1021subscripting.
1022
1023Objective-C Autosynthesis of Properties
1024---------------------------------------
1025
1026Clang provides support for autosynthesis of declared properties. Using this
1027feature, clang provides default synthesis of those properties not declared
1028@dynamic and not having user provided backing getter and setter methods.
1029``__has_feature(objc_default_synthesize_properties)`` checks for availability
1030of this feature in version of clang being used.
1031
Jordan Rose3115f5b62012-12-15 00:37:01 +00001032.. _langext-objc_method_family:
1033
1034The ``objc_method_family`` attribute
1035------------------------------------
1036
1037Many methods in Objective-C have conventional meanings determined by their
1038selectors. It is sometimes useful to be able to mark a method as having a
1039particular conventional meaning despite not having the right selector, or as
1040not having the conventional meaning that its selector would suggest. For these
1041use cases, we provide an attribute to specifically describe the "method family"
1042that a method belongs to.
1043
1044**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
1045``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
1046attribute can only be placed at the end of a method declaration:
1047
1048.. code-block:: objc
1049
1050 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
1051
1052Users who do not wish to change the conventional meaning of a method, and who
1053merely want to document its non-standard retain and release semantics, should
1054use the :ref:`retaining behavior attributes <langext-objc-retain-release>`
1055described below.
1056
1057Query for this feature with ``__has_attribute(objc_method_family)``.
1058
1059.. _langext-objc-retain-release:
1060
1061Objective-C retaining behavior attributes
1062-----------------------------------------
1063
1064In Objective-C, functions and methods are generally assumed to follow the
1065`Cocoa Memory Management
1066<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1067conventions for ownership of object arguments and
1068return values. However, there are exceptions, and so Clang provides attributes
1069to allow these exceptions to be documented. This are used by ARC and the
1070`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
1071better described using the :ref:`objc_method_family
1072<langext-objc_method_family>` attribute instead.
1073
1074**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1075``ns_returns_autoreleased``, ``cf_returns_retained``, and
1076``cf_returns_not_retained`` attributes can be placed on methods and functions
1077that return Objective-C or CoreFoundation objects. They are commonly placed at
1078the end of a function prototype or method declaration:
1079
1080.. code-block:: objc
1081
1082 id foo() __attribute__((ns_returns_retained));
1083
1084 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1085
1086The ``*_returns_retained`` attributes specify that the returned object has a +1
1087retain count. The ``*_returns_not_retained`` attributes specify that the return
1088object has a +0 retain count, even if the normal convention for its selector
1089would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1090+0, but is guaranteed to live at least as long as the next flush of an
1091autorelease pool.
1092
1093**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1094an parameter declaration; they specify that the argument is expected to have a
1095+1 retain count, which will be balanced in some way by the function or method.
1096The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1097method; it specifies that the method expects its ``self`` parameter to have a
1098+1 retain count, which it will balance in some way.
1099
1100.. code-block:: objc
1101
1102 void foo(__attribute__((ns_consumed)) NSString *string);
1103
1104 - (void) bar __attribute__((ns_consumes_self));
1105 - (void) baz:(id) __attribute__((ns_consumed)) x;
1106
1107Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1108<http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1109
1110Query for these features with ``__has_attribute(ns_consumed)``,
1111``__has_attribute(ns_returns_retained)``, etc.
1112
1113
Sean Silva3872b462012-12-12 23:44:55 +00001114Function Overloading in C
1115=========================
1116
1117Clang provides support for C++ function overloading in C. Function overloading
1118in C is introduced using the ``overloadable`` attribute. For example, one
1119might provide several overloaded versions of a ``tgsin`` function that invokes
1120the appropriate standard function computing the sine of a value with ``float``,
1121``double``, or ``long double`` precision:
1122
1123.. code-block:: c
1124
1125 #include <math.h>
1126 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
1127 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
1128 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
1129
1130Given these declarations, one can call ``tgsin`` with a ``float`` value to
1131receive a ``float`` result, with a ``double`` to receive a ``double`` result,
1132etc. Function overloading in C follows the rules of C++ function overloading
1133to pick the best overload given the call arguments, with a few C-specific
1134semantics:
1135
1136* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
1137 floating-point promotion (per C99) rather than as a floating-point conversion
1138 (as in C++).
1139
1140* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
1141 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
1142 compatible types.
1143
1144* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
1145 and ``U`` are compatible types. This conversion is given "conversion" rank.
1146
1147The declaration of ``overloadable`` functions is restricted to function
1148declarations and definitions. Most importantly, if any function with a given
1149name is given the ``overloadable`` attribute, then all function declarations
1150and definitions with that name (and in that scope) must have the
1151``overloadable`` attribute. This rule even applies to redeclarations of
1152functions whose original declaration had the ``overloadable`` attribute, e.g.,
1153
1154.. code-block:: c
1155
1156 int f(int) __attribute__((overloadable));
1157 float f(float); // error: declaration of "f" must have the "overloadable" attribute
1158
1159 int g(int) __attribute__((overloadable));
1160 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
1161
1162Functions marked ``overloadable`` must have prototypes. Therefore, the
1163following code is ill-formed:
1164
1165.. code-block:: c
1166
1167 int h() __attribute__((overloadable)); // error: h does not have a prototype
1168
1169However, ``overloadable`` functions are allowed to use a ellipsis even if there
1170are no named parameters (as is permitted in C++). This feature is particularly
1171useful when combined with the ``unavailable`` attribute:
1172
1173.. code-block:: c++
1174
1175 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
1176
1177Functions declared with the ``overloadable`` attribute have their names mangled
1178according to the same rules as C++ function names. For example, the three
1179``tgsin`` functions in our motivating example get the mangled names
1180``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
1181caveats to this use of name mangling:
1182
1183* Future versions of Clang may change the name mangling of functions overloaded
1184 in C, so you should not depend on an specific mangling. To be completely
1185 safe, we strongly urge the use of ``static inline`` with ``overloadable``
1186 functions.
1187
1188* The ``overloadable`` attribute has almost no meaning when used in C++,
1189 because names will already be mangled and functions are already overloadable.
1190 However, when an ``overloadable`` function occurs within an ``extern "C"``
1191 linkage specification, it's name *will* be mangled in the same way as it
1192 would in C.
1193
1194Query for this feature with ``__has_extension(attribute_overloadable)``.
1195
1196Initializer lists for complex numbers in C
1197==========================================
1198
1199clang supports an extension which allows the following in C:
1200
1201.. code-block:: c++
1202
1203 #include <math.h>
1204 #include <complex.h>
1205 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1206
1207This construct is useful because there is no way to separately initialize the
1208real and imaginary parts of a complex variable in standard C, given that clang
1209does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1210``__imag__`` extensions from gcc, which help in some cases, but are not usable
1211in static initializers.)
1212
1213Note that this extension does not allow eliding the braces; the meaning of the
1214following two lines is different:
1215
1216.. code-block:: c++
1217
1218 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1219 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1220
1221This extension also works in C++ mode, as far as that goes, but does not apply
1222to the C++ ``std::complex``. (In C++11, list initialization allows the same
1223syntax to be used with ``std::complex`` with the same meaning.)
1224
1225Builtin Functions
1226=================
1227
1228Clang supports a number of builtin library functions with the same syntax as
1229GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1230``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
1231``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports
1232a number of builtins that GCC does not, which are listed here.
1233
1234Please note that Clang does not and will not support all of the GCC builtins
1235for vector operations. Instead of using builtins, you should use the functions
1236defined in target-specific header files like ``<xmmintrin.h>``, which define
1237portable wrappers for these. Many of the Clang versions of these functions are
1238implemented directly in terms of :ref:`extended vector support
1239<langext-vectors>` instead of builtins, in order to reduce the number of
1240builtins that we need to implement.
1241
1242``__builtin_readcyclecounter``
1243------------------------------
1244
1245``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1246a similar low-latency, high-accuracy clock) on those targets that support it.
1247
1248**Syntax**:
1249
1250.. code-block:: c++
1251
1252 __builtin_readcyclecounter()
1253
1254**Example of Use**:
1255
1256.. code-block:: c++
1257
1258 unsigned long long t0 = __builtin_readcyclecounter();
1259 do_something();
1260 unsigned long long t1 = __builtin_readcyclecounter();
1261 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1262
1263**Description**:
1264
1265The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1266which may be either global or process/thread-specific depending on the target.
1267As the backing counters often overflow quickly (on the order of seconds) this
1268should only be used for timing small intervals. When not supported by the
1269target, the return value is always zero. This builtin takes no arguments and
1270produces an unsigned long long result.
1271
1272Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``.
1273
1274.. _langext-__builtin_shufflevector:
1275
1276``__builtin_shufflevector``
1277---------------------------
1278
1279``__builtin_shufflevector`` is used to express generic vector
1280permutation/shuffle/swizzle operations. This builtin is also very important
1281for the implementation of various target-specific header files like
1282``<xmmintrin.h>``.
1283
1284**Syntax**:
1285
1286.. code-block:: c++
1287
1288 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1289
1290**Examples**:
1291
1292.. code-block:: c++
1293
1294 // Identity operation - return 4-element vector V1.
1295 __builtin_shufflevector(V1, V1, 0, 1, 2, 3)
1296
1297 // "Splat" element 0 of V1 into a 4-element result.
1298 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1299
1300 // Reverse 4-element vector V1.
1301 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1302
1303 // Concatenate every other element of 4-element vectors V1 and V2.
1304 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1305
1306 // Concatenate every other element of 8-element vectors V1 and V2.
1307 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1308
1309**Description**:
1310
1311The first two arguments to ``__builtin_shufflevector`` are vectors that have
1312the same element type. The remaining arguments are a list of integers that
1313specify the elements indices of the first two vectors that should be extracted
1314and returned in a new vector. These element indices are numbered sequentially
1315starting with the first vector, continuing into the second vector. Thus, if
1316``vec1`` is a 4-element vector, index 5 would refer to the second element of
1317``vec2``.
1318
1319The result of ``__builtin_shufflevector`` is a vector with the same element
1320type as ``vec1``/``vec2`` but that has an element count equal to the number of
1321indices specified.
1322
1323Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1324
1325``__builtin_unreachable``
1326-------------------------
1327
1328``__builtin_unreachable`` is used to indicate that a specific point in the
1329program cannot be reached, even if the compiler might otherwise think it can.
1330This is useful to improve optimization and eliminates certain warnings. For
1331example, without the ``__builtin_unreachable`` in the example below, the
1332compiler assumes that the inline asm can fall through and prints a "function
1333declared '``noreturn``' should not return" warning.
1334
1335**Syntax**:
1336
1337.. code-block:: c++
1338
1339 __builtin_unreachable()
1340
1341**Example of use**:
1342
1343.. code-block:: c++
1344
1345 void myabort(void) __attribute__((noreturn));
1346 void myabort(void) {
1347 asm("int3");
1348 __builtin_unreachable();
1349 }
1350
1351**Description**:
1352
1353The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1354Since it has undefined behavior, it is a statement that it is never reached and
1355the optimizer can take advantage of this to produce better code. This builtin
1356takes no arguments and produces a void result.
1357
1358Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1359
1360``__sync_swap``
1361---------------
1362
1363``__sync_swap`` is used to atomically swap integers or pointers in memory.
1364
1365**Syntax**:
1366
1367.. code-block:: c++
1368
1369 type __sync_swap(type *ptr, type value, ...)
1370
1371**Example of Use**:
1372
1373.. code-block:: c++
1374
1375 int old_value = __sync_swap(&value, new_value);
1376
1377**Description**:
1378
1379The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1380atomic intrinsics to allow code to atomically swap the current value with the
1381new value. More importantly, it helps developers write more efficient and
1382correct code by avoiding expensive loops around
1383``__sync_bool_compare_and_swap()`` or relying on the platform specific
1384implementation details of ``__sync_lock_test_and_set()``. The
1385``__sync_swap()`` builtin is a full barrier.
1386
1387.. _langext-__c11_atomic:
1388
1389__c11_atomic builtins
1390---------------------
1391
1392Clang provides a set of builtins which are intended to be used to implement
1393C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
1394``_explicit`` form of the corresponding C11 operation, and are named with a
1395``__c11_`` prefix. The supported operations are:
1396
1397* ``__c11_atomic_init``
1398* ``__c11_atomic_thread_fence``
1399* ``__c11_atomic_signal_fence``
1400* ``__c11_atomic_is_lock_free``
1401* ``__c11_atomic_store``
1402* ``__c11_atomic_load``
1403* ``__c11_atomic_exchange``
1404* ``__c11_atomic_compare_exchange_strong``
1405* ``__c11_atomic_compare_exchange_weak``
1406* ``__c11_atomic_fetch_add``
1407* ``__c11_atomic_fetch_sub``
1408* ``__c11_atomic_fetch_and``
1409* ``__c11_atomic_fetch_or``
1410* ``__c11_atomic_fetch_xor``
1411
1412Non-standard C++11 Attributes
1413=============================
1414
1415Clang supports one non-standard C++11 attribute. It resides in the ``clang``
1416attribute namespace.
1417
1418The ``clang::fallthrough`` attribute
1419------------------------------------
1420
1421The ``clang::fallthrough`` attribute is used along with the
1422``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
1423between switch labels. It can only be applied to a null statement placed at a
1424point of execution between any statement and the next switch label. It is
1425common to mark these places with a specific comment, but this attribute is
1426meant to replace comments with a more strict annotation, which can be checked
1427by the compiler. This attribute doesn't change semantics of the code and can
1428be used wherever an intended fall-through occurs. It is designed to mimic
1429control-flow statements like ``break;``, so it can be placed in most places
1430where ``break;`` can, but only if there are no statements on the execution path
1431between it and the next switch label.
1432
1433Here is an example:
1434
1435.. code-block:: c++
1436
1437 // compile with -Wimplicit-fallthrough
1438 switch (n) {
1439 case 22:
1440 case 33: // no warning: no statements between case labels
1441 f();
1442 case 44: // warning: unannotated fall-through
1443 g();
1444 [[clang::fallthrough]];
1445 case 55: // no warning
1446 if (x) {
1447 h();
1448 break;
1449 }
1450 else {
1451 i();
1452 [[clang::fallthrough]];
1453 }
1454 case 66: // no warning
1455 p();
1456 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1457 // directly precede case label
1458 q();
1459 case 77: // warning: unannotated fall-through
1460 r();
1461 }
1462
1463Target-Specific Extensions
1464==========================
1465
1466Clang supports some language features conditionally on some targets.
1467
1468X86/X86-64 Language Extensions
1469------------------------------
1470
1471The X86 backend has these language extensions:
1472
1473Memory references off the GS segment
1474^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1475
1476Annotating a pointer with address space #256 causes it to be code generated
1477relative to the X86 GS segment register, and address space #257 causes it to be
1478relative to the X86 FS segment. Note that this is a very very low-level
1479feature that should only be used if you know what you're doing (for example in
1480an OS kernel).
1481
1482Here is an example:
1483
1484.. code-block:: c++
1485
1486 #define GS_RELATIVE __attribute__((address_space(256)))
1487 int foo(int GS_RELATIVE *P) {
1488 return *P;
1489 }
1490
1491Which compiles to (on X86-32):
1492
1493.. code-block:: gas
1494
1495 _foo:
1496 movl 4(%esp), %eax
1497 movl %gs:(%eax), %eax
1498 ret
1499
Jordan Rose3115f5b62012-12-15 00:37:01 +00001500Extensions for Static Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001501==============================
Sean Silva3872b462012-12-12 23:44:55 +00001502
1503Clang supports additional attributes that are useful for documenting program
Jordan Rose3115f5b62012-12-15 00:37:01 +00001504invariants and rules for static analysis tools, such as the `Clang Static
1505Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
1506in the analyzer's `list of source-level annotations
1507<http://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva3872b462012-12-12 23:44:55 +00001508
Sean Silva3872b462012-12-12 23:44:55 +00001509
Jordan Rose3115f5b62012-12-15 00:37:01 +00001510Extensions for Dynamic Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001511===============================
Sean Silva3872b462012-12-12 23:44:55 +00001512
1513.. _langext-address_sanitizer:
1514
1515AddressSanitizer
1516----------------
1517
1518Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001519with :doc:`AddressSanitizer`.
Sean Silva3872b462012-12-12 23:44:55 +00001520
1521Use ``__attribute__((no_address_safety_analysis))`` on a function declaration
1522to specify that address safety instrumentation (e.g. AddressSanitizer) should
1523not be applied to that function.
1524
1525Thread-Safety Annotation Checking
1526=================================
1527
1528Clang supports additional attributes for checking basic locking policies in
1529multithreaded programs. Clang currently parses the following list of
1530attributes, although **the implementation for these annotations is currently in
1531development.** For more details, see the `GCC implementation
1532<http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_.
1533
1534``no_thread_safety_analysis``
1535-----------------------------
1536
1537Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to
1538specify that the thread safety analysis should not be run on that function.
1539This attribute provides an escape hatch (e.g. for situations when it is
1540difficult to annotate the locking policy).
1541
1542``lockable``
1543------------
1544
1545Use ``__attribute__((lockable))`` on a class definition to specify that it has
1546a lockable type (e.g. a Mutex class). This annotation is primarily used to
1547check consistency.
1548
1549``scoped_lockable``
1550-------------------
1551
1552Use ``__attribute__((scoped_lockable))`` on a class definition to specify that
1553it has a "scoped" lockable type. Objects of this type will acquire the lock
1554upon construction and release it upon going out of scope. This annotation is
1555primarily used to check consistency.
1556
1557``guarded_var``
1558---------------
1559
1560Use ``__attribute__((guarded_var))`` on a variable declaration to specify that
1561the variable must be accessed while holding some lock.
1562
1563``pt_guarded_var``
1564------------------
1565
1566Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify
1567that the pointer must be dereferenced while holding some lock.
1568
1569``guarded_by(l)``
1570-----------------
1571
1572Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify
1573that the variable must be accessed while holding lock ``l``.
1574
1575``pt_guarded_by(l)``
1576--------------------
1577
1578Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify
1579that the pointer must be dereferenced while holding lock ``l``.
1580
1581``acquired_before(...)``
1582------------------------
1583
1584Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable
1585variable to specify that the lock must be acquired before all attribute
1586arguments. Arguments must be lockable type, and there must be at least one
1587argument.
1588
1589``acquired_after(...)``
1590-----------------------
1591
1592Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable
1593variable to specify that the lock must be acquired after all attribute
1594arguments. Arguments must be lockable type, and there must be at least one
1595argument.
1596
1597``exclusive_lock_function(...)``
1598--------------------------------
1599
1600Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
1601to specify that the function acquires all listed locks exclusively. This
1602attribute takes zero or more arguments: either of lockable type or integers
1603indexing into function parameters of lockable type. If no arguments are given,
1604the acquired lock is implicitly ``this`` of the enclosing object.
1605
1606``shared_lock_function(...)``
1607-----------------------------
1608
1609Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
1610specify that the function acquires all listed locks, although the locks may be
1611shared (e.g. read locks). This attribute takes zero or more arguments: either
1612of lockable type or integers indexing into function parameters of lockable
1613type. If no arguments are given, the acquired lock is implicitly ``this`` of
1614the enclosing object.
1615
1616``exclusive_trylock_function(...)``
1617-----------------------------------
1618
1619Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
1620to specify that the function will try (without blocking) to acquire all listed
1621locks exclusively. This attribute takes one or more arguments. The first
1622argument is an integer or boolean value specifying the return value of a
1623successful lock acquisition. The remaining arugments are either of lockable
1624type or integers indexing into function parameters of lockable type. If only
1625one argument is given, the acquired lock is implicitly ``this`` of the
1626enclosing object.
1627
1628``shared_trylock_function(...)``
1629--------------------------------
1630
1631Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
1632specify that the function will try (without blocking) to acquire all listed
1633locks, although the locks may be shared (e.g. read locks). This attribute
1634takes one or more arguments. The first argument is an integer or boolean value
1635specifying the return value of a successful lock acquisition. The remaining
1636arugments are either of lockable type or integers indexing into function
1637parameters of lockable type. If only one argument is given, the acquired lock
1638is implicitly ``this`` of the enclosing object.
1639
1640``unlock_function(...)``
1641------------------------
1642
1643Use ``__attribute__((unlock_function(...)))`` on a function declaration to
1644specify that the function release all listed locks. This attribute takes zero
1645or more arguments: either of lockable type or integers indexing into function
1646parameters of lockable type. If no arguments are given, the acquired lock is
1647implicitly ``this`` of the enclosing object.
1648
1649``lock_returned(l)``
1650--------------------
1651
1652Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify
1653that the function returns lock ``l`` (``l`` must be of lockable type). This
1654annotation is used to aid in resolving lock expressions.
1655
1656``locks_excluded(...)``
1657-----------------------
1658
1659Use ``__attribute__((locks_excluded(...)))`` on a function declaration to
1660specify that the function must not be called with the listed locks. Arguments
1661must be lockable type, and there must be at least one argument.
1662
1663``exclusive_locks_required(...)``
1664---------------------------------
1665
1666Use ``__attribute__((exclusive_locks_required(...)))`` on a function
1667declaration to specify that the function must be called while holding the
1668listed exclusive locks. Arguments must be lockable type, and there must be at
1669least one argument.
1670
1671``shared_locks_required(...)``
1672------------------------------
1673
1674Use ``__attribute__((shared_locks_required(...)))`` on a function declaration
1675to specify that the function must be called while holding the listed shared
1676locks. Arguments must be lockable type, and there must be at least one
1677argument.
1678
1679Type Safety Checking
1680====================
1681
1682Clang supports additional attributes to enable checking type safety properties
1683that can't be enforced by C type system. Usecases include:
1684
1685* MPI library implementations, where these attributes enable checking that
1686 buffer type matches the passed ``MPI_Datatype``;
1687* for HDF5 library there is a similar usecase as MPI;
1688* checking types of variadic functions' arguments for functions like
1689 ``fcntl()`` and ``ioctl()``.
1690
1691You can detect support for these attributes with ``__has_attribute()``. For
1692example:
1693
1694.. code-block:: c++
1695
1696 #if defined(__has_attribute)
1697 # if __has_attribute(argument_with_type_tag) && \
1698 __has_attribute(pointer_with_type_tag) && \
1699 __has_attribute(type_tag_for_datatype)
1700 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
1701 /* ... other macros ... */
1702 # endif
1703 #endif
1704
1705 #if !defined(ATTR_MPI_PWT)
1706 # define ATTR_MPI_PWT(buffer_idx, type_idx)
1707 #endif
1708
1709 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1710 ATTR_MPI_PWT(1,3);
1711
1712``argument_with_type_tag(...)``
1713-------------------------------
1714
1715Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
1716type_tag_idx)))`` on a function declaration to specify that the function
1717accepts a type tag that determines the type of some other argument.
1718``arg_kind`` is an identifier that should be used when annotating all
1719applicable type tags.
1720
1721This attribute is primarily useful for checking arguments of variadic functions
1722(``pointer_with_type_tag`` can be used in most of non-variadic cases).
1723
1724For example:
1725
1726.. code-block:: c++
1727
1728 int fcntl(int fd, int cmd, ...)
1729 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
1730
1731``pointer_with_type_tag(...)``
1732------------------------------
1733
1734Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
1735on a function declaration to specify that the function accepts a type tag that
1736determines the pointee type of some other pointer argument.
1737
1738For example:
1739
1740.. code-block:: c++
1741
1742 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1743 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
1744
1745``type_tag_for_datatype(...)``
1746------------------------------
1747
1748Clang supports annotating type tags of two forms.
1749
1750* **Type tag that is an expression containing a reference to some declared
1751 identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
1752 declaration with that identifier:
1753
1754 .. code-block:: c++
1755
1756 extern struct mpi_datatype mpi_datatype_int
1757 __attribute__(( type_tag_for_datatype(mpi,int) ));
1758 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
1759
1760* **Type tag that is an integral literal.** Introduce a ``static const``
1761 variable with a corresponding initializer value and attach
1762 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
1763 for example:
1764
1765 .. code-block:: c++
1766
1767 #define MPI_INT ((MPI_Datatype) 42)
1768 static const MPI_Datatype mpi_datatype_int
1769 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42
1770
1771The attribute also accepts an optional third argument that determines how the
1772expression is compared to the type tag. There are two supported flags:
1773
1774* ``layout_compatible`` will cause types to be compared according to
1775 layout-compatibility rules (C++11 [class.mem] p 17, 18). This is
1776 implemented to support annotating types like ``MPI_DOUBLE_INT``.
1777
1778 For example:
1779
1780 .. code-block:: c++
1781
1782 /* In mpi.h */
1783 struct internal_mpi_double_int { double d; int i; };
1784 extern struct mpi_datatype mpi_datatype_double_int
1785 __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
1786
1787 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
1788
1789 /* In user code */
1790 struct my_pair { double a; int b; };
1791 struct my_pair *buffer;
1792 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning
1793
1794 struct my_int_pair { int a; int b; }
1795 struct my_int_pair *buffer2;
1796 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element
1797 // type 'struct my_int_pair'
1798 // doesn't match specified MPI_Datatype
1799
1800* ``must_be_null`` specifies that the expression should be a null pointer
1801 constant, for example:
1802
1803 .. code-block:: c++
1804
1805 /* In mpi.h */
1806 extern struct mpi_datatype mpi_datatype_null
1807 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
1808
1809 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
1810
1811 /* In user code */
1812 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
1813 // was specified but buffer
1814 // is not a null pointer
1815