1 | ========================= |
2 | Clang Language Extensions |
3 | ========================= |
4 | |
5 | .. contents:: |
6 | :local: |
7 | :depth: 1 |
8 | |
9 | .. toctree:: |
10 | :hidden: |
11 | |
12 | ObjectiveCLiterals |
13 | BlockLanguageSpec |
14 | Block-ABI-Apple |
15 | AutomaticReferenceCounting |
16 | |
17 | Introduction |
18 | ============ |
19 | |
20 | This document describes the language extensions provided by Clang. In addition |
21 | to the language extensions listed here, Clang aims to support a broad range of |
22 | GCC extensions. Please see the `GCC manual |
23 | <https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on |
24 | these extensions. |
25 | |
26 | .. _langext-feature_check: |
27 | |
28 | Feature Checking Macros |
29 | ======================= |
30 | |
31 | Language extensions can be very useful, but only if you know you can depend on |
32 | them. In order to allow fine-grain features checks, we support three builtin |
33 | function-like macros. This allows you to directly test for a feature in your |
34 | code without having to resort to something like autoconf or fragile "compiler |
35 | version checks". |
36 | |
37 | ``__has_builtin`` |
38 | ----------------- |
39 | |
40 | This function-like macro takes a single identifier argument that is the name of |
41 | a builtin function. It evaluates to 1 if the builtin is supported or 0 if not. |
42 | It 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 | |
63 | These function-like macros take a single identifier argument that is the name |
64 | of a feature. ``__has_feature`` evaluates to 1 if the feature is both |
65 | supported by Clang and standardized in the current language standard or 0 if |
66 | not (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 |
68 | current language (either as a language extension or a standard language |
69 | feature) 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 | |
94 | For backward compatibility, ``__has_feature`` can also be used to test |
95 | for support for non-standardized features, i.e. features not prefixed ``c_``, |
96 | ``cxx_`` or ``objc_``. |
97 | |
98 | Another use of ``__has_feature`` is to check for compiler features not related |
99 | to the language standard, such as e.g. :doc:`AddressSanitizer |
100 | <AddressSanitizer>`. |
101 | |
102 | If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent |
103 | to ``__has_feature``. |
104 | |
105 | The feature tag is described along with the language feature below. |
106 | |
107 | The feature name or extension name can also be specified with a preceding and |
108 | following ``__`` (double underscore) to avoid interference from a macro with |
109 | the same name. For instance, ``__cxx_rvalue_references__`` can be used instead |
110 | of ``cxx_rvalue_references``. |
111 | |
112 | ``__has_cpp_attribute`` |
113 | ----------------------- |
114 | |
115 | This function-like macro is available in C++2a by default, and is provided as an |
116 | extension in earlier language standards. It takes a single argument that is the |
117 | name of a double-square-bracket-style attribute. The argument can either be a |
118 | single identifier or a scoped identifier. If the attribute is supported, a |
119 | nonzero value is returned. If the attribute is a standards-based attribute, this |
120 | macro returns a nonzero value based on the year and month in which the attribute |
121 | was voted into the working draft. See `WG21 SD-6 |
122 | <https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_ |
123 | for the list of values returned for standards-based attributes. If the attribute |
124 | is not supported by the current compliation target, this macro evaluates to 0. |
125 | It can be used like this: |
126 | |
127 | .. code-block:: c++ |
128 | |
129 | #ifndef __has_cpp_attribute // For backwards compatibility |
130 | #define __has_cpp_attribute(x) 0 |
131 | #endif |
132 | |
133 | ... |
134 | #if __has_cpp_attribute(clang::fallthrough) |
135 | #define FALLTHROUGH [[clang::fallthrough]] |
136 | #else |
137 | #define FALLTHROUGH |
138 | #endif |
139 | ... |
140 | |
141 | The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are |
142 | the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either |
143 | of these namespaces can be specified with a preceding and following ``__`` |
144 | (double underscore) to avoid interference from a macro with the same name. For |
145 | instance, ``gnu::__const__`` can be used instead of ``gnu::const``. |
146 | |
147 | ``__has_c_attribute`` |
148 | --------------------- |
149 | |
150 | This function-like macro takes a single argument that is the name of an |
151 | attribute exposed with the double square-bracket syntax in C mode. The argument |
152 | can either be a single identifier or a scoped identifier. If the attribute is |
153 | supported, a nonzero value is returned. If the attribute is not supported by the |
154 | current 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 | |
170 | The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are |
171 | the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either |
172 | of these namespaces can be specified with a preceding and following ``__`` |
173 | (double underscore) to avoid interference from a macro with the same name. For |
174 | instance, ``gnu::__const__`` can be used instead of ``gnu::const``. |
175 | |
176 | ``__has_attribute`` |
177 | ------------------- |
178 | |
179 | This function-like macro takes a single identifier argument that is the name of |
180 | a GNU-style attribute. It evaluates to 1 if the attribute is supported by the |
181 | current compilation target, or 0 if not. It can be used like this: |
182 | |
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 | |
197 | The 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 |
199 | instance, ``__always_inline__`` can be used instead of ``always_inline``. |
200 | |
201 | |
202 | ``__has_declspec_attribute`` |
203 | ---------------------------- |
204 | |
205 | This function-like macro takes a single identifier argument that is the name of |
206 | an attribute implemented as a Microsoft-style ``__declspec`` attribute. It |
207 | evaluates to 1 if the attribute is supported by the current compilation target, |
208 | or 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 | |
224 | The 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 |
226 | instance, ``__dllexport__`` can be used instead of ``dllexport``. |
227 | |
228 | ``__is_identifier`` |
229 | ------------------- |
230 | |
231 | This function-like macro takes a single identifier argument that might be either |
232 | a reserved word or a regular identifier. It evaluates to 1 if the argument is just |
233 | a regular identifier and not a reserved word, in the sense that it can then be |
234 | used as the name of a user-defined function or variable. Otherwise it evaluates |
235 | to 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 | ... |
248 | |
249 | Include File Checking Macros |
250 | ============================ |
251 | |
252 | Not all developments systems have the same include files. The |
253 | :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow |
254 | you to check for the existence of an include file before doing a possibly |
255 | failing ``#include`` directive. Include file checking macros must be used |
256 | as expressions in ``#if`` or ``#elif`` preprocessing directives. |
257 | |
258 | .. _langext-__has_include: |
259 | |
260 | ``__has_include`` |
261 | ----------------- |
262 | |
263 | This function-like macro takes a single file name string argument that is the |
264 | name of an include file. It evaluates to 1 if the file can be found using the |
265 | include 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 | |
274 | To test for this feature, use ``#if defined(__has_include)``: |
275 | |
276 | .. code-block:: c++ |
277 | |
278 | // To avoid problem with non-clang compilers not having this macro. |
279 | #if defined(__has_include) |
280 | #if __has_include("myinclude.h") |
281 | # include "myinclude.h" |
282 | #endif |
283 | #endif |
284 | |
285 | .. _langext-__has_include_next: |
286 | |
287 | ``__has_include_next`` |
288 | ---------------------- |
289 | |
290 | This function-like macro takes a single file name string argument that is the |
291 | name of an include file. It is like ``__has_include`` except that it looks for |
292 | the second instance of the given file found in the include paths. It evaluates |
293 | to 1 if the second instance of the file can be found using the include paths, |
294 | or 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. |
304 | #if defined(__has_include_next) |
305 | #if __has_include_next("myinclude.h") |
306 | # include_next "myinclude.h" |
307 | #endif |
308 | #endif |
309 | |
310 | Note that ``__has_include_next``, like the GNU extension ``#include_next`` |
311 | directive, is intended for use in headers only, and will issue a warning if |
312 | used in the top-level compilation file. A warning will also be issued if an |
313 | absolute path is used in the file argument. |
314 | |
315 | ``__has_warning`` |
316 | ----------------- |
317 | |
318 | This function-like macro takes a string literal that represents a command line |
319 | option 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 | |
327 | Builtin Macros |
328 | ============== |
329 | |
330 | ``__BASE_FILE__`` |
331 | Defined to a string that contains the name of the main input file passed to |
332 | Clang. |
333 | |
334 | ``__COUNTER__`` |
335 | Defined to an integer value that starts at zero and is incremented each time |
336 | the ``__COUNTER__`` macro is expanded. |
337 | |
338 | ``__INCLUDE_LEVEL__`` |
339 | Defined to an integral value that is the include depth of the file currently |
340 | being translated. For the main file, this value is zero. |
341 | |
342 | ``__TIMESTAMP__`` |
343 | Defined to the date and time of the last modification of the current source |
344 | file. |
345 | |
346 | ``__clang__`` |
347 | Defined when compiling with Clang |
348 | |
349 | ``__clang_major__`` |
350 | Defined to the major marketing version number of Clang (e.g., the 2 in |
351 | 2.0.1). Note that marketing version numbers should not be used to check for |
352 | language features, as different vendors use different numbering schemes. |
353 | Instead, use the :ref:`langext-feature_check`. |
354 | |
355 | ``__clang_minor__`` |
356 | Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note |
357 | that marketing version numbers should not be used to check for language |
358 | features, as different vendors use different numbering schemes. Instead, use |
359 | the :ref:`langext-feature_check`. |
360 | |
361 | ``__clang_patchlevel__`` |
362 | Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). |
363 | |
364 | ``__clang_version__`` |
365 | Defined to a string that captures the Clang marketing version, including the |
366 | Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". |
367 | |
368 | .. _langext-vectors: |
369 | |
370 | Vectors and Extended Vectors |
371 | ============================ |
372 | |
373 | Supports the GCC, OpenCL, AltiVec and NEON vector extensions. |
374 | |
375 | OpenCL vector types are created using ``ext_vector_type`` attribute. It |
376 | support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example |
377 | is: |
378 | |
379 | .. code-block:: c++ |
380 | |
381 | typedef float float4 __attribute__((ext_vector_type(4))); |
382 | typedef float float2 __attribute__((ext_vector_type(2))); |
383 | |
384 | float4 foo(float2 a, float2 b) { |
385 | float4 c; |
386 | c.xz = a; |
387 | c.yw = b; |
388 | return c; |
389 | } |
390 | |
391 | Query for this feature with ``__has_extension(attribute_ext_vector_type)``. |
392 | |
393 | Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax |
394 | and functions. For example: |
395 | |
396 | .. code-block:: c++ |
397 | |
398 | vector float foo(vector int a) { |
399 | vector int b; |
400 | b = vec_add(a, a) + a; |
401 | return (vector float)b; |
402 | } |
403 | |
404 | NEON vector types are created using ``neon_vector_type`` and |
405 | ``neon_polyvector_type`` attributes. For example: |
406 | |
407 | .. code-block:: c++ |
408 | |
409 | typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; |
410 | typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; |
411 | |
412 | int8x8_t foo(int8x8_t a) { |
413 | int8x8_t v; |
414 | v = a; |
415 | return v; |
416 | } |
417 | |
418 | Vector Literals |
419 | --------------- |
420 | |
421 | Vector literals can be used to create vectors from a set of scalars, or |
422 | vectors. Either parentheses or braces form can be used. In the parentheses |
423 | form the number of literal values specified must be one, i.e. referring to a |
424 | scalar value, or must match the size of the vector type being created. If a |
425 | single scalar literal value is specified, the scalar literal value will be |
426 | replicated to all the components of the vector type. In the brackets form any |
427 | number of literals can be specified. For example: |
428 | |
429 | .. code-block:: c++ |
430 | |
431 | typedef int v4si __attribute__((__vector_size__(16))); |
432 | typedef float float4 __attribute__((ext_vector_type(4))); |
433 | typedef float float2 __attribute__((ext_vector_type(2))); |
434 | |
435 | v4si vsi = (v4si){1, 2, 3, 4}; |
436 | float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); |
437 | vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). |
438 | vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). |
439 | vector int vi3 = (vector int)(1, 2); // error |
440 | vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). |
441 | vector int vi5 = (vector int)(1, 2, 3, 4); |
442 | float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); |
443 | |
444 | Vector Operations |
445 | ----------------- |
446 | |
447 | The table below shows the support for each operation by vector extension. A |
448 | dash indicates that an operation is not accepted according to a corresponding |
449 | specification. |
450 | |
451 | ============================== ======= ======= ======= ======= |
452 | Operator OpenCL AltiVec GCC NEON |
453 | ============================== ======= ======= ======= ======= |
454 | [] yes yes yes -- |
455 | unary operators +, -- yes yes yes -- |
456 | ++, -- -- yes yes yes -- |
457 | +,--,*,/,% yes yes yes -- |
458 | bitwise operators &,|,^,~ yes yes yes -- |
459 | >>,<< yes yes yes -- |
460 | !, &&, || yes -- -- -- |
461 | ==, !=, >, <, >=, <= yes yes -- -- |
462 | = yes yes yes yes |
463 | :? yes -- -- -- |
464 | sizeof yes yes yes yes |
465 | C-style cast yes yes yes no |
466 | reinterpret_cast yes no yes no |
467 | static_cast yes no yes no |
468 | const_cast no no no no |
469 | ============================== ======= ======= ======= ======= |
470 | |
471 | See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`. |
472 | |
473 | Half-Precision Floating Point |
474 | ============================= |
475 | |
476 | Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and |
477 | ``_Float16``. These types are supported in all language modes. |
478 | |
479 | ``__fp16`` is supported on every target, as it is purely a storage format; see below. |
480 | ``_Float16`` is currently only supported on the following targets, with further |
481 | targets pending ABI standardization: |
482 | - 32-bit ARM |
483 | - 64-bit ARM (AArch64) |
484 | - SPIR |
485 | ``_Float16`` will be supported on more targets as they define ABIs for it. |
486 | |
487 | ``__fp16`` is a storage and interchange format only. This means that values of |
488 | ``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic |
489 | operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``. |
490 | The 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>`_). |
491 | Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM |
492 | alternative format. |
493 | |
494 | ``_Float16`` is an extended floating-point type. This means that, just like arithmetic on |
495 | ``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the |
496 | ``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type |
497 | ``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015 |
498 | ("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16`` |
499 | format from IEEE 754-2008 for ``_Float16``. |
500 | |
501 | ``_Float16`` arithmetic will be performed using native half-precision support |
502 | when available on the target (e.g. on ARMv8.2a); otherwise it will be performed |
503 | at a higher precision (currently always ``float``) and then truncated down to |
504 | ``_Float16``. Note that C and C++ allow intermediate floating-point operands |
505 | of an expression to be computed with greater precision than is expressible in |
506 | their type, so Clang may avoid intermediate truncations in certain cases; this may |
507 | lead to results that are inconsistent with native arithmetic. |
508 | |
509 | It is recommended that portable code use ``_Float16`` instead of ``__fp16``, |
510 | as it has been defined by the C standards committee and has behavior that is |
511 | more familiar to most programmers. |
512 | |
513 | Because ``__fp16`` operands are always immediately promoted to ``float``, the |
514 | common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual |
515 | arithmetic conversions is ``float``. |
516 | |
517 | A literal can be given ``_Float16`` type using the suffix ``f16``; for example: |
518 | ``` |
519 | 3.14f16 |
520 | ``` |
521 | |
522 | Because default argument promotion only applies to the standard floating-point |
523 | types, ``_Float16`` values are not promoted to ``double`` when passed as variadic |
524 | or untyped arguments. As a consequence, some caution must be taken when using |
525 | certain library facilities with ``_Float16``; for example, there is no ``printf`` format |
526 | specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to |
527 | ``double`` when passed to ``printf``, so the programmer must explicitly cast it to |
528 | ``double`` before using it with an ``%f`` or similar specifier. |
529 | |
530 | Messages on ``deprecated`` and ``unavailable`` Attributes |
531 | ========================================================= |
532 | |
533 | An optional string message can be added to the ``deprecated`` and |
534 | ``unavailable`` attributes. For example: |
535 | |
536 | .. code-block:: c++ |
537 | |
538 | void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); |
539 | |
540 | If the deprecated or unavailable declaration is used, the message will be |
541 | incorporated into the appropriate diagnostic: |
542 | |
543 | .. code-block:: none |
544 | |
545 | harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! |
546 | [-Wdeprecated-declarations] |
547 | explode(); |
548 | ^ |
549 | |
550 | Query for this feature with |
551 | ``__has_extension(attribute_deprecated_with_message)`` and |
552 | ``__has_extension(attribute_unavailable_with_message)``. |
553 | |
554 | Attributes on Enumerators |
555 | ========================= |
556 | |
557 | Clang allows attributes to be written on individual enumerators. This allows |
558 | enumerators to be deprecated, made unavailable, etc. The attribute must appear |
559 | after the enumerator name and before any initializer, like so: |
560 | |
561 | .. code-block:: c++ |
562 | |
563 | enum OperationMode { |
564 | OM_Invalid, |
565 | OM_Normal, |
566 | OM_Terrified __attribute__((deprecated)), |
567 | OM_AbortOnError __attribute__((deprecated)) = 4 |
568 | }; |
569 | |
570 | Attributes on the ``enum`` declaration do not apply to individual enumerators. |
571 | |
572 | Query for this feature with ``__has_extension(enumerator_attributes)``. |
573 | |
574 | 'User-Specified' System Frameworks |
575 | ================================== |
576 | |
577 | Clang provides a mechanism by which frameworks can be built in such a way that |
578 | they will always be treated as being "system frameworks", even if they are not |
579 | present in a system framework directory. This can be useful to system |
580 | framework developers who want to be able to test building other applications |
581 | with development builds of their framework, including the manner in which the |
582 | compiler changes warning behavior for system headers. |
583 | |
584 | Framework developers can opt-in to this mechanism by creating a |
585 | "``.system_framework``" file at the top-level of their framework. That is, the |
586 | framework should have contents like: |
587 | |
588 | .. code-block:: none |
589 | |
590 | .../TestFramework.framework |
591 | .../TestFramework.framework/.system_framework |
592 | .../TestFramework.framework/Headers |
593 | .../TestFramework.framework/Headers/TestFramework.h |
594 | ... |
595 | |
596 | Clang will treat the presence of this file as an indicator that the framework |
597 | should be treated as a system framework, regardless of how it was found in the |
598 | framework search path. For consistency, we recommend that such files never be |
599 | included in installed versions of the framework. |
600 | |
601 | Checks for Standard Language Features |
602 | ===================================== |
603 | |
604 | The ``__has_feature`` macro can be used to query if certain standard language |
605 | features are enabled. The ``__has_extension`` macro can be used to query if |
606 | language features are available as an extension when compiling for a standard |
607 | which does not provide them. The features which can be tested are listed here. |
608 | |
609 | Since Clang 3.4, the C++ SD-6 feature test macros are also supported. |
610 | These are macros with names of the form ``__cpp_<feature_name>``, and are |
611 | intended to be a portable way to query the supported features of the compiler. |
612 | See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for |
613 | information on the version of SD-6 supported by each Clang release, and the |
614 | macros provided by that revision of the recommendations. |
615 | |
616 | C++98 |
617 | ----- |
618 | |
619 | The features listed below are part of the C++98 standard. These features are |
620 | enabled by default when compiling C++ code. |
621 | |
622 | C++ exceptions |
623 | ^^^^^^^^^^^^^^ |
624 | |
625 | Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been |
626 | enabled. For example, compiling code with ``-fno-exceptions`` disables C++ |
627 | exceptions. |
628 | |
629 | C++ RTTI |
630 | ^^^^^^^^ |
631 | |
632 | Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For |
633 | example, compiling code with ``-fno-rtti`` disables the use of RTTI. |
634 | |
635 | C++11 |
636 | ----- |
637 | |
638 | The features listed below are part of the C++11 standard. As a result, all |
639 | these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option |
640 | when compiling C++ code. |
641 | |
642 | C++11 SFINAE includes access control |
643 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
644 | |
645 | Use ``__has_feature(cxx_access_control_sfinae)`` or |
646 | ``__has_extension(cxx_access_control_sfinae)`` to determine whether |
647 | access-control errors (e.g., calling a private constructor) are considered to |
648 | be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 |
649 | <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. |
650 | |
651 | C++11 alias templates |
652 | ^^^^^^^^^^^^^^^^^^^^^ |
653 | |
654 | Use ``__has_feature(cxx_alias_templates)`` or |
655 | ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's |
656 | alias declarations and alias templates is enabled. |
657 | |
658 | C++11 alignment specifiers |
659 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
660 | |
661 | Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to |
662 | determine if support for alignment specifiers using ``alignas`` is enabled. |
663 | |
664 | Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to |
665 | determine if support for the ``alignof`` keyword is enabled. |
666 | |
667 | C++11 attributes |
668 | ^^^^^^^^^^^^^^^^ |
669 | |
670 | Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to |
671 | determine if support for attribute parsing with C++11's square bracket notation |
672 | is enabled. |
673 | |
674 | C++11 generalized constant expressions |
675 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
676 | |
677 | Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized |
678 | constant expressions (e.g., ``constexpr``) is enabled. |
679 | |
680 | C++11 ``decltype()`` |
681 | ^^^^^^^^^^^^^^^^^^^^ |
682 | |
683 | Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to |
684 | determine if support for the ``decltype()`` specifier is enabled. C++11's |
685 | ``decltype`` does not require type-completeness of a function call expression. |
686 | Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or |
687 | ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if |
688 | support for this feature is enabled. |
689 | |
690 | C++11 default template arguments in function templates |
691 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
692 | |
693 | Use ``__has_feature(cxx_default_function_template_args)`` or |
694 | ``__has_extension(cxx_default_function_template_args)`` to determine if support |
695 | for default template arguments in function templates is enabled. |
696 | |
697 | C++11 ``default``\ ed functions |
698 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
699 | |
700 | Use ``__has_feature(cxx_defaulted_functions)`` or |
701 | ``__has_extension(cxx_defaulted_functions)`` to determine if support for |
702 | defaulted function definitions (with ``= default``) is enabled. |
703 | |
704 | C++11 delegating constructors |
705 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
706 | |
707 | Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for |
708 | delegating constructors is enabled. |
709 | |
710 | C++11 ``deleted`` functions |
711 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
712 | |
713 | Use ``__has_feature(cxx_deleted_functions)`` or |
714 | ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted |
715 | function definitions (with ``= delete``) is enabled. |
716 | |
717 | C++11 explicit conversion functions |
718 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
719 | |
720 | Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for |
721 | ``explicit`` conversion functions is enabled. |
722 | |
723 | C++11 generalized initializers |
724 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
725 | |
726 | Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for |
727 | generalized initializers (using braced lists and ``std::initializer_list``) is |
728 | enabled. |
729 | |
730 | C++11 implicit move constructors/assignment operators |
731 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
732 | |
733 | Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly |
734 | generate move constructors and move assignment operators where needed. |
735 | |
736 | C++11 inheriting constructors |
737 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
738 | |
739 | Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for |
740 | inheriting constructors is enabled. |
741 | |
742 | C++11 inline namespaces |
743 | ^^^^^^^^^^^^^^^^^^^^^^^ |
744 | |
745 | Use ``__has_feature(cxx_inline_namespaces)`` or |
746 | ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline |
747 | namespaces is enabled. |
748 | |
749 | C++11 lambdas |
750 | ^^^^^^^^^^^^^ |
751 | |
752 | Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to |
753 | determine if support for lambdas is enabled. |
754 | |
755 | C++11 local and unnamed types as template arguments |
756 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
757 | |
758 | Use ``__has_feature(cxx_local_type_template_args)`` or |
759 | ``__has_extension(cxx_local_type_template_args)`` to determine if support for |
760 | local and unnamed types as template arguments is enabled. |
761 | |
762 | C++11 noexcept |
763 | ^^^^^^^^^^^^^^ |
764 | |
765 | Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to |
766 | determine if support for noexcept exception specifications is enabled. |
767 | |
768 | C++11 in-class non-static data member initialization |
769 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
770 | |
771 | Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class |
772 | initialization of non-static data members is enabled. |
773 | |
774 | C++11 ``nullptr`` |
775 | ^^^^^^^^^^^^^^^^^ |
776 | |
777 | Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to |
778 | determine if support for ``nullptr`` is enabled. |
779 | |
780 | C++11 ``override control`` |
781 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
782 | |
783 | Use ``__has_feature(cxx_override_control)`` or |
784 | ``__has_extension(cxx_override_control)`` to determine if support for the |
785 | override control keywords is enabled. |
786 | |
787 | C++11 reference-qualified functions |
788 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
789 | |
790 | Use ``__has_feature(cxx_reference_qualified_functions)`` or |
791 | ``__has_extension(cxx_reference_qualified_functions)`` to determine if support |
792 | for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` |
793 | applied to ``*this``) is enabled. |
794 | |
795 | C++11 range-based ``for`` loop |
796 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
797 | |
798 | Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to |
799 | determine if support for the range-based for loop is enabled. |
800 | |
801 | C++11 raw string literals |
802 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
803 | |
804 | Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw |
805 | string literals (e.g., ``R"x(foo\bar)x"``) is enabled. |
806 | |
807 | C++11 rvalue references |
808 | ^^^^^^^^^^^^^^^^^^^^^^^ |
809 | |
810 | Use ``__has_feature(cxx_rvalue_references)`` or |
811 | ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue |
812 | references is enabled. |
813 | |
814 | C++11 ``static_assert()`` |
815 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
816 | |
817 | Use ``__has_feature(cxx_static_assert)`` or |
818 | ``__has_extension(cxx_static_assert)`` to determine if support for compile-time |
819 | assertions using ``static_assert`` is enabled. |
820 | |
821 | C++11 ``thread_local`` |
822 | ^^^^^^^^^^^^^^^^^^^^^^ |
823 | |
824 | Use ``__has_feature(cxx_thread_local)`` to determine if support for |
825 | ``thread_local`` variables is enabled. |
826 | |
827 | C++11 type inference |
828 | ^^^^^^^^^^^^^^^^^^^^ |
829 | |
830 | Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to |
831 | determine C++11 type inference is supported using the ``auto`` specifier. If |
832 | this is disabled, ``auto`` will instead be a storage class specifier, as in C |
833 | or C++98. |
834 | |
835 | C++11 strongly typed enumerations |
836 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
837 | |
838 | Use ``__has_feature(cxx_strong_enums)`` or |
839 | ``__has_extension(cxx_strong_enums)`` to determine if support for strongly |
840 | typed, scoped enumerations is enabled. |
841 | |
842 | C++11 trailing return type |
843 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
844 | |
845 | Use ``__has_feature(cxx_trailing_return)`` or |
846 | ``__has_extension(cxx_trailing_return)`` to determine if support for the |
847 | alternate function declaration syntax with trailing return type is enabled. |
848 | |
849 | C++11 Unicode string literals |
850 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
851 | |
852 | Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode |
853 | string literals is enabled. |
854 | |
855 | C++11 unrestricted unions |
856 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
857 | |
858 | Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for |
859 | unrestricted unions is enabled. |
860 | |
861 | C++11 user-defined literals |
862 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
863 | |
864 | Use ``__has_feature(cxx_user_literals)`` to determine if support for |
865 | user-defined literals is enabled. |
866 | |
867 | C++11 variadic templates |
868 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
869 | |
870 | Use ``__has_feature(cxx_variadic_templates)`` or |
871 | ``__has_extension(cxx_variadic_templates)`` to determine if support for |
872 | variadic templates is enabled. |
873 | |
874 | C++14 |
875 | ----- |
876 | |
877 | The features listed below are part of the C++14 standard. As a result, all |
878 | these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option |
879 | when compiling C++ code. |
880 | |
881 | C++14 binary literals |
882 | ^^^^^^^^^^^^^^^^^^^^^ |
883 | |
884 | Use ``__has_feature(cxx_binary_literals)`` or |
885 | ``__has_extension(cxx_binary_literals)`` to determine whether |
886 | binary literals (for instance, ``0b10010``) are recognized. Clang supports this |
887 | feature as an extension in all language modes. |
888 | |
889 | C++14 contextual conversions |
890 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
891 | |
892 | Use ``__has_feature(cxx_contextual_conversions)`` or |
893 | ``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules |
894 | are used when performing an implicit conversion for an array bound in a |
895 | *new-expression*, the operand of a *delete-expression*, an integral constant |
896 | expression, or a condition in a ``switch`` statement. |
897 | |
898 | C++14 decltype(auto) |
899 | ^^^^^^^^^^^^^^^^^^^^ |
900 | |
901 | Use ``__has_feature(cxx_decltype_auto)`` or |
902 | ``__has_extension(cxx_decltype_auto)`` to determine if support |
903 | for the ``decltype(auto)`` placeholder type is enabled. |
904 | |
905 | C++14 default initializers for aggregates |
906 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
907 | |
908 | Use ``__has_feature(cxx_aggregate_nsdmi)`` or |
909 | ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support |
910 | for default initializers in aggregate members is enabled. |
911 | |
912 | C++14 digit separators |
913 | ^^^^^^^^^^^^^^^^^^^^^^ |
914 | |
915 | Use ``__cpp_digit_separators`` to determine if support for digit separators |
916 | using single quotes (for instance, ``10'000``) is enabled. At this time, there |
917 | is no corresponding ``__has_feature`` name |
918 | |
919 | C++14 generalized lambda capture |
920 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
921 | |
922 | Use ``__has_feature(cxx_init_captures)`` or |
923 | ``__has_extension(cxx_init_captures)`` to determine if support for |
924 | lambda captures with explicit initializers is enabled |
925 | (for instance, ``[n(0)] { return ++n; }``). |
926 | |
927 | C++14 generic lambdas |
928 | ^^^^^^^^^^^^^^^^^^^^^ |
929 | |
930 | Use ``__has_feature(cxx_generic_lambdas)`` or |
931 | ``__has_extension(cxx_generic_lambdas)`` to determine if support for generic |
932 | (polymorphic) lambdas is enabled |
933 | (for instance, ``[] (auto x) { return x + 1; }``). |
934 | |
935 | C++14 relaxed constexpr |
936 | ^^^^^^^^^^^^^^^^^^^^^^^ |
937 | |
938 | Use ``__has_feature(cxx_relaxed_constexpr)`` or |
939 | ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable |
940 | declarations, local variable modification, and control flow constructs |
941 | are permitted in ``constexpr`` functions. |
942 | |
943 | C++14 return type deduction |
944 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
945 | |
946 | Use ``__has_feature(cxx_return_type_deduction)`` or |
947 | ``__has_extension(cxx_return_type_deduction)`` to determine if support |
948 | for return type deduction for functions (using ``auto`` as a return type) |
949 | is enabled. |
950 | |
951 | C++14 runtime-sized arrays |
952 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
953 | |
954 | Use ``__has_feature(cxx_runtime_array)`` or |
955 | ``__has_extension(cxx_runtime_array)`` to determine if support |
956 | for arrays of runtime bound (a restricted form of variable-length arrays) |
957 | is enabled. |
958 | Clang's implementation of this feature is incomplete. |
959 | |
960 | C++14 variable templates |
961 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
962 | |
963 | Use ``__has_feature(cxx_variable_templates)`` or |
964 | ``__has_extension(cxx_variable_templates)`` to determine if support for |
965 | templated variable declarations is enabled. |
966 | |
967 | C11 |
968 | --- |
969 | |
970 | The features listed below are part of the C11 standard. As a result, all these |
971 | features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when |
972 | compiling C code. Additionally, because these features are all |
973 | backward-compatible, they are available as extensions in all language modes. |
974 | |
975 | C11 alignment specifiers |
976 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
977 | |
978 | Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine |
979 | if support for alignment specifiers using ``_Alignas`` is enabled. |
980 | |
981 | Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine |
982 | if support for the ``_Alignof`` keyword is enabled. |
983 | |
984 | C11 atomic operations |
985 | ^^^^^^^^^^^^^^^^^^^^^ |
986 | |
987 | Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine |
988 | if support for atomic types using ``_Atomic`` is enabled. Clang also provides |
989 | :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement |
990 | the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use |
991 | ``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header |
992 | is available. |
993 | |
994 | Clang will use the system's ``<stdatomic.h>`` header when one is available, and |
995 | will otherwise use its own. When using its own, implementations of the atomic |
996 | operations are provided as macros. In the cases where C11 also requires a real |
997 | function, this header provides only the declaration of that function (along |
998 | with a shadowing macro implementation), and you must link to a library which |
999 | provides a definition of the function if you use it instead of the macro. |
1000 | |
1001 | C11 generic selections |
1002 | ^^^^^^^^^^^^^^^^^^^^^^ |
1003 | |
1004 | Use ``__has_feature(c_generic_selections)`` or |
1005 | ``__has_extension(c_generic_selections)`` to determine if support for generic |
1006 | selections is enabled. |
1007 | |
1008 | As an extension, the C11 generic selection expression is available in all |
1009 | languages supported by Clang. The syntax is the same as that given in the C11 |
1010 | standard. |
1011 | |
1012 | In C, type compatibility is decided according to the rules given in the |
1013 | appropriate standard, but in C++, which lacks the type compatibility rules used |
1014 | in C, types are considered compatible only if they are equivalent. |
1015 | |
1016 | C11 ``_Static_assert()`` |
1017 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
1018 | |
1019 | Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` |
1020 | to determine if support for compile-time assertions using ``_Static_assert`` is |
1021 | enabled. |
1022 | |
1023 | C11 ``_Thread_local`` |
1024 | ^^^^^^^^^^^^^^^^^^^^^ |
1025 | |
1026 | Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)`` |
1027 | to determine if support for ``_Thread_local`` variables is enabled. |
1028 | |
1029 | Modules |
1030 | ------- |
1031 | |
1032 | Use ``__has_feature(modules)`` to determine if Modules have been enabled. |
1033 | For example, compiling code with ``-fmodules`` enables the use of Modules. |
1034 | |
1035 | More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_. |
1036 | |
1037 | Checks for Type Trait Primitives |
1038 | ================================ |
1039 | |
1040 | Type trait primitives are special builtin constant expressions that can be used |
1041 | by the standard C++ library to facilitate or simplify the implementation of |
1042 | user-facing type traits in the <type_traits> header. |
1043 | |
1044 | They are not intended to be used directly by user code because they are |
1045 | implementation-defined and subject to change -- as such they're tied closely to |
1046 | the supported set of system headers, currently: |
1047 | |
1048 | * LLVM's own libc++ |
1049 | * GNU libstdc++ |
1050 | * The Microsoft standard C++ library |
1051 | |
1052 | Clang supports the `GNU C++ type traits |
1053 | <https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the |
1054 | `Microsoft Visual C++ Type traits |
1055 | <https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. |
1056 | |
1057 | Feature detection is supported only for some of the primitives at present. User |
1058 | code should not use these checks because they bear no direct relation to the |
1059 | actual set of type traits supported by the C++ standard library. |
1060 | |
1061 | For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the |
1062 | type trait primitive in the compiler. A simplistic usage example as might be |
1063 | seen in standard C++ headers follows: |
1064 | |
1065 | .. code-block:: c++ |
1066 | |
1067 | #if __has_extension(is_convertible_to) |
1068 | template<typename From, typename To> |
1069 | struct is_convertible_to { |
1070 | static const bool value = __is_convertible_to(From, To); |
1071 | }; |
1072 | #else |
1073 | // Emulate type trait for compatibility with other compilers. |
1074 | #endif |
1075 | |
1076 | The following type trait primitives are supported by Clang: |
1077 | |
1078 | * ``__has_nothrow_assign`` (GNU, Microsoft) |
1079 | * ``__has_nothrow_copy`` (GNU, Microsoft) |
1080 | * ``__has_nothrow_constructor`` (GNU, Microsoft) |
1081 | * ``__has_trivial_assign`` (GNU, Microsoft) |
1082 | * ``__has_trivial_copy`` (GNU, Microsoft) |
1083 | * ``__has_trivial_constructor`` (GNU, Microsoft) |
1084 | * ``__has_trivial_destructor`` (GNU, Microsoft) |
1085 | * ``__has_virtual_destructor`` (GNU, Microsoft) |
1086 | * ``__is_abstract`` (GNU, Microsoft) |
1087 | * ``__is_aggregate`` (GNU, Microsoft) |
1088 | * ``__is_base_of`` (GNU, Microsoft) |
1089 | * ``__is_class`` (GNU, Microsoft) |
1090 | * ``__is_convertible_to`` (Microsoft) |
1091 | * ``__is_empty`` (GNU, Microsoft) |
1092 | * ``__is_enum`` (GNU, Microsoft) |
1093 | * ``__is_interface_class`` (Microsoft) |
1094 | * ``__is_pod`` (GNU, Microsoft) |
1095 | * ``__is_polymorphic`` (GNU, Microsoft) |
1096 | * ``__is_union`` (GNU, Microsoft) |
1097 | * ``__is_literal(type)``: Determines whether the given type is a literal type |
1098 | * ``__is_final``: Determines whether the given type is declared with a |
1099 | ``final`` class-virt-specifier. |
1100 | * ``__underlying_type(type)``: Retrieves the underlying type for a given |
1101 | ``enum`` type. This trait is required to implement the C++11 standard |
1102 | library. |
1103 | * ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value |
1104 | of type ``totype`` can be assigned to from a value of type ``fromtype`` such |
1105 | that no non-trivial functions are called as part of that assignment. This |
1106 | trait is required to implement the C++11 standard library. |
1107 | * ``__is_trivially_constructible(type, argtypes...)``: Determines whether a |
1108 | value of type ``type`` can be direct-initialized with arguments of types |
1109 | ``argtypes...`` such that no non-trivial functions are called as part of |
1110 | that initialization. This trait is required to implement the C++11 standard |
1111 | library. |
1112 | * ``__is_destructible`` (MSVC 2013) |
1113 | * ``__is_nothrow_destructible`` (MSVC 2013) |
1114 | * ``__is_nothrow_assignable`` (MSVC 2013, clang) |
1115 | * ``__is_constructible`` (MSVC 2013, clang) |
1116 | * ``__is_nothrow_constructible`` (MSVC 2013, clang) |
1117 | * ``__is_assignable`` (MSVC 2015, clang) |
1118 | * ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a |
1119 | reference of type ``T`` bound to an expression of type ``U`` would bind to a |
1120 | materialized temporary object. If ``T`` is not a reference type the result |
1121 | is false. Note this trait will also return false when the initialization of |
1122 | ``T`` from ``U`` is ill-formed. |
1123 | |
1124 | Blocks |
1125 | ====== |
1126 | |
1127 | The syntax and high level language feature description is in |
1128 | :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for |
1129 | the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`. |
1130 | |
1131 | Query for this feature with ``__has_extension(blocks)``. |
1132 | |
1133 | Objective-C Features |
1134 | ==================== |
1135 | |
1136 | Related result types |
1137 | -------------------- |
1138 | |
1139 | According to Cocoa conventions, Objective-C methods with certain names |
1140 | ("``init``", "``alloc``", etc.) always return objects that are an instance of |
1141 | the receiving class's type. Such methods are said to have a "related result |
1142 | type", meaning that a message send to one of these methods will have the same |
1143 | static type as an instance of the receiver class. For example, given the |
1144 | following classes: |
1145 | |
1146 | .. code-block:: objc |
1147 | |
1148 | @interface NSObject |
1149 | + (id)alloc; |
1150 | - (id)init; |
1151 | @end |
1152 | |
1153 | @interface NSArray : NSObject |
1154 | @end |
1155 | |
1156 | and this common initialization pattern |
1157 | |
1158 | .. code-block:: objc |
1159 | |
1160 | NSArray *array = [[NSArray alloc] init]; |
1161 | |
1162 | the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because |
1163 | ``alloc`` implicitly has a related result type. Similarly, the type of the |
1164 | expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a |
1165 | related result type and its receiver is known to have the type ``NSArray *``. |
1166 | If neither ``alloc`` nor ``init`` had a related result type, the expressions |
1167 | would have had type ``id``, as declared in the method signature. |
1168 | |
1169 | A method with a related result type can be declared by using the type |
1170 | ``instancetype`` as its result type. ``instancetype`` is a contextual keyword |
1171 | that is only permitted in the result type of an Objective-C method, e.g. |
1172 | |
1173 | .. code-block:: objc |
1174 | |
1175 | @interface A |
1176 | + (instancetype)constructAnA; |
1177 | @end |
1178 | |
1179 | The related result type can also be inferred for some methods. To determine |
1180 | whether a method has an inferred related result type, the first word in the |
1181 | camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, |
1182 | and the method will have a related result type if its return type is compatible |
1183 | with the type of its class and if: |
1184 | |
1185 | * the first word is "``alloc``" or "``new``", and the method is a class method, |
1186 | or |
1187 | |
1188 | * the first word is "``autorelease``", "``init``", "``retain``", or "``self``", |
1189 | and the method is an instance method. |
1190 | |
1191 | If a method with a related result type is overridden by a subclass method, the |
1192 | subclass method must also return a type that is compatible with the subclass |
1193 | type. For example: |
1194 | |
1195 | .. code-block:: objc |
1196 | |
1197 | @interface NSString : NSObject |
1198 | - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString |
1199 | @end |
1200 | |
1201 | Related result types only affect the type of a message send or property access |
1202 | via the given method. In all other respects, a method with a related result |
1203 | type is treated the same way as method that returns ``id``. |
1204 | |
1205 | Use ``__has_feature(objc_instancetype)`` to determine whether the |
1206 | ``instancetype`` contextual keyword is available. |
1207 | |
1208 | Automatic reference counting |
1209 | ---------------------------- |
1210 | |
1211 | Clang provides support for :doc:`automated reference counting |
1212 | <AutomaticReferenceCounting>` in Objective-C, which eliminates the need |
1213 | for manual ``retain``/``release``/``autorelease`` message sends. There are three |
1214 | feature macros associated with automatic reference counting: |
1215 | ``__has_feature(objc_arc)`` indicates the availability of automated reference |
1216 | counting in general, while ``__has_feature(objc_arc_weak)`` indicates that |
1217 | automated reference counting also includes support for ``__weak`` pointers to |
1218 | Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs |
1219 | are allowed to have fields that are pointers to Objective-C objects managed by |
1220 | automatic reference counting. |
1221 | |
1222 | .. _objc-weak: |
1223 | |
1224 | Weak references |
1225 | --------------- |
1226 | |
1227 | Clang supports ARC-style weak and unsafe references in Objective-C even |
1228 | outside of ARC mode. Weak references must be explicitly enabled with |
1229 | the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))`` |
1230 | to test whether they are enabled. Unsafe references are enabled |
1231 | unconditionally. ARC-style weak and unsafe references cannot be used |
1232 | when Objective-C garbage collection is enabled. |
1233 | |
1234 | Except as noted below, the language rules for the ``__weak`` and |
1235 | ``__unsafe_unretained`` qualifiers (and the ``weak`` and |
1236 | ``unsafe_unretained`` property attributes) are just as laid out |
1237 | in the :doc:`ARC specification <AutomaticReferenceCounting>`. |
1238 | In particular, note that some classes do not support forming weak |
1239 | references to their instances, and note that special care must be |
1240 | taken when storing weak references in memory where initialization |
1241 | and deinitialization are outside the responsibility of the compiler |
1242 | (such as in ``malloc``-ed memory). |
1243 | |
1244 | Loading from a ``__weak`` variable always implicitly retains the |
1245 | loaded value. In non-ARC modes, this retain is normally balanced |
1246 | by an implicit autorelease. This autorelease can be suppressed |
1247 | by performing the load in the receiver position of a ``-retain`` |
1248 | message send (e.g. ``[weakReference retain]``); note that this performs |
1249 | only a single retain (the retain done when primitively loading from |
1250 | the weak reference). |
1251 | |
1252 | For the most part, ``__unsafe_unretained`` in non-ARC modes is just the |
1253 | default behavior of variables and therefore is not needed. However, |
1254 | it does have an effect on the semantics of block captures: normally, |
1255 | copying a block which captures an Objective-C object or block pointer |
1256 | causes the captured pointer to be retained or copied, respectively, |
1257 | but that behavior is suppressed when the captured variable is qualified |
1258 | with ``__unsafe_unretained``. |
1259 | |
1260 | Note that the ``__weak`` qualifier formerly meant the GC qualifier in |
1261 | all non-ARC modes and was silently ignored outside of GC modes. It now |
1262 | means the ARC-style qualifier in all non-GC modes and is no longer |
1263 | allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``. |
1264 | It is expected that ``-fobjc-weak`` will eventually be enabled by default |
1265 | in all non-GC Objective-C modes. |
1266 | |
1267 | .. _objc-fixed-enum: |
1268 | |
1269 | Enumerations with a fixed underlying type |
1270 | ----------------------------------------- |
1271 | |
1272 | Clang provides support for C++11 enumerations with a fixed underlying type |
1273 | within Objective-C. For example, one can write an enumeration type as: |
1274 | |
1275 | .. code-block:: c++ |
1276 | |
1277 | typedef enum : unsigned char { Red, Green, Blue } Color; |
1278 | |
1279 | This specifies that the underlying type, which is used to store the enumeration |
1280 | value, is ``unsigned char``. |
1281 | |
1282 | Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed |
1283 | underlying types is available in Objective-C. |
1284 | |
1285 | Interoperability with C++11 lambdas |
1286 | ----------------------------------- |
1287 | |
1288 | Clang provides interoperability between C++11 lambdas and blocks-based APIs, by |
1289 | permitting a lambda to be implicitly converted to a block pointer with the |
1290 | corresponding signature. For example, consider an API such as ``NSArray``'s |
1291 | array-sorting method: |
1292 | |
1293 | .. code-block:: objc |
1294 | |
1295 | - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; |
1296 | |
1297 | ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult |
1298 | (^)(id, id)``, and parameters of this type are generally provided with block |
1299 | literals as arguments. However, one can also use a C++11 lambda so long as it |
1300 | provides the same signature (in this case, accepting two parameters of type |
1301 | ``id`` and returning an ``NSComparisonResult``): |
1302 | |
1303 | .. code-block:: objc |
1304 | |
1305 | NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", |
1306 | @"String 02"]; |
1307 | const NSStringCompareOptions comparisonOptions |
1308 | = NSCaseInsensitiveSearch | NSNumericSearch | |
1309 | NSWidthInsensitiveSearch | NSForcedOrderingSearch; |
1310 | NSLocale *currentLocale = [NSLocale currentLocale]; |
1311 | NSArray *sorted |
1312 | = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { |
1313 | NSRange string1Range = NSMakeRange(0, [s1 length]); |
1314 | return [s1 compare:s2 options:comparisonOptions |
1315 | range:string1Range locale:currentLocale]; |
1316 | }]; |
1317 | NSLog(@"sorted: %@", sorted); |
1318 | |
1319 | This code relies on an implicit conversion from the type of the lambda |
1320 | expression (an unnamed, local class type called the *closure type*) to the |
1321 | corresponding block pointer type. The conversion itself is expressed by a |
1322 | conversion operator in that closure type that produces a block pointer with the |
1323 | same signature as the lambda itself, e.g., |
1324 | |
1325 | .. code-block:: objc |
1326 | |
1327 | operator NSComparisonResult (^)(id, id)() const; |
1328 | |
1329 | This conversion function returns a new block that simply forwards the two |
1330 | parameters to the lambda object (which it captures by copy), then returns the |
1331 | result. The returned block is first copied (with ``Block_copy``) and then |
1332 | autoreleased. As an optimization, if a lambda expression is immediately |
1333 | converted to a block pointer (as in the first example, above), then the block |
1334 | is not copied and autoreleased: rather, it is given the same lifetime as a |
1335 | block literal written at that point in the program, which avoids the overhead |
1336 | of copying a block to the heap in the common case. |
1337 | |
1338 | The conversion from a lambda to a block pointer is only available in |
1339 | Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory |
1340 | management (autorelease). |
1341 | |
1342 | Object Literals and Subscripting |
1343 | -------------------------------- |
1344 | |
1345 | Clang provides support for :doc:`Object Literals and Subscripting |
1346 | <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C |
1347 | programming patterns, makes programs more concise, and improves the safety of |
1348 | container creation. There are several feature macros associated with object |
1349 | literals and subscripting: ``__has_feature(objc_array_literals)`` tests the |
1350 | availability of array literals; ``__has_feature(objc_dictionary_literals)`` |
1351 | tests the availability of dictionary literals; |
1352 | ``__has_feature(objc_subscripting)`` tests the availability of object |
1353 | subscripting. |
1354 | |
1355 | Objective-C Autosynthesis of Properties |
1356 | --------------------------------------- |
1357 | |
1358 | Clang provides support for autosynthesis of declared properties. Using this |
1359 | feature, clang provides default synthesis of those properties not declared |
1360 | @dynamic and not having user provided backing getter and setter methods. |
1361 | ``__has_feature(objc_default_synthesize_properties)`` checks for availability |
1362 | of this feature in version of clang being used. |
1363 | |
1364 | .. _langext-objc-retain-release: |
1365 | |
1366 | Objective-C retaining behavior attributes |
1367 | ----------------------------------------- |
1368 | |
1369 | In Objective-C, functions and methods are generally assumed to follow the |
1370 | `Cocoa Memory Management |
1371 | <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ |
1372 | conventions for ownership of object arguments and |
1373 | return values. However, there are exceptions, and so Clang provides attributes |
1374 | to allow these exceptions to be documented. This are used by ARC and the |
1375 | `static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be |
1376 | better described using the ``objc_method_family`` attribute instead. |
1377 | |
1378 | **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, |
1379 | ``ns_returns_autoreleased``, ``cf_returns_retained``, and |
1380 | ``cf_returns_not_retained`` attributes can be placed on methods and functions |
1381 | that return Objective-C or CoreFoundation objects. They are commonly placed at |
1382 | the end of a function prototype or method declaration: |
1383 | |
1384 | .. code-block:: objc |
1385 | |
1386 | id foo() __attribute__((ns_returns_retained)); |
1387 | |
1388 | - (NSString *)bar:(int)x __attribute__((ns_returns_retained)); |
1389 | |
1390 | The ``*_returns_retained`` attributes specify that the returned object has a +1 |
1391 | retain count. The ``*_returns_not_retained`` attributes specify that the return |
1392 | object has a +0 retain count, even if the normal convention for its selector |
1393 | would be +1. ``ns_returns_autoreleased`` specifies that the returned object is |
1394 | +0, but is guaranteed to live at least as long as the next flush of an |
1395 | autorelease pool. |
1396 | |
1397 | **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on |
1398 | an parameter declaration; they specify that the argument is expected to have a |
1399 | +1 retain count, which will be balanced in some way by the function or method. |
1400 | The ``ns_consumes_self`` attribute can only be placed on an Objective-C |
1401 | method; it specifies that the method expects its ``self`` parameter to have a |
1402 | +1 retain count, which it will balance in some way. |
1403 | |
1404 | .. code-block:: objc |
1405 | |
1406 | void foo(__attribute__((ns_consumed)) NSString *string); |
1407 | |
1408 | - (void) bar __attribute__((ns_consumes_self)); |
1409 | - (void) baz:(id) __attribute__((ns_consumed)) x; |
1410 | |
1411 | Further examples of these attributes are available in the static analyzer's `list of annotations for analysis |
1412 | <https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_. |
1413 | |
1414 | Query for these features with ``__has_attribute(ns_consumed)``, |
1415 | ``__has_attribute(ns_returns_retained)``, etc. |
1416 | |
1417 | Objective-C @available |
1418 | ---------------------- |
1419 | |
1420 | It is possible to use the newest SDK but still build a program that can run on |
1421 | older versions of macOS and iOS by passing ``-mmacosx-version-min=`` / |
1422 | ``-miphoneos-version-min=``. |
1423 | |
1424 | Before LLVM 5.0, when calling a function that exists only in the OS that's |
1425 | newer than the target OS (as determined by the minimum deployment version), |
1426 | programmers had to carefully check if the function exists at runtime, using |
1427 | null checks for weakly-linked C functions, ``+class`` for Objective-C classes, |
1428 | and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for |
1429 | Objective-C methods. If such a check was missed, the program would compile |
1430 | fine, run fine on newer systems, but crash on older systems. |
1431 | |
1432 | As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes |
1433 | <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together |
1434 | with the new ``@available()`` keyword to assist with this issue. |
1435 | When a method that's introduced in the OS newer than the target OS is called, a |
1436 | -Wunguarded-availability warning is emitted if that call is not guarded: |
1437 | |
1438 | .. code-block:: objc |
1439 | |
1440 | void my_fun(NSSomeClass* var) { |
1441 | // If fancyNewMethod was added in e.g. macOS 10.12, but the code is |
1442 | // built with -mmacosx-version-min=10.11, then this unconditional call |
1443 | // will emit a -Wunguarded-availability warning: |
1444 | [var fancyNewMethod]; |
1445 | } |
1446 | |
1447 | To fix the warning and to avoid the crash on macOS 10.11, wrap it in |
1448 | ``if(@available())``: |
1449 | |
1450 | .. code-block:: objc |
1451 | |
1452 | void my_fun(NSSomeClass* var) { |
1453 | if (@available(macOS 10.12, *)) { |
1454 | [var fancyNewMethod]; |
1455 | } else { |
1456 | // Put fallback behavior for old macOS versions (and for non-mac |
1457 | // platforms) here. |
1458 | } |
1459 | } |
1460 | |
1461 | The ``*`` is required and means that platforms not explicitly listed will take |
1462 | the true branch, and the compiler will emit ``-Wunguarded-availability`` |
1463 | warnings for unlisted platforms based on those platform's deployment target. |
1464 | More than one platform can be listed in ``@available()``: |
1465 | |
1466 | .. code-block:: objc |
1467 | |
1468 | void my_fun(NSSomeClass* var) { |
1469 | if (@available(macOS 10.12, iOS 10, *)) { |
1470 | [var fancyNewMethod]; |
1471 | } |
1472 | } |
1473 | |
1474 | If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called |
1475 | on 10.12, then add an `availability attribute |
1476 | <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it, |
1477 | which will also suppress the warning and require that calls to my_fun() are |
1478 | checked: |
1479 | |
1480 | .. code-block:: objc |
1481 | |
1482 | API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) { |
1483 | [var fancyNewMethod]; // Now ok. |
1484 | } |
1485 | |
1486 | ``@available()`` is only available in Objective-C code. To use the feature |
1487 | in C and C++ code, use the ``__builtin_available()`` spelling instead. |
1488 | |
1489 | If existing code uses null checks or ``-respondsToSelector:``, it should |
1490 | be changed to use ``@available()`` (or ``__builtin_available``) instead. |
1491 | |
1492 | ``-Wunguarded-availability`` is disabled by default, but |
1493 | ``-Wunguarded-availability-new``, which only emits this warning for APIs |
1494 | that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and |
1495 | tvOS >= 11, is enabled by default. |
1496 | |
1497 | .. _langext-overloading: |
1498 | |
1499 | Objective-C++ ABI: protocol-qualifier mangling of parameters |
1500 | ------------------------------------------------------------ |
1501 | |
1502 | Starting with LLVM 3.4, Clang produces a new mangling for parameters whose |
1503 | type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such |
1504 | parameters to be differentiated from those with the regular unqualified ``id`` |
1505 | type. |
1506 | |
1507 | This was a non-backward compatible mangling change to the ABI. This change |
1508 | allows proper overloading, and also prevents mangling conflicts with template |
1509 | parameters of protocol-qualified type. |
1510 | |
1511 | Query the presence of this new mangling with |
1512 | ``__has_feature(objc_protocol_qualifier_mangling)``. |
1513 | |
1514 | Initializer lists for complex numbers in C |
1515 | ========================================== |
1516 | |
1517 | clang supports an extension which allows the following in C: |
1518 | |
1519 | .. code-block:: c++ |
1520 | |
1521 | #include <math.h> |
1522 | #include <complex.h> |
1523 | complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) |
1524 | |
1525 | This construct is useful because there is no way to separately initialize the |
1526 | real and imaginary parts of a complex variable in standard C, given that clang |
1527 | does not support ``_Imaginary``. (Clang also supports the ``__real__`` and |
1528 | ``__imag__`` extensions from gcc, which help in some cases, but are not usable |
1529 | in static initializers.) |
1530 | |
1531 | Note that this extension does not allow eliding the braces; the meaning of the |
1532 | following two lines is different: |
1533 | |
1534 | .. code-block:: c++ |
1535 | |
1536 | complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) |
1537 | complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) |
1538 | |
1539 | This extension also works in C++ mode, as far as that goes, but does not apply |
1540 | to the C++ ``std::complex``. (In C++11, list initialization allows the same |
1541 | syntax to be used with ``std::complex`` with the same meaning.) |
1542 | |
1543 | Builtin Functions |
1544 | ================= |
1545 | |
1546 | Clang supports a number of builtin library functions with the same syntax as |
1547 | GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, |
1548 | ``__builtin_choose_expr``, ``__builtin_types_compatible_p``, |
1549 | ``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to |
1550 | the GCC builtins, Clang supports a number of builtins that GCC does not, which |
1551 | are listed here. |
1552 | |
1553 | Please note that Clang does not and will not support all of the GCC builtins |
1554 | for vector operations. Instead of using builtins, you should use the functions |
1555 | defined in target-specific header files like ``<xmmintrin.h>``, which define |
1556 | portable wrappers for these. Many of the Clang versions of these functions are |
1557 | implemented directly in terms of :ref:`extended vector support |
1558 | <langext-vectors>` instead of builtins, in order to reduce the number of |
1559 | builtins that we need to implement. |
1560 | |
1561 | ``__builtin_assume`` |
1562 | ------------------------------ |
1563 | |
1564 | ``__builtin_assume`` is used to provide the optimizer with a boolean |
1565 | invariant that is defined to be true. |
1566 | |
1567 | **Syntax**: |
1568 | |
1569 | .. code-block:: c++ |
1570 | |
1571 | __builtin_assume(bool) |
1572 | |
1573 | **Example of Use**: |
1574 | |
1575 | .. code-block:: c++ |
1576 | |
1577 | int foo(int x) { |
1578 | __builtin_assume(x != 0); |
1579 | |
1580 | // The optimizer may short-circuit this check using the invariant. |
1581 | if (x == 0) |
1582 | return do_something(); |
1583 | |
1584 | return do_something_else(); |
1585 | } |
1586 | |
1587 | **Description**: |
1588 | |
1589 | The boolean argument to this function is defined to be true. The optimizer may |
1590 | analyze the form of the expression provided as the argument and deduce from |
1591 | that information used to optimize the program. If the condition is violated |
1592 | during execution, the behavior is undefined. The argument itself is never |
1593 | evaluated, so any side effects of the expression will be discarded. |
1594 | |
1595 | Query for this feature with ``__has_builtin(__builtin_assume)``. |
1596 | |
1597 | ``__builtin_readcyclecounter`` |
1598 | ------------------------------ |
1599 | |
1600 | ``__builtin_readcyclecounter`` is used to access the cycle counter register (or |
1601 | a similar low-latency, high-accuracy clock) on those targets that support it. |
1602 | |
1603 | **Syntax**: |
1604 | |
1605 | .. code-block:: c++ |
1606 | |
1607 | __builtin_readcyclecounter() |
1608 | |
1609 | **Example of Use**: |
1610 | |
1611 | .. code-block:: c++ |
1612 | |
1613 | unsigned long long t0 = __builtin_readcyclecounter(); |
1614 | do_something(); |
1615 | unsigned long long t1 = __builtin_readcyclecounter(); |
1616 | unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow |
1617 | |
1618 | **Description**: |
1619 | |
1620 | The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, |
1621 | which may be either global or process/thread-specific depending on the target. |
1622 | As the backing counters often overflow quickly (on the order of seconds) this |
1623 | should only be used for timing small intervals. When not supported by the |
1624 | target, the return value is always zero. This builtin takes no arguments and |
1625 | produces an unsigned long long result. |
1626 | |
1627 | Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note |
1628 | that even if present, its use may depend on run-time privilege or other OS |
1629 | controlled state. |
1630 | |
1631 | .. _langext-__builtin_shufflevector: |
1632 | |
1633 | ``__builtin_shufflevector`` |
1634 | --------------------------- |
1635 | |
1636 | ``__builtin_shufflevector`` is used to express generic vector |
1637 | permutation/shuffle/swizzle operations. This builtin is also very important |
1638 | for the implementation of various target-specific header files like |
1639 | ``<xmmintrin.h>``. |
1640 | |
1641 | **Syntax**: |
1642 | |
1643 | .. code-block:: c++ |
1644 | |
1645 | __builtin_shufflevector(vec1, vec2, index1, index2, ...) |
1646 | |
1647 | **Examples**: |
1648 | |
1649 | .. code-block:: c++ |
1650 | |
1651 | // identity operation - return 4-element vector v1. |
1652 | __builtin_shufflevector(v1, v1, 0, 1, 2, 3) |
1653 | |
1654 | // "Splat" element 0 of V1 into a 4-element result. |
1655 | __builtin_shufflevector(V1, V1, 0, 0, 0, 0) |
1656 | |
1657 | // Reverse 4-element vector V1. |
1658 | __builtin_shufflevector(V1, V1, 3, 2, 1, 0) |
1659 | |
1660 | // Concatenate every other element of 4-element vectors V1 and V2. |
1661 | __builtin_shufflevector(V1, V2, 0, 2, 4, 6) |
1662 | |
1663 | // Concatenate every other element of 8-element vectors V1 and V2. |
1664 | __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) |
1665 | |
1666 | // Shuffle v1 with some elements being undefined |
1667 | __builtin_shufflevector(v1, v1, 3, -1, 1, -1) |
1668 | |
1669 | **Description**: |
1670 | |
1671 | The first two arguments to ``__builtin_shufflevector`` are vectors that have |
1672 | the same element type. The remaining arguments are a list of integers that |
1673 | specify the elements indices of the first two vectors that should be extracted |
1674 | and returned in a new vector. These element indices are numbered sequentially |
1675 | starting with the first vector, continuing into the second vector. Thus, if |
1676 | ``vec1`` is a 4-element vector, index 5 would refer to the second element of |
1677 | ``vec2``. An index of -1 can be used to indicate that the corresponding element |
1678 | in the returned vector is a don't care and can be optimized by the backend. |
1679 | |
1680 | The result of ``__builtin_shufflevector`` is a vector with the same element |
1681 | type as ``vec1``/``vec2`` but that has an element count equal to the number of |
1682 | indices specified. |
1683 | |
1684 | Query for this feature with ``__has_builtin(__builtin_shufflevector)``. |
1685 | |
1686 | .. _langext-__builtin_convertvector: |
1687 | |
1688 | ``__builtin_convertvector`` |
1689 | --------------------------- |
1690 | |
1691 | ``__builtin_convertvector`` is used to express generic vector |
1692 | type-conversion operations. The input vector and the output vector |
1693 | type must have the same number of elements. |
1694 | |
1695 | **Syntax**: |
1696 | |
1697 | .. code-block:: c++ |
1698 | |
1699 | __builtin_convertvector(src_vec, dst_vec_type) |
1700 | |
1701 | **Examples**: |
1702 | |
1703 | .. code-block:: c++ |
1704 | |
1705 | typedef double vector4double __attribute__((__vector_size__(32))); |
1706 | typedef float vector4float __attribute__((__vector_size__(16))); |
1707 | typedef short vector4short __attribute__((__vector_size__(8))); |
1708 | vector4float vf; vector4short vs; |
1709 | |
1710 | // convert from a vector of 4 floats to a vector of 4 doubles. |
1711 | __builtin_convertvector(vf, vector4double) |
1712 | // equivalent to: |
1713 | (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] } |
1714 | |
1715 | // convert from a vector of 4 shorts to a vector of 4 floats. |
1716 | __builtin_convertvector(vs, vector4float) |
1717 | // equivalent to: |
1718 | (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] } |
1719 | |
1720 | **Description**: |
1721 | |
1722 | The first argument to ``__builtin_convertvector`` is a vector, and the second |
1723 | argument is a vector type with the same number of elements as the first |
1724 | argument. |
1725 | |
1726 | The result of ``__builtin_convertvector`` is a vector with the same element |
1727 | type as the second argument, with a value defined in terms of the action of a |
1728 | C-style cast applied to each element of the first argument. |
1729 | |
1730 | Query for this feature with ``__has_builtin(__builtin_convertvector)``. |
1731 | |
1732 | ``__builtin_bitreverse`` |
1733 | ------------------------ |
1734 | |
1735 | * ``__builtin_bitreverse8`` |
1736 | * ``__builtin_bitreverse16`` |
1737 | * ``__builtin_bitreverse32`` |
1738 | * ``__builtin_bitreverse64`` |
1739 | |
1740 | **Syntax**: |
1741 | |
1742 | .. code-block:: c++ |
1743 | |
1744 | __builtin_bitreverse32(x) |
1745 | |
1746 | **Examples**: |
1747 | |
1748 | .. code-block:: c++ |
1749 | |
1750 | uint8_t rev_x = __builtin_bitreverse8(x); |
1751 | uint16_t rev_x = __builtin_bitreverse16(x); |
1752 | uint32_t rev_y = __builtin_bitreverse32(y); |
1753 | uint64_t rev_z = __builtin_bitreverse64(z); |
1754 | |
1755 | **Description**: |
1756 | |
1757 | The '``__builtin_bitreverse``' family of builtins is used to reverse |
1758 | the bitpattern of an integer value; for example ``0b10110110`` becomes |
1759 | ``0b01101101``. |
1760 | |
1761 | ``__builtin_rotateleft`` |
1762 | ------------------------ |
1763 | |
1764 | * ``__builtin_rotateleft8`` |
1765 | * ``__builtin_rotateleft16`` |
1766 | * ``__builtin_rotateleft32`` |
1767 | * ``__builtin_rotateleft64`` |
1768 | |
1769 | **Syntax**: |
1770 | |
1771 | .. code-block:: c++ |
1772 | |
1773 | __builtin_rotateleft32(x, y) |
1774 | |
1775 | **Examples**: |
1776 | |
1777 | .. code-block:: c++ |
1778 | |
1779 | uint8_t rot_x = __builtin_rotateleft8(x, y); |
1780 | uint16_t rot_x = __builtin_rotateleft16(x, y); |
1781 | uint32_t rot_x = __builtin_rotateleft32(x, y); |
1782 | uint64_t rot_x = __builtin_rotateleft64(x, y); |
1783 | |
1784 | **Description**: |
1785 | |
1786 | The '``__builtin_rotateleft``' family of builtins is used to rotate |
1787 | the bits in the first argument by the amount in the second argument. |
1788 | For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``. |
1789 | The shift value is treated as an unsigned amount modulo the size of |
1790 | the arguments. Both arguments and the result have the bitwidth specified |
1791 | by the name of the builtin. |
1792 | |
1793 | ``__builtin_rotateright`` |
1794 | _------------------------ |
1795 | |
1796 | * ``__builtin_rotateright8`` |
1797 | * ``__builtin_rotateright16`` |
1798 | * ``__builtin_rotateright32`` |
1799 | * ``__builtin_rotateright64`` |
1800 | |
1801 | **Syntax**: |
1802 | |
1803 | .. code-block:: c++ |
1804 | |
1805 | __builtin_rotateright32(x, y) |
1806 | |
1807 | **Examples**: |
1808 | |
1809 | .. code-block:: c++ |
1810 | |
1811 | uint8_t rot_x = __builtin_rotateright8(x, y); |
1812 | uint16_t rot_x = __builtin_rotateright16(x, y); |
1813 | uint32_t rot_x = __builtin_rotateright32(x, y); |
1814 | uint64_t rot_x = __builtin_rotateright64(x, y); |
1815 | |
1816 | **Description**: |
1817 | |
1818 | The '``__builtin_rotateright``' family of builtins is used to rotate |
1819 | the bits in the first argument by the amount in the second argument. |
1820 | For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``. |
1821 | The shift value is treated as an unsigned amount modulo the size of |
1822 | the arguments. Both arguments and the result have the bitwidth specified |
1823 | by the name of the builtin. |
1824 | |
1825 | ``__builtin_unreachable`` |
1826 | ------------------------- |
1827 | |
1828 | ``__builtin_unreachable`` is used to indicate that a specific point in the |
1829 | program cannot be reached, even if the compiler might otherwise think it can. |
1830 | This is useful to improve optimization and eliminates certain warnings. For |
1831 | example, without the ``__builtin_unreachable`` in the example below, the |
1832 | compiler assumes that the inline asm can fall through and prints a "function |
1833 | declared '``noreturn``' should not return" warning. |
1834 | |
1835 | **Syntax**: |
1836 | |
1837 | .. code-block:: c++ |
1838 | |
1839 | __builtin_unreachable() |
1840 | |
1841 | **Example of use**: |
1842 | |
1843 | .. code-block:: c++ |
1844 | |
1845 | void myabort(void) __attribute__((noreturn)); |
1846 | void myabort(void) { |
1847 | asm("int3"); |
1848 | __builtin_unreachable(); |
1849 | } |
1850 | |
1851 | **Description**: |
1852 | |
1853 | The ``__builtin_unreachable()`` builtin has completely undefined behavior. |
1854 | Since it has undefined behavior, it is a statement that it is never reached and |
1855 | the optimizer can take advantage of this to produce better code. This builtin |
1856 | takes no arguments and produces a void result. |
1857 | |
1858 | Query for this feature with ``__has_builtin(__builtin_unreachable)``. |
1859 | |
1860 | ``__builtin_unpredictable`` |
1861 | --------------------------- |
1862 | |
1863 | ``__builtin_unpredictable`` is used to indicate that a branch condition is |
1864 | unpredictable by hardware mechanisms such as branch prediction logic. |
1865 | |
1866 | **Syntax**: |
1867 | |
1868 | .. code-block:: c++ |
1869 | |
1870 | __builtin_unpredictable(long long) |
1871 | |
1872 | **Example of use**: |
1873 | |
1874 | .. code-block:: c++ |
1875 | |
1876 | if (__builtin_unpredictable(x > 0)) { |
1877 | foo(); |
1878 | } |
1879 | |
1880 | **Description**: |
1881 | |
1882 | The ``__builtin_unpredictable()`` builtin is expected to be used with control |
1883 | flow conditions such as in ``if`` and ``switch`` statements. |
1884 | |
1885 | Query for this feature with ``__has_builtin(__builtin_unpredictable)``. |
1886 | |
1887 | ``__sync_swap`` |
1888 | --------------- |
1889 | |
1890 | ``__sync_swap`` is used to atomically swap integers or pointers in memory. |
1891 | |
1892 | **Syntax**: |
1893 | |
1894 | .. code-block:: c++ |
1895 | |
1896 | type __sync_swap(type *ptr, type value, ...) |
1897 | |
1898 | **Example of Use**: |
1899 | |
1900 | .. code-block:: c++ |
1901 | |
1902 | int old_value = __sync_swap(&value, new_value); |
1903 | |
1904 | **Description**: |
1905 | |
1906 | The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of |
1907 | atomic intrinsics to allow code to atomically swap the current value with the |
1908 | new value. More importantly, it helps developers write more efficient and |
1909 | correct code by avoiding expensive loops around |
1910 | ``__sync_bool_compare_and_swap()`` or relying on the platform specific |
1911 | implementation details of ``__sync_lock_test_and_set()``. The |
1912 | ``__sync_swap()`` builtin is a full barrier. |
1913 | |
1914 | ``__builtin_addressof`` |
1915 | ----------------------- |
1916 | |
1917 | ``__builtin_addressof`` performs the functionality of the built-in ``&`` |
1918 | operator, ignoring any ``operator&`` overload. This is useful in constant |
1919 | expressions in C++11, where there is no other way to take the address of an |
1920 | object that overloads ``operator&``. |
1921 | |
1922 | **Example of use**: |
1923 | |
1924 | .. code-block:: c++ |
1925 | |
1926 | template<typename T> constexpr T *addressof(T &value) { |
1927 | return __builtin_addressof(value); |
1928 | } |
1929 | |
1930 | ``__builtin_operator_new`` and ``__builtin_operator_delete`` |
1931 | ------------------------------------------------------------ |
1932 | |
1933 | ``__builtin_operator_new`` allocates memory just like a non-placement non-class |
1934 | *new-expression*. This is exactly like directly calling the normal |
1935 | non-placement ``::operator new``, except that it allows certain optimizations |
1936 | that the C++ standard does not permit for a direct function call to |
1937 | ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and |
1938 | merging allocations). |
1939 | |
1940 | Likewise, ``__builtin_operator_delete`` deallocates memory just like a |
1941 | non-class *delete-expression*, and is exactly like directly calling the normal |
1942 | ``::operator delete``, except that it permits optimizations. Only the unsized |
1943 | form of ``__builtin_operator_delete`` is currently available. |
1944 | |
1945 | These builtins are intended for use in the implementation of ``std::allocator`` |
1946 | and other similar allocation libraries, and are only available in C++. |
1947 | |
1948 | Multiprecision Arithmetic Builtins |
1949 | ---------------------------------- |
1950 | |
1951 | Clang provides a set of builtins which expose multiprecision arithmetic in a |
1952 | manner amenable to C. They all have the following form: |
1953 | |
1954 | .. code-block:: c |
1955 | |
1956 | unsigned x = ..., y = ..., carryin = ..., carryout; |
1957 | unsigned sum = __builtin_addc(x, y, carryin, &carryout); |
1958 | |
1959 | Thus one can form a multiprecision addition chain in the following manner: |
1960 | |
1961 | .. code-block:: c |
1962 | |
1963 | unsigned *x, *y, *z, carryin=0, carryout; |
1964 | z[0] = __builtin_addc(x[0], y[0], carryin, &carryout); |
1965 | carryin = carryout; |
1966 | z[1] = __builtin_addc(x[1], y[1], carryin, &carryout); |
1967 | carryin = carryout; |
1968 | z[2] = __builtin_addc(x[2], y[2], carryin, &carryout); |
1969 | carryin = carryout; |
1970 | z[3] = __builtin_addc(x[3], y[3], carryin, &carryout); |
1971 | |
1972 | The complete list of builtins are: |
1973 | |
1974 | .. code-block:: c |
1975 | |
1976 | unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); |
1977 | unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); |
1978 | unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); |
1979 | unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); |
1980 | unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); |
1981 | unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); |
1982 | unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); |
1983 | unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); |
1984 | unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); |
1985 | unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); |
1986 | |
1987 | Checked Arithmetic Builtins |
1988 | --------------------------- |
1989 | |
1990 | Clang provides a set of builtins that implement checked arithmetic for security |
1991 | critical applications in a manner that is fast and easily expressable in C. As |
1992 | an example of their usage: |
1993 | |
1994 | .. code-block:: c |
1995 | |
1996 | errorcode_t security_critical_application(...) { |
1997 | unsigned x, y, result; |
1998 | ... |
1999 | if (__builtin_mul_overflow(x, y, &result)) |
2000 | return kErrorCodeHackers; |
2001 | ... |
2002 | use_multiply(result); |
2003 | ... |
2004 | } |
2005 | |
2006 | Clang provides the following checked arithmetic builtins: |
2007 | |
2008 | .. code-block:: c |
2009 | |
2010 | bool __builtin_add_overflow (type1 x, type2 y, type3 *sum); |
2011 | bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff); |
2012 | bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod); |
2013 | bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum); |
2014 | bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum); |
2015 | bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum); |
2016 | bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff); |
2017 | bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff); |
2018 | bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff); |
2019 | bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod); |
2020 | bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod); |
2021 | bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod); |
2022 | bool __builtin_sadd_overflow (int x, int y, int *sum); |
2023 | bool __builtin_saddl_overflow (long x, long y, long *sum); |
2024 | bool __builtin_saddll_overflow(long long x, long long y, long long *sum); |
2025 | bool __builtin_ssub_overflow (int x, int y, int *diff); |
2026 | bool __builtin_ssubl_overflow (long x, long y, long *diff); |
2027 | bool __builtin_ssubll_overflow(long long x, long long y, long long *diff); |
2028 | bool __builtin_smul_overflow (int x, int y, int *prod); |
2029 | bool __builtin_smull_overflow (long x, long y, long *prod); |
2030 | bool __builtin_smulll_overflow(long long x, long long y, long long *prod); |
2031 | |
2032 | Each builtin performs the specified mathematical operation on the |
2033 | first two arguments and stores the result in the third argument. If |
2034 | possible, the result will be equal to mathematically-correct result |
2035 | and the builtin will return 0. Otherwise, the builtin will return |
2036 | 1 and the result will be equal to the unique value that is equivalent |
2037 | to the mathematically-correct result modulo two raised to the *k* |
2038 | power, where *k* is the number of bits in the result type. The |
2039 | behavior of these builtins is well-defined for all argument values. |
2040 | |
2041 | The first three builtins work generically for operands of any integer type, |
2042 | including boolean types. The operands need not have the same type as each |
2043 | other, or as the result. The other builtins may implicitly promote or |
2044 | convert their operands before performing the operation. |
2045 | |
2046 | Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc. |
2047 | |
2048 | Floating point builtins |
2049 | --------------------------------------- |
2050 | |
2051 | ``__builtin_canonicalize`` |
2052 | -------------------------- |
2053 | |
2054 | .. code-block:: c |
2055 | |
2056 | double __builtin_canonicalize(double); |
2057 | float __builtin_canonicalizef(float); |
2058 | long double__builtin_canonicalizel(long double); |
2059 | |
2060 | Returns the platform specific canonical encoding of a floating point |
2061 | number. This canonicalization is useful for implementing certain |
2062 | numeric primitives such as frexp. See `LLVM canonicalize intrinsic |
2063 | <https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for |
2064 | more information on the semantics. |
2065 | |
2066 | String builtins |
2067 | --------------- |
2068 | |
2069 | Clang provides constant expression evaluation support for builtins forms of |
2070 | the following functions from the C standard library ``<string.h>`` header: |
2071 | |
2072 | * ``memchr`` |
2073 | * ``memcmp`` |
2074 | * ``strchr`` |
2075 | * ``strcmp`` |
2076 | * ``strlen`` |
2077 | * ``strncmp`` |
2078 | * ``wcschr`` |
2079 | * ``wcscmp`` |
2080 | * ``wcslen`` |
2081 | * ``wcsncmp`` |
2082 | * ``wmemchr`` |
2083 | * ``wmemcmp`` |
2084 | |
2085 | In each case, the builtin form has the name of the C library function prefixed |
2086 | by ``__builtin_``. Example: |
2087 | |
2088 | .. code-block:: c |
2089 | |
2090 | void *p = __builtin_memchr("foobar", 'b', 5); |
2091 | |
2092 | In addition to the above, one further builtin is provided: |
2093 | |
2094 | .. code-block:: c |
2095 | |
2096 | char *__builtin_char_memchr(const char *haystack, int needle, size_t size); |
2097 | |
2098 | ``__builtin_char_memchr(a, b, c)`` is identical to |
2099 | ``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within |
2100 | constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*`` |
2101 | is disallowed in general). |
2102 | |
2103 | Support for constant expression evaluation for the above builtins be detected |
2104 | with ``__has_feature(cxx_constexpr_string_builtins)``. |
2105 | |
2106 | Atomic Min/Max builtins with memory ordering |
2107 | -------------------------------------------- |
2108 | |
2109 | There are two atomic builtins with min/max in-memory comparison and swap. |
2110 | The syntax and semantics are similar to GCC-compatible __atomic_* builtins. |
2111 | |
2112 | * ``__atomic_fetch_min`` |
2113 | * ``__atomic_fetch_max`` |
2114 | |
2115 | The builtins work with signed and unsigned integers and require to specify memory ordering. |
2116 | The return value is the original value that was stored in memory before comparison. |
2117 | |
2118 | Example: |
2119 | |
2120 | .. code-block:: c |
2121 | |
2122 | unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED); |
2123 | |
2124 | The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``, |
2125 | ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``, |
2126 | ``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics. |
2127 | |
2128 | In terms or aquire-release ordering barriers these two operations are always |
2129 | considered as operations with *load-store* semantics, even when the original value |
2130 | is not actually modified after comparison. |
2131 | |
2132 | .. _langext-__c11_atomic: |
2133 | |
2134 | __c11_atomic builtins |
2135 | --------------------- |
2136 | |
2137 | Clang provides a set of builtins which are intended to be used to implement |
2138 | C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the |
2139 | ``_explicit`` form of the corresponding C11 operation, and are named with a |
2140 | ``__c11_`` prefix. The supported operations, and the differences from |
2141 | the corresponding C11 operations, are: |
2142 | |
2143 | * ``__c11_atomic_init`` |
2144 | * ``__c11_atomic_thread_fence`` |
2145 | * ``__c11_atomic_signal_fence`` |
2146 | * ``__c11_atomic_is_lock_free`` (The argument is the size of the |
2147 | ``_Atomic(...)`` object, instead of its address) |
2148 | * ``__c11_atomic_store`` |
2149 | * ``__c11_atomic_load`` |
2150 | * ``__c11_atomic_exchange`` |
2151 | * ``__c11_atomic_compare_exchange_strong`` |
2152 | * ``__c11_atomic_compare_exchange_weak`` |
2153 | * ``__c11_atomic_fetch_add`` |
2154 | * ``__c11_atomic_fetch_sub`` |
2155 | * ``__c11_atomic_fetch_and`` |
2156 | * ``__c11_atomic_fetch_or`` |
2157 | * ``__c11_atomic_fetch_xor`` |
2158 | |
2159 | The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, |
2160 | ``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are |
2161 | provided, with values corresponding to the enumerators of C11's |
2162 | ``memory_order`` enumeration. |
2163 | |
2164 | (Note that Clang additionally provides GCC-compatible ``__atomic_*`` |
2165 | builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0 |
2166 | atomic builtins are an explicit form of the corresponding OpenCL 2.0 |
2167 | builtin function, and are named with a ``__opencl_`` prefix. The macros |
2168 | ``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``, |
2169 | ``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``, |
2170 | and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values |
2171 | corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.) |
2172 | |
2173 | Low-level ARM exclusive memory builtins |
2174 | --------------------------------------- |
2175 | |
2176 | Clang provides overloaded builtins giving direct access to the three key ARM |
2177 | instructions for implementing atomic operations. |
2178 | |
2179 | .. code-block:: c |
2180 | |
2181 | T __builtin_arm_ldrex(const volatile T *addr); |
2182 | T __builtin_arm_ldaex(const volatile T *addr); |
2183 | int __builtin_arm_strex(T val, volatile T *addr); |
2184 | int __builtin_arm_stlex(T val, volatile T *addr); |
2185 | void __builtin_arm_clrex(void); |
2186 | |
2187 | The types ``T`` currently supported are: |
2188 | |
2189 | * Integer types with width at most 64 bits (or 128 bits on AArch64). |
2190 | * Floating-point types |
2191 | * Pointer types. |
2192 | |
2193 | Note that the compiler does not guarantee it will not insert stores which clear |
2194 | the exclusive monitor in between an ``ldrex`` type operation and its paired |
2195 | ``strex``. In practice this is only usually a risk when the extra store is on |
2196 | the same cache line as the variable being modified and Clang will only insert |
2197 | stack stores on its own, so it is best not to use these operations on variables |
2198 | with automatic storage duration. |
2199 | |
2200 | Also, loads and stores may be implicit in code written between the ``ldrex`` and |
2201 | ``strex``. Clang will not necessarily mitigate the effects of these either, so |
2202 | care should be exercised. |
2203 | |
2204 | For these reasons the higher level atomic primitives should be preferred where |
2205 | possible. |
2206 | |
2207 | Non-temporal load/store builtins |
2208 | -------------------------------- |
2209 | |
2210 | Clang provides overloaded builtins allowing generation of non-temporal memory |
2211 | accesses. |
2212 | |
2213 | .. code-block:: c |
2214 | |
2215 | T __builtin_nontemporal_load(T *addr); |
2216 | void __builtin_nontemporal_store(T value, T *addr); |
2217 | |
2218 | The types ``T`` currently supported are: |
2219 | |
2220 | * Integer types. |
2221 | * Floating-point types. |
2222 | * Vector types. |
2223 | |
2224 | Note that the compiler does not guarantee that non-temporal loads or stores |
2225 | will be used. |
2226 | |
2227 | C++ Coroutines support builtins |
2228 | -------------------------------- |
2229 | |
2230 | .. warning:: |
2231 | This is a work in progress. Compatibility across Clang/LLVM releases is not |
2232 | guaranteed. |
2233 | |
2234 | Clang provides experimental builtins to support C++ Coroutines as defined by |
2235 | https://wg21.link/P0057. The following four are intended to be used by the |
2236 | standard library to implement `std::experimental::coroutine_handle` type. |
2237 | |
2238 | **Syntax**: |
2239 | |
2240 | .. code-block:: c |
2241 | |
2242 | void __builtin_coro_resume(void *addr); |
2243 | void __builtin_coro_destroy(void *addr); |
2244 | bool __builtin_coro_done(void *addr); |
2245 | void *__builtin_coro_promise(void *addr, int alignment, bool from_promise) |
2246 | |
2247 | **Example of use**: |
2248 | |
2249 | .. code-block:: c++ |
2250 | |
2251 | template <> struct coroutine_handle<void> { |
2252 | void resume() const { __builtin_coro_resume(ptr); } |
2253 | void destroy() const { __builtin_coro_destroy(ptr); } |
2254 | bool done() const { return __builtin_coro_done(ptr); } |
2255 | // ... |
2256 | protected: |
2257 | void *ptr; |
2258 | }; |
2259 | |
2260 | template <typename Promise> struct coroutine_handle : coroutine_handle<> { |
2261 | // ... |
2262 | Promise &promise() const { |
2263 | return *reinterpret_cast<Promise *>( |
2264 | __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false)); |
2265 | } |
2266 | static coroutine_handle from_promise(Promise &promise) { |
2267 | coroutine_handle p; |
2268 | p.ptr = __builtin_coro_promise(&promise, alignof(Promise), |
2269 | /*from-promise=*/true); |
2270 | return p; |
2271 | } |
2272 | }; |
2273 | |
2274 | |
2275 | Other coroutine builtins are either for internal clang use or for use during |
2276 | development of the coroutine feature. See `Coroutines in LLVM |
2277 | <https://llvm.org/docs/Coroutines.html#intrinsics>`_ for |
2278 | more information on their semantics. Note that builtins matching the intrinsics |
2279 | that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc, |
2280 | llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to |
2281 | an appropriate value during the emission. |
2282 | |
2283 | **Syntax**: |
2284 | |
2285 | .. code-block:: c |
2286 | |
2287 | size_t __builtin_coro_size() |
2288 | void *__builtin_coro_frame() |
2289 | void *__builtin_coro_free(void *coro_frame) |
2290 | |
2291 | void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts) |
2292 | bool __builtin_coro_alloc() |
2293 | void *__builtin_coro_begin(void *memory) |
2294 | void __builtin_coro_end(void *coro_frame, bool unwind) |
2295 | char __builtin_coro_suspend(bool final) |
2296 | bool __builtin_coro_param(void *original, void *copy) |
2297 | |
2298 | Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM |
2299 | automatically will insert one if the first argument to `llvm.coro.suspend` is |
2300 | token `none`. If a user calls `__builin_suspend`, clang will insert `token none` |
2301 | as the first argument to the intrinsic. |
2302 | |
2303 | Non-standard C++11 Attributes |
2304 | ============================= |
2305 | |
2306 | Clang's non-standard C++11 attributes live in the ``clang`` attribute |
2307 | namespace. |
2308 | |
2309 | Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which |
2310 | are accepted with the ``__attribute__((foo))`` syntax are also accepted as |
2311 | ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC |
2312 | (see the list of `GCC function attributes |
2313 | <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable |
2314 | attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and |
2315 | `GCC type attributes |
2316 | <https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC |
2317 | implementation, these attributes must appertain to the *declarator-id* in a |
2318 | declaration, which means they must go either at the start of the declaration or |
2319 | immediately after the name being declared. |
2320 | |
2321 | For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and |
2322 | also applies the GNU ``noreturn`` attribute to ``f``. |
2323 | |
2324 | .. code-block:: c++ |
2325 | |
2326 | [[gnu::unused]] int a, f [[gnu::noreturn]] (); |
2327 | |
2328 | Target-Specific Extensions |
2329 | ========================== |
2330 | |
2331 | Clang supports some language features conditionally on some targets. |
2332 | |
2333 | ARM/AArch64 Language Extensions |
2334 | ------------------------------- |
2335 | |
2336 | Memory Barrier Intrinsics |
2337 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
2338 | Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined |
2339 | in the `ARM C Language Extensions Release 2.0 |
2340 | <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_. |
2341 | Note that these intrinsics are implemented as motion barriers that block |
2342 | reordering of memory accesses and side effect instructions. Other instructions |
2343 | like simple arithmetic may be reordered around the intrinsic. If you expect to |
2344 | have no reordering at all, use inline assembly instead. |
2345 | |
2346 | X86/X86-64 Language Extensions |
2347 | ------------------------------ |
2348 | |
2349 | The X86 backend has these language extensions: |
2350 | |
2351 | Memory references to specified segments |
2352 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
2353 | |
2354 | Annotating a pointer with address space #256 causes it to be code generated |
2355 | relative to the X86 GS segment register, address space #257 causes it to be |
2356 | relative to the X86 FS segment, and address space #258 causes it to be |
2357 | relative to the X86 SS segment. Note that this is a very very low-level |
2358 | feature that should only be used if you know what you're doing (for example in |
2359 | an OS kernel). |
2360 | |
2361 | Here is an example: |
2362 | |
2363 | .. code-block:: c++ |
2364 | |
2365 | #define GS_RELATIVE __attribute__((address_space(256))) |
2366 | int foo(int GS_RELATIVE *P) { |
2367 | return *P; |
2368 | } |
2369 | |
2370 | Which compiles to (on X86-32): |
2371 | |
2372 | .. code-block:: gas |
2373 | |
2374 | _foo: |
2375 | movl 4(%esp), %eax |
2376 | movl %gs:(%eax), %eax |
2377 | ret |
2378 | |
2379 | Extensions for Static Analysis |
2380 | ============================== |
2381 | |
2382 | Clang supports additional attributes that are useful for documenting program |
2383 | invariants and rules for static analysis tools, such as the `Clang Static |
2384 | Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented |
2385 | in the analyzer's `list of source-level annotations |
2386 | <https://clang-analyzer.llvm.org/annotations.html>`_. |
2387 | |
2388 | |
2389 | Extensions for Dynamic Analysis |
2390 | =============================== |
2391 | |
2392 | Use ``__has_feature(address_sanitizer)`` to check if the code is being built |
2393 | with :doc:`AddressSanitizer`. |
2394 | |
2395 | Use ``__has_feature(thread_sanitizer)`` to check if the code is being built |
2396 | with :doc:`ThreadSanitizer`. |
2397 | |
2398 | Use ``__has_feature(memory_sanitizer)`` to check if the code is being built |
2399 | with :doc:`MemorySanitizer`. |
2400 | |
2401 | Use ``__has_feature(safe_stack)`` to check if the code is being built |
2402 | with :doc:`SafeStack`. |
2403 | |
2404 | |
2405 | Extensions for selectively disabling optimization |
2406 | ================================================= |
2407 | |
2408 | Clang provides a mechanism for selectively disabling optimizations in functions |
2409 | and methods. |
2410 | |
2411 | To disable optimizations in a single function definition, the GNU-style or C++11 |
2412 | non-standard attribute ``optnone`` can be used. |
2413 | |
2414 | .. code-block:: c++ |
2415 | |
2416 | // The following functions will not be optimized. |
2417 | // GNU-style attribute |
2418 | __attribute__((optnone)) int foo() { |
2419 | // ... code |
2420 | } |
2421 | // C++11 attribute |
2422 | [[clang::optnone]] int bar() { |
2423 | // ... code |
2424 | } |
2425 | |
2426 | To facilitate disabling optimization for a range of function definitions, a |
2427 | range-based pragma is provided. Its syntax is ``#pragma clang optimize`` |
2428 | followed by ``off`` or ``on``. |
2429 | |
2430 | All function definitions in the region between an ``off`` and the following |
2431 | ``on`` will be decorated with the ``optnone`` attribute unless doing so would |
2432 | conflict with explicit attributes already present on the function (e.g. the |
2433 | ones that control inlining). |
2434 | |
2435 | .. code-block:: c++ |
2436 | |
2437 | #pragma clang optimize off |
2438 | // This function will be decorated with optnone. |
2439 | int foo() { |
2440 | // ... code |
2441 | } |
2442 | |
2443 | // optnone conflicts with always_inline, so bar() will not be decorated. |
2444 | __attribute__((always_inline)) int bar() { |
2445 | // ... code |
2446 | } |
2447 | #pragma clang optimize on |
2448 | |
2449 | If no ``on`` is found to close an ``off`` region, the end of the region is the |
2450 | end of the compilation unit. |
2451 | |
2452 | Note that a stray ``#pragma clang optimize on`` does not selectively enable |
2453 | additional optimizations when compiling at low optimization levels. This feature |
2454 | can only be used to selectively disable optimizations. |
2455 | |
2456 | The pragma has an effect on functions only at the point of their definition; for |
2457 | function templates, this means that the state of the pragma at the point of an |
2458 | instantiation is not necessarily relevant. Consider the following example: |
2459 | |
2460 | .. code-block:: c++ |
2461 | |
2462 | template<typename T> T twice(T t) { |
2463 | return 2 * t; |
2464 | } |
2465 | |
2466 | #pragma clang optimize off |
2467 | template<typename T> T thrice(T t) { |
2468 | return 3 * t; |
2469 | } |
2470 | |
2471 | int container(int a, int b) { |
2472 | return twice(a) + thrice(b); |
2473 | } |
2474 | #pragma clang optimize on |
2475 | |
2476 | In this example, the definition of the template function ``twice`` is outside |
2477 | the pragma region, whereas the definition of ``thrice`` is inside the region. |
2478 | The ``container`` function is also in the region and will not be optimized, but |
2479 | it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of |
2480 | these two instantiations, ``twice`` will be optimized (because its definition |
2481 | was outside the region) and ``thrice`` will not be optimized. |
2482 | |
2483 | Extensions for loop hint optimizations |
2484 | ====================================== |
2485 | |
2486 | The ``#pragma clang loop`` directive is used to specify hints for optimizing the |
2487 | subsequent for, while, do-while, or c++11 range-based for loop. The directive |
2488 | provides options for vectorization, interleaving, unrolling and |
2489 | distribution. Loop hints can be specified before any loop and will be ignored if |
2490 | the optimization is not safe to apply. |
2491 | |
2492 | Vectorization and Interleaving |
2493 | ------------------------------ |
2494 | |
2495 | A vectorized loop performs multiple iterations of the original loop |
2496 | in parallel using vector instructions. The instruction set of the target |
2497 | processor determines which vector instructions are available and their vector |
2498 | widths. This restricts the types of loops that can be vectorized. The vectorizer |
2499 | automatically determines if the loop is safe and profitable to vectorize. A |
2500 | vector instruction cost model is used to select the vector width. |
2501 | |
2502 | Interleaving multiple loop iterations allows modern processors to further |
2503 | improve instruction-level parallelism (ILP) using advanced hardware features, |
2504 | such as multiple execution units and out-of-order execution. The vectorizer uses |
2505 | a cost model that depends on the register pressure and generated code size to |
2506 | select the interleaving count. |
2507 | |
2508 | Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled |
2509 | by ``interleave(enable)``. This is useful when compiling with ``-Os`` to |
2510 | manually enable vectorization or interleaving. |
2511 | |
2512 | .. code-block:: c++ |
2513 | |
2514 | #pragma clang loop vectorize(enable) |
2515 | #pragma clang loop interleave(enable) |
2516 | for(...) { |
2517 | ... |
2518 | } |
2519 | |
2520 | The vector width is specified by ``vectorize_width(_value_)`` and the interleave |
2521 | count is specified by ``interleave_count(_value_)``, where |
2522 | _value_ is a positive integer. This is useful for specifying the optimal |
2523 | width/count of the set of target architectures supported by your application. |
2524 | |
2525 | .. code-block:: c++ |
2526 | |
2527 | #pragma clang loop vectorize_width(2) |
2528 | #pragma clang loop interleave_count(2) |
2529 | for(...) { |
2530 | ... |
2531 | } |
2532 | |
2533 | Specifying a width/count of 1 disables the optimization, and is equivalent to |
2534 | ``vectorize(disable)`` or ``interleave(disable)``. |
2535 | |
2536 | Loop Unrolling |
2537 | -------------- |
2538 | |
2539 | Unrolling a loop reduces the loop control overhead and exposes more |
2540 | opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling |
2541 | eliminates the loop and replaces it with an enumerated sequence of loop |
2542 | iterations. Full unrolling is only possible if the loop trip count is known at |
2543 | compile time. Partial unrolling replicates the loop body within the loop and |
2544 | reduces the trip count. |
2545 | |
2546 | If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the |
2547 | loop if the trip count is known at compile time. If the fully unrolled code size |
2548 | is greater than an internal limit the loop will be partially unrolled up to this |
2549 | limit. If the trip count is not known at compile time the loop will be partially |
2550 | unrolled with a heuristically chosen unroll factor. |
2551 | |
2552 | .. code-block:: c++ |
2553 | |
2554 | #pragma clang loop unroll(enable) |
2555 | for(...) { |
2556 | ... |
2557 | } |
2558 | |
2559 | If ``unroll(full)`` is specified the unroller will attempt to fully unroll the |
2560 | loop if the trip count is known at compile time identically to |
2561 | ``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled |
2562 | if the loop count is not known at compile time. |
2563 | |
2564 | .. code-block:: c++ |
2565 | |
2566 | #pragma clang loop unroll(full) |
2567 | for(...) { |
2568 | ... |
2569 | } |
2570 | |
2571 | The unroll count can be specified explicitly with ``unroll_count(_value_)`` where |
2572 | _value_ is a positive integer. If this value is greater than the trip count the |
2573 | loop will be fully unrolled. Otherwise the loop is partially unrolled subject |
2574 | to the same code size limit as with ``unroll(enable)``. |
2575 | |
2576 | .. code-block:: c++ |
2577 | |
2578 | #pragma clang loop unroll_count(8) |
2579 | for(...) { |
2580 | ... |
2581 | } |
2582 | |
2583 | Unrolling of a loop can be prevented by specifying ``unroll(disable)``. |
2584 | |
2585 | Loop Distribution |
2586 | ----------------- |
2587 | |
2588 | Loop Distribution allows splitting a loop into multiple loops. This is |
2589 | beneficial for example when the entire loop cannot be vectorized but some of the |
2590 | resulting loops can. |
2591 | |
2592 | If ``distribute(enable))`` is specified and the loop has memory dependencies |
2593 | that inhibit vectorization, the compiler will attempt to isolate the offending |
2594 | operations into a new loop. This optimization is not enabled by default, only |
2595 | loops marked with the pragma are considered. |
2596 | |
2597 | .. code-block:: c++ |
2598 | |
2599 | #pragma clang loop distribute(enable) |
2600 | for (i = 0; i < N; ++i) { |
2601 | S1: A[i + 1] = A[i] + B[i]; |
2602 | S2: C[i] = D[i] * E[i]; |
2603 | } |
2604 | |
2605 | This loop will be split into two loops between statements S1 and S2. The |
2606 | second loop containing S2 will be vectorized. |
2607 | |
2608 | Loop Distribution is currently not enabled by default in the optimizer because |
2609 | it can hurt performance in some cases. For example, instruction-level |
2610 | parallelism could be reduced by sequentializing the execution of the |
2611 | statements S1 and S2 above. |
2612 | |
2613 | If Loop Distribution is turned on globally with |
2614 | ``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can |
2615 | be used the disable it on a per-loop basis. |
2616 | |
2617 | Additional Information |
2618 | ---------------------- |
2619 | |
2620 | For convenience multiple loop hints can be specified on a single line. |
2621 | |
2622 | .. code-block:: c++ |
2623 | |
2624 | #pragma clang loop vectorize_width(4) interleave_count(8) |
2625 | for(...) { |
2626 | ... |
2627 | } |
2628 | |
2629 | If an optimization cannot be applied any hints that apply to it will be ignored. |
2630 | For example, the hint ``vectorize_width(4)`` is ignored if the loop is not |
2631 | proven safe to vectorize. To identify and diagnose optimization issues use |
2632 | `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the |
2633 | user guide for details. |
2634 | |
2635 | Extensions to specify floating-point flags |
2636 | ==================================================== |
2637 | |
2638 | The ``#pragma clang fp`` pragma allows floating-point options to be specified |
2639 | for a section of the source code. This pragma can only appear at file scope or |
2640 | at the start of a compound statement (excluding comments). When using within a |
2641 | compound statement, the pragma is active within the scope of the compound |
2642 | statement. |
2643 | |
2644 | Currently, only FP contraction can be controlled with the pragma. ``#pragma |
2645 | clang fp contract`` specifies whether the compiler should contract a multiply |
2646 | and an addition (or subtraction) into a fused FMA operation when supported by |
2647 | the target. |
2648 | |
2649 | The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on`` |
2650 | option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows |
2651 | fusion as specified the language standard. The ``fast`` option allows fusiong |
2652 | in cases when the language standard does not make this possible (e.g. across |
2653 | statements in C) |
2654 | |
2655 | .. code-block:: c++ |
2656 | |
2657 | for(...) { |
2658 | #pragma clang fp contract(fast) |
2659 | a = b[i] * c[i]; |
2660 | d[i] += a; |
2661 | } |
2662 | |
2663 | |
2664 | The pragma can also be used with ``off`` which turns FP contraction off for a |
2665 | section of the code. This can be useful when fast contraction is otherwise |
2666 | enabled for the translation unit with the ``-ffp-contract=fast`` flag. |
2667 | |
2668 | Specifying an attribute for multiple declarations (#pragma clang attribute) |
2669 | =========================================================================== |
2670 | |
2671 | The ``#pragma clang attribute`` directive can be used to apply an attribute to |
2672 | multiple declarations. The ``#pragma clang attribute push`` variation of the |
2673 | directive pushes a new "scope" of ``#pragma clang attribute`` that attributes |
2674 | can be added to. The ``#pragma clang attribute (...)`` variation adds an |
2675 | attribute to that scope, and the ``#pragma clang attribute pop`` variation pops |
2676 | the scope. You can also use ``#pragma clang attribute push (...)``, which is a |
2677 | shorthand for when you want to add one attribute to a new scope. Multiple push |
2678 | directives can be nested inside each other. |
2679 | |
2680 | The attributes that are used in the ``#pragma clang attribute`` directives |
2681 | can be written using the GNU-style syntax: |
2682 | |
2683 | .. code-block:: c++ |
2684 | |
2685 | #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function) |
2686 | |
2687 | void function(); // The function now has the annotate("custom") attribute |
2688 | |
2689 | #pragma clang attribute pop |
2690 | |
2691 | The attributes can also be written using the C++11 style syntax: |
2692 | |
2693 | .. code-block:: c++ |
2694 | |
2695 | #pragma clang attribute push ([[noreturn]], apply_to = function) |
2696 | |
2697 | void function(); // The function now has the [[noreturn]] attribute |
2698 | |
2699 | #pragma clang attribute pop |
2700 | |
2701 | The ``__declspec`` style syntax is also supported: |
2702 | |
2703 | .. code-block:: c++ |
2704 | |
2705 | #pragma clang attribute push (__declspec(dllexport), apply_to = function) |
2706 | |
2707 | void function(); // The function now has the __declspec(dllexport) attribute |
2708 | |
2709 | #pragma clang attribute pop |
2710 | |
2711 | A single push directive accepts only one attribute regardless of the syntax |
2712 | used. |
2713 | |
2714 | Because multiple push directives can be nested, if you're writing a macro that |
2715 | expands to ``_Pragma("clang attribute")`` it's good hygiene (though not |
2716 | required) to add a namespace to your push/pop directives. A pop directive with a |
2717 | namespace will pop the innermost push that has that same namespace. This will |
2718 | ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note |
2719 | that an ``pop`` without a namespace will pop the innermost ``push`` without a |
2720 | namespace. ``push``es with a namespace can only be popped by ``pop`` with the |
2721 | same namespace. For instance: |
2722 | |
2723 | .. code-block:: c++ |
2724 | |
2725 | #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)") |
2726 | #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop") |
2727 | |
2728 | #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)") |
2729 | #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop") |
2730 | |
2731 | |
2732 | ASSUME_NORETURN_BEGIN |
2733 | ASSUME_UNAVAILABLE_BEGIN |
2734 | void function(); // function has [[noreturn]] and __attribute__((unavailable)) |
2735 | ASSUME_NORETURN_END |
2736 | void other_function(); // function has __attribute__((unavailable)) |
2737 | ASSUME_UNAVAILABLE_END |
2738 | |
2739 | Without the namespaces on the macros, ``other_function`` will be annotated with |
2740 | ``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like |
2741 | a contrived example, but its very possible for this kind of situation to appear |
2742 | in real code if the pragmas are spread out across a large file. You can test if |
2743 | your version of clang supports namespaces on ``#pragma clang attribute`` with |
2744 | ``__has_extension(pragma_clang_attribute_namespaces)``. |
2745 | |
2746 | Subject Match Rules |
2747 | ------------------- |
2748 | |
2749 | The set of declarations that receive a single attribute from the attribute stack |
2750 | depends on the subject match rules that were specified in the pragma. Subject |
2751 | match rules are specified after the attribute. The compiler expects an |
2752 | identifier that corresponds to the subject set specifier. The ``apply_to`` |
2753 | specifier is currently the only supported subject set specifier. It allows you |
2754 | to specify match rules that form a subset of the attribute's allowed subject |
2755 | set, i.e. the compiler doesn't require all of the attribute's subjects. For |
2756 | example, an attribute like ``[[nodiscard]]`` whose subject set includes |
2757 | ``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at |
2758 | least one of these rules after ``apply_to``: |
2759 | |
2760 | .. code-block:: c++ |
2761 | |
2762 | #pragma clang attribute push([[nodiscard]], apply_to = enum) |
2763 | |
2764 | enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]] |
2765 | |
2766 | struct Record1 { }; // The struct will *not* receive [[nodiscard]] |
2767 | |
2768 | #pragma clang attribute pop |
2769 | |
2770 | #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum)) |
2771 | |
2772 | enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]] |
2773 | |
2774 | struct Record2 { }; // The struct *will* receive [[nodiscard]] |
2775 | |
2776 | #pragma clang attribute pop |
2777 | |
2778 | // This is an error, since [[nodiscard]] can't be applied to namespaces: |
2779 | #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace)) |
2780 | |
2781 | #pragma clang attribute pop |
2782 | |
2783 | Multiple match rules can be specified using the ``any`` match rule, as shown |
2784 | in the example above. The ``any`` rule applies attributes to all declarations |
2785 | that are matched by at least one of the rules in the ``any``. It doesn't nest |
2786 | and can't be used inside the other match rules. Redundant match rules or rules |
2787 | that conflict with one another should not be used inside of ``any``. |
2788 | |
2789 | Clang supports the following match rules: |
2790 | |
2791 | - ``function``: Can be used to apply attributes to functions. This includes C++ |
2792 | member functions, static functions, operators, and constructors/destructors. |
2793 | |
2794 | - ``function(is_member)``: Can be used to apply attributes to C++ member |
2795 | functions. This includes members like static functions, operators, and |
2796 | constructors/destructors. |
2797 | |
2798 | - ``hasType(functionType)``: Can be used to apply attributes to functions, C++ |
2799 | member functions, and variables/fields whose type is a function pointer. It |
2800 | does not apply attributes to Objective-C methods or blocks. |
2801 | |
2802 | - ``type_alias``: Can be used to apply attributes to ``typedef`` declarations |
2803 | and C++11 type aliases. |
2804 | |
2805 | - ``record``: Can be used to apply attributes to ``struct``, ``class``, and |
2806 | ``union`` declarations. |
2807 | |
2808 | - ``record(unless(is_union))``: Can be used to apply attributes only to |
2809 | ``struct`` and ``class`` declarations. |
2810 | |
2811 | - ``enum``: Can be be used to apply attributes to enumeration declarations. |
2812 | |
2813 | - ``enum_constant``: Can be used to apply attributes to enumerators. |
2814 | |
2815 | - ``variable``: Can be used to apply attributes to variables, including |
2816 | local variables, parameters, global variables, and static member variables. |
2817 | It does not apply attributes to instance member variables or Objective-C |
2818 | ivars. |
2819 | |
2820 | - ``variable(is_thread_local)``: Can be used to apply attributes to thread-local |
2821 | variables only. |
2822 | |
2823 | - ``variable(is_global)``: Can be used to apply attributes to global variables |
2824 | only. |
2825 | |
2826 | - ``variable(is_parameter)``: Can be used to apply attributes to parameters |
2827 | only. |
2828 | |
2829 | - ``variable(unless(is_parameter))``: Can be used to apply attributes to all |
2830 | the variables that are not parameters. |
2831 | |
2832 | - ``field``: Can be used to apply attributes to non-static member variables |
2833 | in a record. This includes Objective-C ivars. |
2834 | |
2835 | - ``namespace``: Can be used to apply attributes to ``namespace`` declarations. |
2836 | |
2837 | - ``objc_interface``: Can be used to apply attributes to ``@interface`` |
2838 | declarations. |
2839 | |
2840 | - ``objc_protocol``: Can be used to apply attributes to ``@protocol`` |
2841 | declarations. |
2842 | |
2843 | - ``objc_category``: Can be used to apply attributes to category declarations, |
2844 | including class extensions. |
2845 | |
2846 | - ``objc_method``: Can be used to apply attributes to Objective-C methods, |
2847 | including instance and class methods. Implicit methods like implicit property |
2848 | getters and setters do not receive the attribute. |
2849 | |
2850 | - ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C |
2851 | instance methods. |
2852 | |
2853 | - ``objc_property``: Can be used to apply attributes to ``@property`` |
2854 | declarations. |
2855 | |
2856 | - ``block``: Can be used to apply attributes to block declarations. This does |
2857 | not include variables/fields of block pointer type. |
2858 | |
2859 | The use of ``unless`` in match rules is currently restricted to a strict set of |
2860 | sub-rules that are used by the supported attributes. That means that even though |
2861 | ``variable(unless(is_parameter))`` is a valid match rule, |
2862 | ``variable(unless(is_thread_local))`` is not. |
2863 | |
2864 | Supported Attributes |
2865 | -------------------- |
2866 | |
2867 | Not all attributes can be used with the ``#pragma clang attribute`` directive. |
2868 | Notably, statement attributes like ``[[fallthrough]]`` or type attributes |
2869 | like ``address_space`` aren't supported by this directive. You can determine |
2870 | whether or not an attribute is supported by the pragma by referring to the |
2871 | :doc:`individual documentation for that attribute <AttributeReference>`. |
2872 | |
2873 | The attributes are applied to all matching declarations individually, even when |
2874 | the attribute is semantically incorrect. The attributes that aren't applied to |
2875 | any declaration are not verified semantically. |
2876 | |
2877 | Specifying section names for global objects (#pragma clang section) |
2878 | =================================================================== |
2879 | |
2880 | The ``#pragma clang section`` directive provides a means to assign section-names |
2881 | to global variables, functions and static variables. |
2882 | |
2883 | The section names can be specified as: |
2884 | |
2885 | .. code-block:: c++ |
2886 | |
2887 | #pragma clang section bss="myBSS" data="myData" rodata="myRodata" text="myText" |
2888 | |
2889 | The section names can be reverted back to default name by supplying an empty |
2890 | string to the section kind, for example: |
2891 | |
2892 | .. code-block:: c++ |
2893 | |
2894 | #pragma clang section bss="" data="" text="" rodata="" |
2895 | |
2896 | The ``#pragma clang section`` directive obeys the following rules: |
2897 | |
2898 | * The pragma applies to all global variable, statics and function declarations |
2899 | from the pragma to the end of the translation unit. |
2900 | |
2901 | * The pragma clang section is enabled automatically, without need of any flags. |
2902 | |
2903 | * This feature is only defined to work sensibly for ELF targets. |
2904 | |
2905 | * If section name is specified through _attribute_((section("myname"))), then |
2906 | the attribute name gains precedence. |
2907 | |
2908 | * Global variables that are initialized to zero will be placed in the named |
2909 | bss section, if one is present. |
2910 | |
2911 | * The ``#pragma clang section`` directive does not does try to infer section-kind |
2912 | from the name. For example, naming a section "``.bss.mySec``" does NOT mean |
2913 | it will be a bss section name. |
2914 | |
2915 | * The decision about which section-kind applies to each global is taken in the back-end. |
2916 | Once the section-kind is known, appropriate section name, as specified by the user using |
2917 | ``#pragma clang section`` directive, is applied to that global. |
2918 | |
2919 | Specifying Linker Options on ELF Targets |
2920 | ======================================== |
2921 | |
2922 | The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets. |
2923 | The second parameter is the library name (without the traditional Unix prefix of |
2924 | ``lib``). This allows you to provide an implicit link of dependent libraries. |
2925 | |
2926 | Evaluating Object Size Dynamically |
2927 | ================================== |
2928 | |
2929 | Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are |
2930 | the same as GCC's ``__builtin_object_size`` (which Clang also supports), but |
2931 | ``__builtin_dynamic_object_size`` can evaluate the object's size at runtime. |
2932 | ``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement |
2933 | for ``__builtin_object_size`` in libraries that support it. |
2934 | |
2935 | For instance, here is a program that ``__builtin_dynamic_object_size`` will make |
2936 | safer: |
2937 | |
2938 | .. code-block:: c |
2939 | |
2940 | void copy_into_buffer(size_t size) { |
2941 | char* buffer = malloc(size); |
2942 | strlcpy(buffer, "some string", strlen("some string")); |
2943 | // Previous line preprocesses to: |
2944 | // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0)) |
2945 | } |
2946 | |
2947 | Since the size of ``buffer`` can't be known at compile time, Clang will fold |
2948 | ``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written |
2949 | as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into |
2950 | ``size``, providing some extra runtime safety. |
2951 | |