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