blob: e8826b5b360997eb108c4a84ee97d201df0c54e7 [file] [log] [blame]
Sean Silva3872b462012-12-12 23:44:55 +00001=========================
2Clang Language Extensions
3=========================
4
5.. contents::
6 :local:
Sean Silva55d3f942013-01-02 21:09:58 +00007 :depth: 1
Sean Silva3872b462012-12-12 23:44:55 +00008
Sean Silvaa0c392d2013-01-02 21:03:11 +00009.. toctree::
10 :hidden:
11
12 ObjectiveCLiterals
13 BlockLanguageSpec
Michael Gottesmana65e0762013-01-07 22:24:45 +000014 Block-ABI-Apple
15 AutomaticReferenceCounting
Sean Silvaa0c392d2013-01-02 21:03:11 +000016
Sean Silva3872b462012-12-12 23:44:55 +000017Introduction
18============
19
20This document describes the language extensions provided by Clang. In addition
21to the language extensions listed here, Clang aims to support a broad range of
22GCC extensions. Please see the `GCC manual
23<http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
24these extensions.
25
26.. _langext-feature_check:
27
28Feature Checking Macros
29=======================
30
31Language extensions can be very useful, but only if you know you can depend on
32them. In order to allow fine-grain features checks, we support three builtin
33function-like macros. This allows you to directly test for a feature in your
34code without having to resort to something like autoconf or fragile "compiler
35version checks".
36
37``__has_builtin``
38-----------------
39
40This function-like macro takes a single identifier argument that is the name of
41a builtin function. It evaluates to 1 if the builtin is supported or 0 if not.
42It can be used like this:
43
44.. code-block:: c++
45
46 #ifndef __has_builtin // Optional of course.
47 #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
48 #endif
49
50 ...
51 #if __has_builtin(__builtin_trap)
52 __builtin_trap();
53 #else
54 abort();
55 #endif
56 ...
57
58.. _langext-__has_feature-__has_extension:
59
60``__has_feature`` and ``__has_extension``
61-----------------------------------------
62
63These function-like macros take a single identifier argument that is the name
64of a feature. ``__has_feature`` evaluates to 1 if the feature is both
65supported by Clang and standardized in the current language standard or 0 if
66not (but see :ref:`below <langext-has-feature-back-compat>`), while
67``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
68current language (either as a language extension or a standard language
69feature) or 0 if not. They can be used like this:
70
71.. code-block:: c++
72
73 #ifndef __has_feature // Optional of course.
74 #define __has_feature(x) 0 // Compatibility with non-clang compilers.
75 #endif
76 #ifndef __has_extension
77 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
78 #endif
79
80 ...
81 #if __has_feature(cxx_rvalue_references)
82 // This code will only be compiled with the -std=c++11 and -std=gnu++11
83 // options, because rvalue references are only standardized in C++11.
84 #endif
85
86 #if __has_extension(cxx_rvalue_references)
87 // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
88 // and -std=gnu++98 options, because rvalue references are supported as a
89 // language extension in C++98.
90 #endif
91
92.. _langext-has-feature-back-compat:
93
94For backwards compatibility reasons, ``__has_feature`` can also be used to test
95for support for non-standardized features, i.e. features not prefixed ``c_``,
96``cxx_`` or ``objc_``.
97
98Another use of ``__has_feature`` is to check for compiler features not related
Sean Silva159cc9e2013-01-02 13:07:47 +000099to the language standard, such as e.g. :doc:`AddressSanitizer
100<AddressSanitizer>`.
Sean Silva3872b462012-12-12 23:44:55 +0000101
102If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
103to ``__has_feature``.
104
105The feature tag is described along with the language feature below.
106
107The feature name or extension name can also be specified with a preceding and
108following ``__`` (double underscore) to avoid interference from a macro with
109the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
110of ``cxx_rvalue_references``.
111
112``__has_attribute``
113-------------------
114
115This function-like macro takes a single identifier argument that is the name of
116an attribute. It evaluates to 1 if the attribute is supported or 0 if not. It
117can be used like this:
118
119.. code-block:: c++
120
121 #ifndef __has_attribute // Optional of course.
122 #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
123 #endif
124
125 ...
126 #if __has_attribute(always_inline)
127 #define ALWAYS_INLINE __attribute__((always_inline))
128 #else
129 #define ALWAYS_INLINE
130 #endif
131 ...
132
133The attribute name can also be specified with a preceding and following ``__``
134(double underscore) to avoid interference from a macro with the same name. For
135instance, ``__always_inline__`` can be used instead of ``always_inline``.
136
137Include File Checking Macros
138============================
139
140Not all developments systems have the same include files. The
141:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
142you to check for the existence of an include file before doing a possibly
Dmitri Gribenko21937c62013-01-17 17:04:54 +0000143failing ``#include`` directive. Include file checking macros must be used
144as expressions in ``#if`` or ``#elif`` preprocessing directives.
Sean Silva3872b462012-12-12 23:44:55 +0000145
146.. _langext-__has_include:
147
148``__has_include``
149-----------------
150
151This function-like macro takes a single file name string argument that is the
152name of an include file. It evaluates to 1 if the file can be found using the
153include paths, or 0 otherwise:
154
155.. code-block:: c++
156
157 // Note the two possible file name string formats.
158 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
159 # include "myinclude.h"
160 #endif
161
Richard Smith9e0a65e2013-07-11 00:27:05 +0000162To test for this feature, use ``#if defined(__has_include)``:
163
164.. code-block:: c++
165
Sean Silva3872b462012-12-12 23:44:55 +0000166 // To avoid problem with non-clang compilers not having this macro.
Richard Smith9e0a65e2013-07-11 00:27:05 +0000167 #if defined(__has_include)
168 #if __has_include("myinclude.h")
Sean Silva3872b462012-12-12 23:44:55 +0000169 # include "myinclude.h"
170 #endif
Richard Smith9e0a65e2013-07-11 00:27:05 +0000171 #endif
Sean Silva3872b462012-12-12 23:44:55 +0000172
173.. _langext-__has_include_next:
174
175``__has_include_next``
176----------------------
177
178This function-like macro takes a single file name string argument that is the
179name of an include file. It is like ``__has_include`` except that it looks for
180the second instance of the given file found in the include paths. It evaluates
181to 1 if the second instance of the file can be found using the include paths,
182or 0 otherwise:
183
184.. code-block:: c++
185
186 // Note the two possible file name string formats.
187 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
188 # include_next "myinclude.h"
189 #endif
190
191 // To avoid problem with non-clang compilers not having this macro.
Richard Smith9e0a65e2013-07-11 00:27:05 +0000192 #if defined(__has_include_next)
193 #if __has_include_next("myinclude.h")
Sean Silva3872b462012-12-12 23:44:55 +0000194 # include_next "myinclude.h"
195 #endif
Richard Smith9e0a65e2013-07-11 00:27:05 +0000196 #endif
Sean Silva3872b462012-12-12 23:44:55 +0000197
198Note that ``__has_include_next``, like the GNU extension ``#include_next``
199directive, is intended for use in headers only, and will issue a warning if
200used in the top-level compilation file. A warning will also be issued if an
201absolute path is used in the file argument.
202
203``__has_warning``
204-----------------
205
206This function-like macro takes a string literal that represents a command line
207option for a warning and returns true if that is a valid warning option.
208
209.. code-block:: c++
210
211 #if __has_warning("-Wformat")
212 ...
213 #endif
214
215Builtin Macros
216==============
217
218``__BASE_FILE__``
219 Defined to a string that contains the name of the main input file passed to
220 Clang.
221
222``__COUNTER__``
223 Defined to an integer value that starts at zero and is incremented each time
224 the ``__COUNTER__`` macro is expanded.
225
226``__INCLUDE_LEVEL__``
227 Defined to an integral value that is the include depth of the file currently
228 being translated. For the main file, this value is zero.
229
230``__TIMESTAMP__``
231 Defined to the date and time of the last modification of the current source
232 file.
233
234``__clang__``
235 Defined when compiling with Clang
236
237``__clang_major__``
238 Defined to the major marketing version number of Clang (e.g., the 2 in
239 2.0.1). Note that marketing version numbers should not be used to check for
240 language features, as different vendors use different numbering schemes.
241 Instead, use the :ref:`langext-feature_check`.
242
243``__clang_minor__``
244 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
245 that marketing version numbers should not be used to check for language
246 features, as different vendors use different numbering schemes. Instead, use
247 the :ref:`langext-feature_check`.
248
249``__clang_patchlevel__``
250 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
251
252``__clang_version__``
253 Defined to a string that captures the Clang marketing version, including the
254 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
255
256.. _langext-vectors:
257
258Vectors and Extended Vectors
259============================
260
261Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
262
263OpenCL vector types are created using ``ext_vector_type`` attribute. It
264support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
265is:
266
267.. code-block:: c++
268
269 typedef float float4 __attribute__((ext_vector_type(4)));
270 typedef float float2 __attribute__((ext_vector_type(2)));
271
272 float4 foo(float2 a, float2 b) {
273 float4 c;
274 c.xz = a;
275 c.yw = b;
276 return c;
277 }
278
279Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
280
281Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax
282and functions. For example:
283
284.. code-block:: c++
285
286 vector float foo(vector int a) {
287 vector int b;
288 b = vec_add(a, a) + a;
289 return (vector float)b;
290 }
291
292NEON vector types are created using ``neon_vector_type`` and
293``neon_polyvector_type`` attributes. For example:
294
295.. code-block:: c++
296
297 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
298 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
299
300 int8x8_t foo(int8x8_t a) {
301 int8x8_t v;
302 v = a;
303 return v;
304 }
305
306Vector Literals
307---------------
308
309Vector literals can be used to create vectors from a set of scalars, or
310vectors. Either parentheses or braces form can be used. In the parentheses
311form the number of literal values specified must be one, i.e. referring to a
312scalar value, or must match the size of the vector type being created. If a
313single scalar literal value is specified, the scalar literal value will be
314replicated to all the components of the vector type. In the brackets form any
315number of literals can be specified. For example:
316
317.. code-block:: c++
318
319 typedef int v4si __attribute__((__vector_size__(16)));
320 typedef float float4 __attribute__((ext_vector_type(4)));
321 typedef float float2 __attribute__((ext_vector_type(2)));
322
323 v4si vsi = (v4si){1, 2, 3, 4};
324 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
325 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
326 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
327 vector int vi3 = (vector int)(1, 2); // error
328 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
329 vector int vi5 = (vector int)(1, 2, 3, 4);
330 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
331
332Vector Operations
333-----------------
334
335The table below shows the support for each operation by vector extension. A
336dash indicates that an operation is not accepted according to a corresponding
337specification.
338
339============================== ====== ======= === ====
340 Opeator OpenCL AltiVec GCC NEON
341============================== ====== ======= === ====
342[] yes yes yes --
343unary operators +, -- yes yes yes --
344++, -- -- yes yes yes --
345+,--,*,/,% yes yes yes --
346bitwise operators &,|,^,~ yes yes yes --
347>>,<< yes yes yes --
348!, &&, || no -- -- --
349==, !=, >, <, >=, <= yes yes -- --
350= yes yes yes yes
351:? yes -- -- --
352sizeof yes yes yes yes
353============================== ====== ======= === ====
354
355See also :ref:`langext-__builtin_shufflevector`.
356
357Messages on ``deprecated`` and ``unavailable`` Attributes
358=========================================================
359
360An optional string message can be added to the ``deprecated`` and
361``unavailable`` attributes. For example:
362
363.. code-block:: c++
364
365 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
366
367If the deprecated or unavailable declaration is used, the message will be
368incorporated into the appropriate diagnostic:
369
370.. code-block:: c++
371
372 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
373 [-Wdeprecated-declarations]
374 explode();
375 ^
376
377Query for this feature with
378``__has_extension(attribute_deprecated_with_message)`` and
379``__has_extension(attribute_unavailable_with_message)``.
380
381Attributes on Enumerators
382=========================
383
384Clang allows attributes to be written on individual enumerators. This allows
385enumerators to be deprecated, made unavailable, etc. The attribute must appear
386after the enumerator name and before any initializer, like so:
387
388.. code-block:: c++
389
390 enum OperationMode {
391 OM_Invalid,
392 OM_Normal,
393 OM_Terrified __attribute__((deprecated)),
394 OM_AbortOnError __attribute__((deprecated)) = 4
395 };
396
397Attributes on the ``enum`` declaration do not apply to individual enumerators.
398
399Query for this feature with ``__has_extension(enumerator_attributes)``.
400
401'User-Specified' System Frameworks
402==================================
403
404Clang provides a mechanism by which frameworks can be built in such a way that
405they will always be treated as being "system frameworks", even if they are not
406present in a system framework directory. This can be useful to system
407framework developers who want to be able to test building other applications
408with development builds of their framework, including the manner in which the
409compiler changes warning behavior for system headers.
410
411Framework developers can opt-in to this mechanism by creating a
412"``.system_framework``" file at the top-level of their framework. That is, the
413framework should have contents like:
414
415.. code-block:: none
416
417 .../TestFramework.framework
418 .../TestFramework.framework/.system_framework
419 .../TestFramework.framework/Headers
420 .../TestFramework.framework/Headers/TestFramework.h
421 ...
422
423Clang will treat the presence of this file as an indicator that the framework
424should be treated as a system framework, regardless of how it was found in the
425framework search path. For consistency, we recommend that such files never be
426included in installed versions of the framework.
427
428Availability attribute
429======================
430
431Clang introduces the ``availability`` attribute, which can be placed on
432declarations to describe the lifecycle of that declaration relative to
433operating system versions. Consider the function declaration for a
434hypothetical function ``f``:
435
436.. code-block:: c++
437
438 void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
439
440The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
441deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
442is used by Clang to determine when it is safe to use ``f``: for example, if
443Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
444succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
445succeeds but Clang emits a warning specifying that the function is deprecated.
446Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
447fails because ``f()`` is no longer available.
448
Douglas Gregor52fb37a2013-01-16 01:12:31 +0000449The availability attribute is a comma-separated list starting with the
Sean Silva3872b462012-12-12 23:44:55 +0000450platform name and then including clauses specifying important milestones in the
451declaration's lifetime (in any order) along with additional information. Those
452clauses can be:
453
454introduced=\ *version*
455 The first version in which this declaration was introduced.
456
457deprecated=\ *version*
458 The first version in which this declaration was deprecated, meaning that
459 users should migrate away from this API.
460
461obsoleted=\ *version*
462 The first version in which this declaration was obsoleted, meaning that it
463 was removed completely and can no longer be used.
464
465unavailable
466 This declaration is never available on this platform.
467
468message=\ *string-literal*
469 Additional message text that Clang will provide when emitting a warning or
470 error about use of a deprecated or obsoleted declaration. Useful to direct
471 users to replacement APIs.
472
473Multiple availability attributes can be placed on a declaration, which may
474correspond to different platforms. Only the availability attribute with the
475platform corresponding to the target platform will be used; any others will be
476ignored. If no availability attribute specifies availability for the current
477target platform, the availability attributes are ignored. Supported platforms
478are:
479
480``ios``
481 Apple's iOS operating system. The minimum deployment target is specified by
482 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
483 command-line arguments.
484
485``macosx``
486 Apple's Mac OS X operating system. The minimum deployment target is
487 specified by the ``-mmacosx-version-min=*version*`` command-line argument.
488
489A declaration can be used even when deploying back to a platform version prior
490to when the declaration was introduced. When this happens, the declaration is
491`weakly linked
492<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
493as if the ``weak_import`` attribute were added to the declaration. A
494weakly-linked declaration may or may not be present a run-time, and a program
495can determine whether the declaration is present by checking whether the
496address of that declaration is non-NULL.
497
Dmitri Gribenko44a1efe2013-01-16 01:17:05 +0000498If there are multiple declarations of the same entity, the availability
Douglas Gregor52fb37a2013-01-16 01:12:31 +0000499attributes must either match on a per-platform basis or later
500declarations must not have availability attributes for that
501platform. For example:
502
503.. code-block:: c
504
505 void g(void) __attribute__((availability(macosx,introduced=10.4)));
506 void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches
507 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
508 void g(void); // okay, inherits both macosx and ios availability from above.
509 void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch
510
511When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
512
513.. code-block:: objc
514
515 @interface A
516 - (id)method __attribute__((availability(macosx,introduced=10.4)));
517 - (id)method2 __attribute__((availability(macosx,introduced=10.4)));
518 @end
519
520 @interface B : A
521 - (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later
522 - (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4
523 @end
524
Sean Silva3872b462012-12-12 23:44:55 +0000525Checks for Standard Language Features
526=====================================
527
528The ``__has_feature`` macro can be used to query if certain standard language
529features are enabled. The ``__has_extension`` macro can be used to query if
530language features are available as an extension when compiling for a standard
531which does not provide them. The features which can be tested are listed here.
532
533C++98
534-----
535
536The features listed below are part of the C++98 standard. These features are
537enabled by default when compiling C++ code.
538
539C++ exceptions
540^^^^^^^^^^^^^^
541
542Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
543enabled. For example, compiling code with ``-fno-exceptions`` disables C++
544exceptions.
545
546C++ RTTI
547^^^^^^^^
548
549Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
550example, compiling code with ``-fno-rtti`` disables the use of RTTI.
551
552C++11
553-----
554
555The features listed below are part of the C++11 standard. As a result, all
556these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
557when compiling C++ code.
558
559C++11 SFINAE includes access control
560^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
561
562Use ``__has_feature(cxx_access_control_sfinae)`` or
563``__has_extension(cxx_access_control_sfinae)`` to determine whether
564access-control errors (e.g., calling a private constructor) are considered to
565be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
566<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
567
568C++11 alias templates
569^^^^^^^^^^^^^^^^^^^^^
570
571Use ``__has_feature(cxx_alias_templates)`` or
572``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
573alias declarations and alias templates is enabled.
574
575C++11 alignment specifiers
576^^^^^^^^^^^^^^^^^^^^^^^^^^
577
578Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
579determine if support for alignment specifiers using ``alignas`` is enabled.
580
581C++11 attributes
582^^^^^^^^^^^^^^^^
583
584Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
585determine if support for attribute parsing with C++11's square bracket notation
586is enabled.
587
588C++11 generalized constant expressions
589^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
590
591Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
592constant expressions (e.g., ``constexpr``) is enabled.
593
594C++11 ``decltype()``
595^^^^^^^^^^^^^^^^^^^^
596
597Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
598determine if support for the ``decltype()`` specifier is enabled. C++11's
599``decltype`` does not require type-completeness of a function call expression.
600Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
601``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
602support for this feature is enabled.
603
604C++11 default template arguments in function templates
605^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
606
607Use ``__has_feature(cxx_default_function_template_args)`` or
608``__has_extension(cxx_default_function_template_args)`` to determine if support
609for default template arguments in function templates is enabled.
610
611C++11 ``default``\ ed functions
612^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
613
614Use ``__has_feature(cxx_defaulted_functions)`` or
615``__has_extension(cxx_defaulted_functions)`` to determine if support for
616defaulted function definitions (with ``= default``) is enabled.
617
618C++11 delegating constructors
619^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
620
621Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
622delegating constructors is enabled.
623
624C++11 ``deleted`` functions
625^^^^^^^^^^^^^^^^^^^^^^^^^^^
626
627Use ``__has_feature(cxx_deleted_functions)`` or
628``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
629function definitions (with ``= delete``) is enabled.
630
631C++11 explicit conversion functions
632^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
633
634Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
635``explicit`` conversion functions is enabled.
636
637C++11 generalized initializers
638^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
639
640Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
641generalized initializers (using braced lists and ``std::initializer_list``) is
642enabled.
643
644C++11 implicit move constructors/assignment operators
645^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
646
647Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
648generate move constructors and move assignment operators where needed.
649
650C++11 inheriting constructors
651^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
652
653Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
Richard Smithe6e68b52013-04-19 17:00:31 +0000654inheriting constructors is enabled.
Sean Silva3872b462012-12-12 23:44:55 +0000655
656C++11 inline namespaces
657^^^^^^^^^^^^^^^^^^^^^^^
658
659Use ``__has_feature(cxx_inline_namespaces)`` or
660``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
661namespaces is enabled.
662
663C++11 lambdas
664^^^^^^^^^^^^^
665
666Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
667determine if support for lambdas is enabled.
668
669C++11 local and unnamed types as template arguments
670^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
671
672Use ``__has_feature(cxx_local_type_template_args)`` or
673``__has_extension(cxx_local_type_template_args)`` to determine if support for
674local and unnamed types as template arguments is enabled.
675
676C++11 noexcept
677^^^^^^^^^^^^^^
678
679Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
680determine if support for noexcept exception specifications is enabled.
681
682C++11 in-class non-static data member initialization
683^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
684
685Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
686initialization of non-static data members is enabled.
687
688C++11 ``nullptr``
689^^^^^^^^^^^^^^^^^
690
691Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
692determine if support for ``nullptr`` is enabled.
693
694C++11 ``override control``
695^^^^^^^^^^^^^^^^^^^^^^^^^^
696
697Use ``__has_feature(cxx_override_control)`` or
698``__has_extension(cxx_override_control)`` to determine if support for the
699override control keywords is enabled.
700
701C++11 reference-qualified functions
702^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
703
704Use ``__has_feature(cxx_reference_qualified_functions)`` or
705``__has_extension(cxx_reference_qualified_functions)`` to determine if support
706for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
707applied to ``*this``) is enabled.
708
709C++11 range-based ``for`` loop
710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
711
712Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
713determine if support for the range-based for loop is enabled.
714
715C++11 raw string literals
716^^^^^^^^^^^^^^^^^^^^^^^^^
717
718Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
719string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
720
721C++11 rvalue references
722^^^^^^^^^^^^^^^^^^^^^^^
723
724Use ``__has_feature(cxx_rvalue_references)`` or
725``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
726references is enabled.
727
728C++11 ``static_assert()``
729^^^^^^^^^^^^^^^^^^^^^^^^^
730
731Use ``__has_feature(cxx_static_assert)`` or
732``__has_extension(cxx_static_assert)`` to determine if support for compile-time
733assertions using ``static_assert`` is enabled.
734
Richard Smithe6e68b52013-04-19 17:00:31 +0000735C++11 ``thread_local``
736^^^^^^^^^^^^^^^^^^^^^^
737
738Use ``__has_feature(cxx_thread_local)`` to determine if support for
739``thread_local`` variables is enabled.
740
Sean Silva3872b462012-12-12 23:44:55 +0000741C++11 type inference
742^^^^^^^^^^^^^^^^^^^^
743
744Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
745determine C++11 type inference is supported using the ``auto`` specifier. If
746this is disabled, ``auto`` will instead be a storage class specifier, as in C
747or C++98.
748
749C++11 strongly typed enumerations
750^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
751
752Use ``__has_feature(cxx_strong_enums)`` or
753``__has_extension(cxx_strong_enums)`` to determine if support for strongly
754typed, scoped enumerations is enabled.
755
756C++11 trailing return type
757^^^^^^^^^^^^^^^^^^^^^^^^^^
758
759Use ``__has_feature(cxx_trailing_return)`` or
760``__has_extension(cxx_trailing_return)`` to determine if support for the
761alternate function declaration syntax with trailing return type is enabled.
762
763C++11 Unicode string literals
764^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
765
766Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
767string literals is enabled.
768
769C++11 unrestricted unions
770^^^^^^^^^^^^^^^^^^^^^^^^^
771
772Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
773unrestricted unions is enabled.
774
775C++11 user-defined literals
776^^^^^^^^^^^^^^^^^^^^^^^^^^^
777
778Use ``__has_feature(cxx_user_literals)`` to determine if support for
779user-defined literals is enabled.
780
781C++11 variadic templates
782^^^^^^^^^^^^^^^^^^^^^^^^
783
784Use ``__has_feature(cxx_variadic_templates)`` or
785``__has_extension(cxx_variadic_templates)`` to determine if support for
786variadic templates is enabled.
787
Richard Smith7f0ffb32013-05-07 19:32:56 +0000788C++1y
789-----
790
791The features listed below are part of the committee draft for the C++1y
792standard. As a result, all these features are enabled with the ``-std=c++1y``
793or ``-std=gnu++1y`` option when compiling C++ code.
794
795C++1y binary literals
796^^^^^^^^^^^^^^^^^^^^^
797
798Use ``__has_feature(cxx_binary_literals)`` or
799``__has_extension(cxx_binary_literals)`` to determine whether
800binary literals (for instance, ``0b10010``) are recognized. Clang supports this
801feature as an extension in all language modes.
802
803C++1y contextual conversions
804^^^^^^^^^^^^^^^^^^^^^^^^^^^^
805
806Use ``__has_feature(cxx_contextual_conversions)`` or
807``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules
808are used when performing an implicit conversion for an array bound in a
809*new-expression*, the operand of a *delete-expression*, an integral constant
Richard Smitha4fb3392013-07-24 17:41:31 +0000810expression, or a condition in a ``switch`` statement.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000811
812C++1y decltype(auto)
813^^^^^^^^^^^^^^^^^^^^
814
815Use ``__has_feature(cxx_decltype_auto)`` or
816``__has_extension(cxx_decltype_auto)`` to determine if support
817for the ``decltype(auto)`` placeholder type is enabled.
818
819C++1y default initializers for aggregates
820^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
821
822Use ``__has_feature(cxx_aggregate_nsdmi)`` or
823``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
824for default initializers in aggregate members is enabled.
825
826C++1y generalized lambda capture
827^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
828
Richard Smith3c3a5222013-07-24 17:51:13 +0000829Use ``__has_feature(cxx_init_capture)`` or
830``__has_extension(cxx_init_capture)`` to determine if support for
831lambda captures with explicit initializers is enabled
Richard Smith7f0ffb32013-05-07 19:32:56 +0000832(for instance, ``[n(0)] { return ++n; }``).
833Clang does not yet support this feature.
834
835C++1y generic lambdas
836^^^^^^^^^^^^^^^^^^^^^
837
838Use ``__has_feature(cxx_generic_lambda)`` or
839``__has_extension(cxx_generic_lambda)`` to determine if support for generic
840(polymorphic) lambdas is enabled
841(for instance, ``[] (auto x) { return x + 1; }``).
842Clang does not yet support this feature.
843
844C++1y relaxed constexpr
845^^^^^^^^^^^^^^^^^^^^^^^
846
847Use ``__has_feature(cxx_relaxed_constexpr)`` or
848``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
849declarations, local variable modification, and control flow constructs
850are permitted in ``constexpr`` functions.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000851
852C++1y return type deduction
853^^^^^^^^^^^^^^^^^^^^^^^^^^^
854
855Use ``__has_feature(cxx_return_type_deduction)`` or
856``__has_extension(cxx_return_type_deduction)`` to determine if support
857for return type deduction for functions (using ``auto`` as a return type)
858is enabled.
Richard Smith7f0ffb32013-05-07 19:32:56 +0000859
860C++1y runtime-sized arrays
861^^^^^^^^^^^^^^^^^^^^^^^^^^
862
863Use ``__has_feature(cxx_runtime_array)`` or
864``__has_extension(cxx_runtime_array)`` to determine if support
865for arrays of runtime bound (a restricted form of variable-length arrays)
866is enabled.
867Clang's implementation of this feature is incomplete.
868
869C++1y variable templates
870^^^^^^^^^^^^^^^^^^^^^^^^
871
872Use ``__has_feature(cxx_variable_templates)`` or
873``__has_extension(cxx_variable_templates)`` to determine if support for
874templated variable declarations is enabled.
875Clang does not yet support this feature.
876
Sean Silva3872b462012-12-12 23:44:55 +0000877C11
878---
879
880The features listed below are part of the C11 standard. As a result, all these
881features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
882compiling C code. Additionally, because these features are all
883backward-compatible, they are available as extensions in all language modes.
884
885C11 alignment specifiers
886^^^^^^^^^^^^^^^^^^^^^^^^
887
888Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
889if support for alignment specifiers using ``_Alignas`` is enabled.
890
891C11 atomic operations
892^^^^^^^^^^^^^^^^^^^^^
893
894Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
895if support for atomic types using ``_Atomic`` is enabled. Clang also provides
896:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
897the ``<stdatomic.h>`` operations on ``_Atomic`` types.
898
899C11 generic selections
900^^^^^^^^^^^^^^^^^^^^^^
901
902Use ``__has_feature(c_generic_selections)`` or
903``__has_extension(c_generic_selections)`` to determine if support for generic
904selections is enabled.
905
906As an extension, the C11 generic selection expression is available in all
907languages supported by Clang. The syntax is the same as that given in the C11
908standard.
909
910In C, type compatibility is decided according to the rules given in the
911appropriate standard, but in C++, which lacks the type compatibility rules used
912in C, types are considered compatible only if they are equivalent.
913
914C11 ``_Static_assert()``
915^^^^^^^^^^^^^^^^^^^^^^^^
916
917Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
918to determine if support for compile-time assertions using ``_Static_assert`` is
919enabled.
920
Richard Smithe6e68b52013-04-19 17:00:31 +0000921C11 ``_Thread_local``
922^^^^^^^^^^^^^^^^^^^^^
923
924Use ``__has_feature(c_thread_local)`` to determine if support for
925``_Thread_local`` variables is enabled.
926
Sean Silva3872b462012-12-12 23:44:55 +0000927Checks for Type Traits
928======================
929
930Clang supports the `GNU C++ type traits
931<http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
932`Microsoft Visual C++ Type traits
933<http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. For each
934supported type trait ``__X``, ``__has_extension(X)`` indicates the presence of
935the type trait. For example:
936
937.. code-block:: c++
938
939 #if __has_extension(is_convertible_to)
940 template<typename From, typename To>
941 struct is_convertible_to {
942 static const bool value = __is_convertible_to(From, To);
943 };
944 #else
945 // Emulate type trait
946 #endif
947
948The following type traits are supported by Clang:
949
950* ``__has_nothrow_assign`` (GNU, Microsoft)
951* ``__has_nothrow_copy`` (GNU, Microsoft)
952* ``__has_nothrow_constructor`` (GNU, Microsoft)
953* ``__has_trivial_assign`` (GNU, Microsoft)
954* ``__has_trivial_copy`` (GNU, Microsoft)
955* ``__has_trivial_constructor`` (GNU, Microsoft)
956* ``__has_trivial_destructor`` (GNU, Microsoft)
957* ``__has_virtual_destructor`` (GNU, Microsoft)
958* ``__is_abstract`` (GNU, Microsoft)
959* ``__is_base_of`` (GNU, Microsoft)
960* ``__is_class`` (GNU, Microsoft)
961* ``__is_convertible_to`` (Microsoft)
962* ``__is_empty`` (GNU, Microsoft)
963* ``__is_enum`` (GNU, Microsoft)
964* ``__is_interface_class`` (Microsoft)
965* ``__is_pod`` (GNU, Microsoft)
966* ``__is_polymorphic`` (GNU, Microsoft)
967* ``__is_union`` (GNU, Microsoft)
968* ``__is_literal(type)``: Determines whether the given type is a literal type
969* ``__is_final``: Determines whether the given type is declared with a
970 ``final`` class-virt-specifier.
971* ``__underlying_type(type)``: Retrieves the underlying type for a given
972 ``enum`` type. This trait is required to implement the C++11 standard
973 library.
974* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
975 of type ``totype`` can be assigned to from a value of type ``fromtype`` such
976 that no non-trivial functions are called as part of that assignment. This
977 trait is required to implement the C++11 standard library.
978* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
979 value of type ``type`` can be direct-initialized with arguments of types
980 ``argtypes...`` such that no non-trivial functions are called as part of
981 that initialization. This trait is required to implement the C++11 standard
982 library.
983
984Blocks
985======
986
987The syntax and high level language feature description is in
Michael Gottesmana65e0762013-01-07 22:24:45 +0000988:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
989the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
Sean Silva3872b462012-12-12 23:44:55 +0000990
991Query for this feature with ``__has_extension(blocks)``.
992
993Objective-C Features
994====================
995
996Related result types
997--------------------
998
999According to Cocoa conventions, Objective-C methods with certain names
1000("``init``", "``alloc``", etc.) always return objects that are an instance of
1001the receiving class's type. Such methods are said to have a "related result
1002type", meaning that a message send to one of these methods will have the same
1003static type as an instance of the receiver class. For example, given the
1004following classes:
1005
1006.. code-block:: objc
1007
1008 @interface NSObject
1009 + (id)alloc;
1010 - (id)init;
1011 @end
1012
1013 @interface NSArray : NSObject
1014 @end
1015
1016and this common initialization pattern
1017
1018.. code-block:: objc
1019
1020 NSArray *array = [[NSArray alloc] init];
1021
1022the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1023``alloc`` implicitly has a related result type. Similarly, the type of the
1024expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1025related result type and its receiver is known to have the type ``NSArray *``.
1026If neither ``alloc`` nor ``init`` had a related result type, the expressions
1027would have had type ``id``, as declared in the method signature.
1028
1029A method with a related result type can be declared by using the type
1030``instancetype`` as its result type. ``instancetype`` is a contextual keyword
1031that is only permitted in the result type of an Objective-C method, e.g.
1032
1033.. code-block:: objc
1034
1035 @interface A
1036 + (instancetype)constructAnA;
1037 @end
1038
1039The related result type can also be inferred for some methods. To determine
1040whether a method has an inferred related result type, the first word in the
1041camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1042and the method will have a related result type if its return type is compatible
1043with the type of its class and if:
1044
1045* the first word is "``alloc``" or "``new``", and the method is a class method,
1046 or
1047
1048* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1049 and the method is an instance method.
1050
1051If a method with a related result type is overridden by a subclass method, the
1052subclass method must also return a type that is compatible with the subclass
1053type. For example:
1054
1055.. code-block:: objc
1056
1057 @interface NSString : NSObject
1058 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1059 @end
1060
1061Related result types only affect the type of a message send or property access
1062via the given method. In all other respects, a method with a related result
1063type is treated the same way as method that returns ``id``.
1064
1065Use ``__has_feature(objc_instancetype)`` to determine whether the
1066``instancetype`` contextual keyword is available.
1067
1068Automatic reference counting
1069----------------------------
1070
Sean Silva159cc9e2013-01-02 13:07:47 +00001071Clang provides support for :doc:`automated reference counting
1072<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
Sean Silva3872b462012-12-12 23:44:55 +00001073for manual ``retain``/``release``/``autorelease`` message sends. There are two
1074feature macros associated with automatic reference counting:
1075``__has_feature(objc_arc)`` indicates the availability of automated reference
1076counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1077automated reference counting also includes support for ``__weak`` pointers to
1078Objective-C objects.
1079
Sean Silva159cc9e2013-01-02 13:07:47 +00001080.. _objc-fixed-enum:
1081
Sean Silva3872b462012-12-12 23:44:55 +00001082Enumerations with a fixed underlying type
1083-----------------------------------------
1084
1085Clang provides support for C++11 enumerations with a fixed underlying type
1086within Objective-C. For example, one can write an enumeration type as:
1087
1088.. code-block:: c++
1089
1090 typedef enum : unsigned char { Red, Green, Blue } Color;
1091
1092This specifies that the underlying type, which is used to store the enumeration
1093value, is ``unsigned char``.
1094
1095Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1096underlying types is available in Objective-C.
1097
1098Interoperability with C++11 lambdas
1099-----------------------------------
1100
1101Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1102permitting a lambda to be implicitly converted to a block pointer with the
1103corresponding signature. For example, consider an API such as ``NSArray``'s
1104array-sorting method:
1105
1106.. code-block:: objc
1107
1108 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1109
1110``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1111(^)(id, id)``, and parameters of this type are generally provided with block
1112literals as arguments. However, one can also use a C++11 lambda so long as it
1113provides the same signature (in this case, accepting two parameters of type
1114``id`` and returning an ``NSComparisonResult``):
1115
1116.. code-block:: objc
1117
1118 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1119 @"String 02"];
1120 const NSStringCompareOptions comparisonOptions
1121 = NSCaseInsensitiveSearch | NSNumericSearch |
1122 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1123 NSLocale *currentLocale = [NSLocale currentLocale];
1124 NSArray *sorted
1125 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1126 NSRange string1Range = NSMakeRange(0, [s1 length]);
1127 return [s1 compare:s2 options:comparisonOptions
1128 range:string1Range locale:currentLocale];
1129 }];
1130 NSLog(@"sorted: %@", sorted);
1131
1132This code relies on an implicit conversion from the type of the lambda
1133expression (an unnamed, local class type called the *closure type*) to the
1134corresponding block pointer type. The conversion itself is expressed by a
1135conversion operator in that closure type that produces a block pointer with the
1136same signature as the lambda itself, e.g.,
1137
1138.. code-block:: objc
1139
1140 operator NSComparisonResult (^)(id, id)() const;
1141
1142This conversion function returns a new block that simply forwards the two
1143parameters to the lambda object (which it captures by copy), then returns the
1144result. The returned block is first copied (with ``Block_copy``) and then
1145autoreleased. As an optimization, if a lambda expression is immediately
1146converted to a block pointer (as in the first example, above), then the block
1147is not copied and autoreleased: rather, it is given the same lifetime as a
1148block literal written at that point in the program, which avoids the overhead
1149of copying a block to the heap in the common case.
1150
1151The conversion from a lambda to a block pointer is only available in
1152Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1153management (autorelease).
1154
1155Object Literals and Subscripting
1156--------------------------------
1157
Sean Silva159cc9e2013-01-02 13:07:47 +00001158Clang provides support for :doc:`Object Literals and Subscripting
1159<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
Sean Silva3872b462012-12-12 23:44:55 +00001160programming patterns, makes programs more concise, and improves the safety of
1161container creation. There are several feature macros associated with object
1162literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1163availability of array literals; ``__has_feature(objc_dictionary_literals)``
1164tests the availability of dictionary literals;
1165``__has_feature(objc_subscripting)`` tests the availability of object
1166subscripting.
1167
1168Objective-C Autosynthesis of Properties
1169---------------------------------------
1170
1171Clang provides support for autosynthesis of declared properties. Using this
1172feature, clang provides default synthesis of those properties not declared
1173@dynamic and not having user provided backing getter and setter methods.
1174``__has_feature(objc_default_synthesize_properties)`` checks for availability
1175of this feature in version of clang being used.
1176
Jordan Rose3115f5b62012-12-15 00:37:01 +00001177.. _langext-objc_method_family:
1178
1179The ``objc_method_family`` attribute
1180------------------------------------
1181
1182Many methods in Objective-C have conventional meanings determined by their
1183selectors. It is sometimes useful to be able to mark a method as having a
1184particular conventional meaning despite not having the right selector, or as
1185not having the conventional meaning that its selector would suggest. For these
1186use cases, we provide an attribute to specifically describe the "method family"
1187that a method belongs to.
1188
1189**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
1190``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
1191attribute can only be placed at the end of a method declaration:
1192
1193.. code-block:: objc
1194
1195 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
1196
1197Users who do not wish to change the conventional meaning of a method, and who
1198merely want to document its non-standard retain and release semantics, should
1199use the :ref:`retaining behavior attributes <langext-objc-retain-release>`
1200described below.
1201
1202Query for this feature with ``__has_attribute(objc_method_family)``.
1203
1204.. _langext-objc-retain-release:
1205
1206Objective-C retaining behavior attributes
1207-----------------------------------------
1208
1209In Objective-C, functions and methods are generally assumed to follow the
1210`Cocoa Memory Management
1211<http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
1212conventions for ownership of object arguments and
1213return values. However, there are exceptions, and so Clang provides attributes
1214to allow these exceptions to be documented. This are used by ARC and the
1215`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
1216better described using the :ref:`objc_method_family
1217<langext-objc_method_family>` attribute instead.
1218
1219**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1220``ns_returns_autoreleased``, ``cf_returns_retained``, and
1221``cf_returns_not_retained`` attributes can be placed on methods and functions
1222that return Objective-C or CoreFoundation objects. They are commonly placed at
1223the end of a function prototype or method declaration:
1224
1225.. code-block:: objc
1226
1227 id foo() __attribute__((ns_returns_retained));
1228
1229 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1230
1231The ``*_returns_retained`` attributes specify that the returned object has a +1
1232retain count. The ``*_returns_not_retained`` attributes specify that the return
1233object has a +0 retain count, even if the normal convention for its selector
1234would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1235+0, but is guaranteed to live at least as long as the next flush of an
1236autorelease pool.
1237
1238**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1239an parameter declaration; they specify that the argument is expected to have a
1240+1 retain count, which will be balanced in some way by the function or method.
1241The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1242method; it specifies that the method expects its ``self`` parameter to have a
1243+1 retain count, which it will balance in some way.
1244
1245.. code-block:: objc
1246
1247 void foo(__attribute__((ns_consumed)) NSString *string);
1248
1249 - (void) bar __attribute__((ns_consumes_self));
1250 - (void) baz:(id) __attribute__((ns_consumed)) x;
1251
1252Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
1253<http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
1254
1255Query for these features with ``__has_attribute(ns_consumed)``,
1256``__has_attribute(ns_returns_retained)``, etc.
1257
Eli Friedman11311ea2013-07-26 00:53:29 +00001258objc_msg_lookup_stret
1259---------------------
1260
1261Traditionally, if a runtime is used that follows the GNU Objective-C ABI, a
1262call to objc_msg_lookup() would be emitted for each message send, which would
1263return a pointer to the actual implementation of the method. However,
1264objc_msg_lookup() has no information at all about the method signature of the
1265actual method. Therefore, certain features like forwarding messages cannot be
1266correctly implemented for methods returning structs using objc_msg_lookup(), as
1267methods returning structs use a slightly different calling convention.
1268
1269To work around this, Clang emits calls to objc_msg_lookup_stret() instead for
1270methods that return structs if the runtime supports this, allowing the runtime
1271to use a different forwarding handler for methods returning structs.
1272
1273To check if Clang emits calls to objc_msg_lookup_stret(),
1274__has_feature(objc_msg_lookup_stret) can be used.
Jordan Rose3115f5b62012-12-15 00:37:01 +00001275
Sean Silva3872b462012-12-12 23:44:55 +00001276Function Overloading in C
1277=========================
1278
1279Clang provides support for C++ function overloading in C. Function overloading
1280in C is introduced using the ``overloadable`` attribute. For example, one
1281might provide several overloaded versions of a ``tgsin`` function that invokes
1282the appropriate standard function computing the sine of a value with ``float``,
1283``double``, or ``long double`` precision:
1284
1285.. code-block:: c
1286
1287 #include <math.h>
1288 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
1289 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
1290 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
1291
1292Given these declarations, one can call ``tgsin`` with a ``float`` value to
1293receive a ``float`` result, with a ``double`` to receive a ``double`` result,
1294etc. Function overloading in C follows the rules of C++ function overloading
1295to pick the best overload given the call arguments, with a few C-specific
1296semantics:
1297
1298* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
1299 floating-point promotion (per C99) rather than as a floating-point conversion
1300 (as in C++).
1301
1302* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
1303 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
1304 compatible types.
1305
1306* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
1307 and ``U`` are compatible types. This conversion is given "conversion" rank.
1308
1309The declaration of ``overloadable`` functions is restricted to function
1310declarations and definitions. Most importantly, if any function with a given
1311name is given the ``overloadable`` attribute, then all function declarations
1312and definitions with that name (and in that scope) must have the
1313``overloadable`` attribute. This rule even applies to redeclarations of
1314functions whose original declaration had the ``overloadable`` attribute, e.g.,
1315
1316.. code-block:: c
1317
1318 int f(int) __attribute__((overloadable));
1319 float f(float); // error: declaration of "f" must have the "overloadable" attribute
1320
1321 int g(int) __attribute__((overloadable));
1322 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
1323
1324Functions marked ``overloadable`` must have prototypes. Therefore, the
1325following code is ill-formed:
1326
1327.. code-block:: c
1328
1329 int h() __attribute__((overloadable)); // error: h does not have a prototype
1330
1331However, ``overloadable`` functions are allowed to use a ellipsis even if there
1332are no named parameters (as is permitted in C++). This feature is particularly
1333useful when combined with the ``unavailable`` attribute:
1334
1335.. code-block:: c++
1336
1337 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
1338
1339Functions declared with the ``overloadable`` attribute have their names mangled
1340according to the same rules as C++ function names. For example, the three
1341``tgsin`` functions in our motivating example get the mangled names
1342``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
1343caveats to this use of name mangling:
1344
1345* Future versions of Clang may change the name mangling of functions overloaded
1346 in C, so you should not depend on an specific mangling. To be completely
1347 safe, we strongly urge the use of ``static inline`` with ``overloadable``
1348 functions.
1349
1350* The ``overloadable`` attribute has almost no meaning when used in C++,
1351 because names will already be mangled and functions are already overloadable.
1352 However, when an ``overloadable`` function occurs within an ``extern "C"``
1353 linkage specification, it's name *will* be mangled in the same way as it
1354 would in C.
1355
1356Query for this feature with ``__has_extension(attribute_overloadable)``.
1357
1358Initializer lists for complex numbers in C
1359==========================================
1360
1361clang supports an extension which allows the following in C:
1362
1363.. code-block:: c++
1364
1365 #include <math.h>
1366 #include <complex.h>
1367 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1368
1369This construct is useful because there is no way to separately initialize the
1370real and imaginary parts of a complex variable in standard C, given that clang
1371does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1372``__imag__`` extensions from gcc, which help in some cases, but are not usable
1373in static initializers.)
1374
1375Note that this extension does not allow eliding the braces; the meaning of the
1376following two lines is different:
1377
1378.. code-block:: c++
1379
1380 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1381 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1382
1383This extension also works in C++ mode, as far as that goes, but does not apply
1384to the C++ ``std::complex``. (In C++11, list initialization allows the same
1385syntax to be used with ``std::complex`` with the same meaning.)
1386
1387Builtin Functions
1388=================
1389
1390Clang supports a number of builtin library functions with the same syntax as
1391GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1392``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
1393``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports
1394a number of builtins that GCC does not, which are listed here.
1395
1396Please note that Clang does not and will not support all of the GCC builtins
1397for vector operations. Instead of using builtins, you should use the functions
1398defined in target-specific header files like ``<xmmintrin.h>``, which define
1399portable wrappers for these. Many of the Clang versions of these functions are
1400implemented directly in terms of :ref:`extended vector support
1401<langext-vectors>` instead of builtins, in order to reduce the number of
1402builtins that we need to implement.
1403
1404``__builtin_readcyclecounter``
1405------------------------------
1406
1407``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1408a similar low-latency, high-accuracy clock) on those targets that support it.
1409
1410**Syntax**:
1411
1412.. code-block:: c++
1413
1414 __builtin_readcyclecounter()
1415
1416**Example of Use**:
1417
1418.. code-block:: c++
1419
1420 unsigned long long t0 = __builtin_readcyclecounter();
1421 do_something();
1422 unsigned long long t1 = __builtin_readcyclecounter();
1423 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1424
1425**Description**:
1426
1427The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1428which may be either global or process/thread-specific depending on the target.
1429As the backing counters often overflow quickly (on the order of seconds) this
1430should only be used for timing small intervals. When not supported by the
1431target, the return value is always zero. This builtin takes no arguments and
1432produces an unsigned long long result.
1433
Tim Northoveref7c6e72013-05-23 19:14:12 +00001434Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
1435that even if present, its use may depend on run-time privilege or other OS
1436controlled state.
Sean Silva3872b462012-12-12 23:44:55 +00001437
1438.. _langext-__builtin_shufflevector:
1439
1440``__builtin_shufflevector``
1441---------------------------
1442
1443``__builtin_shufflevector`` is used to express generic vector
1444permutation/shuffle/swizzle operations. This builtin is also very important
1445for the implementation of various target-specific header files like
1446``<xmmintrin.h>``.
1447
1448**Syntax**:
1449
1450.. code-block:: c++
1451
1452 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1453
1454**Examples**:
1455
1456.. code-block:: c++
1457
1458 // Identity operation - return 4-element vector V1.
1459 __builtin_shufflevector(V1, V1, 0, 1, 2, 3)
1460
1461 // "Splat" element 0 of V1 into a 4-element result.
1462 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1463
1464 // Reverse 4-element vector V1.
1465 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1466
1467 // Concatenate every other element of 4-element vectors V1 and V2.
1468 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1469
1470 // Concatenate every other element of 8-element vectors V1 and V2.
1471 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1472
1473**Description**:
1474
1475The first two arguments to ``__builtin_shufflevector`` are vectors that have
1476the same element type. The remaining arguments are a list of integers that
1477specify the elements indices of the first two vectors that should be extracted
1478and returned in a new vector. These element indices are numbered sequentially
1479starting with the first vector, continuing into the second vector. Thus, if
1480``vec1`` is a 4-element vector, index 5 would refer to the second element of
1481``vec2``.
1482
1483The result of ``__builtin_shufflevector`` is a vector with the same element
1484type as ``vec1``/``vec2`` but that has an element count equal to the number of
1485indices specified.
1486
1487Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1488
1489``__builtin_unreachable``
1490-------------------------
1491
1492``__builtin_unreachable`` is used to indicate that a specific point in the
1493program cannot be reached, even if the compiler might otherwise think it can.
1494This is useful to improve optimization and eliminates certain warnings. For
1495example, without the ``__builtin_unreachable`` in the example below, the
1496compiler assumes that the inline asm can fall through and prints a "function
1497declared '``noreturn``' should not return" warning.
1498
1499**Syntax**:
1500
1501.. code-block:: c++
1502
1503 __builtin_unreachable()
1504
1505**Example of use**:
1506
1507.. code-block:: c++
1508
1509 void myabort(void) __attribute__((noreturn));
1510 void myabort(void) {
1511 asm("int3");
1512 __builtin_unreachable();
1513 }
1514
1515**Description**:
1516
1517The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1518Since it has undefined behavior, it is a statement that it is never reached and
1519the optimizer can take advantage of this to produce better code. This builtin
1520takes no arguments and produces a void result.
1521
1522Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1523
1524``__sync_swap``
1525---------------
1526
1527``__sync_swap`` is used to atomically swap integers or pointers in memory.
1528
1529**Syntax**:
1530
1531.. code-block:: c++
1532
1533 type __sync_swap(type *ptr, type value, ...)
1534
1535**Example of Use**:
1536
1537.. code-block:: c++
1538
1539 int old_value = __sync_swap(&value, new_value);
1540
1541**Description**:
1542
1543The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1544atomic intrinsics to allow code to atomically swap the current value with the
1545new value. More importantly, it helps developers write more efficient and
1546correct code by avoiding expensive loops around
1547``__sync_bool_compare_and_swap()`` or relying on the platform specific
1548implementation details of ``__sync_lock_test_and_set()``. The
1549``__sync_swap()`` builtin is a full barrier.
1550
Richard Smith5154dce2013-07-11 02:27:57 +00001551``__builtin_addressof``
1552-----------------------
1553
1554``__builtin_addressof`` performs the functionality of the built-in ``&``
1555operator, ignoring any ``operator&`` overload. This is useful in constant
1556expressions in C++11, where there is no other way to take the address of an
1557object that overloads ``operator&``.
1558
1559**Example of use**:
1560
1561.. code-block:: c++
1562
1563 template<typename T> constexpr T *addressof(T &value) {
1564 return __builtin_addressof(value);
1565 }
1566
Michael Gottesman377b8c62013-01-13 04:35:31 +00001567Multiprecision Arithmetic Builtins
1568----------------------------------
1569
1570Clang provides a set of builtins which expose multiprecision arithmetic in a
1571manner amenable to C. They all have the following form:
1572
1573.. code-block:: c
1574
1575 unsigned x = ..., y = ..., carryin = ..., carryout;
1576 unsigned sum = __builtin_addc(x, y, carryin, &carryout);
1577
1578Thus one can form a multiprecision addition chain in the following manner:
1579
1580.. code-block:: c
1581
1582 unsigned *x, *y, *z, carryin=0, carryout;
1583 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
1584 carryin = carryout;
1585 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
1586 carryin = carryout;
1587 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
1588 carryin = carryout;
1589 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
1590
1591The complete list of builtins are:
1592
1593.. code-block:: c
1594
Michael Gottesmanee76e722013-06-18 20:40:40 +00001595 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesman377b8c62013-01-13 04:35:31 +00001596 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1597 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1598 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1599 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
Michael Gottesmanee76e722013-06-18 20:40:40 +00001600 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesman377b8c62013-01-13 04:35:31 +00001601 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
1602 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
1603 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
1604 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
1605
Michael Gottesman98d1ec12013-06-20 23:28:10 +00001606Checked Arithmetic Builtins
1607---------------------------
1608
1609Clang provides a set of builtins that implement checked arithmetic for security
1610critical applications in a manner that is fast and easily expressable in C. As
1611an example of their usage:
1612
1613.. code-block:: c
1614
1615 errorcode_t security_critical_application(...) {
1616 unsigned x, y, result;
1617 ...
1618 if (__builtin_umul_overflow(x, y, &result))
1619 return kErrorCodeHackers;
1620 ...
1621 use_multiply(result);
1622 ...
1623 }
1624
1625A complete enumeration of the builtins are:
1626
1627.. code-block:: c
1628
1629 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
1630 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
1631 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
1632 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
1633 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
1634 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
1635 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
1636 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
1637 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
1638 bool __builtin_sadd_overflow (int x, int y, int *sum);
1639 bool __builtin_saddl_overflow (long x, long y, long *sum);
1640 bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
1641 bool __builtin_ssub_overflow (int x, int y, int *diff);
1642 bool __builtin_ssubl_overflow (long x, long y, long *diff);
1643 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
1644 bool __builtin_smul_overflow (int x, int y, int *prod);
1645 bool __builtin_smull_overflow (long x, long y, long *prod);
1646 bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
1647
1648
Sean Silva3872b462012-12-12 23:44:55 +00001649.. _langext-__c11_atomic:
1650
1651__c11_atomic builtins
1652---------------------
1653
1654Clang provides a set of builtins which are intended to be used to implement
1655C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
1656``_explicit`` form of the corresponding C11 operation, and are named with a
1657``__c11_`` prefix. The supported operations are:
1658
1659* ``__c11_atomic_init``
1660* ``__c11_atomic_thread_fence``
1661* ``__c11_atomic_signal_fence``
1662* ``__c11_atomic_is_lock_free``
1663* ``__c11_atomic_store``
1664* ``__c11_atomic_load``
1665* ``__c11_atomic_exchange``
1666* ``__c11_atomic_compare_exchange_strong``
1667* ``__c11_atomic_compare_exchange_weak``
1668* ``__c11_atomic_fetch_add``
1669* ``__c11_atomic_fetch_sub``
1670* ``__c11_atomic_fetch_and``
1671* ``__c11_atomic_fetch_or``
1672* ``__c11_atomic_fetch_xor``
1673
Tim Northover09df2b02013-07-16 09:47:53 +00001674Low-level ARM exclusive memory builtins
1675---------------------------------------
1676
1677Clang provides overloaded builtins giving direct access to the three key ARM
1678instructions for implementing atomic operations.
1679
1680.. code-block:: c
1681 T __builtin_arm_ldrex(const volatile T *addr);
1682 int __builtin_arm_strex(T val, volatile T *addr);
1683 void __builtin_arm_clrex(void);
1684
1685The types ``T`` currently supported are:
1686* Integer types with width at most 64 bits.
1687* Floating-point types
1688* Pointer types.
1689
1690Note that the compiler does not guarantee it will not insert stores which clear
1691the exclusive monitor in between an ``ldrex`` and its paired ``strex``. In
1692practice this is only usually a risk when the extra store is on the same cache
1693line as the variable being modified and Clang will only insert stack stores on
1694its own, so it is best not to use these operations on variables with automatic
1695storage duration.
1696
1697Also, loads and stores may be implicit in code written between the ``ldrex`` and
1698``strex``. Clang will not necessarily mitigate the effects of these either, so
1699care should be exercised.
1700
1701For these reasons the higher level atomic primitives should be preferred where
1702possible.
1703
Sean Silva3872b462012-12-12 23:44:55 +00001704Non-standard C++11 Attributes
1705=============================
1706
Richard Smith6f488192013-02-14 00:13:34 +00001707Clang's non-standard C++11 attributes live in the ``clang`` attribute
1708namespace.
Sean Silva3872b462012-12-12 23:44:55 +00001709
1710The ``clang::fallthrough`` attribute
1711------------------------------------
1712
1713The ``clang::fallthrough`` attribute is used along with the
1714``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
1715between switch labels. It can only be applied to a null statement placed at a
1716point of execution between any statement and the next switch label. It is
1717common to mark these places with a specific comment, but this attribute is
1718meant to replace comments with a more strict annotation, which can be checked
1719by the compiler. This attribute doesn't change semantics of the code and can
1720be used wherever an intended fall-through occurs. It is designed to mimic
1721control-flow statements like ``break;``, so it can be placed in most places
1722where ``break;`` can, but only if there are no statements on the execution path
1723between it and the next switch label.
1724
1725Here is an example:
1726
1727.. code-block:: c++
1728
1729 // compile with -Wimplicit-fallthrough
1730 switch (n) {
1731 case 22:
1732 case 33: // no warning: no statements between case labels
1733 f();
1734 case 44: // warning: unannotated fall-through
1735 g();
1736 [[clang::fallthrough]];
1737 case 55: // no warning
1738 if (x) {
1739 h();
1740 break;
1741 }
1742 else {
1743 i();
1744 [[clang::fallthrough]];
1745 }
1746 case 66: // no warning
1747 p();
1748 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1749 // directly precede case label
1750 q();
1751 case 77: // warning: unannotated fall-through
1752 r();
1753 }
1754
Richard Smith6f488192013-02-14 00:13:34 +00001755``gnu::`` attributes
1756--------------------
1757
1758Clang also supports GCC's ``gnu`` attribute namespace. All GCC attributes which
1759are accepted with the ``__attribute__((foo))`` syntax are also accepted as
1760``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
1761(see the list of `GCC function attributes
1762<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
1763attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
1764`GCC type attributes
Richard Smith9e0a65e2013-07-11 00:27:05 +00001765<http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
Richard Smith6f488192013-02-14 00:13:34 +00001766implementation, these attributes must appertain to the *declarator-id* in a
1767declaration, which means they must go either at the start of the declaration or
1768immediately after the name being declared.
1769
1770For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
1771also applies the GNU ``noreturn`` attribute to ``f``.
1772
1773.. code-block:: c++
1774
1775 [[gnu::unused]] int a, f [[gnu::noreturn]] ();
1776
Sean Silva3872b462012-12-12 23:44:55 +00001777Target-Specific Extensions
1778==========================
1779
1780Clang supports some language features conditionally on some targets.
1781
1782X86/X86-64 Language Extensions
1783------------------------------
1784
1785The X86 backend has these language extensions:
1786
1787Memory references off the GS segment
1788^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1789
1790Annotating a pointer with address space #256 causes it to be code generated
1791relative to the X86 GS segment register, and address space #257 causes it to be
1792relative to the X86 FS segment. Note that this is a very very low-level
1793feature that should only be used if you know what you're doing (for example in
1794an OS kernel).
1795
1796Here is an example:
1797
1798.. code-block:: c++
1799
1800 #define GS_RELATIVE __attribute__((address_space(256)))
1801 int foo(int GS_RELATIVE *P) {
1802 return *P;
1803 }
1804
1805Which compiles to (on X86-32):
1806
1807.. code-block:: gas
1808
1809 _foo:
1810 movl 4(%esp), %eax
1811 movl %gs:(%eax), %eax
1812 ret
1813
Jordan Rose3115f5b62012-12-15 00:37:01 +00001814Extensions for Static Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001815==============================
Sean Silva3872b462012-12-12 23:44:55 +00001816
1817Clang supports additional attributes that are useful for documenting program
Jordan Rose3115f5b62012-12-15 00:37:01 +00001818invariants and rules for static analysis tools, such as the `Clang Static
1819Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
1820in the analyzer's `list of source-level annotations
1821<http://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva3872b462012-12-12 23:44:55 +00001822
Sean Silva3872b462012-12-12 23:44:55 +00001823
Jordan Rose3115f5b62012-12-15 00:37:01 +00001824Extensions for Dynamic Analysis
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001825===============================
Sean Silva3872b462012-12-12 23:44:55 +00001826
1827.. _langext-address_sanitizer:
1828
1829AddressSanitizer
1830----------------
1831
1832Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenko1228d662012-12-15 14:25:25 +00001833with :doc:`AddressSanitizer`.
Sean Silva3872b462012-12-12 23:44:55 +00001834
Kostya Serebryany85aee962013-02-26 06:58:27 +00001835Use ``__attribute__((no_sanitize_address))``
1836on a function declaration
Sean Silva3872b462012-12-12 23:44:55 +00001837to specify that address safety instrumentation (e.g. AddressSanitizer) should
1838not be applied to that function.
1839
Kostya Serebryany85aee962013-02-26 06:58:27 +00001840.. _langext-thread_sanitizer:
1841
1842ThreadSanitizer
1843----------------
1844
1845Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
1846with :doc:`ThreadSanitizer`.
1847
1848Use ``__attribute__((no_sanitize_thread))`` on a function declaration
1849to specify that checks for data races on plain (non-atomic) memory accesses
1850should not be inserted by ThreadSanitizer.
1851The function may still be instrumented by the tool
1852to avoid false positives in other places.
1853
1854.. _langext-memory_sanitizer:
1855
1856MemorySanitizer
1857----------------
1858Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
1859with :doc:`MemorySanitizer`.
1860
1861Use ``__attribute__((no_sanitize_memory))`` on a function declaration
1862to specify that checks for uninitialized memory should not be inserted
1863(e.g. by MemorySanitizer). The function may still be instrumented by the tool
1864to avoid false positives in other places.
1865
1866
Sean Silva3872b462012-12-12 23:44:55 +00001867Thread-Safety Annotation Checking
1868=================================
1869
1870Clang supports additional attributes for checking basic locking policies in
1871multithreaded programs. Clang currently parses the following list of
1872attributes, although **the implementation for these annotations is currently in
1873development.** For more details, see the `GCC implementation
1874<http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_.
1875
1876``no_thread_safety_analysis``
1877-----------------------------
1878
1879Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to
1880specify that the thread safety analysis should not be run on that function.
1881This attribute provides an escape hatch (e.g. for situations when it is
1882difficult to annotate the locking policy).
1883
1884``lockable``
1885------------
1886
1887Use ``__attribute__((lockable))`` on a class definition to specify that it has
1888a lockable type (e.g. a Mutex class). This annotation is primarily used to
1889check consistency.
1890
1891``scoped_lockable``
1892-------------------
1893
1894Use ``__attribute__((scoped_lockable))`` on a class definition to specify that
1895it has a "scoped" lockable type. Objects of this type will acquire the lock
1896upon construction and release it upon going out of scope. This annotation is
1897primarily used to check consistency.
1898
1899``guarded_var``
1900---------------
1901
1902Use ``__attribute__((guarded_var))`` on a variable declaration to specify that
1903the variable must be accessed while holding some lock.
1904
1905``pt_guarded_var``
1906------------------
1907
1908Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify
1909that the pointer must be dereferenced while holding some lock.
1910
1911``guarded_by(l)``
1912-----------------
1913
1914Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify
1915that the variable must be accessed while holding lock ``l``.
1916
1917``pt_guarded_by(l)``
1918--------------------
1919
1920Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify
1921that the pointer must be dereferenced while holding lock ``l``.
1922
1923``acquired_before(...)``
1924------------------------
1925
1926Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable
1927variable to specify that the lock must be acquired before all attribute
1928arguments. Arguments must be lockable type, and there must be at least one
1929argument.
1930
1931``acquired_after(...)``
1932-----------------------
1933
1934Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable
1935variable to specify that the lock must be acquired after all attribute
1936arguments. Arguments must be lockable type, and there must be at least one
1937argument.
1938
1939``exclusive_lock_function(...)``
1940--------------------------------
1941
1942Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
1943to specify that the function acquires all listed locks exclusively. This
1944attribute takes zero or more arguments: either of lockable type or integers
1945indexing into function parameters of lockable type. If no arguments are given,
1946the acquired lock is implicitly ``this`` of the enclosing object.
1947
1948``shared_lock_function(...)``
1949-----------------------------
1950
1951Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
1952specify that the function acquires all listed locks, although the locks may be
1953shared (e.g. read locks). This attribute takes zero or more arguments: either
1954of lockable type or integers indexing into function parameters of lockable
1955type. If no arguments are given, the acquired lock is implicitly ``this`` of
1956the enclosing object.
1957
1958``exclusive_trylock_function(...)``
1959-----------------------------------
1960
1961Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
1962to specify that the function will try (without blocking) to acquire all listed
1963locks exclusively. This attribute takes one or more arguments. The first
1964argument is an integer or boolean value specifying the return value of a
1965successful lock acquisition. The remaining arugments are either of lockable
1966type or integers indexing into function parameters of lockable type. If only
1967one argument is given, the acquired lock is implicitly ``this`` of the
1968enclosing object.
1969
1970``shared_trylock_function(...)``
1971--------------------------------
1972
1973Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
1974specify that the function will try (without blocking) to acquire all listed
1975locks, although the locks may be shared (e.g. read locks). This attribute
1976takes one or more arguments. The first argument is an integer or boolean value
1977specifying the return value of a successful lock acquisition. The remaining
1978arugments are either of lockable type or integers indexing into function
1979parameters of lockable type. If only one argument is given, the acquired lock
1980is implicitly ``this`` of the enclosing object.
1981
1982``unlock_function(...)``
1983------------------------
1984
1985Use ``__attribute__((unlock_function(...)))`` on a function declaration to
1986specify that the function release all listed locks. This attribute takes zero
1987or more arguments: either of lockable type or integers indexing into function
1988parameters of lockable type. If no arguments are given, the acquired lock is
1989implicitly ``this`` of the enclosing object.
1990
1991``lock_returned(l)``
1992--------------------
1993
1994Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify
1995that the function returns lock ``l`` (``l`` must be of lockable type). This
1996annotation is used to aid in resolving lock expressions.
1997
1998``locks_excluded(...)``
1999-----------------------
2000
2001Use ``__attribute__((locks_excluded(...)))`` on a function declaration to
2002specify that the function must not be called with the listed locks. Arguments
2003must be lockable type, and there must be at least one argument.
2004
2005``exclusive_locks_required(...)``
2006---------------------------------
2007
2008Use ``__attribute__((exclusive_locks_required(...)))`` on a function
2009declaration to specify that the function must be called while holding the
2010listed exclusive locks. Arguments must be lockable type, and there must be at
2011least one argument.
2012
2013``shared_locks_required(...)``
2014------------------------------
2015
2016Use ``__attribute__((shared_locks_required(...)))`` on a function declaration
2017to specify that the function must be called while holding the listed shared
2018locks. Arguments must be lockable type, and there must be at least one
2019argument.
2020
2021Type Safety Checking
2022====================
2023
2024Clang supports additional attributes to enable checking type safety properties
Richard Smith151a8a82013-07-11 00:34:42 +00002025that can't be enforced by the C type system. Use cases include:
Sean Silva3872b462012-12-12 23:44:55 +00002026
2027* MPI library implementations, where these attributes enable checking that
Richard Smith151a8a82013-07-11 00:34:42 +00002028 the buffer type matches the passed ``MPI_Datatype``;
2029* for HDF5 library there is a similar use case to MPI;
Sean Silva3872b462012-12-12 23:44:55 +00002030* checking types of variadic functions' arguments for functions like
2031 ``fcntl()`` and ``ioctl()``.
2032
2033You can detect support for these attributes with ``__has_attribute()``. For
2034example:
2035
2036.. code-block:: c++
2037
2038 #if defined(__has_attribute)
2039 # if __has_attribute(argument_with_type_tag) && \
2040 __has_attribute(pointer_with_type_tag) && \
2041 __has_attribute(type_tag_for_datatype)
2042 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
2043 /* ... other macros ... */
2044 # endif
2045 #endif
2046
2047 #if !defined(ATTR_MPI_PWT)
2048 # define ATTR_MPI_PWT(buffer_idx, type_idx)
2049 #endif
2050
2051 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2052 ATTR_MPI_PWT(1,3);
2053
2054``argument_with_type_tag(...)``
2055-------------------------------
2056
2057Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
2058type_tag_idx)))`` on a function declaration to specify that the function
2059accepts a type tag that determines the type of some other argument.
2060``arg_kind`` is an identifier that should be used when annotating all
2061applicable type tags.
2062
2063This attribute is primarily useful for checking arguments of variadic functions
Richard Smith151a8a82013-07-11 00:34:42 +00002064(``pointer_with_type_tag`` can be used in most non-variadic cases).
Sean Silva3872b462012-12-12 23:44:55 +00002065
2066For example:
2067
2068.. code-block:: c++
2069
2070 int fcntl(int fd, int cmd, ...)
2071 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
2072
2073``pointer_with_type_tag(...)``
2074------------------------------
2075
2076Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
2077on a function declaration to specify that the function accepts a type tag that
2078determines the pointee type of some other pointer argument.
2079
2080For example:
2081
2082.. code-block:: c++
2083
2084 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2085 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2086
2087``type_tag_for_datatype(...)``
2088------------------------------
2089
2090Clang supports annotating type tags of two forms.
2091
2092* **Type tag that is an expression containing a reference to some declared
2093 identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
2094 declaration with that identifier:
2095
2096 .. code-block:: c++
2097
2098 extern struct mpi_datatype mpi_datatype_int
2099 __attribute__(( type_tag_for_datatype(mpi,int) ));
2100 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
2101
2102* **Type tag that is an integral literal.** Introduce a ``static const``
2103 variable with a corresponding initializer value and attach
2104 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
2105 for example:
2106
2107 .. code-block:: c++
2108
2109 #define MPI_INT ((MPI_Datatype) 42)
2110 static const MPI_Datatype mpi_datatype_int
2111 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42
2112
2113The attribute also accepts an optional third argument that determines how the
2114expression is compared to the type tag. There are two supported flags:
2115
2116* ``layout_compatible`` will cause types to be compared according to
2117 layout-compatibility rules (C++11 [class.mem] p 17, 18). This is
2118 implemented to support annotating types like ``MPI_DOUBLE_INT``.
2119
2120 For example:
2121
2122 .. code-block:: c++
2123
2124 /* In mpi.h */
2125 struct internal_mpi_double_int { double d; int i; };
2126 extern struct mpi_datatype mpi_datatype_double_int
2127 __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
2128
2129 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
2130
2131 /* In user code */
2132 struct my_pair { double a; int b; };
2133 struct my_pair *buffer;
2134 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning
2135
2136 struct my_int_pair { int a; int b; }
2137 struct my_int_pair *buffer2;
2138 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element
2139 // type 'struct my_int_pair'
2140 // doesn't match specified MPI_Datatype
2141
2142* ``must_be_null`` specifies that the expression should be a null pointer
2143 constant, for example:
2144
2145 .. code-block:: c++
2146
2147 /* In mpi.h */
2148 extern struct mpi_datatype mpi_datatype_null
2149 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
2150
2151 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
2152
2153 /* In user code */
2154 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
2155 // was specified but buffer
2156 // is not a null pointer
2157
Dmitri Gribenkob4b970f2013-01-13 16:37:18 +00002158Format String Checking
2159======================
2160
2161Clang supports the ``format`` attribute, which indicates that the function
2162accepts a ``printf`` or ``scanf``-like format string and corresponding
2163arguments or a ``va_list`` that contains these arguments.
2164
2165Please see `GCC documentation about format attribute
2166<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
2167about attribute syntax.
2168
2169Clang implements two kinds of checks with this attribute.
2170
2171#. Clang checks that the function with the ``format`` attribute is called with
2172 a format string that uses format specifiers that are allowed, and that
2173 arguments match the format string. This is the ``-Wformat`` warning, it is
2174 on by default.
2175
2176#. Clang checks that the format string argument is a literal string. This is
2177 the ``-Wformat-nonliteral`` warning, it is off by default.
2178
2179 Clang implements this mostly the same way as GCC, but there is a difference
2180 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
2181 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
2182 fuctions. Clang does not warn if the format string comes from a function
Richard Smith7cdc3112013-02-14 00:22:00 +00002183 parameter, where the function is annotated with a compatible attribute,
Dmitri Gribenkob4b970f2013-01-13 16:37:18 +00002184 otherwise it warns. For example:
2185
2186 .. code-block:: c
2187
2188 __attribute__((__format__ (__scanf__, 1, 3)))
2189 void foo(const char* s, char *buf, ...) {
2190 va_list ap;
2191 va_start(ap, buf);
2192
2193 vprintf(s, ap); // warning: format string is not a string literal
2194 }
2195
2196 In this case we warn because ``s`` contains a format string for a
Richard Smith7cdc3112013-02-14 00:22:00 +00002197 ``scanf``-like function, but it is passed to a ``printf``-like function.
Dmitri Gribenkob4b970f2013-01-13 16:37:18 +00002198
2199 If the attribute is removed, clang still warns, because the format string is
2200 not a string literal.
2201
Richard Smith7cdc3112013-02-14 00:22:00 +00002202 Another example:
Dmitri Gribenkob4b970f2013-01-13 16:37:18 +00002203
Richard Smith3a094442013-02-14 00:23:04 +00002204 .. code-block:: c
Dmitri Gribenkob4b970f2013-01-13 16:37:18 +00002205
2206 __attribute__((__format__ (__printf__, 1, 3)))
2207 void foo(const char* s, char *buf, ...) {
2208 va_list ap;
2209 va_start(ap, buf);
2210
2211 vprintf(s, ap); // warning
2212 }
2213
Richard Smith7cdc3112013-02-14 00:22:00 +00002214 In this case Clang does not warn because the format string ``s`` and
2215 the corresponding arguments are annotated. If the arguments are
2216 incorrect, the caller of ``foo`` will receive a warning.