blob: ecbf04c3c822ac599c54894e10f6fbe5896bacee [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
DeLesley Hutchinsc51e08c2014-02-18 19:42:01 +000015 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
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +000023<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
Sean Silva709c44d2012-12-12 23:44:55 +000024these 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
Alp Toker958027b2014-07-14 19:42:55 +000094For backward compatibility, ``__has_feature`` can also be used to test
Sean Silva709c44d2012-12-12 23:44:55 +000095for 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
Aaron Ballmana0344c52014-11-14 13:44:02 +0000112``__has_cpp_attribute``
Aaron Ballman631bd7b2014-11-14 14:01:55 +0000113-----------------------
Aaron Ballmana0344c52014-11-14 13:44:02 +0000114
Aaron Ballman62015572018-11-20 15:23:07 +0000115This function-like macro is available in C++2a by default, and is provided as an
116extension in earlier language standards. It takes a single argument that is the
117name of a double-square-bracket-style attribute. The argument can either be a
118single identifier or a scoped identifier. If the attribute is supported, a
119nonzero value is returned. If the attribute is a standards-based attribute, this
120macro returns a nonzero value based on the year and month in which the attribute
121was voted into the working draft. See `WG21 SD-6
122<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
123for the list of values returned for standards-based attributes. If the attribute
124is not supported by the current compliation target, this macro evaluates to 0.
125It can be used like this:
Aaron Ballmana0344c52014-11-14 13:44:02 +0000126
127.. code-block:: c++
128
Aaron Ballman62015572018-11-20 15:23:07 +0000129 #ifndef __has_cpp_attribute // For backwards compatibility
130 #define __has_cpp_attribute(x) 0
Aaron Ballmana0344c52014-11-14 13:44:02 +0000131 #endif
132
133 ...
134 #if __has_cpp_attribute(clang::fallthrough)
135 #define FALLTHROUGH [[clang::fallthrough]]
136 #else
137 #define FALLTHROUGH
138 #endif
139 ...
140
Aaron Ballman62015572018-11-20 15:23:07 +0000141The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
142the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
143of these namespaces can be specified with a preceding and following ``__``
144(double underscore) to avoid interference from a macro with the same name. For
145instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
Aaron Ballmana0344c52014-11-14 13:44:02 +0000146
Aaron Ballman48f5f4d2017-12-07 21:37:49 +0000147``__has_c_attribute``
148---------------------
149
150This function-like macro takes a single argument that is the name of an
151attribute exposed with the double square-bracket syntax in C mode. The argument
152can either be a single identifier or a scoped identifier. If the attribute is
153supported, a nonzero value is returned. If the attribute is not supported by the
154current compilation target, this macro evaluates to 0. It can be used like this:
155
156.. code-block:: c
157
158 #ifndef __has_c_attribute // Optional of course.
159 #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers.
160 #endif
161
162 ...
163 #if __has_c_attribute(fallthrough)
164 #define FALLTHROUGH [[fallthrough]]
165 #else
166 #define FALLTHROUGH
167 #endif
168 ...
169
Aaron Ballman62015572018-11-20 15:23:07 +0000170The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
171the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
172of these namespaces can be specified with a preceding and following ``__``
173(double underscore) to avoid interference from a macro with the same name. For
174instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
Aaron Ballman48f5f4d2017-12-07 21:37:49 +0000175
Sean Silva709c44d2012-12-12 23:44:55 +0000176``__has_attribute``
177-------------------
178
179This function-like macro takes a single identifier argument that is the name of
Aaron Ballman4bfaeba2014-12-05 17:11:49 +0000180a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
181current compilation target, or 0 if not. It can be used like this:
Sean Silva709c44d2012-12-12 23:44:55 +0000182
183.. code-block:: c++
184
185 #ifndef __has_attribute // Optional of course.
186 #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
187 #endif
188
189 ...
190 #if __has_attribute(always_inline)
191 #define ALWAYS_INLINE __attribute__((always_inline))
192 #else
193 #define ALWAYS_INLINE
194 #endif
195 ...
196
197The attribute name can also be specified with a preceding and following ``__``
198(double underscore) to avoid interference from a macro with the same name. For
199instance, ``__always_inline__`` can be used instead of ``always_inline``.
200
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000201
202``__has_declspec_attribute``
203----------------------------
204
205This function-like macro takes a single identifier argument that is the name of
206an attribute implemented as a Microsoft-style ``__declspec`` attribute. It
207evaluates to 1 if the attribute is supported by the current compilation target,
208or 0 if not. It can be used like this:
209
210.. code-block:: c++
211
212 #ifndef __has_declspec_attribute // Optional of course.
213 #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers.
214 #endif
215
216 ...
217 #if __has_declspec_attribute(dllexport)
218 #define DLLEXPORT __declspec(dllexport)
219 #else
220 #define DLLEXPORT
221 #endif
222 ...
223
224The attribute name can also be specified with a preceding and following ``__``
225(double underscore) to avoid interference from a macro with the same name. For
226instance, ``__dllexport__`` can be used instead of ``dllexport``.
227
Yunzhong Gaoa8c45c92014-04-12 02:25:32 +0000228``__is_identifier``
229-------------------
230
231This function-like macro takes a single identifier argument that might be either
232a reserved word or a regular identifier. It evaluates to 1 if the argument is just
233a regular identifier and not a reserved word, in the sense that it can then be
234used as the name of a user-defined function or variable. Otherwise it evaluates
235to 0. It can be used like this:
236
237.. code-block:: c++
238
239 ...
240 #ifdef __is_identifier // Compatibility with non-clang compilers.
241 #if __is_identifier(__wchar_t)
242 typedef wchar_t __wchar_t;
243 #endif
244 #endif
245
246 __wchar_t WideCharacter;
247 ...
Aaron Ballmana4bb4b92014-01-09 23:11:13 +0000248
Sean Silva709c44d2012-12-12 23:44:55 +0000249Include File Checking Macros
250============================
251
252Not all developments systems have the same include files. The
253:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
254you to check for the existence of an include file before doing a possibly
Dmitri Gribenko764ea242013-01-17 17:04:54 +0000255failing ``#include`` directive. Include file checking macros must be used
256as expressions in ``#if`` or ``#elif`` preprocessing directives.
Sean Silva709c44d2012-12-12 23:44:55 +0000257
258.. _langext-__has_include:
259
260``__has_include``
261-----------------
262
263This function-like macro takes a single file name string argument that is the
264name of an include file. It evaluates to 1 if the file can be found using the
265include paths, or 0 otherwise:
266
267.. code-block:: c++
268
269 // Note the two possible file name string formats.
270 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
271 # include "myinclude.h"
272 #endif
273
Richard Smithccfc9ff2013-07-11 00:27:05 +0000274To test for this feature, use ``#if defined(__has_include)``:
275
276.. code-block:: c++
277
Sean Silva709c44d2012-12-12 23:44:55 +0000278 // To avoid problem with non-clang compilers not having this macro.
Richard Smithccfc9ff2013-07-11 00:27:05 +0000279 #if defined(__has_include)
280 #if __has_include("myinclude.h")
Sean Silva709c44d2012-12-12 23:44:55 +0000281 # include "myinclude.h"
282 #endif
Richard Smithccfc9ff2013-07-11 00:27:05 +0000283 #endif
Sean Silva709c44d2012-12-12 23:44:55 +0000284
285.. _langext-__has_include_next:
286
287``__has_include_next``
288----------------------
289
290This function-like macro takes a single file name string argument that is the
291name of an include file. It is like ``__has_include`` except that it looks for
292the second instance of the given file found in the include paths. It evaluates
293to 1 if the second instance of the file can be found using the include paths,
294or 0 otherwise:
295
296.. code-block:: c++
297
298 // Note the two possible file name string formats.
299 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
300 # include_next "myinclude.h"
301 #endif
302
303 // To avoid problem with non-clang compilers not having this macro.
Richard Smithccfc9ff2013-07-11 00:27:05 +0000304 #if defined(__has_include_next)
305 #if __has_include_next("myinclude.h")
Sean Silva709c44d2012-12-12 23:44:55 +0000306 # include_next "myinclude.h"
307 #endif
Richard Smithccfc9ff2013-07-11 00:27:05 +0000308 #endif
Sean Silva709c44d2012-12-12 23:44:55 +0000309
310Note that ``__has_include_next``, like the GNU extension ``#include_next``
311directive, is intended for use in headers only, and will issue a warning if
312used in the top-level compilation file. A warning will also be issued if an
313absolute path is used in the file argument.
314
315``__has_warning``
316-----------------
317
318This function-like macro takes a string literal that represents a command line
319option for a warning and returns true if that is a valid warning option.
320
321.. code-block:: c++
322
323 #if __has_warning("-Wformat")
324 ...
325 #endif
326
327Builtin Macros
328==============
329
330``__BASE_FILE__``
331 Defined to a string that contains the name of the main input file passed to
332 Clang.
Sylvestre Ledru0adbe772019-07-09 08:50:17 +0000333
Kristina Brooks56520632019-05-17 06:46:12 +0000334``__FILE_NAME__``
335 Clang-specific extension that functions similar to ``__FILE__`` but only
336 renders the last path component (the filename) instead of an invocation
Sylvestre Ledru0adbe772019-07-09 08:50:17 +0000337 dependent full path to that file.
Sean Silva709c44d2012-12-12 23:44:55 +0000338
339``__COUNTER__``
340 Defined to an integer value that starts at zero and is incremented each time
341 the ``__COUNTER__`` macro is expanded.
342
343``__INCLUDE_LEVEL__``
344 Defined to an integral value that is the include depth of the file currently
345 being translated. For the main file, this value is zero.
346
347``__TIMESTAMP__``
348 Defined to the date and time of the last modification of the current source
349 file.
350
351``__clang__``
352 Defined when compiling with Clang
353
354``__clang_major__``
355 Defined to the major marketing version number of Clang (e.g., the 2 in
356 2.0.1). Note that marketing version numbers should not be used to check for
357 language features, as different vendors use different numbering schemes.
358 Instead, use the :ref:`langext-feature_check`.
359
360``__clang_minor__``
361 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
362 that marketing version numbers should not be used to check for language
363 features, as different vendors use different numbering schemes. Instead, use
364 the :ref:`langext-feature_check`.
365
366``__clang_patchlevel__``
367 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
368
369``__clang_version__``
370 Defined to a string that captures the Clang marketing version, including the
371 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
372
373.. _langext-vectors:
374
375Vectors and Extended Vectors
376============================
377
378Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
379
380OpenCL vector types are created using ``ext_vector_type`` attribute. It
381support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
382is:
383
384.. code-block:: c++
385
386 typedef float float4 __attribute__((ext_vector_type(4)));
387 typedef float float2 __attribute__((ext_vector_type(2)));
388
389 float4 foo(float2 a, float2 b) {
390 float4 c;
391 c.xz = a;
392 c.yw = b;
393 return c;
394 }
395
396Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
397
Eric Christopher758aad72017-03-21 22:06:18 +0000398Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
Sean Silva709c44d2012-12-12 23:44:55 +0000399and functions. For example:
400
401.. code-block:: c++
402
403 vector float foo(vector int a) {
404 vector int b;
405 b = vec_add(a, a) + a;
406 return (vector float)b;
407 }
408
409NEON vector types are created using ``neon_vector_type`` and
410``neon_polyvector_type`` attributes. For example:
411
412.. code-block:: c++
413
414 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
415 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
416
417 int8x8_t foo(int8x8_t a) {
418 int8x8_t v;
419 v = a;
420 return v;
421 }
422
423Vector Literals
424---------------
425
426Vector literals can be used to create vectors from a set of scalars, or
427vectors. Either parentheses or braces form can be used. In the parentheses
428form the number of literal values specified must be one, i.e. referring to a
429scalar value, or must match the size of the vector type being created. If a
430single scalar literal value is specified, the scalar literal value will be
431replicated to all the components of the vector type. In the brackets form any
432number of literals can be specified. For example:
433
434.. code-block:: c++
435
436 typedef int v4si __attribute__((__vector_size__(16)));
437 typedef float float4 __attribute__((ext_vector_type(4)));
438 typedef float float2 __attribute__((ext_vector_type(2)));
439
440 v4si vsi = (v4si){1, 2, 3, 4};
441 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
442 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
443 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
444 vector int vi3 = (vector int)(1, 2); // error
445 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
446 vector int vi5 = (vector int)(1, 2, 3, 4);
447 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
448
449Vector Operations
450-----------------
451
452The table below shows the support for each operation by vector extension. A
453dash indicates that an operation is not accepted according to a corresponding
454specification.
455
Anton Yartsev94e46f32014-09-03 17:59:21 +0000456============================== ======= ======= ======= =======
Nick Lewycky00a5d212015-08-10 19:54:11 +0000457 Operator OpenCL AltiVec GCC NEON
Anton Yartsev94e46f32014-09-03 17:59:21 +0000458============================== ======= ======= ======= =======
459[] yes yes yes --
460unary operators +, -- yes yes yes --
461++, -- -- yes yes yes --
462+,--,*,/,% yes yes yes --
463bitwise operators &,|,^,~ yes yes yes --
464>>,<< yes yes yes --
465!, &&, || yes -- -- --
466==, !=, >, <, >=, <= yes yes -- --
467= yes yes yes yes
468:? yes -- -- --
469sizeof yes yes yes yes
470C-style cast yes yes yes no
471reinterpret_cast yes no yes no
472static_cast yes no yes no
473const_cast no no no no
474============================== ======= ======= ======= =======
Sean Silva709c44d2012-12-12 23:44:55 +0000475
Anton Yartsev94e46f32014-09-03 17:59:21 +0000476See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
Sean Silva709c44d2012-12-12 23:44:55 +0000477
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000478Half-Precision Floating Point
479=============================
480
481Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
Erich Keane1d1d4382019-01-25 17:27:57 +0000482``_Float16``. These types are supported in all language modes.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000483
Erich Keane1d1d4382019-01-25 17:27:57 +0000484``__fp16`` is supported on every target, as it is purely a storage format; see below.
485``_Float16`` is currently only supported on the following targets, with further
486targets pending ABI standardization:
487- 32-bit ARM
488- 64-bit ARM (AArch64)
489- SPIR
490``_Float16`` will be supported on more targets as they define ABIs for it.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000491
Erich Keane1d1d4382019-01-25 17:27:57 +0000492``__fp16`` is a storage and interchange format only. This means that values of
493``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic
494operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``.
495The behavior of ``__fp16`` is specified by the ARM C Language Extensions (`ACLE <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053d/IHI0053D_acle_2_1.pdf>`_).
496Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
497alternative format.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000498
Erich Keane1d1d4382019-01-25 17:27:57 +0000499``_Float16`` is an extended floating-point type. This means that, just like arithmetic on
500``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the
501``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
502``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
503("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16``
504format from IEEE 754-2008 for ``_Float16``.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000505
Erich Keane1d1d4382019-01-25 17:27:57 +0000506``_Float16`` arithmetic will be performed using native half-precision support
507when available on the target (e.g. on ARMv8.2a); otherwise it will be performed
508at a higher precision (currently always ``float``) and then truncated down to
509``_Float16``. Note that C and C++ allow intermediate floating-point operands
510of an expression to be computed with greater precision than is expressible in
511their type, so Clang may avoid intermediate truncations in certain cases; this may
512lead to results that are inconsistent with native arithmetic.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000513
Erich Keane1d1d4382019-01-25 17:27:57 +0000514It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
515as it has been defined by the C standards committee and has behavior that is
516more familiar to most programmers.
517
518Because ``__fp16`` operands are always immediately promoted to ``float``, the
519common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
520arithmetic conversions is ``float``.
521
522A literal can be given ``_Float16`` type using the suffix ``f16``; for example:
523```
Erich Keane599c0bc2019-01-25 17:39:57 +00005243.14f16
525```
Erich Keane1d1d4382019-01-25 17:27:57 +0000526
527Because default argument promotion only applies to the standard floating-point
528types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
529or untyped arguments. As a consequence, some caution must be taken when using
530certain library facilities with ``_Float16``; for example, there is no ``printf`` format
531specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
532``double`` when passed to ``printf``, so the programmer must explicitly cast it to
533``double`` before using it with an ``%f`` or similar specifier.
Sjoerd Meijer167f2e32017-11-07 10:09:45 +0000534
Sean Silva709c44d2012-12-12 23:44:55 +0000535Messages on ``deprecated`` and ``unavailable`` Attributes
536=========================================================
537
538An optional string message can be added to the ``deprecated`` and
539``unavailable`` attributes. For example:
540
541.. code-block:: c++
542
543 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
544
545If the deprecated or unavailable declaration is used, the message will be
546incorporated into the appropriate diagnostic:
547
George Burgess IV61e43272016-06-21 00:16:23 +0000548.. code-block:: none
Sean Silva709c44d2012-12-12 23:44:55 +0000549
550 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
551 [-Wdeprecated-declarations]
552 explode();
553 ^
554
555Query for this feature with
556``__has_extension(attribute_deprecated_with_message)`` and
557``__has_extension(attribute_unavailable_with_message)``.
558
559Attributes on Enumerators
560=========================
561
562Clang allows attributes to be written on individual enumerators. This allows
563enumerators to be deprecated, made unavailable, etc. The attribute must appear
564after the enumerator name and before any initializer, like so:
565
566.. code-block:: c++
567
568 enum OperationMode {
569 OM_Invalid,
570 OM_Normal,
571 OM_Terrified __attribute__((deprecated)),
572 OM_AbortOnError __attribute__((deprecated)) = 4
573 };
574
575Attributes on the ``enum`` declaration do not apply to individual enumerators.
576
577Query for this feature with ``__has_extension(enumerator_attributes)``.
578
579'User-Specified' System Frameworks
580==================================
581
582Clang provides a mechanism by which frameworks can be built in such a way that
583they will always be treated as being "system frameworks", even if they are not
584present in a system framework directory. This can be useful to system
585framework developers who want to be able to test building other applications
586with development builds of their framework, including the manner in which the
587compiler changes warning behavior for system headers.
588
589Framework developers can opt-in to this mechanism by creating a
590"``.system_framework``" file at the top-level of their framework. That is, the
591framework should have contents like:
592
593.. code-block:: none
594
595 .../TestFramework.framework
596 .../TestFramework.framework/.system_framework
597 .../TestFramework.framework/Headers
598 .../TestFramework.framework/Headers/TestFramework.h
599 ...
600
601Clang will treat the presence of this file as an indicator that the framework
602should be treated as a system framework, regardless of how it was found in the
603framework search path. For consistency, we recommend that such files never be
604included in installed versions of the framework.
605
Sean Silva709c44d2012-12-12 23:44:55 +0000606Checks for Standard Language Features
607=====================================
608
609The ``__has_feature`` macro can be used to query if certain standard language
610features are enabled. The ``__has_extension`` macro can be used to query if
611language features are available as an extension when compiling for a standard
612which does not provide them. The features which can be tested are listed here.
613
Richard Smith38af8562014-11-12 21:16:38 +0000614Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
615These are macros with names of the form ``__cpp_<feature_name>``, and are
616intended to be a portable way to query the supported features of the compiler.
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +0000617See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
Richard Smith38af8562014-11-12 21:16:38 +0000618information on the version of SD-6 supported by each Clang release, and the
619macros provided by that revision of the recommendations.
620
Sean Silva709c44d2012-12-12 23:44:55 +0000621C++98
622-----
623
624The features listed below are part of the C++98 standard. These features are
625enabled by default when compiling C++ code.
626
627C++ exceptions
628^^^^^^^^^^^^^^
629
630Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
631enabled. For example, compiling code with ``-fno-exceptions`` disables C++
632exceptions.
633
634C++ RTTI
635^^^^^^^^
636
637Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
638example, compiling code with ``-fno-rtti`` disables the use of RTTI.
639
640C++11
641-----
642
643The features listed below are part of the C++11 standard. As a result, all
644these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
645when compiling C++ code.
646
647C++11 SFINAE includes access control
648^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
649
650Use ``__has_feature(cxx_access_control_sfinae)`` or
651``__has_extension(cxx_access_control_sfinae)`` to determine whether
652access-control errors (e.g., calling a private constructor) are considered to
653be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
654<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
655
656C++11 alias templates
657^^^^^^^^^^^^^^^^^^^^^
658
659Use ``__has_feature(cxx_alias_templates)`` or
660``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
661alias declarations and alias templates is enabled.
662
663C++11 alignment specifiers
664^^^^^^^^^^^^^^^^^^^^^^^^^^
665
666Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
667determine if support for alignment specifiers using ``alignas`` is enabled.
668
Nico Weber736a9932014-12-03 01:25:49 +0000669Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
670determine if support for the ``alignof`` keyword is enabled.
671
Sean Silva709c44d2012-12-12 23:44:55 +0000672C++11 attributes
673^^^^^^^^^^^^^^^^
674
675Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
676determine if support for attribute parsing with C++11's square bracket notation
677is enabled.
678
679C++11 generalized constant expressions
680^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
681
682Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
683constant expressions (e.g., ``constexpr``) is enabled.
684
685C++11 ``decltype()``
686^^^^^^^^^^^^^^^^^^^^
687
688Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
689determine if support for the ``decltype()`` specifier is enabled. C++11's
690``decltype`` does not require type-completeness of a function call expression.
691Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
692``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
693support for this feature is enabled.
694
695C++11 default template arguments in function templates
696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
697
698Use ``__has_feature(cxx_default_function_template_args)`` or
699``__has_extension(cxx_default_function_template_args)`` to determine if support
700for default template arguments in function templates is enabled.
701
702C++11 ``default``\ ed functions
703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
704
705Use ``__has_feature(cxx_defaulted_functions)`` or
706``__has_extension(cxx_defaulted_functions)`` to determine if support for
707defaulted function definitions (with ``= default``) is enabled.
708
709C++11 delegating constructors
710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
711
712Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
713delegating constructors is enabled.
714
715C++11 ``deleted`` functions
716^^^^^^^^^^^^^^^^^^^^^^^^^^^
717
718Use ``__has_feature(cxx_deleted_functions)`` or
719``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
720function definitions (with ``= delete``) is enabled.
721
722C++11 explicit conversion functions
723^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
724
725Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
726``explicit`` conversion functions is enabled.
727
728C++11 generalized initializers
729^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
730
731Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
732generalized initializers (using braced lists and ``std::initializer_list``) is
733enabled.
734
735C++11 implicit move constructors/assignment operators
736^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
737
738Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
739generate move constructors and move assignment operators where needed.
740
741C++11 inheriting constructors
742^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
743
744Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
Richard Smith25b555a2013-04-19 17:00:31 +0000745inheriting constructors is enabled.
Sean Silva709c44d2012-12-12 23:44:55 +0000746
747C++11 inline namespaces
748^^^^^^^^^^^^^^^^^^^^^^^
749
750Use ``__has_feature(cxx_inline_namespaces)`` or
751``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
752namespaces is enabled.
753
754C++11 lambdas
755^^^^^^^^^^^^^
756
757Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
758determine if support for lambdas is enabled.
759
760C++11 local and unnamed types as template arguments
761^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
762
763Use ``__has_feature(cxx_local_type_template_args)`` or
764``__has_extension(cxx_local_type_template_args)`` to determine if support for
765local and unnamed types as template arguments is enabled.
766
767C++11 noexcept
768^^^^^^^^^^^^^^
769
770Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
771determine if support for noexcept exception specifications is enabled.
772
773C++11 in-class non-static data member initialization
774^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
775
776Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
777initialization of non-static data members is enabled.
778
779C++11 ``nullptr``
780^^^^^^^^^^^^^^^^^
781
782Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
783determine if support for ``nullptr`` is enabled.
784
785C++11 ``override control``
786^^^^^^^^^^^^^^^^^^^^^^^^^^
787
788Use ``__has_feature(cxx_override_control)`` or
789``__has_extension(cxx_override_control)`` to determine if support for the
790override control keywords is enabled.
791
792C++11 reference-qualified functions
793^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
794
795Use ``__has_feature(cxx_reference_qualified_functions)`` or
796``__has_extension(cxx_reference_qualified_functions)`` to determine if support
797for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
798applied to ``*this``) is enabled.
799
800C++11 range-based ``for`` loop
801^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
802
803Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
804determine if support for the range-based for loop is enabled.
805
806C++11 raw string literals
807^^^^^^^^^^^^^^^^^^^^^^^^^
808
809Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
810string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
811
812C++11 rvalue references
813^^^^^^^^^^^^^^^^^^^^^^^
814
815Use ``__has_feature(cxx_rvalue_references)`` or
816``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
817references is enabled.
818
819C++11 ``static_assert()``
820^^^^^^^^^^^^^^^^^^^^^^^^^
821
822Use ``__has_feature(cxx_static_assert)`` or
823``__has_extension(cxx_static_assert)`` to determine if support for compile-time
824assertions using ``static_assert`` is enabled.
825
Richard Smith25b555a2013-04-19 17:00:31 +0000826C++11 ``thread_local``
827^^^^^^^^^^^^^^^^^^^^^^
828
829Use ``__has_feature(cxx_thread_local)`` to determine if support for
830``thread_local`` variables is enabled.
831
Sean Silva709c44d2012-12-12 23:44:55 +0000832C++11 type inference
833^^^^^^^^^^^^^^^^^^^^
834
835Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
836determine C++11 type inference is supported using the ``auto`` specifier. If
837this is disabled, ``auto`` will instead be a storage class specifier, as in C
838or C++98.
839
840C++11 strongly typed enumerations
841^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
842
843Use ``__has_feature(cxx_strong_enums)`` or
844``__has_extension(cxx_strong_enums)`` to determine if support for strongly
845typed, scoped enumerations is enabled.
846
847C++11 trailing return type
848^^^^^^^^^^^^^^^^^^^^^^^^^^
849
850Use ``__has_feature(cxx_trailing_return)`` or
851``__has_extension(cxx_trailing_return)`` to determine if support for the
852alternate function declaration syntax with trailing return type is enabled.
853
854C++11 Unicode string literals
855^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
856
857Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
858string literals is enabled.
859
860C++11 unrestricted unions
861^^^^^^^^^^^^^^^^^^^^^^^^^
862
863Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
864unrestricted unions is enabled.
865
866C++11 user-defined literals
867^^^^^^^^^^^^^^^^^^^^^^^^^^^
868
869Use ``__has_feature(cxx_user_literals)`` to determine if support for
870user-defined literals is enabled.
871
872C++11 variadic templates
873^^^^^^^^^^^^^^^^^^^^^^^^
874
875Use ``__has_feature(cxx_variadic_templates)`` or
876``__has_extension(cxx_variadic_templates)`` to determine if support for
877variadic templates is enabled.
878
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000879C++14
Richard Smith0a715422013-05-07 19:32:56 +0000880-----
881
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000882The features listed below are part of the C++14 standard. As a result, all
883these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
884when compiling C++ code.
Richard Smith0a715422013-05-07 19:32:56 +0000885
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000886C++14 binary literals
Richard Smith0a715422013-05-07 19:32:56 +0000887^^^^^^^^^^^^^^^^^^^^^
888
889Use ``__has_feature(cxx_binary_literals)`` or
890``__has_extension(cxx_binary_literals)`` to determine whether
891binary literals (for instance, ``0b10010``) are recognized. Clang supports this
892feature as an extension in all language modes.
893
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000894C++14 contextual conversions
Richard Smith0a715422013-05-07 19:32:56 +0000895^^^^^^^^^^^^^^^^^^^^^^^^^^^^
896
897Use ``__has_feature(cxx_contextual_conversions)`` or
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000898``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
Richard Smith0a715422013-05-07 19:32:56 +0000899are used when performing an implicit conversion for an array bound in a
900*new-expression*, the operand of a *delete-expression*, an integral constant
Richard Smithc0f7b812013-07-24 17:41:31 +0000901expression, or a condition in a ``switch`` statement.
Richard Smith0a715422013-05-07 19:32:56 +0000902
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000903C++14 decltype(auto)
Richard Smith0a715422013-05-07 19:32:56 +0000904^^^^^^^^^^^^^^^^^^^^
905
906Use ``__has_feature(cxx_decltype_auto)`` or
907``__has_extension(cxx_decltype_auto)`` to determine if support
908for the ``decltype(auto)`` placeholder type is enabled.
909
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000910C++14 default initializers for aggregates
Richard Smith0a715422013-05-07 19:32:56 +0000911^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
912
913Use ``__has_feature(cxx_aggregate_nsdmi)`` or
914``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
915for default initializers in aggregate members is enabled.
916
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000917C++14 digit separators
Richard Smith38af8562014-11-12 21:16:38 +0000918^^^^^^^^^^^^^^^^^^^^^^
919
920Use ``__cpp_digit_separators`` to determine if support for digit separators
921using single quotes (for instance, ``10'000``) is enabled. At this time, there
922is no corresponding ``__has_feature`` name
923
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000924C++14 generalized lambda capture
Richard Smith0a715422013-05-07 19:32:56 +0000925^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
926
Richard Smith6d540142014-05-09 21:08:59 +0000927Use ``__has_feature(cxx_init_captures)`` or
928``__has_extension(cxx_init_captures)`` to determine if support for
Richard Smith4fb09722013-07-24 17:51:13 +0000929lambda captures with explicit initializers is enabled
Richard Smith0a715422013-05-07 19:32:56 +0000930(for instance, ``[n(0)] { return ++n; }``).
Richard Smith0a715422013-05-07 19:32:56 +0000931
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000932C++14 generic lambdas
Richard Smith0a715422013-05-07 19:32:56 +0000933^^^^^^^^^^^^^^^^^^^^^
934
Richard Smith6d540142014-05-09 21:08:59 +0000935Use ``__has_feature(cxx_generic_lambdas)`` or
936``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
Richard Smith0a715422013-05-07 19:32:56 +0000937(polymorphic) lambdas is enabled
938(for instance, ``[] (auto x) { return x + 1; }``).
Richard Smith0a715422013-05-07 19:32:56 +0000939
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000940C++14 relaxed constexpr
Richard Smith0a715422013-05-07 19:32:56 +0000941^^^^^^^^^^^^^^^^^^^^^^^
942
943Use ``__has_feature(cxx_relaxed_constexpr)`` or
944``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
945declarations, local variable modification, and control flow constructs
946are permitted in ``constexpr`` functions.
Richard Smith0a715422013-05-07 19:32:56 +0000947
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000948C++14 return type deduction
Richard Smith0a715422013-05-07 19:32:56 +0000949^^^^^^^^^^^^^^^^^^^^^^^^^^^
950
951Use ``__has_feature(cxx_return_type_deduction)`` or
952``__has_extension(cxx_return_type_deduction)`` to determine if support
953for return type deduction for functions (using ``auto`` as a return type)
954is enabled.
Richard Smith0a715422013-05-07 19:32:56 +0000955
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000956C++14 runtime-sized arrays
Richard Smith0a715422013-05-07 19:32:56 +0000957^^^^^^^^^^^^^^^^^^^^^^^^^^
958
959Use ``__has_feature(cxx_runtime_array)`` or
960``__has_extension(cxx_runtime_array)`` to determine if support
961for arrays of runtime bound (a restricted form of variable-length arrays)
962is enabled.
963Clang's implementation of this feature is incomplete.
964
Eric Fiselierd3ff21c2017-05-06 23:26:04 +0000965C++14 variable templates
Richard Smith0a715422013-05-07 19:32:56 +0000966^^^^^^^^^^^^^^^^^^^^^^^^
967
968Use ``__has_feature(cxx_variable_templates)`` or
969``__has_extension(cxx_variable_templates)`` to determine if support for
970templated variable declarations is enabled.
Richard Smith0a715422013-05-07 19:32:56 +0000971
Sean Silva709c44d2012-12-12 23:44:55 +0000972C11
973---
974
975The features listed below are part of the C11 standard. As a result, all these
976features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
977compiling C code. Additionally, because these features are all
978backward-compatible, they are available as extensions in all language modes.
979
980C11 alignment specifiers
981^^^^^^^^^^^^^^^^^^^^^^^^
982
983Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
984if support for alignment specifiers using ``_Alignas`` is enabled.
985
Nico Weber736a9932014-12-03 01:25:49 +0000986Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
987if support for the ``_Alignof`` keyword is enabled.
988
Sean Silva709c44d2012-12-12 23:44:55 +0000989C11 atomic operations
990^^^^^^^^^^^^^^^^^^^^^
991
992Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
993if support for atomic types using ``_Atomic`` is enabled. Clang also provides
994:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
Hal Finkel6970ac82014-10-03 04:29:40 +0000995the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
996``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
997is available.
998
999Clang will use the system's ``<stdatomic.h>`` header when one is available, and
1000will otherwise use its own. When using its own, implementations of the atomic
1001operations are provided as macros. In the cases where C11 also requires a real
1002function, this header provides only the declaration of that function (along
1003with a shadowing macro implementation), and you must link to a library which
1004provides a definition of the function if you use it instead of the macro.
Sean Silva709c44d2012-12-12 23:44:55 +00001005
1006C11 generic selections
1007^^^^^^^^^^^^^^^^^^^^^^
1008
1009Use ``__has_feature(c_generic_selections)`` or
1010``__has_extension(c_generic_selections)`` to determine if support for generic
1011selections is enabled.
1012
1013As an extension, the C11 generic selection expression is available in all
1014languages supported by Clang. The syntax is the same as that given in the C11
1015standard.
1016
1017In C, type compatibility is decided according to the rules given in the
1018appropriate standard, but in C++, which lacks the type compatibility rules used
1019in C, types are considered compatible only if they are equivalent.
1020
1021C11 ``_Static_assert()``
1022^^^^^^^^^^^^^^^^^^^^^^^^
1023
1024Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
1025to determine if support for compile-time assertions using ``_Static_assert`` is
1026enabled.
1027
Richard Smith25b555a2013-04-19 17:00:31 +00001028C11 ``_Thread_local``
1029^^^^^^^^^^^^^^^^^^^^^
1030
Ed Schouten401aeba2013-09-14 16:17:20 +00001031Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
1032to determine if support for ``_Thread_local`` variables is enabled.
Richard Smith25b555a2013-04-19 17:00:31 +00001033
Ben Langmuir921f2e62015-03-10 14:39:26 +00001034Modules
1035-------
1036
1037Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1038For example, compiling code with ``-fmodules`` enables the use of Modules.
1039
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001040More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
Ben Langmuir921f2e62015-03-10 14:39:26 +00001041
Alp Toker64197b92014-01-18 21:49:02 +00001042Checks for Type Trait Primitives
1043================================
1044
1045Type trait primitives are special builtin constant expressions that can be used
1046by the standard C++ library to facilitate or simplify the implementation of
1047user-facing type traits in the <type_traits> header.
1048
1049They are not intended to be used directly by user code because they are
1050implementation-defined and subject to change -- as such they're tied closely to
1051the supported set of system headers, currently:
1052
1053* LLVM's own libc++
1054* GNU libstdc++
1055* The Microsoft standard C++ library
Sean Silva709c44d2012-12-12 23:44:55 +00001056
1057Clang supports the `GNU C++ type traits
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001058<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
Sean Silva709c44d2012-12-12 23:44:55 +00001059`Microsoft Visual C++ Type traits
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001060<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_.
Alp Toker64197b92014-01-18 21:49:02 +00001061
1062Feature detection is supported only for some of the primitives at present. User
1063code should not use these checks because they bear no direct relation to the
1064actual set of type traits supported by the C++ standard library.
1065
1066For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the
1067type trait primitive in the compiler. A simplistic usage example as might be
1068seen in standard C++ headers follows:
Sean Silva709c44d2012-12-12 23:44:55 +00001069
1070.. code-block:: c++
1071
1072 #if __has_extension(is_convertible_to)
1073 template<typename From, typename To>
1074 struct is_convertible_to {
1075 static const bool value = __is_convertible_to(From, To);
1076 };
1077 #else
Alp Toker64197b92014-01-18 21:49:02 +00001078 // Emulate type trait for compatibility with other compilers.
Sean Silva709c44d2012-12-12 23:44:55 +00001079 #endif
1080
Alp Toker64197b92014-01-18 21:49:02 +00001081The following type trait primitives are supported by Clang:
Sean Silva709c44d2012-12-12 23:44:55 +00001082
1083* ``__has_nothrow_assign`` (GNU, Microsoft)
1084* ``__has_nothrow_copy`` (GNU, Microsoft)
1085* ``__has_nothrow_constructor`` (GNU, Microsoft)
1086* ``__has_trivial_assign`` (GNU, Microsoft)
1087* ``__has_trivial_copy`` (GNU, Microsoft)
1088* ``__has_trivial_constructor`` (GNU, Microsoft)
1089* ``__has_trivial_destructor`` (GNU, Microsoft)
1090* ``__has_virtual_destructor`` (GNU, Microsoft)
1091* ``__is_abstract`` (GNU, Microsoft)
Eric Fiselier07360662017-04-12 22:12:15 +00001092* ``__is_aggregate`` (GNU, Microsoft)
Sean Silva709c44d2012-12-12 23:44:55 +00001093* ``__is_base_of`` (GNU, Microsoft)
1094* ``__is_class`` (GNU, Microsoft)
1095* ``__is_convertible_to`` (Microsoft)
1096* ``__is_empty`` (GNU, Microsoft)
1097* ``__is_enum`` (GNU, Microsoft)
1098* ``__is_interface_class`` (Microsoft)
1099* ``__is_pod`` (GNU, Microsoft)
1100* ``__is_polymorphic`` (GNU, Microsoft)
1101* ``__is_union`` (GNU, Microsoft)
1102* ``__is_literal(type)``: Determines whether the given type is a literal type
1103* ``__is_final``: Determines whether the given type is declared with a
1104 ``final`` class-virt-specifier.
1105* ``__underlying_type(type)``: Retrieves the underlying type for a given
1106 ``enum`` type. This trait is required to implement the C++11 standard
1107 library.
1108* ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
1109 of type ``totype`` can be assigned to from a value of type ``fromtype`` such
1110 that no non-trivial functions are called as part of that assignment. This
1111 trait is required to implement the C++11 standard library.
1112* ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
1113 value of type ``type`` can be direct-initialized with arguments of types
1114 ``argtypes...`` such that no non-trivial functions are called as part of
1115 that initialization. This trait is required to implement the C++11 standard
1116 library.
David Majnemer55cf2522015-11-14 07:21:35 +00001117* ``__is_destructible`` (MSVC 2013)
1118* ``__is_nothrow_destructible`` (MSVC 2013)
Alp Toker73287bf2014-01-20 00:24:09 +00001119* ``__is_nothrow_assignable`` (MSVC 2013, clang)
1120* ``__is_constructible`` (MSVC 2013, clang)
1121* ``__is_nothrow_constructible`` (MSVC 2013, clang)
David Majnemerb3d96882016-05-23 17:21:55 +00001122* ``__is_assignable`` (MSVC 2015, clang)
Eric Fiselier1af6c112018-01-12 00:09:37 +00001123* ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a
1124 reference of type ``T`` bound to an expression of type ``U`` would bind to a
1125 materialized temporary object. If ``T`` is not a reference type the result
1126 is false. Note this trait will also return false when the initialization of
1127 ``T`` from ``U`` is ill-formed.
Sean Silva709c44d2012-12-12 23:44:55 +00001128
1129Blocks
1130======
1131
1132The syntax and high level language feature description is in
Michael Gottesman6fd58462013-01-07 22:24:45 +00001133:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1134the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
Sean Silva709c44d2012-12-12 23:44:55 +00001135
1136Query for this feature with ``__has_extension(blocks)``.
1137
1138Objective-C Features
1139====================
1140
1141Related result types
1142--------------------
1143
1144According to Cocoa conventions, Objective-C methods with certain names
1145("``init``", "``alloc``", etc.) always return objects that are an instance of
1146the receiving class's type. Such methods are said to have a "related result
1147type", meaning that a message send to one of these methods will have the same
1148static type as an instance of the receiver class. For example, given the
1149following classes:
1150
1151.. code-block:: objc
1152
1153 @interface NSObject
1154 + (id)alloc;
1155 - (id)init;
1156 @end
1157
1158 @interface NSArray : NSObject
1159 @end
1160
1161and this common initialization pattern
1162
1163.. code-block:: objc
1164
1165 NSArray *array = [[NSArray alloc] init];
1166
1167the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1168``alloc`` implicitly has a related result type. Similarly, the type of the
1169expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1170related result type and its receiver is known to have the type ``NSArray *``.
1171If neither ``alloc`` nor ``init`` had a related result type, the expressions
1172would have had type ``id``, as declared in the method signature.
1173
1174A method with a related result type can be declared by using the type
1175``instancetype`` as its result type. ``instancetype`` is a contextual keyword
1176that is only permitted in the result type of an Objective-C method, e.g.
1177
1178.. code-block:: objc
1179
1180 @interface A
1181 + (instancetype)constructAnA;
1182 @end
1183
1184The related result type can also be inferred for some methods. To determine
1185whether a method has an inferred related result type, the first word in the
1186camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1187and the method will have a related result type if its return type is compatible
1188with the type of its class and if:
1189
1190* the first word is "``alloc``" or "``new``", and the method is a class method,
1191 or
1192
1193* the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1194 and the method is an instance method.
1195
1196If a method with a related result type is overridden by a subclass method, the
1197subclass method must also return a type that is compatible with the subclass
1198type. For example:
1199
1200.. code-block:: objc
1201
1202 @interface NSString : NSObject
1203 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1204 @end
1205
1206Related result types only affect the type of a message send or property access
1207via the given method. In all other respects, a method with a related result
1208type is treated the same way as method that returns ``id``.
1209
1210Use ``__has_feature(objc_instancetype)`` to determine whether the
1211``instancetype`` contextual keyword is available.
1212
1213Automatic reference counting
1214----------------------------
1215
Sean Silva173d2522013-01-02 13:07:47 +00001216Clang provides support for :doc:`automated reference counting
1217<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
Akira Hatanaka7275da02018-02-28 07:15:55 +00001218for manual ``retain``/``release``/``autorelease`` message sends. There are three
Sean Silva709c44d2012-12-12 23:44:55 +00001219feature macros associated with automatic reference counting:
1220``__has_feature(objc_arc)`` indicates the availability of automated reference
1221counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1222automated reference counting also includes support for ``__weak`` pointers to
Akira Hatanaka7275da02018-02-28 07:15:55 +00001223Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
1224are allowed to have fields that are pointers to Objective-C objects managed by
1225automatic reference counting.
Sean Silva709c44d2012-12-12 23:44:55 +00001226
John McCallea9c5802018-07-20 05:40:12 +00001227.. _objc-weak:
1228
1229Weak references
1230---------------
1231
1232Clang supports ARC-style weak and unsafe references in Objective-C even
1233outside of ARC mode. Weak references must be explicitly enabled with
1234the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
1235to test whether they are enabled. Unsafe references are enabled
1236unconditionally. ARC-style weak and unsafe references cannot be used
1237when Objective-C garbage collection is enabled.
1238
1239Except as noted below, the language rules for the ``__weak`` and
1240``__unsafe_unretained`` qualifiers (and the ``weak`` and
1241``unsafe_unretained`` property attributes) are just as laid out
1242in the :doc:`ARC specification <AutomaticReferenceCounting>`.
1243In particular, note that some classes do not support forming weak
1244references to their instances, and note that special care must be
1245taken when storing weak references in memory where initialization
1246and deinitialization are outside the responsibility of the compiler
1247(such as in ``malloc``-ed memory).
1248
1249Loading from a ``__weak`` variable always implicitly retains the
1250loaded value. In non-ARC modes, this retain is normally balanced
1251by an implicit autorelease. This autorelease can be suppressed
1252by performing the load in the receiver position of a ``-retain``
1253message send (e.g. ``[weakReference retain]``); note that this performs
1254only a single retain (the retain done when primitively loading from
1255the weak reference).
1256
1257For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
1258default behavior of variables and therefore is not needed. However,
1259it does have an effect on the semantics of block captures: normally,
1260copying a block which captures an Objective-C object or block pointer
1261causes the captured pointer to be retained or copied, respectively,
1262but that behavior is suppressed when the captured variable is qualified
1263with ``__unsafe_unretained``.
1264
1265Note that the ``__weak`` qualifier formerly meant the GC qualifier in
1266all non-ARC modes and was silently ignored outside of GC modes. It now
1267means the ARC-style qualifier in all non-GC modes and is no longer
1268allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
1269It is expected that ``-fobjc-weak`` will eventually be enabled by default
1270in all non-GC Objective-C modes.
1271
Sean Silva173d2522013-01-02 13:07:47 +00001272.. _objc-fixed-enum:
1273
Sean Silva709c44d2012-12-12 23:44:55 +00001274Enumerations with a fixed underlying type
1275-----------------------------------------
1276
1277Clang provides support for C++11 enumerations with a fixed underlying type
1278within Objective-C. For example, one can write an enumeration type as:
1279
1280.. code-block:: c++
1281
1282 typedef enum : unsigned char { Red, Green, Blue } Color;
1283
1284This specifies that the underlying type, which is used to store the enumeration
1285value, is ``unsigned char``.
1286
1287Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1288underlying types is available in Objective-C.
1289
1290Interoperability with C++11 lambdas
1291-----------------------------------
1292
1293Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1294permitting a lambda to be implicitly converted to a block pointer with the
1295corresponding signature. For example, consider an API such as ``NSArray``'s
1296array-sorting method:
1297
1298.. code-block:: objc
1299
1300 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1301
1302``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1303(^)(id, id)``, and parameters of this type are generally provided with block
1304literals as arguments. However, one can also use a C++11 lambda so long as it
1305provides the same signature (in this case, accepting two parameters of type
1306``id`` and returning an ``NSComparisonResult``):
1307
1308.. code-block:: objc
1309
1310 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1311 @"String 02"];
1312 const NSStringCompareOptions comparisonOptions
1313 = NSCaseInsensitiveSearch | NSNumericSearch |
1314 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1315 NSLocale *currentLocale = [NSLocale currentLocale];
1316 NSArray *sorted
1317 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1318 NSRange string1Range = NSMakeRange(0, [s1 length]);
1319 return [s1 compare:s2 options:comparisonOptions
1320 range:string1Range locale:currentLocale];
1321 }];
1322 NSLog(@"sorted: %@", sorted);
1323
1324This code relies on an implicit conversion from the type of the lambda
1325expression (an unnamed, local class type called the *closure type*) to the
1326corresponding block pointer type. The conversion itself is expressed by a
1327conversion operator in that closure type that produces a block pointer with the
1328same signature as the lambda itself, e.g.,
1329
1330.. code-block:: objc
1331
1332 operator NSComparisonResult (^)(id, id)() const;
1333
1334This conversion function returns a new block that simply forwards the two
1335parameters to the lambda object (which it captures by copy), then returns the
1336result. The returned block is first copied (with ``Block_copy``) and then
1337autoreleased. As an optimization, if a lambda expression is immediately
1338converted to a block pointer (as in the first example, above), then the block
1339is not copied and autoreleased: rather, it is given the same lifetime as a
1340block literal written at that point in the program, which avoids the overhead
1341of copying a block to the heap in the common case.
1342
1343The conversion from a lambda to a block pointer is only available in
1344Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1345management (autorelease).
1346
1347Object Literals and Subscripting
1348--------------------------------
1349
Sean Silva173d2522013-01-02 13:07:47 +00001350Clang provides support for :doc:`Object Literals and Subscripting
1351<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
Sean Silva709c44d2012-12-12 23:44:55 +00001352programming patterns, makes programs more concise, and improves the safety of
1353container creation. There are several feature macros associated with object
1354literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
1355availability of array literals; ``__has_feature(objc_dictionary_literals)``
1356tests the availability of dictionary literals;
1357``__has_feature(objc_subscripting)`` tests the availability of object
1358subscripting.
1359
1360Objective-C Autosynthesis of Properties
1361---------------------------------------
1362
1363Clang provides support for autosynthesis of declared properties. Using this
1364feature, clang provides default synthesis of those properties not declared
1365@dynamic and not having user provided backing getter and setter methods.
1366``__has_feature(objc_default_synthesize_properties)`` checks for availability
1367of this feature in version of clang being used.
1368
Jordan Rose32e94892012-12-15 00:37:01 +00001369.. _langext-objc-retain-release:
1370
1371Objective-C retaining behavior attributes
1372-----------------------------------------
1373
1374In Objective-C, functions and methods are generally assumed to follow the
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00001375`Cocoa Memory Management
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001376<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
Jordan Rose32e94892012-12-15 00:37:01 +00001377conventions for ownership of object arguments and
1378return values. However, there are exceptions, and so Clang provides attributes
1379to allow these exceptions to be documented. This are used by ARC and the
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001380`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
Aaron Ballman840cef32014-02-19 15:45:13 +00001381better described using the ``objc_method_family`` attribute instead.
Jordan Rose32e94892012-12-15 00:37:01 +00001382
1383**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
1384``ns_returns_autoreleased``, ``cf_returns_retained``, and
1385``cf_returns_not_retained`` attributes can be placed on methods and functions
1386that return Objective-C or CoreFoundation objects. They are commonly placed at
1387the end of a function prototype or method declaration:
1388
1389.. code-block:: objc
1390
1391 id foo() __attribute__((ns_returns_retained));
1392
1393 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
1394
1395The ``*_returns_retained`` attributes specify that the returned object has a +1
1396retain count. The ``*_returns_not_retained`` attributes specify that the return
1397object has a +0 retain count, even if the normal convention for its selector
1398would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
1399+0, but is guaranteed to live at least as long as the next flush of an
1400autorelease pool.
1401
1402**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
1403an parameter declaration; they specify that the argument is expected to have a
1404+1 retain count, which will be balanced in some way by the function or method.
1405The ``ns_consumes_self`` attribute can only be placed on an Objective-C
1406method; it specifies that the method expects its ``self`` parameter to have a
1407+1 retain count, which it will balance in some way.
1408
1409.. code-block:: objc
1410
1411 void foo(__attribute__((ns_consumed)) NSString *string);
1412
1413 - (void) bar __attribute__((ns_consumes_self));
1414 - (void) baz:(id) __attribute__((ns_consumed)) x;
1415
1416Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001417<https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
Jordan Rose32e94892012-12-15 00:37:01 +00001418
1419Query for these features with ``__has_attribute(ns_consumed)``,
1420``__has_attribute(ns_returns_retained)``, etc.
1421
Nico Weber11cafc82017-07-14 18:40:52 +00001422Objective-C @available
1423----------------------
1424
1425It is possible to use the newest SDK but still build a program that can run on
Nico Weber564004a2017-07-14 18:52:30 +00001426older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
1427``-miphoneos-version-min=``.
Nico Weber11cafc82017-07-14 18:40:52 +00001428
1429Before LLVM 5.0, when calling a function that exists only in the OS that's
1430newer than the target OS (as determined by the minimum deployment version),
1431programmers had to carefully check if the function exists at runtime, using
1432null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
1433and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
1434Objective-C methods. If such a check was missed, the program would compile
1435fine, run fine on newer systems, but crash on older systems.
1436
1437As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001438<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
Nico Weber11cafc82017-07-14 18:40:52 +00001439with the new ``@available()`` keyword to assist with this issue.
1440When a method that's introduced in the OS newer than the target OS is called, a
1441-Wunguarded-availability warning is emitted if that call is not guarded:
1442
1443.. code-block:: objc
1444
1445 void my_fun(NSSomeClass* var) {
1446 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
1447 // built with -mmacosx-version-min=10.11, then this unconditional call
1448 // will emit a -Wunguarded-availability warning:
1449 [var fancyNewMethod];
1450 }
1451
1452To fix the warning and to avoid the crash on macOS 10.11, wrap it in
1453``if(@available())``:
1454
1455.. code-block:: objc
1456
1457 void my_fun(NSSomeClass* var) {
1458 if (@available(macOS 10.12, *)) {
1459 [var fancyNewMethod];
1460 } else {
1461 // Put fallback behavior for old macOS versions (and for non-mac
1462 // platforms) here.
1463 }
1464 }
1465
1466The ``*`` is required and means that platforms not explicitly listed will take
1467the true branch, and the compiler will emit ``-Wunguarded-availability``
1468warnings for unlisted platforms based on those platform's deployment target.
1469More than one platform can be listed in ``@available()``:
1470
1471.. code-block:: objc
1472
1473 void my_fun(NSSomeClass* var) {
1474 if (@available(macOS 10.12, iOS 10, *)) {
1475 [var fancyNewMethod];
1476 }
1477 }
1478
1479If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
1480on 10.12, then add an `availability attribute
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001481<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
Nico Weber11cafc82017-07-14 18:40:52 +00001482which will also suppress the warning and require that calls to my_fun() are
1483checked:
1484
1485.. code-block:: objc
1486
1487 API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
1488 [var fancyNewMethod]; // Now ok.
1489 }
1490
1491``@available()`` is only available in Objective-C code. To use the feature
1492in C and C++ code, use the ``__builtin_available()`` spelling instead.
1493
1494If existing code uses null checks or ``-respondsToSelector:``, it should
1495be changed to use ``@available()`` (or ``__builtin_available``) instead.
1496
1497``-Wunguarded-availability`` is disabled by default, but
1498``-Wunguarded-availability-new``, which only emits this warning for APIs
1499that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
1500tvOS >= 11, is enabled by default.
1501
1502.. _langext-overloading:
Jordan Rose32e94892012-12-15 00:37:01 +00001503
Ted Kremenek84342d62013-10-15 04:28:42 +00001504Objective-C++ ABI: protocol-qualifier mangling of parameters
1505------------------------------------------------------------
1506
1507Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
1508type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
1509parameters to be differentiated from those with the regular unqualified ``id``
1510type.
1511
1512This was a non-backward compatible mangling change to the ABI. This change
1513allows proper overloading, and also prevents mangling conflicts with template
1514parameters of protocol-qualified type.
1515
1516Query the presence of this new mangling with
1517``__has_feature(objc_protocol_qualifier_mangling)``.
1518
Sean Silva709c44d2012-12-12 23:44:55 +00001519Initializer lists for complex numbers in C
1520==========================================
1521
1522clang supports an extension which allows the following in C:
1523
1524.. code-block:: c++
1525
1526 #include <math.h>
1527 #include <complex.h>
1528 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
1529
1530This construct is useful because there is no way to separately initialize the
1531real and imaginary parts of a complex variable in standard C, given that clang
1532does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
1533``__imag__`` extensions from gcc, which help in some cases, but are not usable
1534in static initializers.)
1535
1536Note that this extension does not allow eliding the braces; the meaning of the
1537following two lines is different:
1538
1539.. code-block:: c++
1540
1541 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
1542 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
1543
1544This extension also works in C++ mode, as far as that goes, but does not apply
1545to the C++ ``std::complex``. (In C++11, list initialization allows the same
1546syntax to be used with ``std::complex`` with the same meaning.)
1547
1548Builtin Functions
1549=================
1550
1551Clang supports a number of builtin library functions with the same syntax as
1552GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
1553``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
Hal Finkelbcc06082014-09-07 22:58:14 +00001554``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to
1555the GCC builtins, Clang supports a number of builtins that GCC does not, which
1556are listed here.
Sean Silva709c44d2012-12-12 23:44:55 +00001557
1558Please note that Clang does not and will not support all of the GCC builtins
1559for vector operations. Instead of using builtins, you should use the functions
1560defined in target-specific header files like ``<xmmintrin.h>``, which define
1561portable wrappers for these. Many of the Clang versions of these functions are
1562implemented directly in terms of :ref:`extended vector support
1563<langext-vectors>` instead of builtins, in order to reduce the number of
1564builtins that we need to implement.
1565
Hal Finkelbcc06082014-09-07 22:58:14 +00001566``__builtin_assume``
1567------------------------------
1568
1569``__builtin_assume`` is used to provide the optimizer with a boolean
1570invariant that is defined to be true.
1571
1572**Syntax**:
1573
1574.. code-block:: c++
1575
1576 __builtin_assume(bool)
1577
1578**Example of Use**:
1579
1580.. code-block:: c++
1581
1582 int foo(int x) {
1583 __builtin_assume(x != 0);
1584
1585 // The optimizer may short-circuit this check using the invariant.
1586 if (x == 0)
1587 return do_something();
1588
1589 return do_something_else();
1590 }
1591
1592**Description**:
1593
1594The boolean argument to this function is defined to be true. The optimizer may
1595analyze the form of the expression provided as the argument and deduce from
1596that information used to optimize the program. If the condition is violated
1597during execution, the behavior is undefined. The argument itself is never
1598evaluated, so any side effects of the expression will be discarded.
1599
1600Query for this feature with ``__has_builtin(__builtin_assume)``.
1601
Sean Silva709c44d2012-12-12 23:44:55 +00001602``__builtin_readcyclecounter``
1603------------------------------
1604
1605``__builtin_readcyclecounter`` is used to access the cycle counter register (or
1606a similar low-latency, high-accuracy clock) on those targets that support it.
1607
1608**Syntax**:
1609
1610.. code-block:: c++
1611
1612 __builtin_readcyclecounter()
1613
1614**Example of Use**:
1615
1616.. code-block:: c++
1617
1618 unsigned long long t0 = __builtin_readcyclecounter();
1619 do_something();
1620 unsigned long long t1 = __builtin_readcyclecounter();
1621 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
1622
1623**Description**:
1624
1625The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
1626which may be either global or process/thread-specific depending on the target.
1627As the backing counters often overflow quickly (on the order of seconds) this
1628should only be used for timing small intervals. When not supported by the
1629target, the return value is always zero. This builtin takes no arguments and
1630produces an unsigned long long result.
1631
Tim Northoverbfe2e5f72013-05-23 19:14:12 +00001632Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
1633that even if present, its use may depend on run-time privilege or other OS
1634controlled state.
Sean Silva709c44d2012-12-12 23:44:55 +00001635
1636.. _langext-__builtin_shufflevector:
1637
1638``__builtin_shufflevector``
1639---------------------------
1640
1641``__builtin_shufflevector`` is used to express generic vector
1642permutation/shuffle/swizzle operations. This builtin is also very important
1643for the implementation of various target-specific header files like
1644``<xmmintrin.h>``.
1645
1646**Syntax**:
1647
1648.. code-block:: c++
1649
1650 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
1651
1652**Examples**:
1653
1654.. code-block:: c++
1655
Craig Topper50ad5b72013-08-03 17:40:38 +00001656 // identity operation - return 4-element vector v1.
1657 __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
Sean Silva709c44d2012-12-12 23:44:55 +00001658
1659 // "Splat" element 0 of V1 into a 4-element result.
1660 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
1661
1662 // Reverse 4-element vector V1.
1663 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
1664
1665 // Concatenate every other element of 4-element vectors V1 and V2.
1666 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
1667
1668 // Concatenate every other element of 8-element vectors V1 and V2.
1669 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
1670
Craig Topper50ad5b72013-08-03 17:40:38 +00001671 // Shuffle v1 with some elements being undefined
1672 __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
1673
Sean Silva709c44d2012-12-12 23:44:55 +00001674**Description**:
1675
1676The first two arguments to ``__builtin_shufflevector`` are vectors that have
1677the same element type. The remaining arguments are a list of integers that
1678specify the elements indices of the first two vectors that should be extracted
1679and returned in a new vector. These element indices are numbered sequentially
1680starting with the first vector, continuing into the second vector. Thus, if
1681``vec1`` is a 4-element vector, index 5 would refer to the second element of
Craig Topper50ad5b72013-08-03 17:40:38 +00001682``vec2``. An index of -1 can be used to indicate that the corresponding element
1683in the returned vector is a don't care and can be optimized by the backend.
Sean Silva709c44d2012-12-12 23:44:55 +00001684
1685The result of ``__builtin_shufflevector`` is a vector with the same element
1686type as ``vec1``/``vec2`` but that has an element count equal to the number of
1687indices specified.
1688
1689Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
1690
Anton Yartsev94e46f32014-09-03 17:59:21 +00001691.. _langext-__builtin_convertvector:
1692
Hal Finkelc4d7c822013-09-18 03:29:45 +00001693``__builtin_convertvector``
1694---------------------------
1695
1696``__builtin_convertvector`` is used to express generic vector
1697type-conversion operations. The input vector and the output vector
1698type must have the same number of elements.
1699
1700**Syntax**:
1701
1702.. code-block:: c++
1703
1704 __builtin_convertvector(src_vec, dst_vec_type)
1705
1706**Examples**:
1707
1708.. code-block:: c++
1709
1710 typedef double vector4double __attribute__((__vector_size__(32)));
1711 typedef float vector4float __attribute__((__vector_size__(16)));
1712 typedef short vector4short __attribute__((__vector_size__(8)));
1713 vector4float vf; vector4short vs;
1714
1715 // convert from a vector of 4 floats to a vector of 4 doubles.
1716 __builtin_convertvector(vf, vector4double)
1717 // equivalent to:
1718 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
1719
1720 // convert from a vector of 4 shorts to a vector of 4 floats.
1721 __builtin_convertvector(vs, vector4float)
1722 // equivalent to:
Yunzhong Gao637cb90b2014-09-02 19:24:14 +00001723 (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
Hal Finkelc4d7c822013-09-18 03:29:45 +00001724
1725**Description**:
1726
1727The first argument to ``__builtin_convertvector`` is a vector, and the second
1728argument is a vector type with the same number of elements as the first
1729argument.
1730
1731The result of ``__builtin_convertvector`` is a vector with the same element
1732type as the second argument, with a value defined in terms of the action of a
1733C-style cast applied to each element of the first argument.
1734
1735Query for this feature with ``__has_builtin(__builtin_convertvector)``.
1736
Matt Arsenault08087c52016-03-23 22:14:43 +00001737``__builtin_bitreverse``
Aaron Ballmanbcf13da2016-03-24 12:34:44 +00001738------------------------
Matt Arsenault08087c52016-03-23 22:14:43 +00001739
1740* ``__builtin_bitreverse8``
1741* ``__builtin_bitreverse16``
1742* ``__builtin_bitreverse32``
1743* ``__builtin_bitreverse64``
1744
1745**Syntax**:
1746
1747.. code-block:: c++
Aaron Ballmanbcf13da2016-03-24 12:34:44 +00001748
Matt Arsenault08087c52016-03-23 22:14:43 +00001749 __builtin_bitreverse32(x)
1750
1751**Examples**:
1752
1753.. code-block:: c++
Aaron Ballmanbcf13da2016-03-24 12:34:44 +00001754
Matt Arsenault08087c52016-03-23 22:14:43 +00001755 uint8_t rev_x = __builtin_bitreverse8(x);
1756 uint16_t rev_x = __builtin_bitreverse16(x);
1757 uint32_t rev_y = __builtin_bitreverse32(y);
1758 uint64_t rev_z = __builtin_bitreverse64(z);
1759
1760**Description**:
1761
1762The '``__builtin_bitreverse``' family of builtins is used to reverse
1763the bitpattern of an integer value; for example ``0b10110110`` becomes
1764``0b01101101``.
1765
Sanjay Patelad823902018-08-19 16:50:30 +00001766``__builtin_rotateleft``
1767------------------------
1768
1769* ``__builtin_rotateleft8``
1770* ``__builtin_rotateleft16``
1771* ``__builtin_rotateleft32``
1772* ``__builtin_rotateleft64``
1773
1774**Syntax**:
1775
1776.. code-block:: c++
1777
1778 __builtin_rotateleft32(x, y)
1779
1780**Examples**:
1781
1782.. code-block:: c++
1783
1784 uint8_t rot_x = __builtin_rotateleft8(x, y);
1785 uint16_t rot_x = __builtin_rotateleft16(x, y);
1786 uint32_t rot_x = __builtin_rotateleft32(x, y);
1787 uint64_t rot_x = __builtin_rotateleft64(x, y);
1788
1789**Description**:
1790
1791The '``__builtin_rotateleft``' family of builtins is used to rotate
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00001792the bits in the first argument by the amount in the second argument.
Sanjay Patelad823902018-08-19 16:50:30 +00001793For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
1794The shift value is treated as an unsigned amount modulo the size of
1795the arguments. Both arguments and the result have the bitwidth specified
1796by the name of the builtin.
1797
1798``__builtin_rotateright``
Kristina Brooks233a4982019-04-05 18:26:43 +00001799-------------------------
Sanjay Patelad823902018-08-19 16:50:30 +00001800
1801* ``__builtin_rotateright8``
1802* ``__builtin_rotateright16``
1803* ``__builtin_rotateright32``
1804* ``__builtin_rotateright64``
1805
1806**Syntax**:
1807
1808.. code-block:: c++
1809
1810 __builtin_rotateright32(x, y)
1811
1812**Examples**:
1813
1814.. code-block:: c++
1815
1816 uint8_t rot_x = __builtin_rotateright8(x, y);
1817 uint16_t rot_x = __builtin_rotateright16(x, y);
1818 uint32_t rot_x = __builtin_rotateright32(x, y);
1819 uint64_t rot_x = __builtin_rotateright64(x, y);
1820
1821**Description**:
1822
1823The '``__builtin_rotateright``' family of builtins is used to rotate
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00001824the bits in the first argument by the amount in the second argument.
Sanjay Patelad823902018-08-19 16:50:30 +00001825For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
1826The shift value is treated as an unsigned amount modulo the size of
1827the arguments. Both arguments and the result have the bitwidth specified
1828by the name of the builtin.
1829
Sean Silva709c44d2012-12-12 23:44:55 +00001830``__builtin_unreachable``
1831-------------------------
1832
1833``__builtin_unreachable`` is used to indicate that a specific point in the
1834program cannot be reached, even if the compiler might otherwise think it can.
1835This is useful to improve optimization and eliminates certain warnings. For
1836example, without the ``__builtin_unreachable`` in the example below, the
1837compiler assumes that the inline asm can fall through and prints a "function
1838declared '``noreturn``' should not return" warning.
1839
1840**Syntax**:
1841
1842.. code-block:: c++
1843
1844 __builtin_unreachable()
1845
1846**Example of use**:
1847
1848.. code-block:: c++
1849
1850 void myabort(void) __attribute__((noreturn));
1851 void myabort(void) {
1852 asm("int3");
1853 __builtin_unreachable();
1854 }
1855
1856**Description**:
1857
1858The ``__builtin_unreachable()`` builtin has completely undefined behavior.
1859Since it has undefined behavior, it is a statement that it is never reached and
1860the optimizer can take advantage of this to produce better code. This builtin
1861takes no arguments and produces a void result.
1862
1863Query for this feature with ``__has_builtin(__builtin_unreachable)``.
1864
Sanjay Patela24296b2015-09-02 20:01:30 +00001865``__builtin_unpredictable``
1866---------------------------
1867
1868``__builtin_unpredictable`` is used to indicate that a branch condition is
1869unpredictable by hardware mechanisms such as branch prediction logic.
1870
1871**Syntax**:
1872
1873.. code-block:: c++
1874
1875 __builtin_unpredictable(long long)
1876
1877**Example of use**:
1878
1879.. code-block:: c++
1880
1881 if (__builtin_unpredictable(x > 0)) {
1882 foo();
1883 }
1884
1885**Description**:
1886
1887The ``__builtin_unpredictable()`` builtin is expected to be used with control
1888flow conditions such as in ``if`` and ``switch`` statements.
1889
1890Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
1891
Sean Silva709c44d2012-12-12 23:44:55 +00001892``__sync_swap``
1893---------------
1894
1895``__sync_swap`` is used to atomically swap integers or pointers in memory.
1896
1897**Syntax**:
1898
1899.. code-block:: c++
1900
1901 type __sync_swap(type *ptr, type value, ...)
1902
1903**Example of Use**:
1904
1905.. code-block:: c++
1906
1907 int old_value = __sync_swap(&value, new_value);
1908
1909**Description**:
1910
1911The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
1912atomic intrinsics to allow code to atomically swap the current value with the
1913new value. More importantly, it helps developers write more efficient and
1914correct code by avoiding expensive loops around
1915``__sync_bool_compare_and_swap()`` or relying on the platform specific
1916implementation details of ``__sync_lock_test_and_set()``. The
1917``__sync_swap()`` builtin is a full barrier.
1918
Richard Smith6cbd65d2013-07-11 02:27:57 +00001919``__builtin_addressof``
1920-----------------------
1921
1922``__builtin_addressof`` performs the functionality of the built-in ``&``
1923operator, ignoring any ``operator&`` overload. This is useful in constant
1924expressions in C++11, where there is no other way to take the address of an
1925object that overloads ``operator&``.
1926
1927**Example of use**:
1928
1929.. code-block:: c++
1930
1931 template<typename T> constexpr T *addressof(T &value) {
1932 return __builtin_addressof(value);
1933 }
1934
Richard Smith760520b2014-06-03 23:27:44 +00001935``__builtin_operator_new`` and ``__builtin_operator_delete``
1936------------------------------------------------------------
1937
1938``__builtin_operator_new`` allocates memory just like a non-placement non-class
1939*new-expression*. This is exactly like directly calling the normal
1940non-placement ``::operator new``, except that it allows certain optimizations
1941that the C++ standard does not permit for a direct function call to
1942``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
1943merging allocations).
1944
1945Likewise, ``__builtin_operator_delete`` deallocates memory just like a
1946non-class *delete-expression*, and is exactly like directly calling the normal
1947``::operator delete``, except that it permits optimizations. Only the unsized
1948form of ``__builtin_operator_delete`` is currently available.
1949
1950These builtins are intended for use in the implementation of ``std::allocator``
1951and other similar allocation libraries, and are only available in C++.
1952
Yonghong Song048493f2019-07-09 04:21:50 +00001953``__builtin_preserve_access_index``
1954-----------------------------------
1955
1956``__builtin_preserve_access_index`` specifies a code section where
1957array subscript access and structure/union member access are relocatable
1958under bpf compile-once run-everywhere framework. Debuginfo (typically
1959with ``-g``) is needed, otherwise, the compiler will exit with an error.
1960
1961**Syntax**:
1962
1963.. code-block:: c
1964
1965 const void * __builtin_preserve_access_index(const void * ptr)
1966
1967**Example of Use**:
1968
1969.. code-block:: c
1970
1971 struct t {
1972 int i;
1973 int j;
1974 union {
1975 int a;
1976 int b;
1977 } c[4];
1978 };
1979 struct t *v = ...;
1980 const void *pb =__builtin_preserve_access_index(&v->c[3].b);
1981
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00001982Multiprecision Arithmetic Builtins
1983----------------------------------
1984
1985Clang provides a set of builtins which expose multiprecision arithmetic in a
1986manner amenable to C. They all have the following form:
1987
1988.. code-block:: c
1989
1990 unsigned x = ..., y = ..., carryin = ..., carryout;
1991 unsigned sum = __builtin_addc(x, y, carryin, &carryout);
1992
1993Thus one can form a multiprecision addition chain in the following manner:
1994
1995.. code-block:: c
1996
1997 unsigned *x, *y, *z, carryin=0, carryout;
1998 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
1999 carryin = carryout;
2000 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
2001 carryin = carryout;
2002 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
2003 carryin = carryout;
2004 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
2005
2006The complete list of builtins are:
2007
2008.. code-block:: c
2009
Michael Gottesman15343992013-06-18 20:40:40 +00002010 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00002011 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
2012 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
2013 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
2014 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
Michael Gottesman15343992013-06-18 20:40:40 +00002015 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
Michael Gottesmanc5cc9f12013-01-13 04:35:31 +00002016 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
2017 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
2018 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
2019 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
2020
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002021Checked Arithmetic Builtins
2022---------------------------
2023
2024Clang provides a set of builtins that implement checked arithmetic for security
2025critical applications in a manner that is fast and easily expressable in C. As
2026an example of their usage:
2027
2028.. code-block:: c
2029
2030 errorcode_t security_critical_application(...) {
2031 unsigned x, y, result;
2032 ...
John McCall03107a42015-10-29 20:48:01 +00002033 if (__builtin_mul_overflow(x, y, &result))
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002034 return kErrorCodeHackers;
2035 ...
2036 use_multiply(result);
2037 ...
2038 }
2039
John McCall03107a42015-10-29 20:48:01 +00002040Clang provides the following checked arithmetic builtins:
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002041
2042.. code-block:: c
2043
John McCall03107a42015-10-29 20:48:01 +00002044 bool __builtin_add_overflow (type1 x, type2 y, type3 *sum);
2045 bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff);
2046 bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod);
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002047 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
2048 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
2049 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
2050 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
2051 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
2052 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
2053 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
2054 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
2055 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
2056 bool __builtin_sadd_overflow (int x, int y, int *sum);
2057 bool __builtin_saddl_overflow (long x, long y, long *sum);
2058 bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
2059 bool __builtin_ssub_overflow (int x, int y, int *diff);
2060 bool __builtin_ssubl_overflow (long x, long y, long *diff);
2061 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
2062 bool __builtin_smul_overflow (int x, int y, int *prod);
2063 bool __builtin_smull_overflow (long x, long y, long *prod);
2064 bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
2065
John McCall03107a42015-10-29 20:48:01 +00002066Each builtin performs the specified mathematical operation on the
2067first two arguments and stores the result in the third argument. If
2068possible, the result will be equal to mathematically-correct result
2069and the builtin will return 0. Otherwise, the builtin will return
20701 and the result will be equal to the unique value that is equivalent
2071to the mathematically-correct result modulo two raised to the *k*
2072power, where *k* is the number of bits in the result type. The
2073behavior of these builtins is well-defined for all argument values.
2074
2075The first three builtins work generically for operands of any integer type,
2076including boolean types. The operands need not have the same type as each
2077other, or as the result. The other builtins may implicitly promote or
2078convert their operands before performing the operation.
2079
2080Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
Michael Gottesman930ecdb2013-06-20 23:28:10 +00002081
Matt Arsenault2d933982016-02-27 09:06:18 +00002082Floating point builtins
2083---------------------------------------
2084
2085``__builtin_canonicalize``
2086--------------------------
2087
2088.. code-block:: c
2089
2090 double __builtin_canonicalize(double);
2091 float __builtin_canonicalizef(float);
2092 long double__builtin_canonicalizel(long double);
2093
2094Returns the platform specific canonical encoding of a floating point
2095number. This canonicalization is useful for implementing certain
2096numeric primitives such as frexp. See `LLVM canonicalize intrinsic
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002097<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
Matt Arsenault2d933982016-02-27 09:06:18 +00002098more information on the semantics.
2099
Richard Smith67d484b2017-01-20 00:57:59 +00002100String builtins
2101---------------
2102
2103Clang provides constant expression evaluation support for builtins forms of
Richard Smith0abb11c2017-01-23 18:17:46 +00002104the following functions from the C standard library ``<string.h>`` header:
Richard Smith67d484b2017-01-20 00:57:59 +00002105
2106* ``memchr``
2107* ``memcmp``
2108* ``strchr``
2109* ``strcmp``
2110* ``strlen``
2111* ``strncmp``
2112* ``wcschr``
2113* ``wcscmp``
2114* ``wcslen``
2115* ``wcsncmp``
2116* ``wmemchr``
2117* ``wmemcmp``
2118
2119In each case, the builtin form has the name of the C library function prefixed
Richard Smith90854c42017-01-20 01:08:15 +00002120by ``__builtin_``. Example:
Richard Smith67d484b2017-01-20 00:57:59 +00002121
2122.. code-block:: c
2123
2124 void *p = __builtin_memchr("foobar", 'b', 5);
2125
2126In addition to the above, one further builtin is provided:
2127
2128.. code-block:: c
2129
2130 char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
2131
2132``__builtin_char_memchr(a, b, c)`` is identical to
2133``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
2134constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
2135is disallowed in general).
2136
2137Support for constant expression evaluation for the above builtins be detected
2138with ``__has_feature(cxx_constexpr_string_builtins)``.
2139
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00002140Atomic Min/Max builtins with memory ordering
2141--------------------------------------------
2142
2143There are two atomic builtins with min/max in-memory comparison and swap.
2144The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
2145
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002146* ``__atomic_fetch_min``
2147* ``__atomic_fetch_max``
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00002148
2149The builtins work with signed and unsigned integers and require to specify memory ordering.
2150The return value is the original value that was stored in memory before comparison.
2151
2152Example:
2153
2154.. code-block:: c
2155
2156 unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
2157
2158The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
2159``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
2160``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
2161
2162In terms or aquire-release ordering barriers these two operations are always
2163considered as operations with *load-store* semantics, even when the original value
2164is not actually modified after comparison.
2165
Sean Silva709c44d2012-12-12 23:44:55 +00002166.. _langext-__c11_atomic:
2167
2168__c11_atomic builtins
2169---------------------
2170
2171Clang provides a set of builtins which are intended to be used to implement
2172C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
2173``_explicit`` form of the corresponding C11 operation, and are named with a
Hal Finkel6970ac82014-10-03 04:29:40 +00002174``__c11_`` prefix. The supported operations, and the differences from
2175the corresponding C11 operations, are:
Sean Silva709c44d2012-12-12 23:44:55 +00002176
2177* ``__c11_atomic_init``
2178* ``__c11_atomic_thread_fence``
2179* ``__c11_atomic_signal_fence``
Hal Finkel6970ac82014-10-03 04:29:40 +00002180* ``__c11_atomic_is_lock_free`` (The argument is the size of the
Dan Liewfe726862014-10-03 12:36:20 +00002181 ``_Atomic(...)`` object, instead of its address)
Sean Silva709c44d2012-12-12 23:44:55 +00002182* ``__c11_atomic_store``
2183* ``__c11_atomic_load``
2184* ``__c11_atomic_exchange``
2185* ``__c11_atomic_compare_exchange_strong``
2186* ``__c11_atomic_compare_exchange_weak``
2187* ``__c11_atomic_fetch_add``
2188* ``__c11_atomic_fetch_sub``
2189* ``__c11_atomic_fetch_and``
2190* ``__c11_atomic_fetch_or``
2191* ``__c11_atomic_fetch_xor``
2192
Hal Finkel6970ac82014-10-03 04:29:40 +00002193The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
JF Bastiene6ccacf2014-10-10 16:09:48 +00002194``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
Hal Finkel6970ac82014-10-03 04:29:40 +00002195provided, with values corresponding to the enumerators of C11's
2196``memory_order`` enumeration.
2197
James Y Knight81167fb2015-08-05 16:57:36 +00002198(Note that Clang additionally provides GCC-compatible ``__atomic_*``
Yaxun Liu39195062017-08-04 18:16:31 +00002199builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
2200atomic builtins are an explicit form of the corresponding OpenCL 2.0
2201builtin function, and are named with a ``__opencl_`` prefix. The macros
2202``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
2203``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
2204and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
2205corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
James Y Knight81167fb2015-08-05 16:57:36 +00002206
Tim Northover6aacd492013-07-16 09:47:53 +00002207Low-level ARM exclusive memory builtins
2208---------------------------------------
2209
2210Clang provides overloaded builtins giving direct access to the three key ARM
2211instructions for implementing atomic operations.
2212
2213.. code-block:: c
Sean Silvaa928c242013-09-09 19:50:40 +00002214
Tim Northover6aacd492013-07-16 09:47:53 +00002215 T __builtin_arm_ldrex(const volatile T *addr);
Tim Northover3acd6bd2014-07-02 12:56:02 +00002216 T __builtin_arm_ldaex(const volatile T *addr);
Tim Northover6aacd492013-07-16 09:47:53 +00002217 int __builtin_arm_strex(T val, volatile T *addr);
Tim Northover3acd6bd2014-07-02 12:56:02 +00002218 int __builtin_arm_stlex(T val, volatile T *addr);
Tim Northover6aacd492013-07-16 09:47:53 +00002219 void __builtin_arm_clrex(void);
2220
2221The types ``T`` currently supported are:
Michael Zolotukhinc3f09ff2015-09-10 23:56:10 +00002222
Tim Northover573cbee2014-05-24 12:52:07 +00002223* Integer types with width at most 64 bits (or 128 bits on AArch64).
Tim Northover6aacd492013-07-16 09:47:53 +00002224* Floating-point types
2225* Pointer types.
2226
2227Note that the compiler does not guarantee it will not insert stores which clear
Tim Northover3acd6bd2014-07-02 12:56:02 +00002228the exclusive monitor in between an ``ldrex`` type operation and its paired
2229``strex``. In practice this is only usually a risk when the extra store is on
2230the same cache line as the variable being modified and Clang will only insert
2231stack stores on its own, so it is best not to use these operations on variables
2232with automatic storage duration.
Tim Northover6aacd492013-07-16 09:47:53 +00002233
2234Also, loads and stores may be implicit in code written between the ``ldrex`` and
2235``strex``. Clang will not necessarily mitigate the effects of these either, so
2236care should be exercised.
2237
2238For these reasons the higher level atomic primitives should be preferred where
2239possible.
2240
Michael Zolotukhin59d72b12015-09-11 02:01:15 +00002241Non-temporal load/store builtins
2242--------------------------------
2243
2244Clang provides overloaded builtins allowing generation of non-temporal memory
2245accesses.
2246
2247.. code-block:: c
2248
2249 T __builtin_nontemporal_load(T *addr);
2250 void __builtin_nontemporal_store(T value, T *addr);
2251
2252The types ``T`` currently supported are:
2253
2254* Integer types.
2255* Floating-point types.
2256* Vector types.
2257
2258Note that the compiler does not guarantee that non-temporal loads or stores
2259will be used.
2260
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002261C++ Coroutines support builtins
2262--------------------------------
2263
2264.. warning::
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002265 This is a work in progress. Compatibility across Clang/LLVM releases is not
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002266 guaranteed.
2267
2268Clang provides experimental builtins to support C++ Coroutines as defined by
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002269https://wg21.link/P0057. The following four are intended to be used by the
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002270standard library to implement `std::experimental::coroutine_handle` type.
2271
2272**Syntax**:
2273
2274.. code-block:: c
2275
2276 void __builtin_coro_resume(void *addr);
2277 void __builtin_coro_destroy(void *addr);
2278 bool __builtin_coro_done(void *addr);
2279 void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
2280
2281**Example of use**:
2282
2283.. code-block:: c++
2284
2285 template <> struct coroutine_handle<void> {
2286 void resume() const { __builtin_coro_resume(ptr); }
2287 void destroy() const { __builtin_coro_destroy(ptr); }
2288 bool done() const { return __builtin_coro_done(ptr); }
2289 // ...
2290 protected:
2291 void *ptr;
2292 };
2293
2294 template <typename Promise> struct coroutine_handle : coroutine_handle<> {
2295 // ...
2296 Promise &promise() const {
2297 return *reinterpret_cast<Promise *>(
2298 __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
2299 }
2300 static coroutine_handle from_promise(Promise &promise) {
2301 coroutine_handle p;
2302 p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
2303 /*from-promise=*/true);
2304 return p;
2305 }
2306 };
2307
2308
2309Other coroutine builtins are either for internal clang use or for use during
2310development of the coroutine feature. See `Coroutines in LLVM
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002311<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002312more information on their semantics. Note that builtins matching the intrinsics
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002313that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00002314llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
2315an appropriate value during the emission.
2316
2317**Syntax**:
2318
2319.. code-block:: c
2320
2321 size_t __builtin_coro_size()
2322 void *__builtin_coro_frame()
2323 void *__builtin_coro_free(void *coro_frame)
2324
2325 void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
2326 bool __builtin_coro_alloc()
2327 void *__builtin_coro_begin(void *memory)
2328 void __builtin_coro_end(void *coro_frame, bool unwind)
2329 char __builtin_coro_suspend(bool final)
2330 bool __builtin_coro_param(void *original, void *copy)
2331
2332Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
2333automatically will insert one if the first argument to `llvm.coro.suspend` is
2334token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
2335as the first argument to the intrinsic.
2336
Eric Fiselier708afb52019-05-16 21:04:15 +00002337Source location builtins
2338------------------------
2339
2340Clang provides experimental builtins to support C++ standard library implementation
2341of ``std::experimental::source_location`` as specified in http://wg21.link/N4600.
2342With the exception of ``__builtin_COLUMN``, these builtins are also implemented by
2343GCC.
2344
2345**Syntax**:
2346
2347.. code-block:: c
2348
2349 const char *__builtin_FILE();
2350 const char *__builtin_FUNCTION();
2351 unsigned __builtin_LINE();
2352 unsigned __builtin_COLUMN(); // Clang only
2353
2354**Example of use**:
2355
2356.. code-block:: c++
2357
2358 void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
2359 const char* file = __builtin_FILE(),
2360 const char* function = __builtin_FUNCTION()) {
2361 if (pred) return;
2362 printf("%s:%d assertion failed in function %s\n", file, line, function);
2363 std::abort();
2364 }
2365
2366 struct MyAggregateType {
2367 int x;
2368 int line = __builtin_LINE(); // captures line where aggregate initialization occurs
2369 };
2370 static_assert(MyAggregateType{42}.line == __LINE__);
2371
2372 struct MyClassType {
2373 int line = __builtin_LINE(); // captures line of the constructor used during initialization
2374 constexpr MyClassType(int) { assert(line == __LINE__); }
2375 };
2376
2377**Description**:
2378
2379The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, and ``__builtin_FILE`` return
2380the values, at the "invocation point", for ``__LINE__``, ``__FUNCTION__``, and
2381``__FILE__`` respectively. These builtins are constant expressions.
2382
2383When the builtins appear as part of a default function argument the invocation
2384point is the location of the caller. When the builtins appear as part of a
2385default member initializer, the invocation point is the location of the
2386constructor or aggregate initialization used to create the object. Otherwise
2387the invocation point is the same as the location of the builtin.
2388
2389When the invocation point of ``__builtin_FUNCTION`` is not a function scope the
2390empty string is returned.
2391
Sean Silva709c44d2012-12-12 23:44:55 +00002392Non-standard C++11 Attributes
2393=============================
2394
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002395Clang's non-standard C++11 attributes live in the ``clang`` attribute
2396namespace.
Sean Silva709c44d2012-12-12 23:44:55 +00002397
Aaron Ballman68893db2014-02-19 23:21:40 +00002398Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002399are accepted with the ``__attribute__((foo))`` syntax are also accepted as
2400``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
2401(see the list of `GCC function attributes
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002402<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
2403attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002404`GCC type attributes
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002405<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
Richard Smithf6d2d3b2013-02-14 00:13:34 +00002406implementation, these attributes must appertain to the *declarator-id* in a
2407declaration, which means they must go either at the start of the declaration or
2408immediately after the name being declared.
2409
2410For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
2411also applies the GNU ``noreturn`` attribute to ``f``.
2412
2413.. code-block:: c++
2414
2415 [[gnu::unused]] int a, f [[gnu::noreturn]] ();
2416
Sean Silva709c44d2012-12-12 23:44:55 +00002417Target-Specific Extensions
2418==========================
2419
2420Clang supports some language features conditionally on some targets.
2421
Yi Kong4de26fb2014-07-23 09:25:02 +00002422ARM/AArch64 Language Extensions
2423-------------------------------
2424
2425Memory Barrier Intrinsics
2426^^^^^^^^^^^^^^^^^^^^^^^^^
2427Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
2428in the `ARM C Language Extensions Release 2.0
2429<http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
2430Note that these intrinsics are implemented as motion barriers that block
2431reordering of memory accesses and side effect instructions. Other instructions
Sylvestre Ledrube8f3962016-02-14 20:20:58 +00002432like simple arithmetic may be reordered around the intrinsic. If you expect to
Yi Kong4de26fb2014-07-23 09:25:02 +00002433have no reordering at all, use inline assembly instead.
2434
Sean Silva709c44d2012-12-12 23:44:55 +00002435X86/X86-64 Language Extensions
2436------------------------------
2437
2438The X86 backend has these language extensions:
2439
David L Kreitzerd8984102016-05-03 20:20:59 +00002440Memory references to specified segments
2441^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silva709c44d2012-12-12 23:44:55 +00002442
2443Annotating a pointer with address space #256 causes it to be code generated
David L Kreitzerd8984102016-05-03 20:20:59 +00002444relative to the X86 GS segment register, address space #257 causes it to be
2445relative to the X86 FS segment, and address space #258 causes it to be
2446relative to the X86 SS segment. Note that this is a very very low-level
Sean Silva709c44d2012-12-12 23:44:55 +00002447feature that should only be used if you know what you're doing (for example in
2448an OS kernel).
2449
2450Here is an example:
2451
2452.. code-block:: c++
2453
2454 #define GS_RELATIVE __attribute__((address_space(256)))
2455 int foo(int GS_RELATIVE *P) {
2456 return *P;
2457 }
2458
2459Which compiles to (on X86-32):
2460
2461.. code-block:: gas
2462
2463 _foo:
2464 movl 4(%esp), %eax
2465 movl %gs:(%eax), %eax
2466 ret
2467
Kang Zhange5ac3852019-03-29 09:11:52 +00002468PowerPC Language Extensions
2469------------------------------
2470
2471Set the Floating Point Rounding Mode
2472^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2473PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
2474the floating point rounding mode. This function will use the least significant
2475two bits of integer argument to set the floating point rounding mode.
2476
2477.. code-block:: c++
2478
2479 double __builtin_setrnd(int mode);
2480
2481The effective values for mode are:
2482
2483 - 0 - round to nearest
2484 - 1 - round to zero
2485 - 2 - round to +infinity
2486 - 3 - round to -infinity
2487
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002488Note that the mode argument will modulo 4, so if the int argument is greater
2489than 3, it will only use the least significant two bits of the mode.
Kang Zhange5ac3852019-03-29 09:11:52 +00002490Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
2491
2492PowerPC Language Extensions
2493------------------------------
2494
2495Set the Floating Point Rounding Mode
2496^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2497PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
2498the floating point rounding mode. This function will use the least significant
2499two bits of integer argument to set the floating point rounding mode.
2500
2501.. code-block:: c++
2502
2503 double __builtin_setrnd(int mode);
2504
2505The effective values for mode are:
2506
2507 - 0 - round to nearest
2508 - 1 - round to zero
2509 - 2 - round to +infinity
2510 - 3 - round to -infinity
2511
2512Note that the mode argument will modulo 4, so if the integer argument is greater
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002513than 3, it will only use the least significant two bits of the mode.
Kang Zhange5ac3852019-03-29 09:11:52 +00002514Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
2515
2516PowerPC Language Extensions
2517------------------------------
2518
2519Set the Floating Point Rounding Mode
2520^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2521PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
2522the floating point rounding mode. This function will use the least significant
2523two bits of integer argument to set the floating point rounding mode.
2524
2525.. code-block:: c++
2526
2527 double __builtin_setrnd(int mode);
2528
2529The effective values for mode are:
2530
2531 - 0 - round to nearest
2532 - 1 - round to zero
2533 - 2 - round to +infinity
2534 - 3 - round to -infinity
2535
2536Note that the mode argument will modulo 4, so if the integer argument is greater
Sylvestre Ledru0adbe772019-07-09 08:50:17 +00002537than 3, it will only use the least significant two bits of the mode.
Kang Zhange5ac3852019-03-29 09:11:52 +00002538Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
2539
Ahsan Saghir3962d6d2019-04-29 23:25:33 +00002540PowerPC cache builtins
2541^^^^^^^^^^^^^^^^^^^^^^
2542
2543The PowerPC architecture specifies instructions implementing cache operations.
2544Clang provides builtins that give direct programmer access to these cache
2545instructions.
2546
2547Currently the following builtins are implemented in clang:
2548
2549``__builtin_dcbf`` copies the contents of a modified block from the data cache
2550to main memory and flushes the copy from the data cache.
2551
2552**Syntax**:
2553
2554.. code-block:: c
2555
2556 void __dcbf(const void* addr); /* Data Cache Block Flush */
2557
2558**Example of Use**:
2559
2560.. code-block:: c
2561
2562 int a = 1;
2563 __builtin_dcbf (&a);
2564
Jordan Rose32e94892012-12-15 00:37:01 +00002565Extensions for Static Analysis
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002566==============================
Sean Silva709c44d2012-12-12 23:44:55 +00002567
2568Clang supports additional attributes that are useful for documenting program
Jordan Rose32e94892012-12-15 00:37:01 +00002569invariants and rules for static analysis tools, such as the `Clang Static
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002570Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
Jordan Rose32e94892012-12-15 00:37:01 +00002571in the analyzer's `list of source-level annotations
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002572<https://clang-analyzer.llvm.org/annotations.html>`_.
Sean Silva709c44d2012-12-12 23:44:55 +00002573
Sean Silva709c44d2012-12-12 23:44:55 +00002574
Jordan Rose32e94892012-12-15 00:37:01 +00002575Extensions for Dynamic Analysis
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002576===============================
Sean Silva709c44d2012-12-12 23:44:55 +00002577
Sean Silva709c44d2012-12-12 23:44:55 +00002578Use ``__has_feature(address_sanitizer)`` to check if the code is being built
Dmitri Gribenkoace09a22012-12-15 14:25:25 +00002579with :doc:`AddressSanitizer`.
Sean Silva709c44d2012-12-12 23:44:55 +00002580
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002581Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
2582with :doc:`ThreadSanitizer`.
2583
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00002584Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
2585with :doc:`MemorySanitizer`.
Dario Domizioli33c17872014-05-28 14:06:38 +00002586
Peter Collingbournec4122c12015-06-15 21:08:13 +00002587Use ``__has_feature(safe_stack)`` to check if the code is being built
2588with :doc:`SafeStack`.
2589
Dario Domizioli33c17872014-05-28 14:06:38 +00002590
2591Extensions for selectively disabling optimization
2592=================================================
2593
2594Clang provides a mechanism for selectively disabling optimizations in functions
2595and methods.
2596
2597To disable optimizations in a single function definition, the GNU-style or C++11
2598non-standard attribute ``optnone`` can be used.
2599
2600.. code-block:: c++
2601
2602 // The following functions will not be optimized.
2603 // GNU-style attribute
2604 __attribute__((optnone)) int foo() {
2605 // ... code
2606 }
2607 // C++11 attribute
2608 [[clang::optnone]] int bar() {
2609 // ... code
2610 }
2611
2612To facilitate disabling optimization for a range of function definitions, a
2613range-based pragma is provided. Its syntax is ``#pragma clang optimize``
2614followed by ``off`` or ``on``.
2615
2616All function definitions in the region between an ``off`` and the following
2617``on`` will be decorated with the ``optnone`` attribute unless doing so would
2618conflict with explicit attributes already present on the function (e.g. the
2619ones that control inlining).
2620
2621.. code-block:: c++
2622
2623 #pragma clang optimize off
2624 // This function will be decorated with optnone.
2625 int foo() {
2626 // ... code
2627 }
2628
2629 // optnone conflicts with always_inline, so bar() will not be decorated.
2630 __attribute__((always_inline)) int bar() {
2631 // ... code
2632 }
2633 #pragma clang optimize on
2634
2635If no ``on`` is found to close an ``off`` region, the end of the region is the
2636end of the compilation unit.
2637
2638Note that a stray ``#pragma clang optimize on`` does not selectively enable
2639additional optimizations when compiling at low optimization levels. This feature
2640can only be used to selectively disable optimizations.
2641
2642The pragma has an effect on functions only at the point of their definition; for
2643function templates, this means that the state of the pragma at the point of an
2644instantiation is not necessarily relevant. Consider the following example:
2645
2646.. code-block:: c++
2647
2648 template<typename T> T twice(T t) {
2649 return 2 * t;
2650 }
2651
2652 #pragma clang optimize off
2653 template<typename T> T thrice(T t) {
2654 return 3 * t;
2655 }
2656
2657 int container(int a, int b) {
2658 return twice(a) + thrice(b);
2659 }
2660 #pragma clang optimize on
2661
2662In this example, the definition of the template function ``twice`` is outside
2663the pragma region, whereas the definition of ``thrice`` is inside the region.
2664The ``container`` function is also in the region and will not be optimized, but
2665it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
2666these two instantiations, ``twice`` will be optimized (because its definition
2667was outside the region) and ``thrice`` will not be optimized.
Tyler Nowickidb2668a2014-06-18 00:51:32 +00002668
2669Extensions for loop hint optimizations
2670======================================
2671
2672The ``#pragma clang loop`` directive is used to specify hints for optimizing the
2673subsequent for, while, do-while, or c++11 range-based for loop. The directive
Adam Nemet2de463e2016-06-14 12:04:26 +00002674provides options for vectorization, interleaving, unrolling and
2675distribution. Loop hints can be specified before any loop and will be ignored if
2676the optimization is not safe to apply.
Eli Bendersky778268d2014-06-19 18:12:44 +00002677
2678Vectorization and Interleaving
2679------------------------------
Tyler Nowickidb2668a2014-06-18 00:51:32 +00002680
2681A vectorized loop performs multiple iterations of the original loop
2682in parallel using vector instructions. The instruction set of the target
2683processor determines which vector instructions are available and their vector
2684widths. This restricts the types of loops that can be vectorized. The vectorizer
2685automatically determines if the loop is safe and profitable to vectorize. A
2686vector instruction cost model is used to select the vector width.
2687
2688Interleaving multiple loop iterations allows modern processors to further
2689improve instruction-level parallelism (ILP) using advanced hardware features,
2690such as multiple execution units and out-of-order execution. The vectorizer uses
2691a cost model that depends on the register pressure and generated code size to
2692select the interleaving count.
2693
2694Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
2695by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
2696manually enable vectorization or interleaving.
2697
2698.. code-block:: c++
2699
2700 #pragma clang loop vectorize(enable)
2701 #pragma clang loop interleave(enable)
2702 for(...) {
2703 ...
2704 }
2705
2706The vector width is specified by ``vectorize_width(_value_)`` and the interleave
2707count is specified by ``interleave_count(_value_)``, where
2708_value_ is a positive integer. This is useful for specifying the optimal
2709width/count of the set of target architectures supported by your application.
2710
2711.. code-block:: c++
2712
Tyler Nowickidb2668a2014-06-18 00:51:32 +00002713 #pragma clang loop vectorize_width(2)
2714 #pragma clang loop interleave_count(2)
2715 for(...) {
2716 ...
2717 }
2718
2719Specifying a width/count of 1 disables the optimization, and is equivalent to
2720``vectorize(disable)`` or ``interleave(disable)``.
2721
Eli Bendersky778268d2014-06-19 18:12:44 +00002722Loop Unrolling
2723--------------
2724
2725Unrolling a loop reduces the loop control overhead and exposes more
2726opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
2727eliminates the loop and replaces it with an enumerated sequence of loop
2728iterations. Full unrolling is only possible if the loop trip count is known at
2729compile time. Partial unrolling replicates the loop body within the loop and
2730reduces the trip count.
2731
Mark Heffernan397a98d2015-08-10 17:29:39 +00002732If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
Mark Heffernan7ccb5e22015-07-13 18:31:37 +00002733loop if the trip count is known at compile time. If the fully unrolled code size
2734is greater than an internal limit the loop will be partially unrolled up to this
Mark Heffernan397a98d2015-08-10 17:29:39 +00002735limit. If the trip count is not known at compile time the loop will be partially
2736unrolled with a heuristically chosen unroll factor.
2737
2738.. code-block:: c++
2739
2740 #pragma clang loop unroll(enable)
2741 for(...) {
2742 ...
2743 }
2744
2745If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
2746loop if the trip count is known at compile time identically to
2747``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
2748if the loop count is not known at compile time.
Eli Bendersky778268d2014-06-19 18:12:44 +00002749
2750.. code-block:: c++
2751
Mark Heffernan450c2382014-07-23 17:31:31 +00002752 #pragma clang loop unroll(full)
Eli Bendersky778268d2014-06-19 18:12:44 +00002753 for(...) {
2754 ...
2755 }
2756
2757The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
2758_value_ is a positive integer. If this value is greater than the trip count the
2759loop will be fully unrolled. Otherwise the loop is partially unrolled subject
Mark Heffernan397a98d2015-08-10 17:29:39 +00002760to the same code size limit as with ``unroll(enable)``.
Eli Bendersky778268d2014-06-19 18:12:44 +00002761
2762.. code-block:: c++
2763
2764 #pragma clang loop unroll_count(8)
2765 for(...) {
2766 ...
2767 }
2768
2769Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
2770
Adam Nemet2de463e2016-06-14 12:04:26 +00002771Loop Distribution
2772-----------------
2773
2774Loop Distribution allows splitting a loop into multiple loops. This is
2775beneficial for example when the entire loop cannot be vectorized but some of the
2776resulting loops can.
2777
Adam Nemet0c58eb72016-06-14 19:33:16 +00002778If ``distribute(enable))`` is specified and the loop has memory dependencies
Adam Nemet2de463e2016-06-14 12:04:26 +00002779that inhibit vectorization, the compiler will attempt to isolate the offending
2780operations into a new loop. This optimization is not enabled by default, only
2781loops marked with the pragma are considered.
2782
2783.. code-block:: c++
2784
2785 #pragma clang loop distribute(enable)
2786 for (i = 0; i < N; ++i) {
2787 S1: A[i + 1] = A[i] + B[i];
2788 S2: C[i] = D[i] * E[i];
2789 }
2790
2791This loop will be split into two loops between statements S1 and S2. The
2792second loop containing S2 will be vectorized.
2793
2794Loop Distribution is currently not enabled by default in the optimizer because
2795it can hurt performance in some cases. For example, instruction-level
2796parallelism could be reduced by sequentializing the execution of the
2797statements S1 and S2 above.
2798
2799If Loop Distribution is turned on globally with
2800``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
2801be used the disable it on a per-loop basis.
2802
Eli Bendersky778268d2014-06-19 18:12:44 +00002803Additional Information
2804----------------------
2805
Tyler Nowickidb2668a2014-06-18 00:51:32 +00002806For convenience multiple loop hints can be specified on a single line.
2807
2808.. code-block:: c++
2809
2810 #pragma clang loop vectorize_width(4) interleave_count(8)
2811 for(...) {
2812 ...
2813 }
2814
2815If an optimization cannot be applied any hints that apply to it will be ignored.
2816For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
2817proven safe to vectorize. To identify and diagnose optimization issues use
2818`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
2819user guide for details.
Adam Nemet60d32642017-04-04 21:18:36 +00002820
2821Extensions to specify floating-point flags
2822====================================================
2823
2824The ``#pragma clang fp`` pragma allows floating-point options to be specified
2825for a section of the source code. This pragma can only appear at file scope or
2826at the start of a compound statement (excluding comments). When using within a
2827compound statement, the pragma is active within the scope of the compound
2828statement.
2829
2830Currently, only FP contraction can be controlled with the pragma. ``#pragma
2831clang fp contract`` specifies whether the compiler should contract a multiply
2832and an addition (or subtraction) into a fused FMA operation when supported by
2833the target.
2834
2835The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on``
2836option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
2837fusion as specified the language standard. The ``fast`` option allows fusiong
2838in cases when the language standard does not make this possible (e.g. across
2839statements in C)
2840
2841.. code-block:: c++
2842
2843 for(...) {
2844 #pragma clang fp contract(fast)
2845 a = b[i] * c[i];
2846 d[i] += a;
2847 }
2848
2849
Adam Nemete73e00c2017-04-04 22:45:20 +00002850The pragma can also be used with ``off`` which turns FP contraction off for a
Adam Nemet60d32642017-04-04 21:18:36 +00002851section of the code. This can be useful when fast contraction is otherwise
Adam Nemetd7f95112017-04-04 23:46:34 +00002852enabled for the translation unit with the ``-ffp-contract=fast`` flag.
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002853
2854Specifying an attribute for multiple declarations (#pragma clang attribute)
2855===========================================================================
2856
2857The ``#pragma clang attribute`` directive can be used to apply an attribute to
2858multiple declarations. The ``#pragma clang attribute push`` variation of the
Erik Pilkington7d180942018-10-29 17:38:42 +00002859directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
2860can be added to. The ``#pragma clang attribute (...)`` variation adds an
2861attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
2862the scope. You can also use ``#pragma clang attribute push (...)``, which is a
2863shorthand for when you want to add one attribute to a new scope. Multiple push
2864directives can be nested inside each other.
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002865
2866The attributes that are used in the ``#pragma clang attribute`` directives
2867can be written using the GNU-style syntax:
2868
2869.. code-block:: c++
2870
Erik Pilkington7d180942018-10-29 17:38:42 +00002871 #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002872
2873 void function(); // The function now has the annotate("custom") attribute
2874
2875 #pragma clang attribute pop
2876
2877The attributes can also be written using the C++11 style syntax:
2878
2879.. code-block:: c++
2880
Erik Pilkington7d180942018-10-29 17:38:42 +00002881 #pragma clang attribute push ([[noreturn]], apply_to = function)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002882
2883 void function(); // The function now has the [[noreturn]] attribute
2884
2885 #pragma clang attribute pop
2886
2887The ``__declspec`` style syntax is also supported:
2888
2889.. code-block:: c++
2890
Erik Pilkington7d180942018-10-29 17:38:42 +00002891 #pragma clang attribute push (__declspec(dllexport), apply_to = function)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002892
2893 void function(); // The function now has the __declspec(dllexport) attribute
2894
2895 #pragma clang attribute pop
2896
2897A single push directive accepts only one attribute regardless of the syntax
2898used.
2899
Erik Pilkington0876cae2018-12-20 22:32:04 +00002900Because multiple push directives can be nested, if you're writing a macro that
2901expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
2902required) to add a namespace to your push/pop directives. A pop directive with a
2903namespace will pop the innermost push that has that same namespace. This will
2904ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
2905that an ``pop`` without a namespace will pop the innermost ``push`` without a
2906namespace. ``push``es with a namespace can only be popped by ``pop`` with the
2907same namespace. For instance:
2908
2909.. code-block:: c++
2910
2911 #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
2912 #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop")
2913
2914 #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
2915 #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop")
2916
2917
2918 ASSUME_NORETURN_BEGIN
2919 ASSUME_UNAVAILABLE_BEGIN
2920 void function(); // function has [[noreturn]] and __attribute__((unavailable))
2921 ASSUME_NORETURN_END
2922 void other_function(); // function has __attribute__((unavailable))
2923 ASSUME_UNAVAILABLE_END
2924
2925Without the namespaces on the macros, ``other_function`` will be annotated with
2926``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
2927a contrived example, but its very possible for this kind of situation to appear
Erik Pilkingtonb460f162019-01-07 21:54:00 +00002928in real code if the pragmas are spread out across a large file. You can test if
2929your version of clang supports namespaces on ``#pragma clang attribute`` with
Erik Pilkington6ccc1732019-01-08 18:24:39 +00002930``__has_extension(pragma_clang_attribute_namespaces)``.
Erik Pilkington0876cae2018-12-20 22:32:04 +00002931
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002932Subject Match Rules
2933-------------------
2934
2935The set of declarations that receive a single attribute from the attribute stack
2936depends on the subject match rules that were specified in the pragma. Subject
2937match rules are specified after the attribute. The compiler expects an
2938identifier that corresponds to the subject set specifier. The ``apply_to``
2939specifier is currently the only supported subject set specifier. It allows you
2940to specify match rules that form a subset of the attribute's allowed subject
2941set, i.e. the compiler doesn't require all of the attribute's subjects. For
2942example, an attribute like ``[[nodiscard]]`` whose subject set includes
2943``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
2944least one of these rules after ``apply_to``:
2945
2946.. code-block:: c++
2947
2948 #pragma clang attribute push([[nodiscard]], apply_to = enum)
2949
2950 enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
2951
2952 struct Record1 { }; // The struct will *not* receive [[nodiscard]]
2953
2954 #pragma clang attribute pop
2955
2956 #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
2957
2958 enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
2959
2960 struct Record2 { }; // The struct *will* receive [[nodiscard]]
2961
2962 #pragma clang attribute pop
2963
2964 // This is an error, since [[nodiscard]] can't be applied to namespaces:
2965 #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
2966
2967 #pragma clang attribute pop
2968
2969Multiple match rules can be specified using the ``any`` match rule, as shown
2970in the example above. The ``any`` rule applies attributes to all declarations
2971that are matched by at least one of the rules in the ``any``. It doesn't nest
2972and can't be used inside the other match rules. Redundant match rules or rules
2973that conflict with one another should not be used inside of ``any``.
2974
2975Clang supports the following match rules:
2976
2977- ``function``: Can be used to apply attributes to functions. This includes C++
2978 member functions, static functions, operators, and constructors/destructors.
2979
2980- ``function(is_member)``: Can be used to apply attributes to C++ member
2981 functions. This includes members like static functions, operators, and
2982 constructors/destructors.
2983
2984- ``hasType(functionType)``: Can be used to apply attributes to functions, C++
2985 member functions, and variables/fields whose type is a function pointer. It
2986 does not apply attributes to Objective-C methods or blocks.
2987
2988- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
2989 and C++11 type aliases.
2990
2991- ``record``: Can be used to apply attributes to ``struct``, ``class``, and
2992 ``union`` declarations.
2993
2994- ``record(unless(is_union))``: Can be used to apply attributes only to
2995 ``struct`` and ``class`` declarations.
2996
2997- ``enum``: Can be be used to apply attributes to enumeration declarations.
2998
2999- ``enum_constant``: Can be used to apply attributes to enumerators.
3000
3001- ``variable``: Can be used to apply attributes to variables, including
3002 local variables, parameters, global variables, and static member variables.
3003 It does not apply attributes to instance member variables or Objective-C
3004 ivars.
3005
3006- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
3007 variables only.
3008
3009- ``variable(is_global)``: Can be used to apply attributes to global variables
3010 only.
3011
3012- ``variable(is_parameter)``: Can be used to apply attributes to parameters
3013 only.
3014
3015- ``variable(unless(is_parameter))``: Can be used to apply attributes to all
3016 the variables that are not parameters.
3017
3018- ``field``: Can be used to apply attributes to non-static member variables
3019 in a record. This includes Objective-C ivars.
3020
3021- ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
3022
3023- ``objc_interface``: Can be used to apply attributes to ``@interface``
3024 declarations.
3025
3026- ``objc_protocol``: Can be used to apply attributes to ``@protocol``
3027 declarations.
3028
3029- ``objc_category``: Can be used to apply attributes to category declarations,
3030 including class extensions.
3031
3032- ``objc_method``: Can be used to apply attributes to Objective-C methods,
3033 including instance and class methods. Implicit methods like implicit property
3034 getters and setters do not receive the attribute.
3035
3036- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
3037 instance methods.
3038
3039- ``objc_property``: Can be used to apply attributes to ``@property``
3040 declarations.
3041
3042- ``block``: Can be used to apply attributes to block declarations. This does
3043 not include variables/fields of block pointer type.
3044
3045The use of ``unless`` in match rules is currently restricted to a strict set of
3046sub-rules that are used by the supported attributes. That means that even though
3047``variable(unless(is_parameter))`` is a valid match rule,
3048``variable(unless(is_thread_local))`` is not.
3049
3050Supported Attributes
3051--------------------
3052
3053Not all attributes can be used with the ``#pragma clang attribute`` directive.
3054Notably, statement attributes like ``[[fallthrough]]`` or type attributes
3055like ``address_space`` aren't supported by this directive. You can determine
3056whether or not an attribute is supported by the pragma by referring to the
3057:doc:`individual documentation for that attribute <AttributeReference>`.
3058
3059The attributes are applied to all matching declarations individually, even when
3060the attribute is semantically incorrect. The attributes that aren't applied to
3061any declaration are not verified semantically.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003062
3063Specifying section names for global objects (#pragma clang section)
3064===================================================================
3065
3066The ``#pragma clang section`` directive provides a means to assign section-names
3067to global variables, functions and static variables.
3068
3069The section names can be specified as:
3070
3071.. code-block:: c++
3072
3073 #pragma clang section bss="myBSS" data="myData" rodata="myRodata" text="myText"
3074
3075The section names can be reverted back to default name by supplying an empty
3076string to the section kind, for example:
3077
3078.. code-block:: c++
3079
3080 #pragma clang section bss="" data="" text="" rodata=""
3081
3082The ``#pragma clang section`` directive obeys the following rules:
3083
3084* The pragma applies to all global variable, statics and function declarations
3085 from the pragma to the end of the translation unit.
3086
3087* The pragma clang section is enabled automatically, without need of any flags.
3088
3089* This feature is only defined to work sensibly for ELF targets.
3090
3091* If section name is specified through _attribute_((section("myname"))), then
3092 the attribute name gains precedence.
3093
3094* Global variables that are initialized to zero will be placed in the named
3095 bss section, if one is present.
3096
3097* The ``#pragma clang section`` directive does not does try to infer section-kind
3098 from the name. For example, naming a section "``.bss.mySec``" does NOT mean
3099 it will be a bss section name.
3100
3101* The decision about which section-kind applies to each global is taken in the back-end.
3102 Once the section-kind is known, appropriate section name, as specified by the user using
3103 ``#pragma clang section`` directive, is applied to that global.
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00003104
3105Specifying Linker Options on ELF Targets
3106========================================
3107
3108The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
3109The second parameter is the library name (without the traditional Unix prefix of
3110``lib``). This allows you to provide an implicit link of dependent libraries.
Erik Pilkington9c3b5882019-01-30 20:34:53 +00003111
3112Evaluating Object Size Dynamically
3113==================================
3114
3115Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are
3116the same as GCC's ``__builtin_object_size`` (which Clang also supports), but
3117``__builtin_dynamic_object_size`` can evaluate the object's size at runtime.
3118``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement
3119for ``__builtin_object_size`` in libraries that support it.
3120
3121For instance, here is a program that ``__builtin_dynamic_object_size`` will make
3122safer:
3123
3124.. code-block:: c
3125
3126 void copy_into_buffer(size_t size) {
3127 char* buffer = malloc(size);
3128 strlcpy(buffer, "some string", strlen("some string"));
3129 // Previous line preprocesses to:
3130 // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
3131 }
3132
3133Since the size of ``buffer`` can't be known at compile time, Clang will fold
3134``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
3135as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
3136``size``, providing some extra runtime safety.