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