Debian Codegraph @

clang/docs/LanguageExtensions.rst

raw
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 PointerAuthentication
17 MatrixTypes
18
19 Introduction
20 ============
21
22 This document describes the language extensions provided by Clang. In addition
23 to the language extensions listed here, Clang aims to support a broad range of
24 GCC extensions. Please see the `GCC manual
25 <https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
26 these extensions.
27
28 .. _langext-feature_check:
29
30 Feature Checking Macros
31 =======================
32
33 Language extensions can be very useful, but only if you know you can depend on
34 them. In order to allow fine-grain features checks, we support three builtin
35 function-like macros. This allows you to directly test for a feature in your
36 code without having to resort to something like autoconf or fragile "compiler
37 version checks".
38
39 ``__has_builtin``
40 -----------------
41
42 This function-like macro takes a single identifier argument that is the name of
43 a builtin function, a builtin pseudo-function (taking one or more type
44 arguments), or a builtin template.
45 It evaluates to 1 if the builtin is supported or 0 if not.
46 It can be used like this:
47
48 .. code-block:: c++
49
50 #ifndef __has_builtin // Optional of course.
51 #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
52 #endif
53
54 ...
55 #if __has_builtin(__builtin_trap)
56 __builtin_trap();
57 #else
58 abort();
59 #endif
60 ...
61
62 .. note::
63
64 Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin
65 pseudo-functions.
66
67 ``__has_builtin`` should not be used to detect support for a builtin macro;
68 use ``#ifdef`` instead.
69
70 ``__has_constexpr_builtin``
71 ---------------------------
72
73 This function-like macro takes a single identifier argument that is the name of
74 a builtin function, a builtin pseudo-function (taking one or more type
75 arguments), or a builtin template.
76 It evaluates to 1 if the builtin is supported and can be constant evaluated or
77 0 if not. It can be used for writing conditionally constexpr code like this:
78
79 .. code-block:: c++
80
81 #ifndef __has_constexpr_builtin // Optional of course.
82 #define __has_constexpr_builtin(x) 0 // Compatibility with non-clang compilers.
83 #endif
84
85 ...
86 #if __has_constexpr_builtin(__builtin_fmax)
87 constexpr
88 #endif
89 double money_fee(double amount) {
90 return __builtin_fmax(amount * 0.03, 10.0);
91 }
92 ...
93
94 For example, ``__has_constexpr_builtin`` is used in libcxx's implementation of
95 the ``<cmath>`` header file to conditionally make a function constexpr whenever
96 the constant evaluation of the corresponding builtin (for example,
97 ``std::fmax`` calls ``__builtin_fmax``) is supported in Clang.
98
99 .. _langext-__has_feature-__has_extension:
100
101 ``__has_feature`` and ``__has_extension``
102 -----------------------------------------
103
104 These function-like macros take a single identifier argument that is the name
105 of a feature. ``__has_feature`` evaluates to 1 if the feature is both
106 supported by Clang and standardized in the current language standard or 0 if
107 not (but see :ref:`below <langext-has-feature-back-compat>`), while
108 ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
109 current language (either as a language extension or a standard language
110 feature) or 0 if not. They can be used like this:
111
112 .. code-block:: c++
113
114 #ifndef __has_feature // Optional of course.
115 #define __has_feature(x) 0 // Compatibility with non-clang compilers.
116 #endif
117 #ifndef __has_extension
118 #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
119 #endif
120
121 ...
122 #if __has_feature(cxx_rvalue_references)
123 // This code will only be compiled with the -std=c++11 and -std=gnu++11
124 // options, because rvalue references are only standardized in C++11.
125 #endif
126
127 #if __has_extension(cxx_rvalue_references)
128 // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
129 // and -std=gnu++98 options, because rvalue references are supported as a
130 // language extension in C++98.
131 #endif
132
133 .. _langext-has-feature-back-compat:
134
135 For backward compatibility, ``__has_feature`` can also be used to test
136 for support for non-standardized features, i.e. features not prefixed ``c_``,
137 ``cxx_`` or ``objc_``.
138
139 Another use of ``__has_feature`` is to check for compiler features not related
140 to the language standard, such as e.g. :doc:`AddressSanitizer
141 <AddressSanitizer>`.
142
143 If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
144 to ``__has_feature``.
145
146 The feature tag is described along with the language feature below.
147
148 The feature name or extension name can also be specified with a preceding and
149 following ``__`` (double underscore) to avoid interference from a macro with
150 the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
151 of ``cxx_rvalue_references``.
152
153 ``__has_cpp_attribute``
154 -----------------------
155
156 This function-like macro is available in C++20 by default, and is provided as an
157 extension in earlier language standards. It takes a single argument that is the
158 name of a double-square-bracket-style attribute. The argument can either be a
159 single identifier or a scoped identifier. If the attribute is supported, a
160 nonzero value is returned. If the attribute is a standards-based attribute, this
161 macro returns a nonzero value based on the year and month in which the attribute
162 was voted into the working draft. See `WG21 SD-6
163 <https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
164 for the list of values returned for standards-based attributes. If the attribute
165 is not supported by the current compilation target, this macro evaluates to 0.
166 It can be used like this:
167
168 .. code-block:: c++
169
170 #ifndef __has_cpp_attribute // For backwards compatibility
171 #define __has_cpp_attribute(x) 0
172 #endif
173
174 ...
175 #if __has_cpp_attribute(clang::fallthrough)
176 #define FALLTHROUGH [[clang::fallthrough]]
177 #else
178 #define FALLTHROUGH
179 #endif
180 ...
181
182 The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
183 the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
184 of these namespaces can be specified with a preceding and following ``__``
185 (double underscore) to avoid interference from a macro with the same name. For
186 instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
187
188 ``__has_c_attribute``
189 ---------------------
190
191 This function-like macro takes a single argument that is the name of an
192 attribute exposed with the double square-bracket syntax in C mode. The argument
193 can either be a single identifier or a scoped identifier. If the attribute is
194 supported, a nonzero value is returned. If the attribute is not supported by the
195 current compilation target, this macro evaluates to 0. It can be used like this:
196
197 .. code-block:: c
198
199 #ifndef __has_c_attribute // Optional of course.
200 #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers.
201 #endif
202
203 ...
204 #if __has_c_attribute(fallthrough)
205 #define FALLTHROUGH [[fallthrough]]
206 #else
207 #define FALLTHROUGH
208 #endif
209 ...
210
211 The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
212 the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
213 of these namespaces can be specified with a preceding and following ``__``
214 (double underscore) to avoid interference from a macro with the same name. For
215 instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
216
217 ``__has_attribute``
218 -------------------
219
220 This function-like macro takes a single identifier argument that is the name of
221 a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
222 current compilation target, or 0 if not. It can be used like this:
223
224 .. code-block:: c++
225
226 #ifndef __has_attribute // Optional of course.
227 #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
228 #endif
229
230 ...
231 #if __has_attribute(always_inline)
232 #define ALWAYS_INLINE __attribute__((always_inline))
233 #else
234 #define ALWAYS_INLINE
235 #endif
236 ...
237
238 The attribute name can also be specified with a preceding and following ``__``
239 (double underscore) to avoid interference from a macro with the same name. For
240 instance, ``__always_inline__`` can be used instead of ``always_inline``.
241
242
243 ``__has_declspec_attribute``
244 ----------------------------
245
246 This function-like macro takes a single identifier argument that is the name of
247 an attribute implemented as a Microsoft-style ``__declspec`` attribute. It
248 evaluates to 1 if the attribute is supported by the current compilation target,
249 or 0 if not. It can be used like this:
250
251 .. code-block:: c++
252
253 #ifndef __has_declspec_attribute // Optional of course.
254 #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers.
255 #endif
256
257 ...
258 #if __has_declspec_attribute(dllexport)
259 #define DLLEXPORT __declspec(dllexport)
260 #else
261 #define DLLEXPORT
262 #endif
263 ...
264
265 The attribute name can also be specified with a preceding and following ``__``
266 (double underscore) to avoid interference from a macro with the same name. For
267 instance, ``__dllexport__`` can be used instead of ``dllexport``.
268
269 ``__is_identifier``
270 -------------------
271
272 This function-like macro takes a single identifier argument that might be either
273 a reserved word or a regular identifier. It evaluates to 1 if the argument is just
274 a regular identifier and not a reserved word, in the sense that it can then be
275 used as the name of a user-defined function or variable. Otherwise it evaluates
276 to 0. It can be used like this:
277
278 .. code-block:: c++
279
280 ...
281 #ifdef __is_identifier // Compatibility with non-clang compilers.
282 #if __is_identifier(__wchar_t)
283 typedef wchar_t __wchar_t;
284 #endif
285 #endif
286
287 __wchar_t WideCharacter;
288 ...
289
290 Include File Checking Macros
291 ============================
292
293 Not all developments systems have the same include files. The
294 :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
295 you to check for the existence of an include file before doing a possibly
296 failing ``#include`` directive. Include file checking macros must be used
297 as expressions in ``#if`` or ``#elif`` preprocessing directives.
298
299 .. _langext-__has_include:
300
301 ``__has_include``
302 -----------------
303
304 This function-like macro takes a single file name string argument that is the
305 name of an include file. It evaluates to 1 if the file can be found using the
306 include paths, or 0 otherwise:
307
308 .. code-block:: c++
309
310 // Note the two possible file name string formats.
311 #if __has_include("myinclude.h") && __has_include(<stdint.h>)
312 # include "myinclude.h"
313 #endif
314
315 To test for this feature, use ``#if defined(__has_include)``:
316
317 .. code-block:: c++
318
319 // To avoid problem with non-clang compilers not having this macro.
320 #if defined(__has_include)
321 #if __has_include("myinclude.h")
322 # include "myinclude.h"
323 #endif
324 #endif
325
326 .. _langext-__has_include_next:
327
328 ``__has_include_next``
329 ----------------------
330
331 This function-like macro takes a single file name string argument that is the
332 name of an include file. It is like ``__has_include`` except that it looks for
333 the second instance of the given file found in the include paths. It evaluates
334 to 1 if the second instance of the file can be found using the include paths,
335 or 0 otherwise:
336
337 .. code-block:: c++
338
339 // Note the two possible file name string formats.
340 #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
341 # include_next "myinclude.h"
342 #endif
343
344 // To avoid problem with non-clang compilers not having this macro.
345 #if defined(__has_include_next)
346 #if __has_include_next("myinclude.h")
347 # include_next "myinclude.h"
348 #endif
349 #endif
350
351 Note that ``__has_include_next``, like the GNU extension ``#include_next``
352 directive, is intended for use in headers only, and will issue a warning if
353 used in the top-level compilation file. A warning will also be issued if an
354 absolute path is used in the file argument.
355
356 ``__has_warning``
357 -----------------
358
359 This function-like macro takes a string literal that represents a command line
360 option for a warning and returns true if that is a valid warning option.
361
362 .. code-block:: c++
363
364 #if __has_warning("-Wformat")
365 ...
366 #endif
367
368 .. _languageextensions-builtin-macros:
369
370 Builtin Macros
371 ==============
372
373 ``__BASE_FILE__``
374 Defined to a string that contains the name of the main input file passed to
375 Clang.
376
377 ``__FILE_NAME__``
378 Clang-specific extension that functions similar to ``__FILE__`` but only
379 renders the last path component (the filename) instead of an invocation
380 dependent full path to that file.
381
382 ``__COUNTER__``
383 Defined to an integer value that starts at zero and is incremented each time
384 the ``__COUNTER__`` macro is expanded.
385
386 ``__INCLUDE_LEVEL__``
387 Defined to an integral value that is the include depth of the file currently
388 being translated. For the main file, this value is zero.
389
390 ``__TIMESTAMP__``
391 Defined to the date and time of the last modification of the current source
392 file.
393
394 ``__clang__``
395 Defined when compiling with Clang
396
397 ``__clang_major__``
398 Defined to the major marketing version number of Clang (e.g., the 2 in
399 2.0.1). Note that marketing version numbers should not be used to check for
400 language features, as different vendors use different numbering schemes.
401 Instead, use the :ref:`langext-feature_check`.
402
403 ``__clang_minor__``
404 Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
405 that marketing version numbers should not be used to check for language
406 features, as different vendors use different numbering schemes. Instead, use
407 the :ref:`langext-feature_check`.
408
409 ``__clang_patchlevel__``
410 Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
411
412 ``__clang_version__``
413 Defined to a string that captures the Clang marketing version, including the
414 Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
415
416 ``__clang_literal_encoding__``
417 Defined to a narrow string literal that represents the current encoding of
418 narrow string literals, e.g., ``"hello"``. This macro typically expands to
419 "UTF-8" (but may change in the future if the
420 ``-fexec-charset="Encoding-Name"`` option is implemented.)
421
422 ``__clang_wide_literal_encoding__``
423 Defined to a narrow string literal that represents the current encoding of
424 wide string literals, e.g., ``L"hello"``. This macro typically expands to
425 "UTF-16" or "UTF-32" (but may change in the future if the
426 ``-fwide-exec-charset="Encoding-Name"`` option is implemented.)
427
428 Implementation-defined keywords
429 ===============================
430
431 __datasizeof
432 ------------
433
434 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of the
435 type ignoring tail padding.
436
437 ..
438 FIXME: This should list all the keyword extensions
439
440 .. _langext-vectors:
441
442 Vectors and Extended Vectors
443 ============================
444
445 Supports the GCC, OpenCL, AltiVec, NEON and SVE vector extensions.
446
447 OpenCL vector types are created using the ``ext_vector_type`` attribute. It
448 supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
449 is:
450
451 .. code-block:: c++
452
453 typedef float float4 __attribute__((ext_vector_type(4)));
454 typedef float float2 __attribute__((ext_vector_type(2)));
455
456 float4 foo(float2 a, float2 b) {
457 float4 c;
458 c.xz = a;
459 c.yw = b;
460 return c;
461 }
462
463 Query for this feature with ``__has_attribute(ext_vector_type)``.
464
465 Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
466 and functions. For example:
467
468 .. code-block:: c++
469
470 vector float foo(vector int a) {
471 vector int b;
472 b = vec_add(a, a) + a;
473 return (vector float)b;
474 }
475
476 NEON vector types are created using ``neon_vector_type`` and
477 ``neon_polyvector_type`` attributes. For example:
478
479 .. code-block:: c++
480
481 typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
482 typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
483
484 int8x8_t foo(int8x8_t a) {
485 int8x8_t v;
486 v = a;
487 return v;
488 }
489
490 GCC vector types are created using the ``vector_size(N)`` attribute. The
491 argument ``N`` specifies the number of bytes that will be allocated for an
492 object of this type. The size has to be multiple of the size of the vector
493 element type. For example:
494
495 .. code-block:: c++
496
497 // OK: This declares a vector type with four 'int' elements
498 typedef int int4 __attribute__((vector_size(4 * sizeof(int))));
499
500 // ERROR: '11' is not a multiple of sizeof(int)
501 typedef int int_impossible __attribute__((vector_size(11)));
502
503 int4 foo(int4 a) {
504 int4 v;
505 v = a;
506 return v;
507 }
508
509
510 Boolean Vectors
511 ---------------
512
513 Clang also supports the ext_vector_type attribute with boolean element types in
514 C and C++. For example:
515
516 .. code-block:: c++
517
518 // legal for Clang, error for GCC:
519 typedef bool bool4 __attribute__((ext_vector_type(4)));
520 // Objects of bool4 type hold 8 bits, sizeof(bool4) == 1
521
522 bool4 foo(bool4 a) {
523 bool4 v;
524 v = a;
525 return v;
526 }
527
528 Boolean vectors are a Clang extension of the ext vector type. Boolean vectors
529 are intended, though not guaranteed, to map to vector mask registers. The size
530 parameter of a boolean vector type is the number of bits in the vector. The
531 boolean vector is dense and each bit in the boolean vector is one vector
532 element.
533
534 The semantics of boolean vectors borrows from C bit-fields with the following
535 differences:
536
537 * Distinct boolean vectors are always distinct memory objects (there is no
538 packing).
539 * Only the operators `?:`, `!`, `~`, `|`, `&`, `^` and comparison are allowed on
540 boolean vectors.
541 * Casting a scalar bool value to a boolean vector type means broadcasting the
542 scalar value onto all lanes (same as general ext_vector_type).
543 * It is not possible to access or swizzle elements of a boolean vector
544 (different than general ext_vector_type).
545
546 The size and alignment are both the number of bits rounded up to the next power
547 of two, but the alignment is at most the maximum vector alignment of the
548 target.
549
550
551 Vector Literals
552 ---------------
553
554 Vector literals can be used to create vectors from a set of scalars, or
555 vectors. Either parentheses or braces form can be used. In the parentheses
556 form the number of literal values specified must be one, i.e. referring to a
557 scalar value, or must match the size of the vector type being created. If a
558 single scalar literal value is specified, the scalar literal value will be
559 replicated to all the components of the vector type. In the brackets form any
560 number of literals can be specified. For example:
561
562 .. code-block:: c++
563
564 typedef int v4si __attribute__((__vector_size__(16)));
565 typedef float float4 __attribute__((ext_vector_type(4)));
566 typedef float float2 __attribute__((ext_vector_type(2)));
567
568 v4si vsi = (v4si){1, 2, 3, 4};
569 float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
570 vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
571 vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
572 vector int vi3 = (vector int)(1, 2); // error
573 vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
574 vector int vi5 = (vector int)(1, 2, 3, 4);
575 float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
576
577 Vector Operations
578 -----------------
579
580 The table below shows the support for each operation by vector extension. A
581 dash indicates that an operation is not accepted according to a corresponding
582 specification.
583
584 ============================== ======= ======= ============= ======= =====
585 Operator OpenCL AltiVec GCC NEON SVE
586 ============================== ======= ======= ============= ======= =====
587 [] yes yes yes yes yes
588 unary operators +, -- yes yes yes yes yes
589 ++, -- -- yes yes yes no no
590 +,--,*,/,% yes yes yes yes yes
591 bitwise operators &,|,^,~ yes yes yes yes yes
592 >>,<< yes yes yes yes yes
593 !, &&, || yes -- yes yes yes
594 ==, !=, >, <, >=, <= yes yes yes yes yes
595 = yes yes yes yes yes
596 ?: [#]_ yes -- yes yes yes
597 sizeof yes yes yes yes yes [#]_
598 C-style cast yes yes yes no no
599 reinterpret_cast yes no yes no no
600 static_cast yes no yes no no
601 const_cast no no no no no
602 address &v[i] no no no [#]_ no no
603 ============================== ======= ======= ============= ======= =====
604
605 See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
606
607 .. [#] ternary operator(?:) has different behaviors depending on condition
608 operand's vector type. If the condition is a GNU vector (i.e. __vector_size__),
609 a NEON vector or an SVE vector, it's only available in C++ and uses normal bool
610 conversions (that is, != 0).
611 If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.
612 And it selects base on signedness of the condition operands (OpenCL v1.1 s6.3.9).
613 .. [#] sizeof can only be used on vector length specific SVE types.
614 .. [#] Clang does not allow the address of an element to be taken while GCC
615 allows this. This is intentional for vectors with a boolean element type and
616 not implemented otherwise.
617
618 Vector Builtins
619 ---------------
620
621 **Note: The implementation of vector builtins is work-in-progress and incomplete.**
622
623 In addition to the operators mentioned above, Clang provides a set of builtins
624 to perform additional operations on certain scalar and vector types.
625
626 Let ``T`` be one of the following types:
627
628 * an integer type (as in C23 6.2.5p22), but excluding enumerated types and ``bool``
629 * the standard floating types float or double
630 * a half-precision floating point type, if one is supported on the target
631 * a vector type.
632
633 For scalar types, consider the operation applied to a vector with a single element.
634
635 *Vector Size*
636 To determine the number of elements in a vector, use ``__builtin_vectorelements()``.
637 For fixed-sized vectors, e.g., defined via ``__attribute__((vector_size(N)))`` or ARM
638 NEON's vector types (e.g., ``uint16x8_t``), this returns the constant number of
639 elements at compile-time. For scalable vectors, e.g., SVE or RISC-V V, the number of
640 elements is not known at compile-time and is determined at runtime. This builtin can
641 be used, e.g., to increment the loop-counter in vector-type agnostic loops.
642
643 *Elementwise Builtins*
644
645 Each builtin returns a vector equivalent to applying the specified operation
646 elementwise to the input.
647
648 Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = ±infinity
649
650 =========================================== ================================================================ =========================================
651 Name Operation Supported element types
652 =========================================== ================================================================ =========================================
653 T __builtin_elementwise_abs(T x) return the absolute value of a number x; the absolute value of signed integer and floating point types
654 the most negative integer remains the most negative integer
655 T __builtin_elementwise_fma(T x, T y, T z) fused multiply add, (x * y) + z. floating point types
656 T __builtin_elementwise_ceil(T x) return the smallest integral value greater than or equal to x floating point types
657 T __builtin_elementwise_sin(T x) return the sine of x interpreted as an angle in radians floating point types
658 T __builtin_elementwise_cos(T x) return the cosine of x interpreted as an angle in radians floating point types
659 T __builtin_elementwise_tan(T x) return the tangent of x interpreted as an angle in radians floating point types
660 T __builtin_elementwise_asin(T x) return the arcsine of x interpreted as an angle in radians floating point types
661 T __builtin_elementwise_acos(T x) return the arccosine of x interpreted as an angle in radians floating point types
662 T __builtin_elementwise_atan(T x) return the arctangent of x interpreted as an angle in radians floating point types
663 T __builtin_elementwise_sinh(T x) return the hyperbolic sine of angle x in radians floating point types
664 T __builtin_elementwise_cosh(T x) return the hyperbolic cosine of angle x in radians floating point types
665 T __builtin_elementwise_tanh(T x) return the hyperbolic tangent of angle x in radians floating point types
666 T __builtin_elementwise_floor(T x) return the largest integral value less than or equal to x floating point types
667 T __builtin_elementwise_log(T x) return the natural logarithm of x floating point types
668 T __builtin_elementwise_log2(T x) return the base 2 logarithm of x floating point types
669 T __builtin_elementwise_log10(T x) return the base 10 logarithm of x floating point types
670 T __builtin_elementwise_pow(T x, T y) return x raised to the power of y floating point types
671 T __builtin_elementwise_bitreverse(T x) return the integer represented after reversing the bits of x integer types
672 T __builtin_elementwise_exp(T x) returns the base-e exponential, e^x, of the specified value floating point types
673 T __builtin_elementwise_exp2(T x) returns the base-2 exponential, 2^x, of the specified value floating point types
674
675 T __builtin_elementwise_sqrt(T x) return the square root of a floating-point number floating point types
676 T __builtin_elementwise_roundeven(T x) round x to the nearest integer value in floating point format, floating point types
677 rounding halfway cases to even (that is, to the nearest value
678 that is an even integer), regardless of the current rounding
679 direction.
680 T __builtin_elementwise_round(T x) round x to the nearest integer value in floating point format, floating point types
681 rounding halfway cases away from zero, regardless of the
682 current rounding direction. May raise floating-point
683 exceptions.
684 T __builtin_elementwise_trunc(T x) return the integral value nearest to but no larger in floating point types
685 magnitude than x
686
687 T __builtin_elementwise_nearbyint(T x) round x to the nearest integer value in floating point format, floating point types
688 rounding according to the current rounding direction.
689 May not raise the inexact floating-point exception. This is
690 treated the same as ``__builtin_elementwise_rint`` unless
691 :ref:`FENV_ACCESS is enabled <floating-point-environment>`.
692
693 T __builtin_elementwise_rint(T x) round x to the nearest integer value in floating point format, floating point types
694 rounding according to the current rounding
695 direction. May raise floating-point exceptions. This is treated
696 the same as ``__builtin_elementwise_nearbyint`` unless
697 :ref:`FENV_ACCESS is enabled <floating-point-environment>`.
698
699 T __builtin_elementwise_canonicalize(T x) return the platform specific canonical encoding floating point types
700 of a floating-point number
701 T __builtin_elementwise_copysign(T x, T y) return the magnitude of x with the sign of y. floating point types
702 T __builtin_elementwise_max(T x, T y) return x or y, whichever is larger integer and floating point types
703 T __builtin_elementwise_min(T x, T y) return x or y, whichever is smaller integer and floating point types
704 T __builtin_elementwise_add_sat(T x, T y) return the sum of x and y, clamped to the range of integer types
705 representable values for the signed/unsigned integer type.
706 T __builtin_elementwise_sub_sat(T x, T y) return the difference of x and y, clamped to the range of integer types
707 representable values for the signed/unsigned integer type.
708 =========================================== ================================================================ =========================================
709
710
711 *Reduction Builtins*
712
713 Each builtin returns a scalar equivalent to applying the specified
714 operation(x, y) as recursive even-odd pairwise reduction to all vector
715 elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping
716 even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with
717 ``i in [0, Number of elements / 2)``. If the numbers of elements is not a
718 power of 2, the vector is widened with neutral elements for the reduction
719 at the end to the next power of 2.
720
721 These reductions support both fixed-sized and scalable vector types.
722
723 Example:
724
725 .. code-block:: c++
726
727 __builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0])
728 = (e3 + e2) + (e1 + e0)
729
730
731 Let ``VT`` be a vector type and ``ET`` the element type of ``VT``.
732
733 ======================================= ================================================================ ==================================
734 Name Operation Supported element types
735 ======================================= ================================================================ ==================================
736 ET __builtin_reduce_max(VT a) return x or y, whichever is larger; If exactly one argument is integer and floating point types
737 a NaN, return the other argument. If both arguments are NaNs,
738 fmax() return a NaN.
739 ET __builtin_reduce_min(VT a) return x or y, whichever is smaller; If exactly one argument integer and floating point types
740 is a NaN, return the other argument. If both arguments are
741 NaNs, fmax() return a NaN.
742 ET __builtin_reduce_add(VT a) \+ integer types
743 ET __builtin_reduce_mul(VT a) \* integer types
744 ET __builtin_reduce_and(VT a) & integer types
745 ET __builtin_reduce_or(VT a) \| integer types
746 ET __builtin_reduce_xor(VT a) ^ integer types
747 ======================================= ================================================================ ==================================
748
749 Matrix Types
750 ============
751
752 Clang provides an extension for matrix types, which is currently being
753 implemented. See :ref:`the draft specification <matrixtypes>` for more details.
754
755 For example, the code below uses the matrix types extension to multiply two 4x4
756 float matrices and add the result to a third 4x4 matrix.
757
758 .. code-block:: c++
759
760 typedef float m4x4_t __attribute__((matrix_type(4, 4)));
761
762 m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) {
763 return a + b * c;
764 }
765
766 The matrix type extension also supports operations on a matrix and a scalar.
767
768 .. code-block:: c++
769
770 typedef float m4x4_t __attribute__((matrix_type(4, 4)));
771
772 m4x4_t f(m4x4_t a) {
773 return (a + 23) * 12;
774 }
775
776 The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix.
777
778 .. code-block:: c++
779
780 typedef float m4x4_t __attribute__((matrix_type(4, 4)));
781
782 m4x4_t f(m4x4_t a) {
783 a = a / 3.0;
784 return a;
785 }
786
787 The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices
788 and on a matrix and a scalar, provided their types are consistent.
789
790 .. code-block:: c++
791
792 typedef float m4x4_t __attribute__((matrix_type(4, 4)));
793
794 m4x4_t f(m4x4_t a, m4x4_t b) {
795 a += b;
796 a -= b;
797 a *= b;
798 a += 23;
799 a -= 12;
800 return a;
801 }
802
803 The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed.
804
805 .. code-block:: c++
806
807 typedef int ix5x5 __attribute__((matrix_type(5, 5)));
808 typedef float fx5x5 __attribute__((matrix_type(5, 5)));
809
810 fx5x5 f1(ix5x5 i, fx5x5 f) {
811 return (fx5x5) i;
812 }
813
814
815 template <typename X>
816 using matrix_4_4 = X __attribute__((matrix_type(4, 4)));
817
818 void f2() {
819 matrix_5_5<double> d;
820 matrix_5_5<int> i;
821 i = (matrix_5_5<int>)d;
822 i = static_cast<matrix_5_5<int>>(d);
823 }
824
825 Half-Precision Floating Point
826 =============================
827
828 Clang supports three half-precision (16-bit) floating point types:
829 ``__fp16``, ``_Float16`` and ``__bf16``. These types are supported
830 in all language modes, but their support differs between targets.
831 A target is said to have "native support" for a type if the target
832 processor offers instructions for directly performing basic arithmetic
833 on that type. In the absence of native support, a type can still be
834 supported if the compiler can emulate arithmetic on the type by promoting
835 to ``float``; see below for more information on this emulation.
836
837 * ``__fp16`` is supported on all targets. The special semantics of this
838 type mean that no arithmetic is ever performed directly on ``__fp16`` values;
839 see below.
840
841 * ``_Float16`` is supported on the following targets:
842
843 * 32-bit ARM (natively on some architecture versions)
844 * 64-bit ARM (AArch64) (natively on ARMv8.2a and above)
845 * AMDGPU (natively)
846 * NVPTX (natively)
847 * SPIR (natively)
848 * X86 (if SSE2 is available; natively if AVX512-FP16 is also available)
849 * RISC-V (natively if Zfh or Zhinx is available)
850
851 * ``__bf16`` is supported on the following targets (currently never natively):
852
853 * 32-bit ARM
854 * 64-bit ARM (AArch64)
855 * RISC-V
856 * X86 (when SSE2 is available)
857
858 (For X86, SSE2 is available on 64-bit and all recent 32-bit processors.)
859
860 ``__fp16`` and ``_Float16`` both use the binary16 format from IEEE
861 754-2008, which provides a 5-bit exponent and an 11-bit significand
862 (counting the implicit leading 1). ``__bf16`` uses the `bfloat16
863 <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format>`_ format,
864 which provides an 8-bit exponent and an 8-bit significand; this is the same
865 exponent range as `float`, just with greatly reduced precision.
866
867 ``_Float16`` and ``__bf16`` follow the usual rules for arithmetic
868 floating-point types. Most importantly, this means that arithmetic operations
869 on operands of these types are formally performed in the type and produce
870 values of the type. ``__fp16`` does not follow those rules: most operations
871 immediately promote operands of type ``__fp16`` to ``float``, and so
872 arithmetic operations are defined to be performed in ``float`` and so result in
873 a value of type ``float`` (unless further promoted because of other operands).
874 See below for more information on the exact specifications of these types.
875
876 When compiling arithmetic on ``_Float16`` and ``__bf16`` for a target without
877 native support, Clang will perform the arithmetic in ``float``, inserting
878 extensions and truncations as necessary. This can be done in a way that
879 exactly matches the operation-by-operation behavior of native support,
880 but that can require many extra truncations and extensions. By default,
881 when emulating ``_Float16`` and ``__bf16`` arithmetic using ``float``, Clang
882 does not truncate intermediate operands back to their true type unless the
883 operand is the result of an explicit cast or assignment. This is generally
884 much faster but can generate different results from strict operation-by-operation
885 emulation. Usually the results are more precise. This is permitted by the
886 C and C++ standards under the rules for excess precision in intermediate operands;
887 see the discussion of evaluation formats in the C standard and [expr.pre] in
888 the C++ standard.
889
890 The use of excess precision can be independently controlled for these two
891 types with the ``-ffloat16-excess-precision=`` and
892 ``-fbfloat16-excess-precision=`` options. Valid values include:
893
894 * ``none``: meaning to perform strict operation-by-operation emulation
895 * ``standard``: meaning that excess precision is permitted under the rules
896 described in the standard, i.e. never across explicit casts or statements
897 * ``fast``: meaning that excess precision is permitted whenever the
898 optimizer sees an opportunity to avoid truncations; currently this has no
899 effect beyond ``standard``
900
901 The ``_Float16`` type is an interchange floating type specified in
902 ISO/IEC TS 18661-3:2015 ("Floating-point extensions for C"). It will
903 be supported on more targets as they define ABIs for it.
904
905 The ``__bf16`` type is a non-standard extension, but it generally follows
906 the rules for arithmetic interchange floating types from ISO/IEC TS
907 18661-3:2015. In previous versions of Clang, it was a storage-only type
908 that forbade arithmetic operations. It will be supported on more targets
909 as they define ABIs for it.
910
911 The ``__fp16`` type was originally an ARM extension and is specified
912 by the `ARM C Language Extensions <https://github.com/ARM-software/acle/releases>`_.
913 Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``,
914 not the ARM alternative format. Operators that expect arithmetic operands
915 immediately promote ``__fp16`` operands to ``float``.
916
917 It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
918 as it has been defined by the C standards committee and has behavior that is
919 more familiar to most programmers.
920
921 Because ``__fp16`` operands are always immediately promoted to ``float``, the
922 common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
923 arithmetic conversions is ``float``.
924
925 A literal can be given ``_Float16`` type using the suffix ``f16``. For example,
926 ``3.14f16``.
927
928 Because default argument promotion only applies to the standard floating-point
929 types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
930 or untyped arguments. As a consequence, some caution must be taken when using
931 certain library facilities with ``_Float16``; for example, there is no ``printf`` format
932 specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
933 ``double`` when passed to ``printf``, so the programmer must explicitly cast it to
934 ``double`` before using it with an ``%f`` or similar specifier.
935
936 Messages on ``deprecated`` and ``unavailable`` Attributes
937 =========================================================
938
939 An optional string message can be added to the ``deprecated`` and
940 ``unavailable`` attributes. For example:
941
942 .. code-block:: c++
943
944 void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
945
946 If the deprecated or unavailable declaration is used, the message will be
947 incorporated into the appropriate diagnostic:
948
949 .. code-block:: none
950
951 harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
952 [-Wdeprecated-declarations]
953 explode();
954 ^
955
956 Query for this feature with
957 ``__has_extension(attribute_deprecated_with_message)`` and
958 ``__has_extension(attribute_unavailable_with_message)``.
959
960 Attributes on Enumerators
961 =========================
962
963 Clang allows attributes to be written on individual enumerators. This allows
964 enumerators to be deprecated, made unavailable, etc. The attribute must appear
965 after the enumerator name and before any initializer, like so:
966
967 .. code-block:: c++
968
969 enum OperationMode {
970 OM_Invalid,
971 OM_Normal,
972 OM_Terrified __attribute__((deprecated)),
973 OM_AbortOnError __attribute__((deprecated)) = 4
974 };
975
976 Attributes on the ``enum`` declaration do not apply to individual enumerators.
977
978 Query for this feature with ``__has_extension(enumerator_attributes)``.
979
980 C++11 Attributes on using-declarations
981 ======================================
982
983 Clang allows C++-style ``[[]]`` attributes to be written on using-declarations.
984 For instance:
985
986 .. code-block:: c++
987
988 [[clang::using_if_exists]] using foo::bar;
989 using foo::baz [[clang::using_if_exists]];
990
991 You can test for support for this extension with
992 ``__has_extension(cxx_attributes_on_using_declarations)``.
993
994 'User-Specified' System Frameworks
995 ==================================
996
997 Clang provides a mechanism by which frameworks can be built in such a way that
998 they will always be treated as being "system frameworks", even if they are not
999 present in a system framework directory. This can be useful to system
1000 framework developers who want to be able to test building other applications
1001 with development builds of their framework, including the manner in which the
1002 compiler changes warning behavior for system headers.
1003
1004 Framework developers can opt-in to this mechanism by creating a
1005 "``.system_framework``" file at the top-level of their framework. That is, the
1006 framework should have contents like:
1007
1008 .. code-block:: none
1009
1010 .../TestFramework.framework
1011 .../TestFramework.framework/.system_framework
1012 .../TestFramework.framework/Headers
1013 .../TestFramework.framework/Headers/TestFramework.h
1014 ...
1015
1016 Clang will treat the presence of this file as an indicator that the framework
1017 should be treated as a system framework, regardless of how it was found in the
1018 framework search path. For consistency, we recommend that such files never be
1019 included in installed versions of the framework.
1020
1021 Checks for Standard Language Features
1022 =====================================
1023
1024 The ``__has_feature`` macro can be used to query if certain standard language
1025 features are enabled. The ``__has_extension`` macro can be used to query if
1026 language features are available as an extension when compiling for a standard
1027 which does not provide them. The features which can be tested are listed here.
1028
1029 Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
1030 These are macros with names of the form ``__cpp_<feature_name>``, and are
1031 intended to be a portable way to query the supported features of the compiler.
1032 See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
1033 information on the version of SD-6 supported by each Clang release, and the
1034 macros provided by that revision of the recommendations.
1035
1036 C++98
1037 -----
1038
1039 The features listed below are part of the C++98 standard. These features are
1040 enabled by default when compiling C++ code.
1041
1042 C++ exceptions
1043 ^^^^^^^^^^^^^^
1044
1045 Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
1046 enabled. For example, compiling code with ``-fno-exceptions`` disables C++
1047 exceptions.
1048
1049 C++ RTTI
1050 ^^^^^^^^
1051
1052 Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
1053 example, compiling code with ``-fno-rtti`` disables the use of RTTI.
1054
1055 C++11
1056 -----
1057
1058 The features listed below are part of the C++11 standard. As a result, all
1059 these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
1060 when compiling C++ code.
1061
1062 C++11 SFINAE includes access control
1063 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1064
1065 Use ``__has_feature(cxx_access_control_sfinae)`` or
1066 ``__has_extension(cxx_access_control_sfinae)`` to determine whether
1067 access-control errors (e.g., calling a private constructor) are considered to
1068 be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
1069 <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
1070
1071 C++11 alias templates
1072 ^^^^^^^^^^^^^^^^^^^^^
1073
1074 Use ``__has_feature(cxx_alias_templates)`` or
1075 ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
1076 alias declarations and alias templates is enabled.
1077
1078 C++11 alignment specifiers
1079 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1080
1081 Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
1082 determine if support for alignment specifiers using ``alignas`` is enabled.
1083
1084 Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
1085 determine if support for the ``alignof`` keyword is enabled.
1086
1087 C++11 attributes
1088 ^^^^^^^^^^^^^^^^
1089
1090 Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
1091 determine if support for attribute parsing with C++11's square bracket notation
1092 is enabled.
1093
1094 C++11 generalized constant expressions
1095 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1096
1097 Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
1098 constant expressions (e.g., ``constexpr``) is enabled.
1099
1100 C++11 ``decltype()``
1101 ^^^^^^^^^^^^^^^^^^^^
1102
1103 Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
1104 determine if support for the ``decltype()`` specifier is enabled. C++11's
1105 ``decltype`` does not require type-completeness of a function call expression.
1106 Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
1107 ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
1108 support for this feature is enabled.
1109
1110 C++11 default template arguments in function templates
1111 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1112
1113 Use ``__has_feature(cxx_default_function_template_args)`` or
1114 ``__has_extension(cxx_default_function_template_args)`` to determine if support
1115 for default template arguments in function templates is enabled.
1116
1117 C++11 ``default``\ ed functions
1118 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1119
1120 Use ``__has_feature(cxx_defaulted_functions)`` or
1121 ``__has_extension(cxx_defaulted_functions)`` to determine if support for
1122 defaulted function definitions (with ``= default``) is enabled.
1123
1124 C++11 delegating constructors
1125 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1126
1127 Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
1128 delegating constructors is enabled.
1129
1130 C++11 ``deleted`` functions
1131 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1132
1133 Use ``__has_feature(cxx_deleted_functions)`` or
1134 ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
1135 function definitions (with ``= delete``) is enabled.
1136
1137 C++11 explicit conversion functions
1138 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1139
1140 Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
1141 ``explicit`` conversion functions is enabled.
1142
1143 C++11 generalized initializers
1144 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1145
1146 Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
1147 generalized initializers (using braced lists and ``std::initializer_list``) is
1148 enabled.
1149
1150 C++11 implicit move constructors/assignment operators
1151 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1152
1153 Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
1154 generate move constructors and move assignment operators where needed.
1155
1156 C++11 inheriting constructors
1157 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1158
1159 Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
1160 inheriting constructors is enabled.
1161
1162 C++11 inline namespaces
1163 ^^^^^^^^^^^^^^^^^^^^^^^
1164
1165 Use ``__has_feature(cxx_inline_namespaces)`` or
1166 ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
1167 namespaces is enabled.
1168
1169 C++11 lambdas
1170 ^^^^^^^^^^^^^
1171
1172 Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
1173 determine if support for lambdas is enabled.
1174
1175 C++11 local and unnamed types as template arguments
1176 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1177
1178 Use ``__has_feature(cxx_local_type_template_args)`` or
1179 ``__has_extension(cxx_local_type_template_args)`` to determine if support for
1180 local and unnamed types as template arguments is enabled.
1181
1182 C++11 noexcept
1183 ^^^^^^^^^^^^^^
1184
1185 Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
1186 determine if support for noexcept exception specifications is enabled.
1187
1188 C++11 in-class non-static data member initialization
1189 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1190
1191 Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
1192 initialization of non-static data members is enabled.
1193
1194 C++11 ``nullptr``
1195 ^^^^^^^^^^^^^^^^^
1196
1197 Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
1198 determine if support for ``nullptr`` is enabled.
1199
1200 C++11 ``override control``
1201 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1202
1203 Use ``__has_feature(cxx_override_control)`` or
1204 ``__has_extension(cxx_override_control)`` to determine if support for the
1205 override control keywords is enabled.
1206
1207 C++11 reference-qualified functions
1208 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1209
1210 Use ``__has_feature(cxx_reference_qualified_functions)`` or
1211 ``__has_extension(cxx_reference_qualified_functions)`` to determine if support
1212 for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
1213 applied to ``*this``) is enabled.
1214
1215 C++11 range-based ``for`` loop
1216 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1217
1218 Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
1219 determine if support for the range-based for loop is enabled.
1220
1221 C++11 raw string literals
1222 ^^^^^^^^^^^^^^^^^^^^^^^^^
1223
1224 Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
1225 string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
1226
1227 C++11 rvalue references
1228 ^^^^^^^^^^^^^^^^^^^^^^^
1229
1230 Use ``__has_feature(cxx_rvalue_references)`` or
1231 ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
1232 references is enabled.
1233
1234 C++11 ``static_assert()``
1235 ^^^^^^^^^^^^^^^^^^^^^^^^^
1236
1237 Use ``__has_feature(cxx_static_assert)`` or
1238 ``__has_extension(cxx_static_assert)`` to determine if support for compile-time
1239 assertions using ``static_assert`` is enabled.
1240
1241 C++11 ``thread_local``
1242 ^^^^^^^^^^^^^^^^^^^^^^
1243
1244 Use ``__has_feature(cxx_thread_local)`` to determine if support for
1245 ``thread_local`` variables is enabled.
1246
1247 C++11 type inference
1248 ^^^^^^^^^^^^^^^^^^^^
1249
1250 Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
1251 determine C++11 type inference is supported using the ``auto`` specifier. If
1252 this is disabled, ``auto`` will instead be a storage class specifier, as in C
1253 or C++98.
1254
1255 C++11 strongly typed enumerations
1256 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1257
1258 Use ``__has_feature(cxx_strong_enums)`` or
1259 ``__has_extension(cxx_strong_enums)`` to determine if support for strongly
1260 typed, scoped enumerations is enabled.
1261
1262 C++11 trailing return type
1263 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1264
1265 Use ``__has_feature(cxx_trailing_return)`` or
1266 ``__has_extension(cxx_trailing_return)`` to determine if support for the
1267 alternate function declaration syntax with trailing return type is enabled.
1268
1269 C++11 Unicode string literals
1270 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1271
1272 Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
1273 string literals is enabled.
1274
1275 C++11 unrestricted unions
1276 ^^^^^^^^^^^^^^^^^^^^^^^^^
1277
1278 Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
1279 unrestricted unions is enabled.
1280
1281 C++11 user-defined literals
1282 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1283
1284 Use ``__has_feature(cxx_user_literals)`` to determine if support for
1285 user-defined literals is enabled.
1286
1287 C++11 variadic templates
1288 ^^^^^^^^^^^^^^^^^^^^^^^^
1289
1290 Use ``__has_feature(cxx_variadic_templates)`` or
1291 ``__has_extension(cxx_variadic_templates)`` to determine if support for
1292 variadic templates is enabled.
1293
1294 C++14
1295 -----
1296
1297 The features listed below are part of the C++14 standard. As a result, all
1298 these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
1299 when compiling C++ code.
1300
1301 C++14 binary literals
1302 ^^^^^^^^^^^^^^^^^^^^^
1303
1304 Use ``__has_feature(cxx_binary_literals)`` or
1305 ``__has_extension(cxx_binary_literals)`` to determine whether
1306 binary literals (for instance, ``0b10010``) are recognized. Clang supports this
1307 feature as an extension in all language modes.
1308
1309 C++14 contextual conversions
1310 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1311
1312 Use ``__has_feature(cxx_contextual_conversions)`` or
1313 ``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
1314 are used when performing an implicit conversion for an array bound in a
1315 *new-expression*, the operand of a *delete-expression*, an integral constant
1316 expression, or a condition in a ``switch`` statement.
1317
1318 C++14 decltype(auto)
1319 ^^^^^^^^^^^^^^^^^^^^
1320
1321 Use ``__has_feature(cxx_decltype_auto)`` or
1322 ``__has_extension(cxx_decltype_auto)`` to determine if support
1323 for the ``decltype(auto)`` placeholder type is enabled.
1324
1325 C++14 default initializers for aggregates
1326 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1327
1328 Use ``__has_feature(cxx_aggregate_nsdmi)`` or
1329 ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
1330 for default initializers in aggregate members is enabled.
1331
1332 C++14 digit separators
1333 ^^^^^^^^^^^^^^^^^^^^^^
1334
1335 Use ``__cpp_digit_separators`` to determine if support for digit separators
1336 using single quotes (for instance, ``10'000``) is enabled. At this time, there
1337 is no corresponding ``__has_feature`` name
1338
1339 C++14 generalized lambda capture
1340 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1341
1342 Use ``__has_feature(cxx_init_captures)`` or
1343 ``__has_extension(cxx_init_captures)`` to determine if support for
1344 lambda captures with explicit initializers is enabled
1345 (for instance, ``[n(0)] { return ++n; }``).
1346
1347 C++14 generic lambdas
1348 ^^^^^^^^^^^^^^^^^^^^^
1349
1350 Use ``__has_feature(cxx_generic_lambdas)`` or
1351 ``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
1352 (polymorphic) lambdas is enabled
1353 (for instance, ``[] (auto x) { return x + 1; }``).
1354
1355 C++14 relaxed constexpr
1356 ^^^^^^^^^^^^^^^^^^^^^^^
1357
1358 Use ``__has_feature(cxx_relaxed_constexpr)`` or
1359 ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
1360 declarations, local variable modification, and control flow constructs
1361 are permitted in ``constexpr`` functions.
1362
1363 C++14 return type deduction
1364 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1365
1366 Use ``__has_feature(cxx_return_type_deduction)`` or
1367 ``__has_extension(cxx_return_type_deduction)`` to determine if support
1368 for return type deduction for functions (using ``auto`` as a return type)
1369 is enabled.
1370
1371 C++14 runtime-sized arrays
1372 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1373
1374 Use ``__has_feature(cxx_runtime_array)`` or
1375 ``__has_extension(cxx_runtime_array)`` to determine if support
1376 for arrays of runtime bound (a restricted form of variable-length arrays)
1377 is enabled.
1378 Clang's implementation of this feature is incomplete.
1379
1380 C++14 variable templates
1381 ^^^^^^^^^^^^^^^^^^^^^^^^
1382
1383 Use ``__has_feature(cxx_variable_templates)`` or
1384 ``__has_extension(cxx_variable_templates)`` to determine if support for
1385 templated variable declarations is enabled.
1386
1387 C11
1388 ---
1389
1390 The features listed below are part of the C11 standard. As a result, all these
1391 features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
1392 compiling C code. Additionally, because these features are all
1393 backward-compatible, they are available as extensions in all language modes.
1394
1395 C11 alignment specifiers
1396 ^^^^^^^^^^^^^^^^^^^^^^^^
1397
1398 Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
1399 if support for alignment specifiers using ``_Alignas`` is enabled.
1400
1401 Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
1402 if support for the ``_Alignof`` keyword is enabled.
1403
1404 C11 atomic operations
1405 ^^^^^^^^^^^^^^^^^^^^^
1406
1407 Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
1408 if support for atomic types using ``_Atomic`` is enabled. Clang also provides
1409 :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
1410 the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
1411 ``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
1412 is available.
1413
1414 Clang will use the system's ``<stdatomic.h>`` header when one is available, and
1415 will otherwise use its own. When using its own, implementations of the atomic
1416 operations are provided as macros. In the cases where C11 also requires a real
1417 function, this header provides only the declaration of that function (along
1418 with a shadowing macro implementation), and you must link to a library which
1419 provides a definition of the function if you use it instead of the macro.
1420
1421 C11 generic selections
1422 ^^^^^^^^^^^^^^^^^^^^^^
1423
1424 Use ``__has_feature(c_generic_selections)`` or
1425 ``__has_extension(c_generic_selections)`` to determine if support for generic
1426 selections is enabled.
1427
1428 As an extension, the C11 generic selection expression is available in all
1429 languages supported by Clang. The syntax is the same as that given in the C11
1430 standard.
1431
1432 In C, type compatibility is decided according to the rules given in the
1433 appropriate standard, but in C++, which lacks the type compatibility rules used
1434 in C, types are considered compatible only if they are equivalent.
1435
1436 Clang also supports an extended form of ``_Generic`` with a controlling type
1437 rather than a controlling expression. Unlike with a controlling expression, a
1438 controlling type argument does not undergo any conversions and thus is suitable
1439 for use when trying to match qualified types, incomplete types, or function
1440 types. Variable-length array types lack the necessary compile-time information
1441 to resolve which association they match with and thus are not allowed as a
1442 controlling type argument.
1443
1444 Use ``__has_extension(c_generic_selection_with_controlling_type)`` to determine
1445 if support for this extension is enabled.
1446
1447 C11 ``_Static_assert()``
1448 ^^^^^^^^^^^^^^^^^^^^^^^^
1449
1450 Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
1451 to determine if support for compile-time assertions using ``_Static_assert`` is
1452 enabled.
1453
1454 C11 ``_Thread_local``
1455 ^^^^^^^^^^^^^^^^^^^^^
1456
1457 Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
1458 to determine if support for ``_Thread_local`` variables is enabled.
1459
1460 Modules
1461 -------
1462
1463 Use ``__has_feature(modules)`` to determine if Modules have been enabled.
1464 For example, compiling code with ``-fmodules`` enables the use of Modules.
1465
1466 More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
1467
1468 Language Extensions Back-ported to Previous Standards
1469 =====================================================
1470
1471 ============================================ ================================ ============= =============
1472 Feature Feature Test Macro Introduced In Backported To
1473 ============================================ ================================ ============= =============
1474 variadic templates __cpp_variadic_templates C++11 C++03
1475 Alias templates __cpp_alias_templates C++11 C++03
1476 Non-static data member initializers __cpp_nsdmi C++11 C++03
1477 Range-based ``for`` loop __cpp_range_based_for C++11 C++03
1478 RValue references __cpp_rvalue_references C++11 C++03
1479 Attributes __cpp_attributes C++11 C++03
1480 Lambdas __cpp_lambdas C++11 C++03
1481 Generalized lambda captures __cpp_init_captures C++14 C++03
1482 Generic lambda expressions __cpp_generic_lambdas C++14 C++03
1483 variable templates __cpp_variable_templates C++14 C++03
1484 Binary literals __cpp_binary_literals C++14 C++03
1485 Relaxed constexpr __cpp_constexpr C++14 C++11
1486 Pack expansion in generalized lambda-capture __cpp_init_captures C++17 C++03
1487 ``if constexpr`` __cpp_if_constexpr C++17 C++11
1488 fold expressions __cpp_fold_expressions C++17 C++03
1489 Lambda capture of \*this by value __cpp_capture_star_this C++17 C++03
1490 Attributes on enums __cpp_enumerator_attributes C++17 C++03
1491 Guaranteed copy elision __cpp_guaranteed_copy_elision C++17 C++03
1492 Hexadecimal floating literals __cpp_hex_float C++17 C++03
1493 ``inline`` variables __cpp_inline_variables C++17 C++03
1494 Attributes on namespaces __cpp_namespace_attributes C++17 C++11
1495 Structured bindings __cpp_structured_bindings C++17 C++03
1496 template template arguments __cpp_template_template_args C++17 C++03
1497 Familiar template syntax for generic lambdas __cpp_generic_lambdas C++20 C++03
1498 ``static operator[]`` __cpp_multidimensional_subscript C++20 C++03
1499 Designated initializers __cpp_designated_initializers C++20 C++03
1500 Conditional ``explicit`` __cpp_conditional_explicit C++20 C++03
1501 ``using enum`` __cpp_using_enum C++20 C++03
1502 ``if consteval`` __cpp_if_consteval C++23 C++20
1503 ``static operator()`` __cpp_static_call_operator C++23 C++03
1504 Attributes on Lambda-Expressions C++23 C++11
1505 Attributes on Structured Bindings __cpp_structured_bindings C++26 C++03
1506 Pack Indexing __cpp_pack_indexing C++26 C++03
1507 ``= delete ("should have a reason");`` __cpp_deleted_function C++26 C++03
1508 -------------------------------------------- -------------------------------- ------------- -------------
1509 Designated initializers (N494) C99 C89
1510 Array & element qualification (N2607) C23 C89
1511 Attributes (N2335) C23 C89
1512 ``#embed`` (N3017) C23 C89, C++
1513 ============================================ ================================ ============= =============
1514
1515 Type Trait Primitives
1516 =====================
1517
1518 Type trait primitives are special builtin constant expressions that can be used
1519 by the standard C++ library to facilitate or simplify the implementation of
1520 user-facing type traits in the <type_traits> header.
1521
1522 They are not intended to be used directly by user code because they are
1523 implementation-defined and subject to change -- as such they're tied closely to
1524 the supported set of system headers, currently:
1525
1526 * LLVM's own libc++
1527 * GNU libstdc++
1528 * The Microsoft standard C++ library
1529
1530 Clang supports the `GNU C++ type traits
1531 <https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
1532 `Microsoft Visual C++ type traits
1533 <https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,
1534 as well as nearly all of the
1535 `Embarcadero C++ type traits
1536 <http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.
1537
1538 The following type trait primitives are supported by Clang. Those traits marked
1539 (C++) provide implementations for type traits specified by the C++ standard;
1540 ``__X(...)`` has the same semantics and constraints as the corresponding
1541 ``std::X_t<...>`` or ``std::X_v<...>`` type trait.
1542
1543 * ``__array_rank(type)`` (Embarcadero):
1544 Returns the number of levels of array in the type ``type``:
1545 ``0`` if ``type`` is not an array type, and
1546 ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.
1547 * ``__array_extent(type, dim)`` (Embarcadero):
1548 The ``dim``'th array bound in the type ``type``, or ``0`` if
1549 ``dim >= __array_rank(type)``.
1550 * ``__can_pass_in_regs`` (C++)
1551 Returns whether a class can be passed in registers under the current
1552 ABI. This type can only be applied to unqualified class types.
1553 This is not a portable type trait.
1554 * ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero):
1555 Deprecated, use ``__is_nothrow_assignable`` instead.
1556 * ``__has_nothrow_move_assign`` (GNU, Microsoft):
1557 Deprecated, use ``__is_nothrow_assignable`` instead.
1558 * ``__has_nothrow_copy`` (GNU, Microsoft):
1559 Deprecated, use ``__is_nothrow_constructible`` instead.
1560 * ``__has_nothrow_constructor`` (GNU, Microsoft):
1561 Deprecated, use ``__is_nothrow_constructible`` instead.
1562 * ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero):
1563 Deprecated, use ``__is_trivially_assignable`` instead.
1564 * ``__has_trivial_move_assign`` (GNU, Microsoft):
1565 Deprecated, use ``__is_trivially_assignable`` instead.
1566 * ``__has_trivial_copy`` (GNU, Microsoft):
1567 Deprecated, use ``__is_trivially_copyable`` instead.
1568 * ``__has_trivial_constructor`` (GNU, Microsoft):
1569 Deprecated, use ``__is_trivially_constructible`` instead.
1570 * ``__has_trivial_move_constructor`` (GNU, Microsoft):
1571 Deprecated, use ``__is_trivially_constructible`` instead.
1572 * ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero):
1573 Deprecated, use ``__is_trivially_destructible`` instead.
1574 * ``__has_unique_object_representations`` (C++, GNU)
1575 * ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero)
1576 * ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero)
1577 * ``__is_aggregate`` (C++, GNU, Microsoft)
1578 * ``__is_arithmetic`` (C++, Embarcadero)
1579 * ``__is_array`` (C++, Embarcadero)
1580 * ``__is_assignable`` (C++, MSVC 2015)
1581 * ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero)
1582 * ``__is_bounded_array`` (C++, GNU, Microsoft, Embarcadero)
1583 * ``__is_class`` (C++, GNU, Microsoft, Embarcadero)
1584 * ``__is_complete_type(type)`` (Embarcadero):
1585 Return ``true`` if ``type`` is a complete type.
1586 Warning: this trait is dangerous because it can return different values at
1587 different points in the same program.
1588 * ``__is_compound`` (C++, Embarcadero)
1589 * ``__is_const`` (C++, Embarcadero)
1590 * ``__is_constructible`` (C++, MSVC 2013)
1591 * ``__is_convertible`` (C++, Embarcadero)
1592 * ``__is_nothrow_convertible`` (C++, GNU)
1593 * ``__is_convertible_to`` (Microsoft):
1594 Synonym for ``__is_convertible``.
1595 * ``__is_destructible`` (C++, MSVC 2013)
1596 * ``__is_empty`` (C++, GNU, Microsoft, Embarcadero)
1597 * ``__is_enum`` (C++, GNU, Microsoft, Embarcadero)
1598 * ``__is_final`` (C++, GNU, Microsoft)
1599 * ``__is_floating_point`` (C++, Embarcadero)
1600 * ``__is_function`` (C++, Embarcadero)
1601 * ``__is_fundamental`` (C++, Embarcadero)
1602 * ``__is_integral`` (C++, Embarcadero)
1603 * ``__is_interface_class`` (Microsoft):
1604 Returns ``false``, even for types defined with ``__interface``.
1605 * ``__is_layout_compatible`` (C++, GNU, Microsoft)
1606 * ``__is_literal`` (Clang):
1607 Synonym for ``__is_literal_type``.
1608 * ``__is_literal_type`` (C++, GNU, Microsoft):
1609 Note, the corresponding standard trait was deprecated in C++17
1610 and removed in C++20.
1611 * ``__is_lvalue_reference`` (C++, Embarcadero)
1612 * ``__is_member_object_pointer`` (C++, Embarcadero)
1613 * ``__is_member_function_pointer`` (C++, Embarcadero)
1614 * ``__is_member_pointer`` (C++, Embarcadero)
1615 * ``__is_nothrow_assignable`` (C++, MSVC 2013)
1616 * ``__is_nothrow_constructible`` (C++, MSVC 2013)
1617 * ``__is_nothrow_destructible`` (C++, MSVC 2013)
1618 * ``__is_nullptr`` (C++, GNU, Microsoft, Embarcadero):
1619 Returns true for ``std::nullptr_t`` and false for everything else. The
1620 corresponding standard library feature is ``std::is_null_pointer``, but
1621 ``__is_null_pointer`` is already in use by some implementations.
1622 * ``__is_object`` (C++, Embarcadero)
1623 * ``__is_pod`` (C++, GNU, Microsoft, Embarcadero):
1624 Note, the corresponding standard trait was deprecated in C++20.
1625 * ``__is_pointer`` (C++, Embarcadero)
1626 * ``__is_pointer_interconvertible_base_of`` (C++, GNU, Microsoft)
1627 * ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero)
1628 * ``__is_reference`` (C++, Embarcadero)
1629 * ``__is_referenceable`` (C++, GNU, Microsoft, Embarcadero):
1630 Returns true if a type is referenceable, and false otherwise. A referenceable
1631 type is a type that's either an object type, a reference type, or an unqualified
1632 function type.
1633 * ``__is_rvalue_reference`` (C++, Embarcadero)
1634 * ``__is_same`` (C++, Embarcadero)
1635 * ``__is_same_as`` (GCC): Synonym for ``__is_same``.
1636 * ``__is_scalar`` (C++, Embarcadero)
1637 * ``__is_scoped_enum`` (C++, GNU, Microsoft, Embarcadero)
1638 * ``__is_sealed`` (Microsoft):
1639 Synonym for ``__is_final``.
1640 * ``__is_signed`` (C++, Embarcadero):
1641 Returns false for enumeration types, and returns true for floating-point
1642 types. Note, before Clang 10, returned true for enumeration types if the
1643 underlying type was signed, and returned false for floating-point types.
1644 * ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero)
1645 * ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero)
1646 * ``__is_trivially_assignable`` (C++, GNU, Microsoft)
1647 * ``__is_trivially_constructible`` (C++, GNU, Microsoft)
1648 * ``__is_trivially_copyable`` (C++, GNU, Microsoft)
1649 * ``__is_trivially_destructible`` (C++, MSVC 2013)
1650 * ``__is_trivially_relocatable`` (Clang): Returns true if moving an object
1651 of the given type, and then destroying the source object, is known to be
1652 functionally equivalent to copying the underlying bytes and then dropping the
1653 source object on the floor. This is true of trivial types and types which
1654 were made trivially relocatable via the ``clang::trivial_abi`` attribute.
1655 * ``__is_trivially_equality_comparable`` (Clang): Returns true if comparing two
1656 objects of the provided type is known to be equivalent to comparing their
1657 object representations. Note that types containing padding bytes are never
1658 trivially equality comparable.
1659 * ``__is_unbounded_array`` (C++, GNU, Microsoft, Embarcadero)
1660 * ``__is_union`` (C++, GNU, Microsoft, Embarcadero)
1661 * ``__is_unsigned`` (C++, Embarcadero):
1662 Returns false for enumeration types. Note, before Clang 13, returned true for
1663 enumeration types if the underlying type was unsigned.
1664 * ``__is_void`` (C++, Embarcadero)
1665 * ``__is_volatile`` (C++, Embarcadero)
1666 * ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a
1667 reference of type ``T`` bound to an expression of type ``U`` would bind to a
1668 materialized temporary object. If ``T`` is not a reference type the result
1669 is false. Note this trait will also return false when the initialization of
1670 ``T`` from ``U`` is ill-formed.
1671 Deprecated, use ``__reference_constructs_from_temporary``.
1672 * ``__reference_constructs_from_temporary(T, U)`` (C++)
1673 Returns true if a reference ``T`` can be direct-initialized from a temporary of type
1674 a non-cv-qualified ``U``.
1675 * ``__reference_converts_from_temporary(T, U)`` (C++)
1676 Returns true if a reference ``T`` can be copy-initialized from a temporary of type
1677 a non-cv-qualified ``U``.
1678 * ``__underlying_type`` (C++, GNU, Microsoft)
1679
1680 In addition, the following expression traits are supported:
1681
1682 * ``__is_lvalue_expr(e)`` (Embarcadero):
1683 Returns true if ``e`` is an lvalue expression.
1684 Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.
1685 * ``__is_rvalue_expr(e)`` (Embarcadero):
1686 Returns true if ``e`` is a prvalue expression.
1687 Deprecated, use ``!__is_reference(decltype((e)))`` instead.
1688
1689 There are multiple ways to detect support for a type trait ``__X`` in the
1690 compiler, depending on the oldest version of Clang you wish to support.
1691
1692 * From Clang 10 onwards, ``__has_builtin(__X)`` can be used.
1693 * From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.
1694 * From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports
1695 the following traits:
1696
1697 * ``__has_nothrow_assign``
1698 * ``__has_nothrow_copy``
1699 * ``__has_nothrow_constructor``
1700 * ``__has_trivial_assign``
1701 * ``__has_trivial_copy``
1702 * ``__has_trivial_constructor``
1703 * ``__has_trivial_destructor``
1704 * ``__has_virtual_destructor``
1705 * ``__is_abstract``
1706 * ``__is_base_of``
1707 * ``__is_class``
1708 * ``__is_constructible``
1709 * ``__is_convertible_to``
1710 * ``__is_empty``
1711 * ``__is_enum``
1712 * ``__is_final``
1713 * ``__is_literal``
1714 * ``__is_standard_layout``
1715 * ``__is_pod``
1716 * ``__is_polymorphic``
1717 * ``__is_sealed``
1718 * ``__is_trivial``
1719 * ``__is_trivially_assignable``
1720 * ``__is_trivially_constructible``
1721 * ``__is_trivially_copyable``
1722 * ``__is_union``
1723 * ``__underlying_type``
1724
1725 A simplistic usage example as might be seen in standard C++ headers follows:
1726
1727 .. code-block:: c++
1728
1729 #if __has_builtin(__is_convertible_to)
1730 template<typename From, typename To>
1731 struct is_convertible_to {
1732 static const bool value = __is_convertible_to(From, To);
1733 };
1734 #else
1735 // Emulate type trait for compatibility with other compilers.
1736 #endif
1737
1738 Blocks
1739 ======
1740
1741 The syntax and high level language feature description is in
1742 :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
1743 the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
1744
1745 Query for this feature with ``__has_extension(blocks)``.
1746
1747 ASM Goto with Output Constraints
1748 ================================
1749
1750 Outputs may be used along any branches from the ``asm goto`` whether the
1751 branches are taken or not.
1752
1753 Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.
1754
1755 Prior to clang-16, the output may only be used safely when the indirect
1756 branches are not taken. Query for this difference with
1757 ``__has_extension(gnu_asm_goto_with_outputs_full)``.
1758
1759 When using tied-outputs (i.e. outputs that are inputs and outputs, not just
1760 outputs) with the `+r` constraint, there is a hidden input that's created
1761 before the label, so numeric references to operands must account for that.
1762
1763 .. code-block:: c++
1764
1765 int foo(int x) {
1766 // %0 and %1 both refer to x
1767 // %l2 refers to err
1768 asm goto("# %0 %1 %l2" : "+r"(x) : : : err);
1769 return x;
1770 err:
1771 return -1;
1772 }
1773
1774 This was changed to match GCC in clang-13; for better portability, symbolic
1775 references can be used instead of numeric references.
1776
1777 .. code-block:: c++
1778
1779 int foo(int x) {
1780 asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err);
1781 return x;
1782 err:
1783 return -1;
1784 }
1785
1786 Objective-C Features
1787 ====================
1788
1789 Related result types
1790 --------------------
1791
1792 According to Cocoa conventions, Objective-C methods with certain names
1793 ("``init``", "``alloc``", etc.) always return objects that are an instance of
1794 the receiving class's type. Such methods are said to have a "related result
1795 type", meaning that a message send to one of these methods will have the same
1796 static type as an instance of the receiver class. For example, given the
1797 following classes:
1798
1799 .. code-block:: objc
1800
1801 @interface NSObject
1802 + (id)alloc;
1803 - (id)init;
1804 @end
1805
1806 @interface NSArray : NSObject
1807 @end
1808
1809 and this common initialization pattern
1810
1811 .. code-block:: objc
1812
1813 NSArray *array = [[NSArray alloc] init];
1814
1815 the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
1816 ``alloc`` implicitly has a related result type. Similarly, the type of the
1817 expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
1818 related result type and its receiver is known to have the type ``NSArray *``.
1819 If neither ``alloc`` nor ``init`` had a related result type, the expressions
1820 would have had type ``id``, as declared in the method signature.
1821
1822 A method with a related result type can be declared by using the type
1823 ``instancetype`` as its result type. ``instancetype`` is a contextual keyword
1824 that is only permitted in the result type of an Objective-C method, e.g.
1825
1826 .. code-block:: objc
1827
1828 @interface A
1829 + (instancetype)constructAnA;
1830 @end
1831
1832 The related result type can also be inferred for some methods. To determine
1833 whether a method has an inferred related result type, the first word in the
1834 camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
1835 and the method will have a related result type if its return type is compatible
1836 with the type of its class and if:
1837
1838 * the first word is "``alloc``" or "``new``", and the method is a class method,
1839 or
1840
1841 * the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
1842 and the method is an instance method.
1843
1844 If a method with a related result type is overridden by a subclass method, the
1845 subclass method must also return a type that is compatible with the subclass
1846 type. For example:
1847
1848 .. code-block:: objc
1849
1850 @interface NSString : NSObject
1851 - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
1852 @end
1853
1854 Related result types only affect the type of a message send or property access
1855 via the given method. In all other respects, a method with a related result
1856 type is treated the same way as method that returns ``id``.
1857
1858 Use ``__has_feature(objc_instancetype)`` to determine whether the
1859 ``instancetype`` contextual keyword is available.
1860
1861 Automatic reference counting
1862 ----------------------------
1863
1864 Clang provides support for :doc:`automated reference counting
1865 <AutomaticReferenceCounting>` in Objective-C, which eliminates the need
1866 for manual ``retain``/``release``/``autorelease`` message sends. There are three
1867 feature macros associated with automatic reference counting:
1868 ``__has_feature(objc_arc)`` indicates the availability of automated reference
1869 counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
1870 automated reference counting also includes support for ``__weak`` pointers to
1871 Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
1872 are allowed to have fields that are pointers to Objective-C objects managed by
1873 automatic reference counting.
1874
1875 .. _objc-weak:
1876
1877 Weak references
1878 ---------------
1879
1880 Clang supports ARC-style weak and unsafe references in Objective-C even
1881 outside of ARC mode. Weak references must be explicitly enabled with
1882 the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
1883 to test whether they are enabled. Unsafe references are enabled
1884 unconditionally. ARC-style weak and unsafe references cannot be used
1885 when Objective-C garbage collection is enabled.
1886
1887 Except as noted below, the language rules for the ``__weak`` and
1888 ``__unsafe_unretained`` qualifiers (and the ``weak`` and
1889 ``unsafe_unretained`` property attributes) are just as laid out
1890 in the :doc:`ARC specification <AutomaticReferenceCounting>`.
1891 In particular, note that some classes do not support forming weak
1892 references to their instances, and note that special care must be
1893 taken when storing weak references in memory where initialization
1894 and deinitialization are outside the responsibility of the compiler
1895 (such as in ``malloc``-ed memory).
1896
1897 Loading from a ``__weak`` variable always implicitly retains the
1898 loaded value. In non-ARC modes, this retain is normally balanced
1899 by an implicit autorelease. This autorelease can be suppressed
1900 by performing the load in the receiver position of a ``-retain``
1901 message send (e.g. ``[weakReference retain]``); note that this performs
1902 only a single retain (the retain done when primitively loading from
1903 the weak reference).
1904
1905 For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
1906 default behavior of variables and therefore is not needed. However,
1907 it does have an effect on the semantics of block captures: normally,
1908 copying a block which captures an Objective-C object or block pointer
1909 causes the captured pointer to be retained or copied, respectively,
1910 but that behavior is suppressed when the captured variable is qualified
1911 with ``__unsafe_unretained``.
1912
1913 Note that the ``__weak`` qualifier formerly meant the GC qualifier in
1914 all non-ARC modes and was silently ignored outside of GC modes. It now
1915 means the ARC-style qualifier in all non-GC modes and is no longer
1916 allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
1917 It is expected that ``-fobjc-weak`` will eventually be enabled by default
1918 in all non-GC Objective-C modes.
1919
1920 .. _objc-fixed-enum:
1921
1922 Enumerations with a fixed underlying type
1923 -----------------------------------------
1924
1925 Clang provides support for C++11 enumerations with a fixed underlying type
1926 within Objective-C. For example, one can write an enumeration type as:
1927
1928 .. code-block:: c++
1929
1930 typedef enum : unsigned char { Red, Green, Blue } Color;
1931
1932 This specifies that the underlying type, which is used to store the enumeration
1933 value, is ``unsigned char``.
1934
1935 Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
1936 underlying types is available in Objective-C.
1937
1938 Interoperability with C++11 lambdas
1939 -----------------------------------
1940
1941 Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
1942 permitting a lambda to be implicitly converted to a block pointer with the
1943 corresponding signature. For example, consider an API such as ``NSArray``'s
1944 array-sorting method:
1945
1946 .. code-block:: objc
1947
1948 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
1949
1950 ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
1951 (^)(id, id)``, and parameters of this type are generally provided with block
1952 literals as arguments. However, one can also use a C++11 lambda so long as it
1953 provides the same signature (in this case, accepting two parameters of type
1954 ``id`` and returning an ``NSComparisonResult``):
1955
1956 .. code-block:: objc
1957
1958 NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
1959 @"String 02"];
1960 const NSStringCompareOptions comparisonOptions
1961 = NSCaseInsensitiveSearch | NSNumericSearch |
1962 NSWidthInsensitiveSearch | NSForcedOrderingSearch;
1963 NSLocale *currentLocale = [NSLocale currentLocale];
1964 NSArray *sorted
1965 = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
1966 NSRange string1Range = NSMakeRange(0, [s1 length]);
1967 return [s1 compare:s2 options:comparisonOptions
1968 range:string1Range locale:currentLocale];
1969 }];
1970 NSLog(@"sorted: %@", sorted);
1971
1972 This code relies on an implicit conversion from the type of the lambda
1973 expression (an unnamed, local class type called the *closure type*) to the
1974 corresponding block pointer type. The conversion itself is expressed by a
1975 conversion operator in that closure type that produces a block pointer with the
1976 same signature as the lambda itself, e.g.,
1977
1978 .. code-block:: objc
1979
1980 operator NSComparisonResult (^)(id, id)() const;
1981
1982 This conversion function returns a new block that simply forwards the two
1983 parameters to the lambda object (which it captures by copy), then returns the
1984 result. The returned block is first copied (with ``Block_copy``) and then
1985 autoreleased. As an optimization, if a lambda expression is immediately
1986 converted to a block pointer (as in the first example, above), then the block
1987 is not copied and autoreleased: rather, it is given the same lifetime as a
1988 block literal written at that point in the program, which avoids the overhead
1989 of copying a block to the heap in the common case.
1990
1991 The conversion from a lambda to a block pointer is only available in
1992 Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
1993 management (autorelease).
1994
1995 Object Literals and Subscripting
1996 --------------------------------
1997
1998 Clang provides support for :doc:`Object Literals and Subscripting
1999 <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
2000 programming patterns, makes programs more concise, and improves the safety of
2001 container creation. There are several feature macros associated with object
2002 literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
2003 availability of array literals; ``__has_feature(objc_dictionary_literals)``
2004 tests the availability of dictionary literals;
2005 ``__has_feature(objc_subscripting)`` tests the availability of object
2006 subscripting.
2007
2008 Objective-C Autosynthesis of Properties
2009 ---------------------------------------
2010
2011 Clang provides support for autosynthesis of declared properties. Using this
2012 feature, clang provides default synthesis of those properties not declared
2013 @dynamic and not having user provided backing getter and setter methods.
2014 ``__has_feature(objc_default_synthesize_properties)`` checks for availability
2015 of this feature in version of clang being used.
2016
2017 .. _langext-objc-retain-release:
2018
2019 Objective-C retaining behavior attributes
2020 -----------------------------------------
2021
2022 In Objective-C, functions and methods are generally assumed to follow the
2023 `Cocoa Memory Management
2024 <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
2025 conventions for ownership of object arguments and
2026 return values. However, there are exceptions, and so Clang provides attributes
2027 to allow these exceptions to be documented. This are used by ARC and the
2028 `static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
2029 better described using the ``objc_method_family`` attribute instead.
2030
2031 **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
2032 ``ns_returns_autoreleased``, ``cf_returns_retained``, and
2033 ``cf_returns_not_retained`` attributes can be placed on methods and functions
2034 that return Objective-C or CoreFoundation objects. They are commonly placed at
2035 the end of a function prototype or method declaration:
2036
2037 .. code-block:: objc
2038
2039 id foo() __attribute__((ns_returns_retained));
2040
2041 - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
2042
2043 The ``*_returns_retained`` attributes specify that the returned object has a +1
2044 retain count. The ``*_returns_not_retained`` attributes specify that the return
2045 object has a +0 retain count, even if the normal convention for its selector
2046 would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
2047 +0, but is guaranteed to live at least as long as the next flush of an
2048 autorelease pool.
2049
2050 **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
2051 a parameter declaration; they specify that the argument is expected to have a
2052 +1 retain count, which will be balanced in some way by the function or method.
2053 The ``ns_consumes_self`` attribute can only be placed on an Objective-C
2054 method; it specifies that the method expects its ``self`` parameter to have a
2055 +1 retain count, which it will balance in some way.
2056
2057 .. code-block:: objc
2058
2059 void foo(__attribute__((ns_consumed)) NSString *string);
2060
2061 - (void) bar __attribute__((ns_consumes_self));
2062 - (void) baz:(id) __attribute__((ns_consumed)) x;
2063
2064 Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
2065 <https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
2066
2067 Query for these features with ``__has_attribute(ns_consumed)``,
2068 ``__has_attribute(ns_returns_retained)``, etc.
2069
2070 Objective-C @available
2071 ----------------------
2072
2073 It is possible to use the newest SDK but still build a program that can run on
2074 older versions of macOS and iOS by passing ``-mmacos-version-min=`` /
2075 ``-miphoneos-version-min=``.
2076
2077 Before LLVM 5.0, when calling a function that exists only in the OS that's
2078 newer than the target OS (as determined by the minimum deployment version),
2079 programmers had to carefully check if the function exists at runtime, using
2080 null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
2081 and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
2082 Objective-C methods. If such a check was missed, the program would compile
2083 fine, run fine on newer systems, but crash on older systems.
2084
2085 As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
2086 <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
2087 with the new ``@available()`` keyword to assist with this issue.
2088 When a method that's introduced in the OS newer than the target OS is called, a
2089 -Wunguarded-availability warning is emitted if that call is not guarded:
2090
2091 .. code-block:: objc
2092
2093 void my_fun(NSSomeClass* var) {
2094 // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
2095 // built with -mmacos-version-min=10.11, then this unconditional call
2096 // will emit a -Wunguarded-availability warning:
2097 [var fancyNewMethod];
2098 }
2099
2100 To fix the warning and to avoid the crash on macOS 10.11, wrap it in
2101 ``if(@available())``:
2102
2103 .. code-block:: objc
2104
2105 void my_fun(NSSomeClass* var) {
2106 if (@available(macOS 10.12, *)) {
2107 [var fancyNewMethod];
2108 } else {
2109 // Put fallback behavior for old macOS versions (and for non-mac
2110 // platforms) here.
2111 }
2112 }
2113
2114 The ``*`` is required and means that platforms not explicitly listed will take
2115 the true branch, and the compiler will emit ``-Wunguarded-availability``
2116 warnings for unlisted platforms based on those platform's deployment target.
2117 More than one platform can be listed in ``@available()``:
2118
2119 .. code-block:: objc
2120
2121 void my_fun(NSSomeClass* var) {
2122 if (@available(macOS 10.12, iOS 10, *)) {
2123 [var fancyNewMethod];
2124 }
2125 }
2126
2127 If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
2128 on 10.12, then add an `availability attribute
2129 <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
2130 which will also suppress the warning and require that calls to my_fun() are
2131 checked:
2132
2133 .. code-block:: objc
2134
2135 API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
2136 [var fancyNewMethod]; // Now ok.
2137 }
2138
2139 ``@available()`` is only available in Objective-C code. To use the feature
2140 in C and C++ code, use the ``__builtin_available()`` spelling instead.
2141
2142 If existing code uses null checks or ``-respondsToSelector:``, it should
2143 be changed to use ``@available()`` (or ``__builtin_available``) instead.
2144
2145 ``-Wunguarded-availability`` is disabled by default, but
2146 ``-Wunguarded-availability-new``, which only emits this warning for APIs
2147 that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
2148 tvOS >= 11, is enabled by default.
2149
2150 .. _langext-overloading:
2151
2152 Objective-C++ ABI: protocol-qualifier mangling of parameters
2153 ------------------------------------------------------------
2154
2155 Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
2156 type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
2157 parameters to be differentiated from those with the regular unqualified ``id``
2158 type.
2159
2160 This was a non-backward compatible mangling change to the ABI. This change
2161 allows proper overloading, and also prevents mangling conflicts with template
2162 parameters of protocol-qualified type.
2163
2164 Query the presence of this new mangling with
2165 ``__has_feature(objc_protocol_qualifier_mangling)``.
2166
2167 Initializer lists for complex numbers in C
2168 ==========================================
2169
2170 clang supports an extension which allows the following in C:
2171
2172 .. code-block:: c++
2173
2174 #include <math.h>
2175 #include <complex.h>
2176 complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
2177
2178 This construct is useful because there is no way to separately initialize the
2179 real and imaginary parts of a complex variable in standard C, given that clang
2180 does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
2181 ``__imag__`` extensions from gcc, which help in some cases, but are not usable
2182 in static initializers.)
2183
2184 Note that this extension does not allow eliding the braces; the meaning of the
2185 following two lines is different:
2186
2187 .. code-block:: c++
2188
2189 complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
2190 complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
2191
2192 This extension also works in C++ mode, as far as that goes, but does not apply
2193 to the C++ ``std::complex``. (In C++11, list initialization allows the same
2194 syntax to be used with ``std::complex`` with the same meaning.)
2195
2196 For GCC compatibility, ``__builtin_complex(re, im)`` can also be used to
2197 construct a complex number from the given real and imaginary components.
2198
2199 OpenCL Features
2200 ===============
2201
2202 Clang supports internal OpenCL extensions documented below.
2203
2204 ``__cl_clang_bitfields``
2205 --------------------------------
2206
2207 With this extension it is possible to enable bitfields in structs
2208 or unions using the OpenCL extension pragma mechanism detailed in
2209 `the OpenCL Extension Specification, section 1.2
2210 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2211
2212 Use of bitfields in OpenCL kernels can result in reduced portability as struct
2213 layout is not guaranteed to be consistent when compiled by different compilers.
2214 If structs with bitfields are used as kernel function parameters, it can result
2215 in incorrect functionality when the layout is different between the host and
2216 device code.
2217
2218 **Example of Use**:
2219
2220 .. code-block:: c++
2221
2222 #pragma OPENCL EXTENSION __cl_clang_bitfields : enable
2223 struct with_bitfield {
2224 unsigned int i : 5; // compiled - no diagnostic generated
2225 };
2226
2227 #pragma OPENCL EXTENSION __cl_clang_bitfields : disable
2228 struct without_bitfield {
2229 unsigned int i : 5; // error - bitfields are not supported
2230 };
2231
2232 ``__cl_clang_function_pointers``
2233 --------------------------------
2234
2235 With this extension it is possible to enable various language features that
2236 are relying on function pointers using regular OpenCL extension pragma
2237 mechanism detailed in `the OpenCL Extension Specification,
2238 section 1.2
2239 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2240
2241 In C++ for OpenCL this also enables:
2242
2243 - Use of member function pointers;
2244
2245 - Unrestricted use of references to functions;
2246
2247 - Virtual member functions.
2248
2249 Such functionality is not conformant and does not guarantee to compile
2250 correctly in any circumstances. It can be used if:
2251
2252 - the kernel source does not contain call expressions to (member-) function
2253 pointers, or virtual functions. For example this extension can be used in
2254 metaprogramming algorithms to be able to specify/detect types generically.
2255
2256 - the generated kernel binary does not contain indirect calls because they
2257 are eliminated using compiler optimizations e.g. devirtualization.
2258
2259 - the selected target supports the function pointer like functionality e.g.
2260 most CPU targets.
2261
2262 **Example of Use**:
2263
2264 .. code-block:: c++
2265
2266 #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable
2267 void foo()
2268 {
2269 void (*fp)(); // compiled - no diagnostic generated
2270 }
2271
2272 #pragma OPENCL EXTENSION __cl_clang_function_pointers : disable
2273 void bar()
2274 {
2275 void (*fp)(); // error - pointers to function are not allowed
2276 }
2277
2278 ``__cl_clang_variadic_functions``
2279 ---------------------------------
2280
2281 With this extension it is possible to enable variadic arguments in functions
2282 using regular OpenCL extension pragma mechanism detailed in `the OpenCL
2283 Extension Specification, section 1.2
2284 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2285
2286 This is not conformant behavior and it can only be used portably when the
2287 functions with variadic prototypes do not get generated in binary e.g. the
2288 variadic prototype is used to specify a function type with any number of
2289 arguments in metaprogramming algorithms in C++ for OpenCL.
2290
2291 This extensions can also be used when the kernel code is intended for targets
2292 supporting the variadic arguments e.g. majority of CPU targets.
2293
2294 **Example of Use**:
2295
2296 .. code-block:: c++
2297
2298 #pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable
2299 void foo(int a, ...); // compiled - no diagnostic generated
2300
2301 #pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable
2302 void bar(int a, ...); // error - variadic prototype is not allowed
2303
2304 ``__cl_clang_non_portable_kernel_param_types``
2305 ----------------------------------------------
2306
2307 With this extension it is possible to enable the use of some restricted types
2308 in kernel parameters specified in `C++ for OpenCL v1.0 s2.4
2309 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_.
2310 The restrictions can be relaxed using regular OpenCL extension pragma mechanism
2311 detailed in `the OpenCL Extension Specification, section 1.2
2312 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_.
2313
2314 This is not a conformant behavior and it can only be used when the
2315 kernel arguments are not accessed on the host side or the data layout/size
2316 between the host and device is known to be compatible.
2317
2318 **Example of Use**:
2319
2320 .. code-block:: c++
2321
2322 // Plain Old Data type.
2323 struct Pod {
2324 int a;
2325 int b;
2326 };
2327
2328 // Not POD type because of the constructor.
2329 // Standard layout type because there is only one access control.
2330 struct OnlySL {
2331 int a;
2332 int b;
2333 OnlySL() : a(0), b(0) {}
2334 };
2335
2336 // Not standard layout type because of two different access controls.
2337 struct NotSL {
2338 int a;
2339 private:
2340 int b;
2341 };
2342
2343 #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable
2344 kernel void kernel_main(
2345 Pod a,
2346
2347 OnlySL b,
2348 global NotSL *c,
2349 global OnlySL *d
2350 );
2351 #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable
2352
2353 Remove address space builtin function
2354 -------------------------------------
2355
2356 ``__remove_address_space`` allows to derive types in C++ for OpenCL
2357 that have address space qualifiers removed. This utility only affects
2358 address space qualifiers, therefore, other type qualifiers such as
2359 ``const`` or ``volatile`` remain unchanged.
2360
2361 **Example of Use**:
2362
2363 .. code-block:: c++
2364
2365 template<typename T>
2366 void foo(T *par){
2367 T var1; // error - local function variable with global address space
2368 __private T var2; // error - conflicting address space qualifiers
2369 __private __remove_address_space<T>::type var3; // var3 is __private int
2370 }
2371
2372 void bar(){
2373 __global int* ptr;
2374 foo(ptr);
2375 }
2376
2377 Legacy 1.x atomics with generic address space
2378 ---------------------------------------------
2379
2380 Clang allows use of atomic functions from the OpenCL 1.x standards
2381 with the generic address space pointer in C++ for OpenCL mode.
2382
2383 This is a non-portable feature and might not be supported by all
2384 targets.
2385
2386 **Example of Use**:
2387
2388 .. code-block:: c++
2389
2390 void foo(__generic volatile unsigned int* a) {
2391 atomic_add(a, 1);
2392 }
2393
2394 WebAssembly Features
2395 ====================
2396
2397 Clang supports the WebAssembly features documented below. For further
2398 information related to the semantics of the builtins, please refer to the `WebAssembly Specification <https://webassembly.github.io/spec/core/>`_.
2399 In this section, when we refer to reference types, we are referring to
2400 WebAssembly reference types, not C++ reference types unless stated
2401 otherwise.
2402
2403 ``__builtin_wasm_table_set``
2404 ----------------------------
2405
2406 This builtin function stores a value in a WebAssembly table.
2407 It takes three arguments.
2408 The first argument is the table to store a value into, the second
2409 argument is the index to which to store the value into, and the
2410 third argument is a value of reference type to store in the table.
2411 It returns nothing.
2412
2413 .. code-block:: c++
2414
2415 static __externref_t table[0];
2416 extern __externref_t JSObj;
2417
2418 void store(int index) {
2419 __builtin_wasm_table_set(table, index, JSObj);
2420 }
2421
2422 ``__builtin_wasm_table_get``
2423 ----------------------------
2424
2425 This builtin function is the counterpart to ``__builtin_wasm_table_set``
2426 and loads a value from a WebAssembly table of reference typed values.
2427 It takes 2 arguments.
2428 The first argument is a table of reference typed values and the
2429 second argument is an index from which to load the value. It returns
2430 the loaded reference typed value.
2431
2432 .. code-block:: c++
2433
2434 static __externref_t table[0];
2435
2436 __externref_t load(int index) {
2437 __externref_t Obj = __builtin_wasm_table_get(table, index);
2438 return Obj;
2439 }
2440
2441 ``__builtin_wasm_table_size``
2442 -----------------------------
2443
2444 This builtin function returns the size of the WebAssembly table.
2445 Takes the table as an argument and returns an unsigned integer (``size_t``)
2446 with the current table size.
2447
2448 .. code-block:: c++
2449
2450 typedef void (*__funcref funcref_t)();
2451 static __funcref table[0];
2452
2453 size_t getSize() {
2454 return __builtin_wasm_table_size(table);
2455 }
2456
2457 ``__builtin_wasm_table_grow``
2458 -----------------------------
2459
2460 This builtin function grows the WebAssembly table by a certain amount.
2461 Currently, as all WebAssembly tables created in C/C++ are zero-sized,
2462 this always needs to be called to grow the table.
2463
2464 It takes three arguments. The first argument is the WebAssembly table
2465 to grow. The second argument is the reference typed value to store in
2466 the new table entries (the initialization value), and the third argument
2467 is the amount to grow the table by. It returns the previous table size
2468 or -1. It will return -1 if not enough space could be allocated.
2469
2470 .. code-block:: c++
2471
2472 typedef void (*__funcref funcref_t)();
2473 static __funcref table[0];
2474
2475 // grow returns the new table size or -1 on error.
2476 int grow(__funcref fn, int delta) {
2477 int prevSize = __builtin_wasm_table_grow(table, fn, delta);
2478 if (prevSize == -1)
2479 return -1;
2480 return prevSize + delta;
2481 }
2482
2483 ``__builtin_wasm_table_fill``
2484 -----------------------------
2485
2486 This builtin function sets all the entries of a WebAssembly table to a given
2487 reference typed value. It takes four arguments. The first argument is
2488 the WebAssembly table, the second argument is the index that starts the
2489 range, the third argument is the value to set in the new entries, and
2490 the fourth and the last argument is the size of the range. It returns
2491 nothing.
2492
2493 .. code-block:: c++
2494
2495 static __externref_t table[0];
2496
2497 // resets a table by setting all of its entries to a given value.
2498 void reset(__externref_t Obj) {
2499 int Size = __builtin_wasm_table_size(table);
2500 __builtin_wasm_table_fill(table, 0, Obj, Size);
2501 }
2502
2503 ``__builtin_wasm_table_copy``
2504 -----------------------------
2505
2506 This builtin function copies elements from a source WebAssembly table
2507 to a possibly overlapping destination region. It takes five arguments.
2508 The first argument is the destination WebAssembly table, and the second
2509 argument is the source WebAssembly table. The third argument is the
2510 destination index from where the copy starts, the fourth argument is the
2511 source index from there the copy starts, and the fifth and last argument
2512 is the number of elements to copy. It returns nothing.
2513
2514 .. code-block:: c++
2515
2516 static __externref_t tableSrc[0];
2517 static __externref_t tableDst[0];
2518
2519 // Copy nelem elements from [src, src + nelem - 1] in tableSrc to
2520 // [dst, dst + nelem - 1] in tableDst
2521 void copy(int dst, int src, int nelem) {
2522 __builtin_wasm_table_copy(tableDst, tableSrc, dst, src, nelem);
2523 }
2524
2525
2526 Builtin Functions
2527 =================
2528
2529 Clang supports a number of builtin library functions with the same syntax as
2530 GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
2531 ``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
2532 ``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to
2533 the GCC builtins, Clang supports a number of builtins that GCC does not, which
2534 are listed here.
2535
2536 Please note that Clang does not and will not support all of the GCC builtins
2537 for vector operations. Instead of using builtins, you should use the functions
2538 defined in target-specific header files like ``<xmmintrin.h>``, which define
2539 portable wrappers for these. Many of the Clang versions of these functions are
2540 implemented directly in terms of :ref:`extended vector support
2541 <langext-vectors>` instead of builtins, in order to reduce the number of
2542 builtins that we need to implement.
2543
2544 ``__builtin_alloca``
2545 --------------------
2546
2547 ``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory
2548 is automatically freed upon function termination.
2549
2550 **Syntax**:
2551
2552 .. code-block:: c++
2553
2554 __builtin_alloca(size_t n)
2555
2556 **Example of Use**:
2557
2558 .. code-block:: c++
2559
2560 void init(float* data, size_t nbelems);
2561 void process(float* data, size_t nbelems);
2562 int foo(size_t n) {
2563 auto mem = (float*)__builtin_alloca(n * sizeof(float));
2564 init(mem, n);
2565 process(mem, n);
2566 /* mem is automatically freed at this point */
2567 }
2568
2569 **Description**:
2570
2571 ``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory
2572 on the stack. This amount is subject to stack allocation limits.
2573
2574 Query for this feature with ``__has_builtin(__builtin_alloca)``.
2575
2576 ``__builtin_alloca_with_align``
2577 -------------------------------
2578
2579 ``__builtin_alloca_with_align`` is used to dynamically allocate memory on the
2580 stack while controlling its alignment. Memory is automatically freed upon
2581 function termination.
2582
2583
2584 **Syntax**:
2585
2586 .. code-block:: c++
2587
2588 __builtin_alloca_with_align(size_t n, size_t align)
2589
2590 **Example of Use**:
2591
2592 .. code-block:: c++
2593
2594 void init(float* data, size_t nbelems);
2595 void process(float* data, size_t nbelems);
2596 int foo(size_t n) {
2597 auto mem = (float*)__builtin_alloca_with_align(
2598 n * sizeof(float),
2599 CHAR_BIT * alignof(float));
2600 init(mem, n);
2601 process(mem, n);
2602 /* mem is automatically freed at this point */
2603 }
2604
2605 **Description**:
2606
2607 ``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory
2608 on the stack. It is similar to ``__builtin_alloca`` but accepts a second
2609 argument whose value is the alignment constraint, as a power of 2 in *bits*.
2610
2611 Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``.
2612
2613 .. _langext-__builtin_assume:
2614
2615 ``__builtin_assume``
2616 --------------------
2617
2618 ``__builtin_assume`` is used to provide the optimizer with a boolean
2619 invariant that is defined to be true.
2620
2621 **Syntax**:
2622
2623 .. code-block:: c++
2624
2625 __builtin_assume(bool)
2626
2627 **Example of Use**:
2628
2629 .. code-block:: c++
2630
2631 int foo(int x) {
2632 __builtin_assume(x != 0);
2633 // The optimizer may short-circuit this check using the invariant.
2634 if (x == 0)
2635 return do_something();
2636 return do_something_else();
2637 }
2638
2639 **Description**:
2640
2641 The boolean argument to this function is defined to be true. The optimizer may
2642 analyze the form of the expression provided as the argument and deduce from
2643 that information used to optimize the program. If the condition is violated
2644 during execution, the behavior is undefined. The argument itself is never
2645 evaluated, so any side effects of the expression will be discarded.
2646
2647 Query for this feature with ``__has_builtin(__builtin_assume)``.
2648
2649 .. _langext-__builtin_assume_separate_storage:
2650
2651 ``__builtin_assume_separate_storage``
2652 -------------------------------------
2653
2654 ``__builtin_assume_separate_storage`` is used to provide the optimizer with the
2655 knowledge that its two arguments point to separately allocated objects.
2656
2657 **Syntax**:
2658
2659 .. code-block:: c++
2660
2661 __builtin_assume_separate_storage(const volatile void *, const volatile void *)
2662
2663 **Example of Use**:
2664
2665 .. code-block:: c++
2666
2667 int foo(int *x, int *y) {
2668 __builtin_assume_separate_storage(x, y);
2669 *x = 0;
2670 *y = 1;
2671 // The optimizer may optimize this to return 0 without reloading from *x.
2672 return *x;
2673 }
2674
2675 **Description**:
2676
2677 The arguments to this function are assumed to point into separately allocated
2678 storage (either different variable definitions or different dynamic storage
2679 allocations). The optimizer may use this fact to aid in alias analysis. If the
2680 arguments point into the same storage, the behavior is undefined. Note that the
2681 definition of "storage" here refers to the outermost enclosing allocation of any
2682 particular object (so for example, it's never correct to call this function
2683 passing the addresses of fields in the same struct, elements of the same array,
2684 etc.).
2685
2686 Query for this feature with ``__has_builtin(__builtin_assume_separate_storage)``.
2687
2688
2689 ``__builtin_offsetof``
2690 ----------------------
2691
2692 ``__builtin_offsetof`` is used to implement the ``offsetof`` macro, which
2693 calculates the offset (in bytes) to a given member of the given type.
2694
2695 **Syntax**:
2696
2697 .. code-block:: c++
2698
2699 __builtin_offsetof(type-name, member-designator)
2700
2701 **Example of Use**:
2702
2703 .. code-block:: c++
2704
2705 struct S {
2706 char c;
2707 int i;
2708 struct T {
2709 float f[2];
2710 } t;
2711 };
2712
2713 const int offset_to_i = __builtin_offsetof(struct S, i);
2714 const int ext1 = __builtin_offsetof(struct U { int i; }, i); // C extension
2715 const int offset_to_subobject = __builtin_offsetof(struct S, t.f[1]);
2716
2717 **Description**:
2718
2719 This builtin is usable in an integer constant expression which returns a value
2720 of type ``size_t``. The value returned is the offset in bytes to the subobject
2721 designated by the member-designator from the beginning of an object of type
2722 ``type-name``. Clang extends the required standard functionality in the
2723 following way:
2724
2725 * In C language modes, the first argument may be the definition of a new type.
2726 Any type declared this way is scoped to the nearest scope containing the call
2727 to the builtin.
2728
2729 Query for this feature with ``__has_builtin(__builtin_offsetof)``.
2730
2731 ``__builtin_call_with_static_chain``
2732 ------------------------------------
2733
2734 ``__builtin_call_with_static_chain`` is used to perform a static call while
2735 setting updating the static chain register.
2736
2737 **Syntax**:
2738
2739 .. code-block:: c++
2740
2741 T __builtin_call_with_static_chain(T expr, void* ptr)
2742
2743 **Example of Use**:
2744
2745 .. code-block:: c++
2746
2747 auto v = __builtin_call_with_static_chain(foo(3), foo);
2748
2749 **Description**:
2750
2751 This builtin returns ``expr`` after checking that ``expr`` is a non-member
2752 static call expression. The call to that expression is made while using ``ptr``
2753 as a function pointer stored in a dedicated register to implement *static chain*
2754 calling convention, as used by some language to implement closures or nested
2755 functions.
2756
2757 Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``.
2758
2759 ``__builtin_readcyclecounter``
2760 ------------------------------
2761
2762 ``__builtin_readcyclecounter`` is used to access the cycle counter register (or
2763 a similar low-latency, high-accuracy clock) on those targets that support it.
2764
2765 **Syntax**:
2766
2767 .. code-block:: c++
2768
2769 __builtin_readcyclecounter()
2770
2771 **Example of Use**:
2772
2773 .. code-block:: c++
2774
2775 unsigned long long t0 = __builtin_readcyclecounter();
2776 do_something();
2777 unsigned long long t1 = __builtin_readcyclecounter();
2778 unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
2779
2780 **Description**:
2781
2782 The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
2783 which may be either global or process/thread-specific depending on the target.
2784 As the backing counters often overflow quickly (on the order of seconds) this
2785 should only be used for timing small intervals. When not supported by the
2786 target, the return value is always zero. This builtin takes no arguments and
2787 produces an unsigned long long result.
2788
2789 Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
2790 that even if present, its use may depend on run-time privilege or other OS
2791 controlled state.
2792
2793 ``__builtin_readsteadycounter``
2794 -------------------------------
2795
2796 ``__builtin_readsteadycounter`` is used to access the fixed frequency counter
2797 register (or a similar steady-rate clock) on those targets that support it.
2798 The function is similar to ``__builtin_readcyclecounter`` above except that the
2799 frequency is fixed, making it suitable for measuring elapsed time.
2800
2801 **Syntax**:
2802
2803 .. code-block:: c++
2804
2805 __builtin_readsteadycounter()
2806
2807 **Example of Use**:
2808
2809 .. code-block:: c++
2810
2811 unsigned long long t0 = __builtin_readsteadycounter();
2812 do_something();
2813 unsigned long long t1 = __builtin_readsteadycounter();
2814 unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
2815
2816 **Description**:
2817
2818 The ``__builtin_readsteadycounter()`` builtin returns the frequency counter value.
2819 When not supported by the target, the return value is always zero. This builtin
2820 takes no arguments and produces an unsigned long long result. The builtin does
2821 not guarantee any particular frequency, only that it is stable. Knowledge of the
2822 counter's true frequency will need to be provided by the user.
2823
2824 Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.
2825
2826 ``__builtin_cpu_supports``
2827 --------------------------
2828
2829 **Syntax**:
2830
2831 .. code-block:: c++
2832
2833 int __builtin_cpu_supports(const char *features);
2834
2835 **Example of Use:**:
2836
2837 .. code-block:: c++
2838
2839 if (__builtin_cpu_supports("sve"))
2840 sve_code();
2841
2842 **Description**:
2843
2844 The ``__builtin_cpu_supports`` function detects if the run-time CPU supports
2845 features specified in string argument. It returns a positive integer if all
2846 features are supported and 0 otherwise. Feature names are target specific. On
2847 AArch64 features are combined using ``+`` like this
2848 ``__builtin_cpu_supports("flagm+sha3+lse+rcpc2+fcma+memtag+bti+sme2")``.
2849 If a feature name is not supported, Clang will issue a warning and replace
2850 builtin by the constant 0.
2851
2852 Query for this feature with ``__has_builtin(__builtin_cpu_supports)``.
2853
2854 ``__builtin_dump_struct``
2855 -------------------------
2856
2857 **Syntax**:
2858
2859 .. code-block:: c++
2860
2861 __builtin_dump_struct(&some_struct, some_printf_func, args...);
2862
2863 **Examples**:
2864
2865 .. code-block:: c++
2866
2867 struct S {
2868 int x, y;
2869 float f;
2870 struct T {
2871 int i;
2872 } t;
2873 };
2874
2875 void func(struct S *s) {
2876 __builtin_dump_struct(s, printf);
2877 }
2878
2879 Example output:
2880
2881 .. code-block:: none
2882
2883 struct S {
2884 int x = 100
2885 int y = 42
2886 float f = 3.141593
2887 struct T t = {
2888 int i = 1997
2889 }
2890 }
2891
2892 .. code-block:: c++
2893
2894 #include <string>
2895 struct T { int a, b; };
2896 constexpr void constexpr_sprintf(std::string &out, const char *format,
2897 auto ...args) {
2898 // ...
2899 }
2900 constexpr std::string dump_struct(auto &x) {
2901 std::string s;
2902 __builtin_dump_struct(&x, constexpr_sprintf, s);
2903 return s;
2904 }
2905 static_assert(dump_struct(T{1, 2}) == R"(struct T {
2906 int a = 1
2907 int b = 2
2908 }
2909 )");
2910
2911 **Description**:
2912
2913 The ``__builtin_dump_struct`` function is used to print the fields of a simple
2914 structure and their values for debugging purposes. The first argument of the
2915 builtin should be a pointer to a complete record type to dump. The second argument ``f``
2916 should be some callable expression, and can be a function object or an overload
2917 set. The builtin calls ``f``, passing any further arguments ``args...``
2918 followed by a ``printf``-compatible format string and the corresponding
2919 arguments. ``f`` may be called more than once, and ``f`` and ``args`` will be
2920 evaluated once per call. In C++, ``f`` may be a template or overload set and
2921 resolve to different functions for each call.
2922
2923 In the format string, a suitable format specifier will be used for builtin
2924 types that Clang knows how to format. This includes standard builtin types, as
2925 well as aggregate structures, ``void*`` (printed with ``%p``), and ``const
2926 char*`` (printed with ``%s``). A ``*%p`` specifier will be used for a field
2927 that Clang doesn't know how to format, and the corresponding argument will be a
2928 pointer to the field. This allows a C++ templated formatting function to detect
2929 this case and implement custom formatting. A ``*`` will otherwise not precede a
2930 format specifier.
2931
2932 This builtin does not return a value.
2933
2934 This builtin can be used in constant expressions.
2935
2936 Query for this feature with ``__has_builtin(__builtin_dump_struct)``
2937
2938 .. _langext-__builtin_shufflevector:
2939
2940 ``__builtin_shufflevector``
2941 ---------------------------
2942
2943 ``__builtin_shufflevector`` is used to express generic vector
2944 permutation/shuffle/swizzle operations. This builtin is also very important
2945 for the implementation of various target-specific header files like
2946 ``<xmmintrin.h>``. This builtin can be used within constant expressions.
2947
2948 **Syntax**:
2949
2950 .. code-block:: c++
2951
2952 __builtin_shufflevector(vec1, vec2, index1, index2, ...)
2953
2954 **Examples**:
2955
2956 .. code-block:: c++
2957
2958 // identity operation - return 4-element vector v1.
2959 __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
2960
2961 // "Splat" element 0 of V1 into a 4-element result.
2962 __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
2963
2964 // Reverse 4-element vector V1.
2965 __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
2966
2967 // Concatenate every other element of 4-element vectors V1 and V2.
2968 __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
2969
2970 // Concatenate every other element of 8-element vectors V1 and V2.
2971 __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
2972
2973 // Shuffle v1 with some elements being undefined. Not allowed in constexpr.
2974 __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
2975
2976 **Description**:
2977
2978 The first two arguments to ``__builtin_shufflevector`` are vectors that have
2979 the same element type. The remaining arguments are a list of integers that
2980 specify the elements indices of the first two vectors that should be extracted
2981 and returned in a new vector. These element indices are numbered sequentially
2982 starting with the first vector, continuing into the second vector. Thus, if
2983 ``vec1`` is a 4-element vector, index 5 would refer to the second element of
2984 ``vec2``. An index of -1 can be used to indicate that the corresponding element
2985 in the returned vector is a don't care and can be optimized by the backend.
2986 Values of -1 are not supported in constant expressions.
2987
2988 The result of ``__builtin_shufflevector`` is a vector with the same element
2989 type as ``vec1``/``vec2`` but that has an element count equal to the number of
2990 indices specified.
2991
2992 Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
2993
2994 .. _langext-__builtin_convertvector:
2995
2996 ``__builtin_convertvector``
2997 ---------------------------
2998
2999 ``__builtin_convertvector`` is used to express generic vector
3000 type-conversion operations. The input vector and the output vector
3001 type must have the same number of elements. This builtin can be used within
3002 constant expressions.
3003
3004 **Syntax**:
3005
3006 .. code-block:: c++
3007
3008 __builtin_convertvector(src_vec, dst_vec_type)
3009
3010 **Examples**:
3011
3012 .. code-block:: c++
3013
3014 typedef double vector4double __attribute__((__vector_size__(32)));
3015 typedef float vector4float __attribute__((__vector_size__(16)));
3016 typedef short vector4short __attribute__((__vector_size__(8)));
3017 vector4float vf; vector4short vs;
3018
3019 // convert from a vector of 4 floats to a vector of 4 doubles.
3020 __builtin_convertvector(vf, vector4double)
3021 // equivalent to:
3022 (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
3023
3024 // convert from a vector of 4 shorts to a vector of 4 floats.
3025 __builtin_convertvector(vs, vector4float)
3026 // equivalent to:
3027 (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
3028
3029 **Description**:
3030
3031 The first argument to ``__builtin_convertvector`` is a vector, and the second
3032 argument is a vector type with the same number of elements as the first
3033 argument.
3034
3035 The result of ``__builtin_convertvector`` is a vector with the same element
3036 type as the second argument, with a value defined in terms of the action of a
3037 C-style cast applied to each element of the first argument.
3038
3039 Query for this feature with ``__has_builtin(__builtin_convertvector)``.
3040
3041 ``__builtin_bitreverse``
3042 ------------------------
3043
3044 * ``__builtin_bitreverse8``
3045 * ``__builtin_bitreverse16``
3046 * ``__builtin_bitreverse32``
3047 * ``__builtin_bitreverse64``
3048
3049 **Syntax**:
3050
3051 .. code-block:: c++
3052
3053 __builtin_bitreverse32(x)
3054
3055 **Examples**:
3056
3057 .. code-block:: c++
3058
3059 uint8_t rev_x = __builtin_bitreverse8(x);
3060 uint16_t rev_x = __builtin_bitreverse16(x);
3061 uint32_t rev_y = __builtin_bitreverse32(y);
3062 uint64_t rev_z = __builtin_bitreverse64(z);
3063
3064 **Description**:
3065
3066 The '``__builtin_bitreverse``' family of builtins is used to reverse
3067 the bitpattern of an integer value; for example ``0b10110110`` becomes
3068 ``0b01101101``. These builtins can be used within constant expressions.
3069
3070 ``__builtin_rotateleft``
3071 ------------------------
3072
3073 * ``__builtin_rotateleft8``
3074 * ``__builtin_rotateleft16``
3075 * ``__builtin_rotateleft32``
3076 * ``__builtin_rotateleft64``
3077
3078 **Syntax**:
3079
3080 .. code-block:: c++
3081
3082 __builtin_rotateleft32(x, y)
3083
3084 **Examples**:
3085
3086 .. code-block:: c++
3087
3088 uint8_t rot_x = __builtin_rotateleft8(x, y);
3089 uint16_t rot_x = __builtin_rotateleft16(x, y);
3090 uint32_t rot_x = __builtin_rotateleft32(x, y);
3091 uint64_t rot_x = __builtin_rotateleft64(x, y);
3092
3093 **Description**:
3094
3095 The '``__builtin_rotateleft``' family of builtins is used to rotate
3096 the bits in the first argument by the amount in the second argument.
3097 For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
3098 The shift value is treated as an unsigned amount modulo the size of
3099 the arguments. Both arguments and the result have the bitwidth specified
3100 by the name of the builtin. These builtins can be used within constant
3101 expressions.
3102
3103 ``__builtin_rotateright``
3104 -------------------------
3105
3106 * ``__builtin_rotateright8``
3107 * ``__builtin_rotateright16``
3108 * ``__builtin_rotateright32``
3109 * ``__builtin_rotateright64``
3110
3111 **Syntax**:
3112
3113 .. code-block:: c++
3114
3115 __builtin_rotateright32(x, y)
3116
3117 **Examples**:
3118
3119 .. code-block:: c++
3120
3121 uint8_t rot_x = __builtin_rotateright8(x, y);
3122 uint16_t rot_x = __builtin_rotateright16(x, y);
3123 uint32_t rot_x = __builtin_rotateright32(x, y);
3124 uint64_t rot_x = __builtin_rotateright64(x, y);
3125
3126 **Description**:
3127
3128 The '``__builtin_rotateright``' family of builtins is used to rotate
3129 the bits in the first argument by the amount in the second argument.
3130 For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
3131 The shift value is treated as an unsigned amount modulo the size of
3132 the arguments. Both arguments and the result have the bitwidth specified
3133 by the name of the builtin. These builtins can be used within constant
3134 expressions.
3135
3136 ``__builtin_unreachable``
3137 -------------------------
3138
3139 ``__builtin_unreachable`` is used to indicate that a specific point in the
3140 program cannot be reached, even if the compiler might otherwise think it can.
3141 This is useful to improve optimization and eliminates certain warnings. For
3142 example, without the ``__builtin_unreachable`` in the example below, the
3143 compiler assumes that the inline asm can fall through and prints a "function
3144 declared '``noreturn``' should not return" warning.
3145
3146 **Syntax**:
3147
3148 .. code-block:: c++
3149
3150 __builtin_unreachable()
3151
3152 **Example of use**:
3153
3154 .. code-block:: c++
3155
3156 void myabort(void) __attribute__((noreturn));
3157 void myabort(void) {
3158 asm("int3");
3159 __builtin_unreachable();
3160 }
3161
3162 **Description**:
3163
3164 The ``__builtin_unreachable()`` builtin has completely undefined behavior.
3165 Since it has undefined behavior, it is a statement that it is never reached and
3166 the optimizer can take advantage of this to produce better code. This builtin
3167 takes no arguments and produces a void result.
3168
3169 Query for this feature with ``__has_builtin(__builtin_unreachable)``.
3170
3171 ``__builtin_unpredictable``
3172 ---------------------------
3173
3174 ``__builtin_unpredictable`` is used to indicate that a branch condition is
3175 unpredictable by hardware mechanisms such as branch prediction logic.
3176
3177 **Syntax**:
3178
3179 .. code-block:: c++
3180
3181 __builtin_unpredictable(long long)
3182
3183 **Example of use**:
3184
3185 .. code-block:: c++
3186
3187 if (__builtin_unpredictable(x > 0)) {
3188 foo();
3189 }
3190
3191 **Description**:
3192
3193 The ``__builtin_unpredictable()`` builtin is expected to be used with control
3194 flow conditions such as in ``if`` and ``switch`` statements.
3195
3196 Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
3197
3198
3199 ``__builtin_expect``
3200 --------------------
3201
3202 ``__builtin_expect`` is used to indicate that the value of an expression is
3203 anticipated to be the same as a statically known result.
3204
3205 **Syntax**:
3206
3207 .. code-block:: c++
3208
3209 long __builtin_expect(long expr, long val)
3210
3211 **Example of use**:
3212
3213 .. code-block:: c++
3214
3215 if (__builtin_expect(x, 0)) {
3216 bar();
3217 }
3218
3219 **Description**:
3220
3221 The ``__builtin_expect()`` builtin is typically used with control flow
3222 conditions such as in ``if`` and ``switch`` statements to help branch
3223 prediction. It means that its first argument ``expr`` is expected to take the
3224 value of its second argument ``val``. It always returns ``expr``.
3225
3226 Query for this feature with ``__has_builtin(__builtin_expect)``.
3227
3228 ``__builtin_expect_with_probability``
3229 -------------------------------------
3230
3231 ``__builtin_expect_with_probability`` is similar to ``__builtin_expect`` but it
3232 takes a probability as third argument.
3233
3234 **Syntax**:
3235
3236 .. code-block:: c++
3237
3238 long __builtin_expect_with_probability(long expr, long val, double p)
3239
3240 **Example of use**:
3241
3242 .. code-block:: c++
3243
3244 if (__builtin_expect_with_probability(x, 0, .3)) {
3245 bar();
3246 }
3247
3248 **Description**:
3249
3250 The ``__builtin_expect_with_probability()`` builtin is typically used with
3251 control flow conditions such as in ``if`` and ``switch`` statements to help
3252 branch prediction. It means that its first argument ``expr`` is expected to take
3253 the value of its second argument ``val`` with probability ``p``. ``p`` must be
3254 within ``[0.0 ; 1.0]`` bounds. This builtin always returns the value of ``expr``.
3255
3256 Query for this feature with ``__has_builtin(__builtin_expect_with_probability)``.
3257
3258 ``__builtin_prefetch``
3259 ----------------------
3260
3261 ``__builtin_prefetch`` is used to communicate with the cache handler to bring
3262 data into the cache before it gets used.
3263
3264 **Syntax**:
3265
3266 .. code-block:: c++
3267
3268 void __builtin_prefetch(const void *addr, int rw=0, int locality=3)
3269
3270 **Example of use**:
3271
3272 .. code-block:: c++
3273
3274 __builtin_prefetch(a + i);
3275
3276 **Description**:
3277
3278 The ``__builtin_prefetch(addr, rw, locality)`` builtin is expected to be used to
3279 avoid cache misses when the developer has a good understanding of which data
3280 are going to be used next. ``addr`` is the address that needs to be brought into
3281 the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and ``1``
3282 for *write*. In case of *read write* access, ``1`` is to be used. ``locality``
3283 indicates the expected persistence of data in cache, from ``0`` which means that
3284 data can be discarded from cache after its next use to ``3`` which means that
3285 data is going to be reused a lot once in cache. ``1`` and ``2`` provide
3286 intermediate behavior between these two extremes.
3287
3288 Query for this feature with ``__has_builtin(__builtin_prefetch)``.
3289
3290 ``__sync_swap``
3291 ---------------
3292
3293 ``__sync_swap`` is used to atomically swap integers or pointers in memory.
3294
3295 **Syntax**:
3296
3297 .. code-block:: c++
3298
3299 type __sync_swap(type *ptr, type value, ...)
3300
3301 **Example of Use**:
3302
3303 .. code-block:: c++
3304
3305 int old_value = __sync_swap(&value, new_value);
3306
3307 **Description**:
3308
3309 The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
3310 atomic intrinsics to allow code to atomically swap the current value with the
3311 new value. More importantly, it helps developers write more efficient and
3312 correct code by avoiding expensive loops around
3313 ``__sync_bool_compare_and_swap()`` or relying on the platform specific
3314 implementation details of ``__sync_lock_test_and_set()``. The
3315 ``__sync_swap()`` builtin is a full barrier.
3316
3317 ``__builtin_addressof``
3318 -----------------------
3319
3320 ``__builtin_addressof`` performs the functionality of the built-in ``&``
3321 operator, ignoring any ``operator&`` overload. This is useful in constant
3322 expressions in C++11, where there is no other way to take the address of an
3323 object that overloads ``operator&``. Clang automatically adds
3324 ``[[clang::lifetimebound]]`` to the parameter of ``__builtin_addressof``.
3325
3326 **Example of use**:
3327
3328 .. code-block:: c++
3329
3330 template<typename T> constexpr T *addressof(T &value) {
3331 return __builtin_addressof(value);
3332 }
3333
3334 ``__builtin_function_start``
3335 -----------------------------
3336
3337 ``__builtin_function_start`` returns the address of a function body.
3338
3339 **Syntax**:
3340
3341 .. code-block:: c++
3342
3343 void *__builtin_function_start(function)
3344
3345 **Example of use**:
3346
3347 .. code-block:: c++
3348
3349 void a() {}
3350 void *p = __builtin_function_start(a);
3351
3352 class A {
3353 public:
3354 void a(int n);
3355 void a();
3356 };
3357
3358 void A::a(int n) {}
3359 void A::a() {}
3360
3361 void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a);
3362 void *pa2 = __builtin_function_start((void(A::*)()) &A::a);
3363
3364 **Description**:
3365
3366 The ``__builtin_function_start`` builtin accepts an argument that can be
3367 constant-evaluated to a function, and returns the address of the function
3368 body. This builtin is not supported on all targets.
3369
3370 The returned pointer may differ from the normally taken function address
3371 and is not safe to call. For example, with ``-fsanitize=cfi``, taking a
3372 function address produces a callable pointer to a CFI jump table, while
3373 ``__builtin_function_start`` returns an address that fails
3374 :doc:`cfi-icall<ControlFlowIntegrity>` checks.
3375
3376 ``__builtin_operator_new`` and ``__builtin_operator_delete``
3377 ------------------------------------------------------------
3378
3379 A call to ``__builtin_operator_new(args)`` is exactly the same as a call to
3380 ``::operator new(args)``, except that it allows certain optimizations
3381 that the C++ standard does not permit for a direct function call to
3382 ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
3383 merging allocations), and that the call is required to resolve to a
3384 `replaceable global allocation function
3385 <https://en.cppreference.com/w/cpp/memory/new/operator_new>`_.
3386
3387 Likewise, ``__builtin_operator_delete`` is exactly the same as a call to
3388 ``::operator delete(args)``, except that it permits optimizations
3389 and that the call is required to resolve to a
3390 `replaceable global deallocation function
3391 <https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_.
3392
3393 These builtins are intended for use in the implementation of ``std::allocator``
3394 and other similar allocation libraries, and are only available in C++.
3395
3396 Query for this feature with ``__has_builtin(__builtin_operator_new)`` or
3397 ``__has_builtin(__builtin_operator_delete)``:
3398
3399 * If the value is at least ``201802L``, the builtins behave as described above.
3400
3401 * If the value is non-zero, the builtins may not support calling arbitrary
3402 replaceable global (de)allocation functions, but do support calling at least
3403 ``::operator new(size_t)`` and ``::operator delete(void*)``.
3404
3405 ``__builtin_preserve_access_index``
3406 -----------------------------------
3407
3408 ``__builtin_preserve_access_index`` specifies a code section where
3409 array subscript access and structure/union member access are relocatable
3410 under bpf compile-once run-everywhere framework. Debuginfo (typically
3411 with ``-g``) is needed, otherwise, the compiler will exit with an error.
3412 The return type for the intrinsic is the same as the type of the
3413 argument.
3414
3415 **Syntax**:
3416
3417 .. code-block:: c
3418
3419 type __builtin_preserve_access_index(type arg)
3420
3421 **Example of Use**:
3422
3423 .. code-block:: c
3424
3425 struct t {
3426 int i;
3427 int j;
3428 union {
3429 int a;
3430 int b;
3431 } c[4];
3432 };
3433 struct t *v = ...;
3434 int *pb =__builtin_preserve_access_index(&v->c[3].b);
3435 __builtin_preserve_access_index(v->j);
3436
3437 ``__builtin_debugtrap``
3438 -----------------------
3439
3440 ``__builtin_debugtrap`` causes the program to stop its execution in such a way that a debugger can catch it.
3441
3442 **Syntax**:
3443
3444 .. code-block:: c++
3445
3446 __builtin_debugtrap()
3447
3448 **Description**
3449
3450 ``__builtin_debugtrap`` is lowered to the ` ``llvm.debugtrap`` <https://llvm.org/docs/LangRef.html#llvm-debugtrap-intrinsic>`_ builtin. It should have the same effect as setting a breakpoint on the line where the builtin is called.
3451
3452 Query for this feature with ``__has_builtin(__builtin_debugtrap)``.
3453
3454
3455 ``__builtin_trap``
3456 ------------------
3457
3458 ``__builtin_trap`` causes the program to stop its execution abnormally.
3459
3460 **Syntax**:
3461
3462 .. code-block:: c++
3463
3464 __builtin_trap()
3465
3466 **Description**
3467
3468 ``__builtin_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.
3469
3470 Query for this feature with ``__has_builtin(__builtin_trap)``.
3471
3472 ``__builtin_arm_trap``
3473 ----------------------
3474
3475 ``__builtin_arm_trap`` is an AArch64 extension to ``__builtin_trap`` which also accepts a compile-time constant value, encoded directly into the trap instruction for later inspection.
3476
3477 **Syntax**:
3478
3479 .. code-block:: c++
3480
3481 __builtin_arm_trap(const unsigned short payload)
3482
3483 **Description**
3484
3485 ``__builtin_arm_trap`` is lowered to the ``llvm.aarch64.break`` builtin, and then to ``brk #payload``.
3486
3487 ``__builtin_verbose_trap``
3488 --------------------------
3489
3490 ``__builtin_verbose_trap`` causes the program to stop its execution abnormally
3491 and shows a human-readable description of the reason for the termination when a
3492 debugger is attached or in a symbolicated crash log.
3493
3494 **Syntax**:
3495
3496 .. code-block:: c++
3497
3498 __builtin_verbose_trap(const char *category, const char *reason)
3499
3500 **Description**
3501
3502 ``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin.
3503 Additionally, clang emits debugging information that represents an artificial
3504 inline frame whose name encodes the category and reason strings passed to the builtin,
3505 prefixed by a "magic" prefix.
3506
3507 For example, consider the following code:
3508
3509 .. code-block:: c++
3510
3511 void foo(int* p) {
3512 if (p == nullptr)
3513 __builtin_verbose_trap("check null", "Argument must not be null!");
3514 }
3515
3516 The debugging information would look as if it were produced for the following code:
3517
3518 .. code-block:: c++
3519
3520 __attribute__((always_inline))
3521 inline void "__clang_trap_msg$check null$Argument must not be null!"() {
3522 __builtin_trap();
3523 }
3524
3525 void foo(int* p) {
3526 if (p == nullptr)
3527 "__clang_trap_msg$check null$Argument must not be null!"();
3528 }
3529
3530 However, the generated code would not actually contain a call to the artificial
3531 function — it only exists in the debugging information.
3532
3533 Query for this feature with ``__has_builtin(__builtin_verbose_trap)``. Note that
3534 users need to enable debug information to enable this feature. A call to this
3535 builtin is equivalent to a call to ``__builtin_trap`` if debug information isn't
3536 enabled.
3537
3538 The optimizer can merge calls to trap with different messages, which degrades
3539 the debugging experience.
3540
3541 ``__builtin_allow_runtime_check``
3542 ---------------------------------
3543
3544 ``__builtin_allow_runtime_check`` return true if the check at the current
3545 program location should be executed. It is expected to be used to implement
3546 ``assert`` like checks which can be safely removed by optimizer.
3547
3548 **Syntax**:
3549
3550 .. code-block:: c++
3551
3552 bool __builtin_allow_runtime_check(const char* kind)
3553
3554 **Example of use**:
3555
3556 .. code-block:: c++
3557
3558 if (__builtin_allow_runtime_check("mycheck") && !ExpensiveCheck()) {
3559 abort();
3560 }
3561
3562 **Description**
3563
3564 ``__builtin_allow_runtime_check`` is lowered to ` ``llvm.allow.runtime.check``
3565 <https://llvm.org/docs/LangRef.html#llvm-allow-runtime-check-intrinsic>`_
3566 builtin.
3567
3568 The ``__builtin_allow_runtime_check()`` is expected to be used with control
3569 flow conditions such as in ``if`` to guard expensive runtime checks. The
3570 specific rules for selecting permitted checks can differ and are controlled by
3571 the compiler options.
3572
3573 Flags to control checks:
3574 * ``-mllvm -lower-allow-check-percentile-cutoff-hot=N`` where N is PGO hotness
3575 cutoff in range ``[0, 999999]`` to disallow checks in hot code.
3576 * ``-mllvm -lower-allow-check-random-rate=P`` where P is number in range
3577 ``[0.0, 1.0]`` representation probability of keeping a check.
3578 * If both flags are specified, ``-lower-allow-check-random-rate`` takes
3579 precedence.
3580 * If none is specified, ``__builtin_allow_runtime_check`` is lowered as
3581 ``true``, allowing all checks.
3582
3583 Parameter ``kind`` is a string literal representing a user selected kind for
3584 guarded check. It's unused now. It will enable kind-specific lowering in future.
3585 E.g. a higher hotness cutoff can be used for more expensive kind of check.
3586
3587 Query for this feature with ``__has_builtin(__builtin_allow_runtime_check)``.
3588
3589 ``__builtin_nondeterministic_value``
3590 ------------------------------------
3591
3592 ``__builtin_nondeterministic_value`` returns a valid nondeterministic value of the same type as the provided argument.
3593
3594 **Syntax**:
3595
3596 .. code-block:: c++
3597
3598 type __builtin_nondeterministic_value(type x)
3599
3600 **Examples**:
3601
3602 .. code-block:: c++
3603
3604 int x = __builtin_nondeterministic_value(x);
3605 float y = __builtin_nondeterministic_value(y);
3606 __m256i a = __builtin_nondeterministic_value(a);
3607
3608 **Description**
3609
3610 Each call to ``__builtin_nondeterministic_value`` returns a valid value of the type given by the argument.
3611
3612 The types currently supported are: integer types, floating-point types, vector types.
3613
3614 Query for this feature with ``__has_builtin(__builtin_nondeterministic_value)``.
3615
3616 ``__builtin_sycl_unique_stable_name``
3617 -------------------------------------
3618
3619 ``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and
3620 produces a string literal containing a unique name for the type that is stable
3621 across split compilations, mainly to support SYCL/Data Parallel C++ language.
3622
3623 In cases where the split compilation needs to share a unique token for a type
3624 across the boundary (such as in an offloading situation), this name can be used
3625 for lookup purposes, such as in the SYCL Integration Header.
3626
3627 The value of this builtin is computed entirely at compile time, so it can be
3628 used in constant expressions. This value encodes lambda functions based on a
3629 stable numbering order in which they appear in their local declaration contexts.
3630 Once this builtin is evaluated in a constexpr context, it is erroneous to use
3631 it in an instantiation which changes its value.
3632
3633 In order to produce the unique name, the current implementation of the builtin
3634 uses Itanium mangling even if the host compilation uses a different name
3635 mangling scheme at runtime. The mangler marks all the lambdas required to name
3636 the SYCL kernel and emits a stable local ordering of the respective lambdas.
3637 The resulting pattern is demanglable. When non-lambda types are passed to the
3638 builtin, the mangler emits their usual pattern without any special treatment.
3639
3640 **Syntax**:
3641
3642 .. code-block:: c
3643
3644 // Computes a unique stable name for the given type.
3645 constexpr const char * __builtin_sycl_unique_stable_name( type-id );
3646
3647 ``__builtin_popcountg``
3648 -----------------------
3649
3650 ``__builtin_popcountg`` returns the number of 1 bits in the argument. The
3651 argument can be of any unsigned integer type.
3652
3653 **Syntax**:
3654
3655 .. code-block:: c++
3656
3657 int __builtin_popcountg(type x)
3658
3659 **Examples**:
3660
3661 .. code-block:: c++
3662
3663 unsigned int x = 1;
3664 int x_pop = __builtin_popcountg(x);
3665
3666 unsigned long y = 3;
3667 int y_pop = __builtin_popcountg(y);
3668
3669 unsigned _BitInt(128) z = 7;
3670 int z_pop = __builtin_popcountg(z);
3671
3672 **Description**:
3673
3674 ``__builtin_popcountg`` is meant to be a type-generic alternative to the
3675 ``__builtin_popcount{,l,ll}`` builtins, with support for other integer types,
3676 such as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.
3677
3678 ``__builtin_clzg`` and ``__builtin_ctzg``
3679 -----------------------------------------
3680
3681 ``__builtin_clzg`` (respectively ``__builtin_ctzg``) returns the number of
3682 leading (respectively trailing) 0 bits in the first argument. The first argument
3683 can be of any unsigned integer type.
3684
3685 If the first argument is 0 and an optional second argument of ``int`` type is
3686 provided, then the second argument is returned. If the first argument is 0, but
3687 only one argument is provided, then the behavior is undefined.
3688
3689 **Syntax**:
3690
3691 .. code-block:: c++
3692
3693 int __builtin_clzg(type x[, int fallback])
3694 int __builtin_ctzg(type x[, int fallback])
3695
3696 **Examples**:
3697
3698 .. code-block:: c++
3699
3700 unsigned int x = 1;
3701 int x_lz = __builtin_clzg(x);
3702 int x_tz = __builtin_ctzg(x);
3703
3704 unsigned long y = 2;
3705 int y_lz = __builtin_clzg(y);
3706 int y_tz = __builtin_ctzg(y);
3707
3708 unsigned _BitInt(128) z = 4;
3709 int z_lz = __builtin_clzg(z);
3710 int z_tz = __builtin_ctzg(z);
3711
3712 **Description**:
3713
3714 ``__builtin_clzg`` (respectively ``__builtin_ctzg``) is meant to be a
3715 type-generic alternative to the ``__builtin_clz{,l,ll}`` (respectively
3716 ``__builtin_ctz{,l,ll}``) builtins, with support for other integer types, such
3717 as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.
3718
3719 Multiprecision Arithmetic Builtins
3720 ----------------------------------
3721
3722 Clang provides a set of builtins which expose multiprecision arithmetic in a
3723 manner amenable to C. They all have the following form:
3724
3725 .. code-block:: c
3726
3727 unsigned x = ..., y = ..., carryin = ..., carryout;
3728 unsigned sum = __builtin_addc(x, y, carryin, &carryout);
3729
3730 Thus one can form a multiprecision addition chain in the following manner:
3731
3732 .. code-block:: c
3733
3734 unsigned *x, *y, *z, carryin=0, carryout;
3735 z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
3736 carryin = carryout;
3737 z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
3738 carryin = carryout;
3739 z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
3740 carryin = carryout;
3741 z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
3742
3743 The complete list of builtins are:
3744
3745 .. code-block:: c
3746
3747 unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
3748 unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
3749 unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
3750 unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
3751 unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
3752 unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
3753 unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
3754 unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
3755 unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
3756 unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
3757
3758 Checked Arithmetic Builtins
3759 ---------------------------
3760
3761 Clang provides a set of builtins that implement checked arithmetic for security
3762 critical applications in a manner that is fast and easily expressible in C. As
3763 an example of their usage:
3764
3765 .. code-block:: c
3766
3767 errorcode_t security_critical_application(...) {
3768 unsigned x, y, result;
3769 ...
3770 if (__builtin_mul_overflow(x, y, &result))
3771 return kErrorCodeHackers;
3772 ...
3773 use_multiply(result);
3774 ...
3775 }
3776
3777 Clang provides the following checked arithmetic builtins:
3778
3779 .. code-block:: c
3780
3781 bool __builtin_add_overflow (type1 x, type2 y, type3 *sum);
3782 bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff);
3783 bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod);
3784 bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
3785 bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
3786 bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
3787 bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
3788 bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
3789 bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
3790 bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
3791 bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
3792 bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
3793 bool __builtin_sadd_overflow (int x, int y, int *sum);
3794 bool __builtin_saddl_overflow (long x, long y, long *sum);
3795 bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
3796 bool __builtin_ssub_overflow (int x, int y, int *diff);
3797 bool __builtin_ssubl_overflow (long x, long y, long *diff);
3798 bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
3799 bool __builtin_smul_overflow (int x, int y, int *prod);
3800 bool __builtin_smull_overflow (long x, long y, long *prod);
3801 bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
3802
3803 Each builtin performs the specified mathematical operation on the
3804 first two arguments and stores the result in the third argument. If
3805 possible, the result will be equal to mathematically-correct result
3806 and the builtin will return 0. Otherwise, the builtin will return
3807 1 and the result will be equal to the unique value that is equivalent
3808 to the mathematically-correct result modulo two raised to the *k*
3809 power, where *k* is the number of bits in the result type. The
3810 behavior of these builtins is well-defined for all argument values.
3811
3812 The first three builtins work generically for operands of any integer type,
3813 including boolean types. The operands need not have the same type as each
3814 other, or as the result. The other builtins may implicitly promote or
3815 convert their operands before performing the operation.
3816
3817 Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
3818
3819 Floating point builtins
3820 ---------------------------------------
3821
3822 ``__builtin_isfpclass``
3823 -----------------------
3824
3825 ``__builtin_isfpclass`` is used to test if the specified floating-point values
3826 fall into one of the specified floating-point classes.
3827
3828 **Syntax**:
3829
3830 .. code-block:: c++
3831
3832 int __builtin_isfpclass(fp_type expr, int mask)
3833 int_vector __builtin_isfpclass(fp_vector expr, int mask)
3834
3835 **Example of use**:
3836
3837 .. code-block:: c++
3838
3839 if (__builtin_isfpclass(x, 448)) {
3840 // `x` is positive finite value
3841 ...
3842 }
3843
3844 **Description**:
3845
3846 The ``__builtin_isfpclass()`` builtin is a generalization of functions ``isnan``,
3847 ``isinf``, ``isfinite`` and some others defined by the C standard. It tests if
3848 the floating-point value, specified by the first argument, falls into any of data
3849 classes, specified by the second argument. The latter is an integer constant
3850 bitmask expression, in which each data class is represented by a bit
3851 using the encoding:
3852
3853 ========== =================== ======================
3854 Mask value Data class Macro
3855 ========== =================== ======================
3856 0x0001 Signaling NaN __FPCLASS_SNAN
3857 0x0002 Quiet NaN __FPCLASS_QNAN
3858 0x0004 Negative infinity __FPCLASS_NEGINF
3859 0x0008 Negative normal __FPCLASS_NEGNORMAL
3860 0x0010 Negative subnormal __FPCLASS_NEGSUBNORMAL
3861 0x0020 Negative zero __FPCLASS_NEGZERO
3862 0x0040 Positive zero __FPCLASS_POSZERO
3863 0x0080 Positive subnormal __FPCLASS_POSSUBNORMAL
3864 0x0100 Positive normal __FPCLASS_POSNORMAL
3865 0x0200 Positive infinity __FPCLASS_POSINF
3866 ========== =================== ======================
3867
3868 For convenience preprocessor defines macros for these values. The function
3869 returns 1 if ``expr`` falls into one of the specified data classes, 0 otherwise.
3870
3871 In the example above the mask value 448 (0x1C0) contains the bits selecting
3872 positive zero, positive subnormal and positive normal classes.
3873 ``__builtin_isfpclass(x, 448)`` would return true only if ``x`` if of any of
3874 these data classes. Using suitable mask value, the function can implement any of
3875 the standard classification functions, for example, ``__builtin_isfpclass(x, 3)``
3876 is identical to ``isnan``,``__builtin_isfpclass(x, 504)`` - to ``isfinite``
3877 and so on.
3878
3879 If the first argument is a vector, the function is equivalent to the set of
3880 scalar calls of ``__builtin_isfpclass`` applied to the input elementwise.
3881
3882 The result of ``__builtin_isfpclass`` is a boolean value, if the first argument
3883 is a scalar, or an integer vector with the same element count as the first
3884 argument. The element type in this vector has the same bit length as the
3885 element of the first argument type.
3886
3887 This function never raises floating-point exceptions and does not canonicalize
3888 its input. The floating-point argument is not promoted, its data class is
3889 determined based on its representation in its actual semantic type.
3890
3891 ``__builtin_canonicalize``
3892 --------------------------
3893
3894 .. code-block:: c
3895
3896 double __builtin_canonicalize(double);
3897 float __builtin_canonicalizef(float);
3898 long double __builtin_canonicalizel(long double);
3899
3900 Returns the platform specific canonical encoding of a floating point
3901 number. This canonicalization is useful for implementing certain
3902 numeric primitives such as frexp. See `LLVM canonicalize intrinsic
3903 <https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
3904 more information on the semantics.
3905
3906 ``__builtin_flt_rounds`` and ``__builtin_set_flt_rounds``
3907 ---------------------------------------------------------
3908
3909 .. code-block:: c
3910
3911 int __builtin_flt_rounds();
3912 void __builtin_set_flt_rounds(int);
3913
3914 Returns and sets current floating point rounding mode. The encoding of returned
3915 values and input parameters is same as the result of FLT_ROUNDS, specified by C
3916 standard:
3917 - ``0`` - toward zero
3918 - ``1`` - to nearest, ties to even
3919 - ``2`` - toward positive infinity
3920 - ``3`` - toward negative infinity
3921 - ``4`` - to nearest, ties away from zero
3922 The effect of passing some other value to ``__builtin_flt_rounds`` is
3923 implementation-defined. ``__builtin_set_flt_rounds`` is currently only supported
3924 to work on x86, x86_64, Arm and AArch64 targets. These builtins read and modify
3925 the floating-point environment, which is not always allowed and may have unexpected
3926 behavior. Please see the section on `Accessing the floating point environment <https://clang.llvm.org/docs/UsersManual.html#accessing-the-floating-point-environment>`_ for more information.
3927
3928 String builtins
3929 ---------------
3930
3931 Clang provides constant expression evaluation support for builtins forms of
3932 the following functions from the C standard library headers
3933 ``<string.h>`` and ``<wchar.h>``:
3934
3935 * ``memchr``
3936 * ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``)
3937 * ``strchr``
3938 * ``strcmp``
3939 * ``strlen``
3940 * ``strncmp``
3941 * ``wcschr``
3942 * ``wcscmp``
3943 * ``wcslen``
3944 * ``wcsncmp``
3945 * ``wmemchr``
3946 * ``wmemcmp``
3947
3948 In each case, the builtin form has the name of the C library function prefixed
3949 by ``__builtin_``. Example:
3950
3951 .. code-block:: c
3952
3953 void *p = __builtin_memchr("foobar", 'b', 5);
3954
3955 In addition to the above, one further builtin is provided:
3956
3957 .. code-block:: c
3958
3959 char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
3960
3961 ``__builtin_char_memchr(a, b, c)`` is identical to
3962 ``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
3963 constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
3964 is disallowed in general).
3965
3966 Constant evaluation support for the ``__builtin_mem*`` functions is provided
3967 only for arrays of ``char``, ``signed char``, ``unsigned char``, or ``char8_t``,
3968 despite these functions accepting an argument of type ``const void*``.
3969
3970 Support for constant expression evaluation for the above builtins can be detected
3971 with ``__has_feature(cxx_constexpr_string_builtins)``.
3972
3973 Variadic function builtins
3974 --------------------------
3975
3976 Clang provides several builtins for working with variadic functions from the C
3977 standard library ``<stdarg.h>`` header:
3978
3979 * ``__builtin_va_list``
3980
3981 A predefined typedef for the target-specific ``va_list`` type. It is undefined
3982 behavior to use a byte-wise copy of this type produced by calling ``memcpy``,
3983 ``memmove``, or similar. Valid explicit copies are only produced by calling
3984 ``va_copy`` or ``__builtin_va_copy``.
3985
3986 * ``void __builtin_va_start(__builtin_va_list list, <parameter-name>)``
3987
3988 A builtin function for the target-specific ``va_start`` function-like macro.
3989 The ``parameter-name`` argument is the name of the parameter preceding the
3990 ellipsis (``...``) in the function signature. Alternatively, in C23 mode or
3991 later, it may be the integer literal ``0`` if there is no parameter preceding
3992 the ellipsis. This function initializes the given ``__builtin_va_list`` object.
3993 It is undefined behavior to call this function on an already initialized
3994 ``__builin_va_list`` object.
3995
3996 * ``void __builtin_va_end(__builtin_va_list list)``
3997
3998 A builtin function for the target-specific ``va_end`` function-like macro. This
3999 function finalizes the given ``__builtin_va_list`` object such that it is no
4000 longer usable unless re-initialized with a call to ``__builtin_va_start`` or
4001 ``__builtin_va_copy``. It is undefined behavior to call this function with a
4002 ``list`` that has not been initialized by either ``__builtin_va_start`` or
4003 ``__builtin_va_copy``.
4004
4005 * ``<type-name> __builtin_va_arg(__builtin_va_list list, <type-name>)``
4006
4007 A builtin function for the target-specific ``va_arg`` function-like macro. This
4008 function returns the value of the next variadic argument to the call. It is
4009 undefined behavior to call this builtin when there is no next variadic argument
4010 to retrieve or if the next variadic argument does not have a type compatible
4011 with the given ``type-name``. The return type of the function is the
4012 ``type-name`` given as the second argument. It is undefined behavior to call
4013 this function with a ``list`` that has not been initialized by either
4014 ``__builtin_va_start`` or ``__builtin_va_copy``.
4015
4016 * ``void __builtin_va_copy(__builtin_va_list dest, __builtin_va_list src)``
4017
4018 A builtin function for the target-specific ``va_copy`` function-like macro.
4019 This function initializes ``dest`` as a copy of ``src``. It is undefined
4020 behavior to call this function with an already initialized ``dest`` argument.
4021
4022 Memory builtins
4023 ---------------
4024
4025 Clang provides constant expression evaluation support for builtin forms of the
4026 following functions from the C standard library headers
4027 ``<string.h>`` and ``<wchar.h>``:
4028
4029 * ``memcpy``
4030 * ``memmove``
4031 * ``wmemcpy``
4032 * ``wmemmove``
4033
4034 In each case, the builtin form has the name of the C library function prefixed
4035 by ``__builtin_``.
4036
4037 Constant evaluation support is only provided when the source and destination
4038 are pointers to arrays with the same trivially copyable element type, and the
4039 given size is an exact multiple of the element size that is no greater than
4040 the number of elements accessible through the source and destination operands.
4041
4042 Guaranteed inlined copy
4043 ^^^^^^^^^^^^^^^^^^^^^^^
4044
4045 .. code-block:: c
4046
4047 void __builtin_memcpy_inline(void *dst, const void *src, size_t size);
4048
4049
4050 ``__builtin_memcpy_inline`` has been designed as a building block for efficient
4051 ``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also
4052 guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline
4053 <https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic
4054 for more information.
4055
4056 This is useful to implement a custom version of ``memcpy``, implement a
4057 ``libc`` memcpy or work around the absence of a ``libc``.
4058
4059 Note that the `size` argument must be a compile time constant.
4060
4061 Note that this intrinsic cannot yet be called in a ``constexpr`` context.
4062
4063 Guaranteed inlined memset
4064 ^^^^^^^^^^^^^^^^^^^^^^^^^
4065
4066 .. code-block:: c
4067
4068 void __builtin_memset_inline(void *dst, int value, size_t size);
4069
4070
4071 ``__builtin_memset_inline`` has been designed as a building block for efficient
4072 ``memset`` implementations. It is identical to ``__builtin_memset`` but also
4073 guarantees not to call any external functions. See LLVM IR `llvm.memset.inline
4074 <https://llvm.org/docs/LangRef.html#llvm-memset-inline-intrinsic>`_ intrinsic
4075 for more information.
4076
4077 This is useful to implement a custom version of ``memset``, implement a
4078 ``libc`` memset or work around the absence of a ``libc``.
4079
4080 Note that the `size` argument must be a compile time constant.
4081
4082 Note that this intrinsic cannot yet be called in a ``constexpr`` context.
4083
4084 ``__is_bitwise_cloneable``
4085 --------------------------
4086
4087 A type trait is used to check whether a type can be safely copied by memcpy.
4088
4089 **Syntax**:
4090
4091 .. code-block:: c++
4092
4093 bool __is_bitwise_cloneable(Type)
4094
4095 **Description**:
4096
4097 Objects of bitwise cloneable types can be bitwise copied by memcpy/memmove. The
4098 Clang compiler warrants that this behavior is well defined, and won't be
4099 broken by compiler optimizations and sanitizers.
4100
4101 For implicit-lifetime types, the lifetime of the new object is implicitly
4102 started after the copy. For other types (e.g., classes with virtual methods),
4103 the lifetime isn't started, and using the object results in undefined behavior
4104 according to the C++ Standard.
4105
4106 This builtin can be used in constant expressions.
4107
4108 Atomic Min/Max builtins with memory ordering
4109 --------------------------------------------
4110
4111 There are two atomic builtins with min/max in-memory comparison and swap.
4112 The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
4113
4114 * ``__atomic_fetch_min``
4115 * ``__atomic_fetch_max``
4116
4117 The builtins work with signed and unsigned integers and require to specify memory ordering.
4118 The return value is the original value that was stored in memory before comparison.
4119
4120 Example:
4121
4122 .. code-block:: c
4123
4124 unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
4125
4126 The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
4127 ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
4128 ``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
4129
4130 In terms of acquire-release ordering barriers these two operations are always
4131 considered as operations with *load-store* semantics, even when the original value
4132 is not actually modified after comparison.
4133
4134 .. _langext-__c11_atomic:
4135
4136 __c11_atomic builtins
4137 ---------------------
4138
4139 Clang provides a set of builtins which are intended to be used to implement
4140 C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
4141 ``_explicit`` form of the corresponding C11 operation, and are named with a
4142 ``__c11_`` prefix. The supported operations, and the differences from
4143 the corresponding C11 operations, are:
4144
4145 * ``__c11_atomic_init``
4146 * ``__c11_atomic_thread_fence``
4147 * ``__c11_atomic_signal_fence``
4148 * ``__c11_atomic_is_lock_free`` (The argument is the size of the
4149 ``_Atomic(...)`` object, instead of its address)
4150 * ``__c11_atomic_store``
4151 * ``__c11_atomic_load``
4152 * ``__c11_atomic_exchange``
4153 * ``__c11_atomic_compare_exchange_strong``
4154 * ``__c11_atomic_compare_exchange_weak``
4155 * ``__c11_atomic_fetch_add``
4156 * ``__c11_atomic_fetch_sub``
4157 * ``__c11_atomic_fetch_and``
4158 * ``__c11_atomic_fetch_or``
4159 * ``__c11_atomic_fetch_xor``
4160 * ``__c11_atomic_fetch_nand`` (Nand is not presented in ``<stdatomic.h>``)
4161 * ``__c11_atomic_fetch_max``
4162 * ``__c11_atomic_fetch_min``
4163
4164 The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
4165 ``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
4166 provided, with values corresponding to the enumerators of C11's
4167 ``memory_order`` enumeration.
4168
4169 (Note that Clang additionally provides GCC-compatible ``__atomic_*``
4170 builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
4171 atomic builtins are an explicit form of the corresponding OpenCL 2.0
4172 builtin function, and are named with a ``__opencl_`` prefix. The macros
4173 ``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
4174 ``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
4175 and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
4176 corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
4177
4178 __scoped_atomic builtins
4179 ------------------------
4180
4181 Clang provides a set of atomics taking a memory scope argument. These atomics
4182 are identical to the standard GNU / GCC atomic builtins but taking an extra
4183 memory scope argument. These are designed to be a generic alternative to the
4184 ``__opencl_atomic_*`` builtin functions for targets that support atomic memory
4185 scopes.
4186
4187 Atomic memory scopes are designed to assist optimizations for systems with
4188 several levels of memory hierarchy like GPUs. The following memory scopes are
4189 currently supported:
4190
4191 * ``__MEMORY_SCOPE_SYSTEM``
4192 * ``__MEMORY_SCOPE_DEVICE``
4193 * ``__MEMORY_SCOPE_WRKGRP``
4194 * ``__MEMORY_SCOPE_WVFRNT``
4195 * ``__MEMORY_SCOPE_SINGLE``
4196
4197 This controls whether or not the atomic operation is ordered with respect to the
4198 whole system, the current device, an OpenCL workgroup, wavefront, or just a
4199 single thread. If these are used on a target that does not support atomic
4200 scopes, then they will behave exactly as the standard GNU atomic builtins.
4201
4202 Low-level ARM exclusive memory builtins
4203 ---------------------------------------
4204
4205 Clang provides overloaded builtins giving direct access to the three key ARM
4206 instructions for implementing atomic operations.
4207
4208 .. code-block:: c
4209
4210 T __builtin_arm_ldrex(const volatile T *addr);
4211 T __builtin_arm_ldaex(const volatile T *addr);
4212 int __builtin_arm_strex(T val, volatile T *addr);
4213 int __builtin_arm_stlex(T val, volatile T *addr);
4214 void __builtin_arm_clrex(void);
4215
4216 The types ``T`` currently supported are:
4217
4218 * Integer types with width at most 64 bits (or 128 bits on AArch64).
4219 * Floating-point types
4220 * Pointer types.
4221
4222 Note that the compiler does not guarantee it will not insert stores which clear
4223 the exclusive monitor in between an ``ldrex`` type operation and its paired
4224 ``strex``. In practice this is only usually a risk when the extra store is on
4225 the same cache line as the variable being modified and Clang will only insert
4226 stack stores on its own, so it is best not to use these operations on variables
4227 with automatic storage duration.
4228
4229 Also, loads and stores may be implicit in code written between the ``ldrex`` and
4230 ``strex``. Clang will not necessarily mitigate the effects of these either, so
4231 care should be exercised.
4232
4233 For these reasons the higher level atomic primitives should be preferred where
4234 possible.
4235
4236 Non-temporal load/store builtins
4237 --------------------------------
4238
4239 Clang provides overloaded builtins allowing generation of non-temporal memory
4240 accesses.
4241
4242 .. code-block:: c
4243
4244 T __builtin_nontemporal_load(T *addr);
4245 void __builtin_nontemporal_store(T value, T *addr);
4246
4247 The types ``T`` currently supported are:
4248
4249 * Integer types.
4250 * Floating-point types.
4251 * Vector types.
4252
4253 Note that the compiler does not guarantee that non-temporal loads or stores
4254 will be used.
4255
4256 C++ Coroutines support builtins
4257 --------------------------------
4258
4259 .. warning::
4260 This is a work in progress. Compatibility across Clang/LLVM releases is not
4261 guaranteed.
4262
4263 Clang provides experimental builtins to support C++ Coroutines as defined by
4264 https://wg21.link/P0057. The following four are intended to be used by the
4265 standard library to implement the ``std::coroutine_handle`` type.
4266
4267 **Syntax**:
4268
4269 .. code-block:: c
4270
4271 void __builtin_coro_resume(void *addr);
4272 void __builtin_coro_destroy(void *addr);
4273 bool __builtin_coro_done(void *addr);
4274 void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
4275
4276 **Example of use**:
4277
4278 .. code-block:: c++
4279
4280 template <> struct coroutine_handle<void> {
4281 void resume() const { __builtin_coro_resume(ptr); }
4282 void destroy() const { __builtin_coro_destroy(ptr); }
4283 bool done() const { return __builtin_coro_done(ptr); }
4284 // ...
4285 protected:
4286 void *ptr;
4287 };
4288
4289 template <typename Promise> struct coroutine_handle : coroutine_handle<> {
4290 // ...
4291 Promise &promise() const {
4292 return *reinterpret_cast<Promise *>(
4293 __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
4294 }
4295 static coroutine_handle from_promise(Promise &promise) {
4296 coroutine_handle p;
4297 p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
4298 /*from-promise=*/true);
4299 return p;
4300 }
4301 };
4302
4303
4304 Other coroutine builtins are either for internal clang use or for use during
4305 development of the coroutine feature. See `Coroutines in LLVM
4306 <https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
4307 more information on their semantics. Note that builtins matching the intrinsics
4308 that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
4309 llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
4310 an appropriate value during the emission.
4311
4312 **Syntax**:
4313
4314 .. code-block:: c
4315
4316 size_t __builtin_coro_size()
4317 void *__builtin_coro_frame()
4318 void *__builtin_coro_free(void *coro_frame)
4319
4320 void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
4321 bool __builtin_coro_alloc()
4322 void *__builtin_coro_begin(void *memory)
4323 void __builtin_coro_end(void *coro_frame, bool unwind)
4324 char __builtin_coro_suspend(bool final)
4325
4326 Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
4327 automatically will insert one if the first argument to `llvm.coro.suspend` is
4328 token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
4329 as the first argument to the intrinsic.
4330
4331 Source location builtins
4332 ------------------------
4333
4334 Clang provides builtins to support C++ standard library implementation
4335 of ``std::source_location`` as specified in C++20. With the exception
4336 of ``__builtin_COLUMN``, ``__builtin_FILE_NAME`` and ``__builtin_FUNCSIG``,
4337 these builtins are also implemented by GCC.
4338
4339 **Syntax**:
4340
4341 .. code-block:: c
4342
4343 const char *__builtin_FILE();
4344 const char *__builtin_FILE_NAME(); // Clang only
4345 const char *__builtin_FUNCTION();
4346 const char *__builtin_FUNCSIG(); // Microsoft
4347 unsigned __builtin_LINE();
4348 unsigned __builtin_COLUMN(); // Clang only
4349 const std::source_location::__impl *__builtin_source_location();
4350
4351 **Example of use**:
4352
4353 .. code-block:: c++
4354
4355 void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
4356 const char* file = __builtin_FILE(),
4357 const char* function = __builtin_FUNCTION()) {
4358 if (pred) return;
4359 printf("%s:%d assertion failed in function %s\n", file, line, function);
4360 std::abort();
4361 }
4362
4363 struct MyAggregateType {
4364 int x;
4365 int line = __builtin_LINE(); // captures line where aggregate initialization occurs
4366 };
4367 static_assert(MyAggregateType{42}.line == __LINE__);
4368
4369 struct MyClassType {
4370 int line = __builtin_LINE(); // captures line of the constructor used during initialization
4371 constexpr MyClassType(int) { assert(line == __LINE__); }
4372 };
4373
4374 **Description**:
4375
4376 The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, ``__builtin_FUNCSIG``,
4377 ``__builtin_FILE`` and ``__builtin_FILE_NAME`` return the values, at the
4378 "invocation point", for ``__LINE__``, ``__FUNCTION__``, ``__FUNCSIG__``,
4379 ``__FILE__`` and ``__FILE_NAME__`` respectively. ``__builtin_COLUMN`` similarly
4380 returns the column, though there is no corresponding macro. These builtins are
4381 constant expressions.
4382
4383 When the builtins appear as part of a default function argument the invocation
4384 point is the location of the caller. When the builtins appear as part of a
4385 default member initializer, the invocation point is the location of the
4386 constructor or aggregate initialization used to create the object. Otherwise
4387 the invocation point is the same as the location of the builtin.
4388
4389 When the invocation point of ``__builtin_FUNCTION`` is not a function scope the
4390 empty string is returned.
4391
4392 The builtin ``__builtin_source_location`` returns a pointer to constant static
4393 data of type ``std::source_location::__impl``. This type must have already been
4394 defined, and must contain exactly four fields: ``const char *_M_file_name``,
4395 ``const char *_M_function_name``, ``<any-integral-type> _M_line``, and
4396 ``<any-integral-type> _M_column``. The fields will be populated in the same
4397 manner as the above four builtins, except that ``_M_function_name`` is populated
4398 with ``__PRETTY_FUNCTION__`` rather than ``__FUNCTION__``.
4399
4400
4401 Alignment builtins
4402 ------------------
4403 Clang provides builtins to support checking and adjusting alignment of
4404 pointers and integers.
4405 These builtins can be used to avoid relying on implementation-defined behavior
4406 of arithmetic on integers derived from pointers.
4407 Additionally, these builtins retain type information and, unlike bitwise
4408 arithmetic, they can perform semantic checking on the alignment value.
4409
4410 **Syntax**:
4411
4412 .. code-block:: c
4413
4414 Type __builtin_align_up(Type value, size_t alignment);
4415 Type __builtin_align_down(Type value, size_t alignment);
4416 bool __builtin_is_aligned(Type value, size_t alignment);
4417
4418
4419 **Example of use**:
4420
4421 .. code-block:: c++
4422
4423 char* global_alloc_buffer;
4424 void* my_aligned_allocator(size_t alloc_size, size_t alignment) {
4425 char* result = __builtin_align_up(global_alloc_buffer, alignment);
4426 // result now contains the value of global_alloc_buffer rounded up to the
4427 // next multiple of alignment.
4428 global_alloc_buffer = result + alloc_size;
4429 return result;
4430 }
4431
4432 void* get_start_of_page(void* ptr) {
4433 return __builtin_align_down(ptr, PAGE_SIZE);
4434 }
4435
4436 void example(char* buffer) {
4437 if (__builtin_is_aligned(buffer, 64)) {
4438 do_fast_aligned_copy(buffer);
4439 } else {
4440 do_unaligned_copy(buffer);
4441 }
4442 }
4443
4444 // In addition to pointers, the builtins can also be used on integer types
4445 // and are evaluatable inside constant expressions.
4446 static_assert(__builtin_align_up(123, 64) == 128, "");
4447 static_assert(__builtin_align_down(123u, 64) == 64u, "");
4448 static_assert(!__builtin_is_aligned(123, 64), "");
4449
4450
4451 **Description**:
4452
4453 The builtins ``__builtin_align_up``, ``__builtin_align_down``, return their
4454 first argument aligned up/down to the next multiple of the second argument.
4455 If the value is already sufficiently aligned, it is returned unchanged.
4456 The builtin ``__builtin_is_aligned`` returns whether the first argument is
4457 aligned to a multiple of the second argument.
4458 All of these builtins expect the alignment to be expressed as a number of bytes.
4459
4460 These builtins can be used for all integer types as well as (non-function)
4461 pointer types. For pointer types, these builtins operate in terms of the integer
4462 address of the pointer and return a new pointer of the same type (including
4463 qualifiers such as ``const``) with an adjusted address.
4464 When aligning pointers up or down, the resulting value must be within the same
4465 underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]).
4466 This means that arbitrary integer values stored in pointer-type variables must
4467 not be passed to these builtins. For those use cases, the builtins can still be
4468 used, but the operation must be performed on the pointer cast to ``uintptr_t``.
4469
4470 If Clang can determine that the alignment is not a power of two at compile time,
4471 it will result in a compilation failure. If the alignment argument is not a
4472 power of two at run time, the behavior of these builtins is undefined.
4473
4474 Non-standard C++11 Attributes
4475 =============================
4476
4477 Clang's non-standard C++11 attributes live in the ``clang`` attribute
4478 namespace.
4479
4480 Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
4481 are accepted with the ``__attribute__((foo))`` syntax are also accepted as
4482 ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
4483 (see the list of `GCC function attributes
4484 <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
4485 attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
4486 `GCC type attributes
4487 <https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
4488 implementation, these attributes must appertain to the *declarator-id* in a
4489 declaration, which means they must go either at the start of the declaration or
4490 immediately after the name being declared.
4491
4492 For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
4493 also applies the GNU ``noreturn`` attribute to ``f``.
4494
4495 Examples:
4496 .. code-block:: c++
4497
4498 [[gnu::unused]] int a, f [[gnu::noreturn]] ();
4499
4500 Target-Specific Extensions
4501 ==========================
4502
4503 Clang supports some language features conditionally on some targets.
4504
4505 AMDGPU Language Extensions
4506 --------------------------
4507
4508 __builtin_amdgcn_fence
4509 ^^^^^^^^^^^^^^^^^^^^^^
4510
4511 ``__builtin_amdgcn_fence`` emits a fence.
4512
4513 * ``unsigned`` atomic ordering, e.g. ``__ATOMIC_ACQUIRE``
4514 * ``const char *`` synchronization scope, e.g. ``workgroup``
4515 * Zero or more ``const char *`` address spaces names.
4516
4517 The address spaces arguments must be one of the following string literals:
4518
4519 * ``"local"``
4520 * ``"global"``
4521
4522 If one or more address space name are provided, the code generator will attempt
4523 to emit potentially faster instructions that order access to at least those
4524 address spaces.
4525 Emitting such instructions may not always be possible and the compiler is free
4526 to fence more aggressively.
4527
4528 If no address spaces names are provided, all address spaces are fenced.
4529
4530 .. code-block:: c++
4531
4532 // Fence all address spaces.
4533 __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
4534 __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
4535
4536 // Fence only requested address spaces.
4537 __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")
4538 __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local", "global")
4539
4540
4541 ARM/AArch64 Language Extensions
4542 -------------------------------
4543
4544 Memory Barrier Intrinsics
4545 ^^^^^^^^^^^^^^^^^^^^^^^^^
4546 Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
4547 in the `Arm C Language Extensions
4548 <https://github.com/ARM-software/acle/releases>`_.
4549 Note that these intrinsics are implemented as motion barriers that block
4550 reordering of memory accesses and side effect instructions. Other instructions
4551 like simple arithmetic may be reordered around the intrinsic. If you expect to
4552 have no reordering at all, use inline assembly instead.
4553
4554 Pointer Authentication
4555 ^^^^^^^^^^^^^^^^^^^^^^
4556 See :doc:`PointerAuthentication`.
4557
4558 X86/X86-64 Language Extensions
4559 ------------------------------
4560
4561 The X86 backend has these language extensions:
4562
4563 Memory references to specified segments
4564 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4565
4566 Annotating a pointer with address space #256 causes it to be code generated
4567 relative to the X86 GS segment register, address space #257 causes it to be
4568 relative to the X86 FS segment, and address space #258 causes it to be
4569 relative to the X86 SS segment. Note that this is a very very low-level
4570 feature that should only be used if you know what you're doing (for example in
4571 an OS kernel).
4572
4573 Here is an example:
4574
4575 .. code-block:: c++
4576
4577 #define GS_RELATIVE __attribute__((address_space(256)))
4578 int foo(int GS_RELATIVE *P) {
4579 return *P;
4580 }
4581
4582 Which compiles to (on X86-32):
4583
4584 .. code-block:: gas
4585
4586 _foo:
4587 movl 4(%esp), %eax
4588 movl %gs:(%eax), %eax
4589 ret
4590
4591 You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for
4592 the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``
4593 indicate their support.
4594
4595 PowerPC Language Extensions
4596 ---------------------------
4597
4598 Set the Floating Point Rounding Mode
4599 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4600 PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
4601 the floating point rounding mode. This function will use the least significant
4602 two bits of integer argument to set the floating point rounding mode.
4603
4604 .. code-block:: c++
4605
4606 double __builtin_setrnd(int mode);
4607
4608 The effective values for mode are:
4609
4610 - 0 - round to nearest
4611 - 1 - round to zero
4612 - 2 - round to +infinity
4613 - 3 - round to -infinity
4614
4615 Note that the mode argument will modulo 4, so if the integer argument is greater
4616 than 3, it will only use the least significant two bits of the mode.
4617 Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
4618
4619 PowerPC cache builtins
4620 ^^^^^^^^^^^^^^^^^^^^^^
4621
4622 The PowerPC architecture specifies instructions implementing cache operations.
4623 Clang provides builtins that give direct programmer access to these cache
4624 instructions.
4625
4626 Currently the following builtins are implemented in clang:
4627
4628 ``__builtin_dcbf`` copies the contents of a modified block from the data cache
4629 to main memory and flushes the copy from the data cache.
4630
4631 **Syntax**:
4632
4633 .. code-block:: c
4634
4635 void __dcbf(const void* addr); /* Data Cache Block Flush */
4636
4637 **Example of Use**:
4638
4639 .. code-block:: c
4640
4641 int a = 1;
4642 __builtin_dcbf (&a);
4643
4644 Extensions for Static Analysis
4645 ==============================
4646
4647 Clang supports additional attributes that are useful for documenting program
4648 invariants and rules for static analysis tools, such as the `Clang Static
4649 Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
4650 in the analyzer's `list of source-level annotations
4651 <https://clang-analyzer.llvm.org/annotations.html>`_.
4652
4653
4654 Extensions for Dynamic Analysis
4655 ===============================
4656
4657 Use ``__has_feature(address_sanitizer)`` to check if the code is being built
4658 with :doc:`AddressSanitizer`.
4659
4660 Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
4661 with :doc:`ThreadSanitizer`.
4662
4663 Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
4664 with :doc:`MemorySanitizer`.
4665
4666 Use ``__has_feature(dataflow_sanitizer)`` to check if the code is being built
4667 with :doc:`DataFlowSanitizer`.
4668
4669 Use ``__has_feature(safe_stack)`` to check if the code is being built
4670 with :doc:`SafeStack`.
4671
4672
4673 Extensions for selectively disabling optimization
4674 =================================================
4675
4676 Clang provides a mechanism for selectively disabling optimizations in functions
4677 and methods.
4678
4679 To disable optimizations in a single function definition, the GNU-style or C++11
4680 non-standard attribute ``optnone`` can be used.
4681
4682 .. code-block:: c++
4683
4684 // The following functions will not be optimized.
4685 // GNU-style attribute
4686 __attribute__((optnone)) int foo() {
4687 // ... code
4688 }
4689 // C++11 attribute
4690 [[clang::optnone]] int bar() {
4691 // ... code
4692 }
4693
4694 To facilitate disabling optimization for a range of function definitions, a
4695 range-based pragma is provided. Its syntax is ``#pragma clang optimize``
4696 followed by ``off`` or ``on``.
4697
4698 All function definitions in the region between an ``off`` and the following
4699 ``on`` will be decorated with the ``optnone`` attribute unless doing so would
4700 conflict with explicit attributes already present on the function (e.g. the
4701 ones that control inlining).
4702
4703 .. code-block:: c++
4704
4705 #pragma clang optimize off
4706 // This function will be decorated with optnone.
4707 int foo() {
4708 // ... code
4709 }
4710
4711 // optnone conflicts with always_inline, so bar() will not be decorated.
4712 __attribute__((always_inline)) int bar() {
4713 // ... code
4714 }
4715 #pragma clang optimize on
4716
4717 If no ``on`` is found to close an ``off`` region, the end of the region is the
4718 end of the compilation unit.
4719
4720 Note that a stray ``#pragma clang optimize on`` does not selectively enable
4721 additional optimizations when compiling at low optimization levels. This feature
4722 can only be used to selectively disable optimizations.
4723
4724 The pragma has an effect on functions only at the point of their definition; for
4725 function templates, this means that the state of the pragma at the point of an
4726 instantiation is not necessarily relevant. Consider the following example:
4727
4728 .. code-block:: c++
4729
4730 template<typename T> T twice(T t) {
4731 return 2 * t;
4732 }
4733
4734 #pragma clang optimize off
4735 template<typename T> T thrice(T t) {
4736 return 3 * t;
4737 }
4738
4739 int container(int a, int b) {
4740 return twice(a) + thrice(b);
4741 }
4742 #pragma clang optimize on
4743
4744 In this example, the definition of the template function ``twice`` is outside
4745 the pragma region, whereas the definition of ``thrice`` is inside the region.
4746 The ``container`` function is also in the region and will not be optimized, but
4747 it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
4748 these two instantiations, ``twice`` will be optimized (because its definition
4749 was outside the region) and ``thrice`` will not be optimized.
4750
4751 Clang also implements MSVC's range-based pragma,
4752 ``#pragma optimize("[optimization-list]", on | off)``. At the moment, Clang only
4753 supports an empty optimization list, whereas MSVC supports the arguments, ``s``,
4754 ``g``, ``t``, and ``y``. Currently, the implementation of ``pragma optimize`` behaves
4755 the same as ``#pragma clang optimize``. All functions
4756 between ``off`` and ``on`` will be decorated with the ``optnone`` attribute.
4757
4758 .. code-block:: c++
4759
4760 #pragma optimize("", off)
4761 // This function will be decorated with optnone.
4762 void f1() {}
4763
4764 #pragma optimize("", on)
4765 // This function will be optimized with whatever was specified on
4766 // the commandline.
4767 void f2() {}
4768
4769 // This will warn with Clang's current implementation.
4770 #pragma optimize("g", on)
4771 void f3() {}
4772
4773 For MSVC, an empty optimization list and ``off`` parameter will turn off
4774 all optimizations, ``s``, ``g``, ``t``, and ``y``. An empty optimization and
4775 ``on`` parameter will reset the optimizations to the ones specified on the
4776 commandline.
4777
4778 .. list-table:: Parameters (unsupported by Clang)
4779
4780 * - Parameter
4781 - Type of optimization
4782 * - g
4783 - Deprecated
4784 * - s or t
4785 - Short or fast sequences of machine code
4786 * - y
4787 - Enable frame pointers
4788
4789 Extensions for loop hint optimizations
4790 ======================================
4791
4792 The ``#pragma clang loop`` directive is used to specify hints for optimizing the
4793 subsequent for, while, do-while, or c++11 range-based for loop. The directive
4794 provides options for vectorization, interleaving, predication, unrolling and
4795 distribution. Loop hints can be specified before any loop and will be ignored if
4796 the optimization is not safe to apply.
4797
4798 There are loop hints that control transformations (e.g. vectorization, loop
4799 unrolling) and there are loop hints that set transformation options (e.g.
4800 ``vectorize_width``, ``unroll_count``). Pragmas setting transformation options
4801 imply the transformation is enabled, as if it was enabled via the corresponding
4802 transformation pragma (e.g. ``vectorize(enable)``). If the transformation is
4803 disabled (e.g. ``vectorize(disable)``), that takes precedence over
4804 transformations option pragmas implying that transformation.
4805
4806 Vectorization, Interleaving, and Predication
4807 --------------------------------------------
4808
4809 A vectorized loop performs multiple iterations of the original loop
4810 in parallel using vector instructions. The instruction set of the target
4811 processor determines which vector instructions are available and their vector
4812 widths. This restricts the types of loops that can be vectorized. The vectorizer
4813 automatically determines if the loop is safe and profitable to vectorize. A
4814 vector instruction cost model is used to select the vector width.
4815
4816 Interleaving multiple loop iterations allows modern processors to further
4817 improve instruction-level parallelism (ILP) using advanced hardware features,
4818 such as multiple execution units and out-of-order execution. The vectorizer uses
4819 a cost model that depends on the register pressure and generated code size to
4820 select the interleaving count.
4821
4822 Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
4823 by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
4824 manually enable vectorization or interleaving.
4825
4826 .. code-block:: c++
4827
4828 #pragma clang loop vectorize(enable)
4829 #pragma clang loop interleave(enable)
4830 for(...) {
4831 ...
4832 }
4833
4834 The vector width is specified by
4835 ``vectorize_width(_value_[, fixed|scalable])``, where _value_ is a positive
4836 integer and the type of vectorization can be specified with an optional
4837 second parameter. The default for the second parameter is 'fixed' and
4838 refers to fixed width vectorization, whereas 'scalable' indicates the
4839 compiler should use scalable vectors instead. Another use of vectorize_width
4840 is ``vectorize_width(fixed|scalable)`` where the user can hint at the type
4841 of vectorization to use without specifying the exact width. In both variants
4842 of the pragma the vectorizer may decide to fall back on fixed width
4843 vectorization if the target does not support scalable vectors.
4844
4845 The interleave count is specified by ``interleave_count(_value_)``, where
4846 _value_ is a positive integer. This is useful for specifying the optimal
4847 width/count of the set of target architectures supported by your application.
4848
4849 .. code-block:: c++
4850
4851 #pragma clang loop vectorize_width(2)
4852 #pragma clang loop interleave_count(2)
4853 for(...) {
4854 ...
4855 }
4856
4857 Specifying a width/count of 1 disables the optimization, and is equivalent to
4858 ``vectorize(disable)`` or ``interleave(disable)``.
4859
4860 Vector predication is enabled by ``vectorize_predicate(enable)``, for example:
4861
4862 .. code-block:: c++
4863
4864 #pragma clang loop vectorize(enable)
4865 #pragma clang loop vectorize_predicate(enable)
4866 for(...) {
4867 ...
4868 }
4869
4870 This predicates (masks) all instructions in the loop, which allows the scalar
4871 remainder loop (the tail) to be folded into the main vectorized loop. This
4872 might be more efficient when vector predication is efficiently supported by the
4873 target platform.
4874
4875 Loop Unrolling
4876 --------------
4877
4878 Unrolling a loop reduces the loop control overhead and exposes more
4879 opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
4880 eliminates the loop and replaces it with an enumerated sequence of loop
4881 iterations. Full unrolling is only possible if the loop trip count is known at
4882 compile time. Partial unrolling replicates the loop body within the loop and
4883 reduces the trip count.
4884
4885 If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
4886 loop if the trip count is known at compile time. If the fully unrolled code size
4887 is greater than an internal limit the loop will be partially unrolled up to this
4888 limit. If the trip count is not known at compile time the loop will be partially
4889 unrolled with a heuristically chosen unroll factor.
4890
4891 .. code-block:: c++
4892
4893 #pragma clang loop unroll(enable)
4894 for(...) {
4895 ...
4896 }
4897
4898 If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
4899 loop if the trip count is known at compile time identically to
4900 ``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
4901 if the loop count is not known at compile time.
4902
4903 .. code-block:: c++
4904
4905 #pragma clang loop unroll(full)
4906 for(...) {
4907 ...
4908 }
4909
4910 The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
4911 _value_ is a positive integer. If this value is greater than the trip count the
4912 loop will be fully unrolled. Otherwise the loop is partially unrolled subject
4913 to the same code size limit as with ``unroll(enable)``.
4914
4915 .. code-block:: c++
4916
4917 #pragma clang loop unroll_count(8)
4918 for(...) {
4919 ...
4920 }
4921
4922 Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
4923
4924 Loop unroll parameters can be controlled by options
4925 `-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`.
4926
4927 Loop Distribution
4928 -----------------
4929
4930 Loop Distribution allows splitting a loop into multiple loops. This is
4931 beneficial for example when the entire loop cannot be vectorized but some of the
4932 resulting loops can.
4933
4934 If ``distribute(enable))`` is specified and the loop has memory dependencies
4935 that inhibit vectorization, the compiler will attempt to isolate the offending
4936 operations into a new loop. This optimization is not enabled by default, only
4937 loops marked with the pragma are considered.
4938
4939 .. code-block:: c++
4940
4941 #pragma clang loop distribute(enable)
4942 for (i = 0; i < N; ++i) {
4943 S1: A[i + 1] = A[i] + B[i];
4944 S2: C[i] = D[i] * E[i];
4945 }
4946
4947 This loop will be split into two loops between statements S1 and S2. The
4948 second loop containing S2 will be vectorized.
4949
4950 Loop Distribution is currently not enabled by default in the optimizer because
4951 it can hurt performance in some cases. For example, instruction-level
4952 parallelism could be reduced by sequentializing the execution of the
4953 statements S1 and S2 above.
4954
4955 If Loop Distribution is turned on globally with
4956 ``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
4957 be used the disable it on a per-loop basis.
4958
4959 Additional Information
4960 ----------------------
4961
4962 For convenience multiple loop hints can be specified on a single line.
4963
4964 .. code-block:: c++
4965
4966 #pragma clang loop vectorize_width(4) interleave_count(8)
4967 for(...) {
4968 ...
4969 }
4970
4971 If an optimization cannot be applied any hints that apply to it will be ignored.
4972 For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
4973 proven safe to vectorize. To identify and diagnose optimization issues use
4974 `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
4975 user guide for details.
4976
4977 Extensions to specify floating-point flags
4978 ====================================================
4979
4980 The ``#pragma clang fp`` pragma allows floating-point options to be specified
4981 for a section of the source code. This pragma can only appear at file scope or
4982 at the start of a compound statement (excluding comments). When using within a
4983 compound statement, the pragma is active within the scope of the compound
4984 statement.
4985
4986 Currently, the following settings can be controlled with this pragma:
4987
4988 ``#pragma clang fp reassociate`` allows control over the reassociation
4989 of floating point expressions. When enabled, this pragma allows the expression
4990 ``x + (y + z)`` to be reassociated as ``(x + y) + z``.
4991 Reassociation can also occur across multiple statements.
4992 This pragma can be used to disable reassociation when it is otherwise
4993 enabled for the translation unit with the ``-fassociative-math`` flag.
4994 The pragma can take two values: ``on`` and ``off``.
4995
4996 .. code-block:: c++
4997
4998 float f(float x, float y, float z)
4999 {
5000 // Enable floating point reassociation across statements
5001 #pragma clang fp reassociate(on)
5002 float t = x + y;
5003 float v = t + z;
5004 }
5005
5006 ``#pragma clang fp reciprocal`` allows control over using reciprocal
5007 approximations in floating point expressions. When enabled, this
5008 pragma allows the expression ``x / y`` to be approximated as ``x *
5009 (1.0 / y)``. This pragma can be used to disable reciprocal
5010 approximation when it is otherwise enabled for the translation unit
5011 with the ``-freciprocal-math`` flag or other fast-math options. The
5012 pragma can take two values: ``on`` and ``off``.
5013
5014 .. code-block:: c++
5015
5016 float f(float x, float y)
5017 {
5018 // Enable floating point reciprocal approximation
5019 #pragma clang fp reciprocal(on)
5020 return x / y;
5021 }
5022
5023 ``#pragma clang fp contract`` specifies whether the compiler should
5024 contract a multiply and an addition (or subtraction) into a fused FMA
5025 operation when supported by the target.
5026
5027 The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on``
5028 option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
5029 fusion as specified the language standard. The ``fast`` option allows fusion
5030 in cases when the language standard does not make this possible (e.g. across
5031 statements in C).
5032
5033 .. code-block:: c++
5034
5035 for(...) {
5036 #pragma clang fp contract(fast)
5037 a = b[i] * c[i];
5038 d[i] += a;
5039 }
5040
5041
5042 The pragma can also be used with ``off`` which turns FP contraction off for a
5043 section of the code. This can be useful when fast contraction is otherwise
5044 enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag.
5045 Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and
5046 addition across statements regardless of any controlling pragmas.
5047
5048 ``#pragma clang fp exceptions`` specifies floating point exception behavior. It
5049 may take one of the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of
5050 these values is same as for `constrained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics>`_.
5051
5052 .. code-block:: c++
5053
5054 {
5055 // Preserve floating point exceptions
5056 #pragma clang fp exceptions(strict)
5057 z = x + y;
5058 if (fetestexcept(FE_OVERFLOW))
5059 ...
5060 }
5061
5062 A ``#pragma clang fp`` pragma may contain any number of options:
5063
5064 .. code-block:: c++
5065
5066 void func(float *dest, float a, float b) {
5067 #pragma clang fp exceptions(maytrap) contract(fast) reassociate(on)
5068 ...
5069 }
5070
5071 ``#pragma clang fp eval_method`` allows floating-point behavior to be specified
5072 for a section of the source code. This pragma can appear at file or namespace
5073 scope, or at the start of a compound statement (excluding comments).
5074 The pragma is active within the scope of the compound statement.
5075
5076 When ``pragma clang fp eval_method(source)`` is enabled, the section of code
5077 governed by the pragma behaves as though the command-line option
5078 ``-ffp-eval-method=source`` is enabled. Rounds intermediate results to
5079 source-defined precision.
5080
5081 When ``pragma clang fp eval_method(double)`` is enabled, the section of code
5082 governed by the pragma behaves as though the command-line option
5083 ``-ffp-eval-method=double`` is enabled. Rounds intermediate results to
5084 ``double`` precision.
5085
5086 When ``pragma clang fp eval_method(extended)`` is enabled, the section of code
5087 governed by the pragma behaves as though the command-line option
5088 ``-ffp-eval-method=extended`` is enabled. Rounds intermediate results to
5089 target-dependent ``long double`` precision. In Win32 programming, for instance,
5090 the long double data type maps to the double, 64-bit precision data type.
5091
5092 The full syntax this pragma supports is
5093 ``#pragma clang fp eval_method(source|double|extended)``.
5094
5095 .. code-block:: c++
5096
5097 for(...) {
5098 // The compiler will use long double as the floating-point evaluation
5099 // method.
5100 #pragma clang fp eval_method(extended)
5101 a = b[i] * c[i] + e;
5102 }
5103
5104 Note: ``math.h`` defines the typedefs ``float_t`` and ``double_t`` based on the active
5105 evaluation method at the point where the header is included, not where the
5106 typedefs are used. Because of this, it is unwise to combine these typedefs with
5107 ``#pragma clang fp eval_method``. To catch obvious bugs, Clang will emit an
5108 error for any references to these typedefs within the scope of this pragma;
5109 however, this is not a fool-proof protection, and programmers must take care.
5110
5111 The ``#pragma float_control`` pragma allows precise floating-point
5112 semantics and floating-point exception behavior to be specified
5113 for a section of the source code. This pragma can only appear at file or
5114 namespace scope, within a language linkage specification or at the start of a
5115 compound statement (excluding comments). When used within a compound statement,
5116 the pragma is active within the scope of the compound statement. This pragma
5117 is modeled after a Microsoft pragma with the same spelling and syntax. For
5118 pragmas specified at file or namespace scope, or within a language linkage
5119 specification, a stack is supported so that the ``pragma float_control``
5120 settings can be pushed or popped.
5121
5122 When ``pragma float_control(precise, on)`` is enabled, the section of code
5123 governed by the pragma uses precise floating point semantics, effectively
5124 ``-ffast-math`` is disabled and ``-ffp-contract=on``
5125 (fused multiply add) is enabled. This pragma enables ``-fmath-errno``.
5126
5127 When ``pragma float_control(precise, off)`` is enabled, unsafe-floating point
5128 optimizations are enabled in the section of code governed by the pragma.
5129 Effectively ``-ffast-math`` is enabled and ``-ffp-contract=fast``. This pragma
5130 disables ``-fmath-errno``.
5131
5132 When ``pragma float_control(except, on)`` is enabled, the section of code
5133 governed by the pragma behaves as though the command-line option
5134 ``-ffp-exception-behavior=strict`` is enabled,
5135 when ``pragma float_control(except, off)`` is enabled, the section of code
5136 governed by the pragma behaves as though the command-line option
5137 ``-ffp-exception-behavior=ignore`` is enabled.
5138
5139 The full syntax this pragma supports is
5140 ``float_control(except|precise, on|off [, push])`` and
5141 ``float_control(push|pop)``.
5142 The ``push`` and ``pop`` forms, including using ``push`` as the optional
5143 third argument, can only occur at file scope.
5144
5145 .. code-block:: c++
5146
5147 for(...) {
5148 // This block will be compiled with -fno-fast-math and -ffp-contract=on
5149 #pragma float_control(precise, on)
5150 a = b[i] * c[i] + e;
5151 }
5152
5153 Specifying an attribute for multiple declarations (#pragma clang attribute)
5154 ===========================================================================
5155
5156 The ``#pragma clang attribute`` directive can be used to apply an attribute to
5157 multiple declarations. The ``#pragma clang attribute push`` variation of the
5158 directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
5159 can be added to. The ``#pragma clang attribute (...)`` variation adds an
5160 attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
5161 the scope. You can also use ``#pragma clang attribute push (...)``, which is a
5162 shorthand for when you want to add one attribute to a new scope. Multiple push
5163 directives can be nested inside each other.
5164
5165 The attributes that are used in the ``#pragma clang attribute`` directives
5166 can be written using the GNU-style syntax:
5167
5168 .. code-block:: c++
5169
5170 #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
5171
5172 void function(); // The function now has the annotate("custom") attribute
5173
5174 #pragma clang attribute pop
5175
5176 The attributes can also be written using the C++11 style syntax:
5177
5178 .. code-block:: c++
5179
5180 #pragma clang attribute push ([[noreturn]], apply_to = function)
5181
5182 void function(); // The function now has the [[noreturn]] attribute
5183
5184 #pragma clang attribute pop
5185
5186 The ``__declspec`` style syntax is also supported:
5187
5188 .. code-block:: c++
5189
5190 #pragma clang attribute push (__declspec(dllexport), apply_to = function)
5191
5192 void function(); // The function now has the __declspec(dllexport) attribute
5193
5194 #pragma clang attribute pop
5195
5196 A single push directive can contain multiple attributes, however,
5197 only one syntax style can be used within a single directive:
5198
5199 .. code-block:: c++
5200
5201 #pragma clang attribute push ([[noreturn, noinline]], apply_to = function)
5202
5203 void function1(); // The function now has the [[noreturn]] and [[noinline]] attributes
5204
5205 #pragma clang attribute pop
5206
5207 #pragma clang attribute push (__attribute((noreturn, noinline)), apply_to = function)
5208
5209 void function2(); // The function now has the __attribute((noreturn)) and __attribute((noinline)) attributes
5210
5211 #pragma clang attribute pop
5212
5213 Because multiple push directives can be nested, if you're writing a macro that
5214 expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
5215 required) to add a namespace to your push/pop directives. A pop directive with a
5216 namespace will pop the innermost push that has that same namespace. This will
5217 ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
5218 that an ``pop`` without a namespace will pop the innermost ``push`` without a
5219 namespace. ``push``es with a namespace can only be popped by ``pop`` with the
5220 same namespace. For instance:
5221
5222 .. code-block:: c++
5223
5224 #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
5225 #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop")
5226
5227 #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
5228 #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop")
5229
5230
5231 ASSUME_NORETURN_BEGIN
5232 ASSUME_UNAVAILABLE_BEGIN
5233 void function(); // function has [[noreturn]] and __attribute__((unavailable))
5234 ASSUME_NORETURN_END
5235 void other_function(); // function has __attribute__((unavailable))
5236 ASSUME_UNAVAILABLE_END
5237
5238 Without the namespaces on the macros, ``other_function`` will be annotated with
5239 ``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
5240 a contrived example, but its very possible for this kind of situation to appear
5241 in real code if the pragmas are spread out across a large file. You can test if
5242 your version of clang supports namespaces on ``#pragma clang attribute`` with
5243 ``__has_extension(pragma_clang_attribute_namespaces)``.
5244
5245 Subject Match Rules
5246 -------------------
5247
5248 The set of declarations that receive a single attribute from the attribute stack
5249 depends on the subject match rules that were specified in the pragma. Subject
5250 match rules are specified after the attribute. The compiler expects an
5251 identifier that corresponds to the subject set specifier. The ``apply_to``
5252 specifier is currently the only supported subject set specifier. It allows you
5253 to specify match rules that form a subset of the attribute's allowed subject
5254 set, i.e. the compiler doesn't require all of the attribute's subjects. For
5255 example, an attribute like ``[[nodiscard]]`` whose subject set includes
5256 ``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
5257 least one of these rules after ``apply_to``:
5258
5259 .. code-block:: c++
5260
5261 #pragma clang attribute push([[nodiscard]], apply_to = enum)
5262
5263 enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
5264
5265 struct Record1 { }; // The struct will *not* receive [[nodiscard]]
5266
5267 #pragma clang attribute pop
5268
5269 #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
5270
5271 enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
5272
5273 struct Record2 { }; // The struct *will* receive [[nodiscard]]
5274
5275 #pragma clang attribute pop
5276
5277 // This is an error, since [[nodiscard]] can't be applied to namespaces:
5278 #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
5279
5280 #pragma clang attribute pop
5281
5282 Multiple match rules can be specified using the ``any`` match rule, as shown
5283 in the example above. The ``any`` rule applies attributes to all declarations
5284 that are matched by at least one of the rules in the ``any``. It doesn't nest
5285 and can't be used inside the other match rules. Redundant match rules or rules
5286 that conflict with one another should not be used inside of ``any``. Failing to
5287 specify a rule within the ``any`` rule results in an error.
5288
5289 Clang supports the following match rules:
5290
5291 - ``function``: Can be used to apply attributes to functions. This includes C++
5292 member functions, static functions, operators, and constructors/destructors.
5293
5294 - ``function(is_member)``: Can be used to apply attributes to C++ member
5295 functions. This includes members like static functions, operators, and
5296 constructors/destructors.
5297
5298 - ``hasType(functionType)``: Can be used to apply attributes to functions, C++
5299 member functions, and variables/fields whose type is a function pointer. It
5300 does not apply attributes to Objective-C methods or blocks.
5301
5302 - ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
5303 and C++11 type aliases.
5304
5305 - ``record``: Can be used to apply attributes to ``struct``, ``class``, and
5306 ``union`` declarations.
5307
5308 - ``record(unless(is_union))``: Can be used to apply attributes only to
5309 ``struct`` and ``class`` declarations.
5310
5311 - ``enum``: Can be used to apply attributes to enumeration declarations.
5312
5313 - ``enum_constant``: Can be used to apply attributes to enumerators.
5314
5315 - ``variable``: Can be used to apply attributes to variables, including
5316 local variables, parameters, global variables, and static member variables.
5317 It does not apply attributes to instance member variables or Objective-C
5318 ivars.
5319
5320 - ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
5321 variables only.
5322
5323 - ``variable(is_global)``: Can be used to apply attributes to global variables
5324 only.
5325
5326 - ``variable(is_local)``: Can be used to apply attributes to local variables
5327 only.
5328
5329 - ``variable(is_parameter)``: Can be used to apply attributes to parameters
5330 only.
5331
5332 - ``variable(unless(is_parameter))``: Can be used to apply attributes to all
5333 the variables that are not parameters.
5334
5335 - ``field``: Can be used to apply attributes to non-static member variables
5336 in a record. This includes Objective-C ivars.
5337
5338 - ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
5339
5340 - ``objc_interface``: Can be used to apply attributes to ``@interface``
5341 declarations.
5342
5343 - ``objc_protocol``: Can be used to apply attributes to ``@protocol``
5344 declarations.
5345
5346 - ``objc_category``: Can be used to apply attributes to category declarations,
5347 including class extensions.
5348
5349 - ``objc_method``: Can be used to apply attributes to Objective-C methods,
5350 including instance and class methods. Implicit methods like implicit property
5351 getters and setters do not receive the attribute.
5352
5353 - ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
5354 instance methods.
5355
5356 - ``objc_property``: Can be used to apply attributes to ``@property``
5357 declarations.
5358
5359 - ``block``: Can be used to apply attributes to block declarations. This does
5360 not include variables/fields of block pointer type.
5361
5362 The use of ``unless`` in match rules is currently restricted to a strict set of
5363 sub-rules that are used by the supported attributes. That means that even though
5364 ``variable(unless(is_parameter))`` is a valid match rule,
5365 ``variable(unless(is_thread_local))`` is not.
5366
5367 Supported Attributes
5368 --------------------
5369
5370 Not all attributes can be used with the ``#pragma clang attribute`` directive.
5371 Notably, statement attributes like ``[[fallthrough]]`` or type attributes
5372 like ``address_space`` aren't supported by this directive. You can determine
5373 whether or not an attribute is supported by the pragma by referring to the
5374 :doc:`individual documentation for that attribute <AttributeReference>`.
5375
5376 The attributes are applied to all matching declarations individually, even when
5377 the attribute is semantically incorrect. The attributes that aren't applied to
5378 any declaration are not verified semantically.
5379
5380 Specifying section names for global objects (#pragma clang section)
5381 ===================================================================
5382
5383 The ``#pragma clang section`` directive provides a means to assign section-names
5384 to global variables, functions and static variables.
5385
5386 The section names can be specified as:
5387
5388 .. code-block:: c++
5389
5390 #pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText"
5391
5392 The section names can be reverted back to default name by supplying an empty
5393 string to the section kind, for example:
5394
5395 .. code-block:: c++
5396
5397 #pragma clang section bss="" data="" text="" rodata="" relro=""
5398
5399 The ``#pragma clang section`` directive obeys the following rules:
5400
5401 * The pragma applies to all global variable, statics and function declarations
5402 from the pragma to the end of the translation unit.
5403
5404 * The pragma clang section is enabled automatically, without need of any flags.
5405
5406 * This feature is only defined to work sensibly for ELF and Mach-O targets.
5407
5408 * If section name is specified through _attribute_((section("myname"))), then
5409 the attribute name gains precedence.
5410
5411 * Global variables that are initialized to zero will be placed in the named
5412 bss section, if one is present.
5413
5414 * The ``#pragma clang section`` directive does not does try to infer section-kind
5415 from the name. For example, naming a section "``.bss.mySec``" does NOT mean
5416 it will be a bss section name.
5417
5418 * The decision about which section-kind applies to each global is taken in the back-end.
5419 Once the section-kind is known, appropriate section name, as specified by the user using
5420 ``#pragma clang section`` directive, is applied to that global.
5421
5422 Specifying Linker Options on ELF Targets
5423 ========================================
5424
5425 The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
5426 The second parameter is the library name (without the traditional Unix prefix of
5427 ``lib``). This allows you to provide an implicit link of dependent libraries.
5428
5429 Evaluating Object Size
5430 ======================
5431
5432 Clang supports the builtins ``__builtin_object_size`` and
5433 ``__builtin_dynamic_object_size``. The semantics are compatible with GCC's
5434 builtins of the same names, but the details are slightly different.
5435
5436 .. code-block:: c
5437
5438 size_t __builtin_[dynamic_]object_size(const void *ptr, int type)
5439
5440 Returns the number of accessible bytes ``n`` past ``ptr``. The value returned
5441 depends on ``type``, which is required to be an integer constant between 0 and
5442 3:
5443
5444 * If ``type & 2 == 0``, the least ``n`` is returned such that accesses to
5445 ``(const char*)ptr + n`` and beyond are known to be out of bounds. This is
5446 ``(size_t)-1`` if no better bound is known.
5447 * If ``type & 2 == 2``, the greatest ``n`` is returned such that accesses to
5448 ``(const char*)ptr + i`` are known to be in bounds, for 0 <= ``i`` < ``n``.
5449 This is ``(size_t)0`` if no better bound is known.
5450
5451 .. code-block:: c
5452
5453 char small[10], large[100];
5454 bool cond;
5455 // Returns 100: writes of more than 100 bytes are known to be out of bounds.
5456 int n100 = __builtin_object_size(cond ? small : large, 0);
5457 // Returns 10: writes of 10 or fewer bytes are known to be in bounds.
5458 int n10 = __builtin_object_size(cond ? small : large, 2);
5459
5460 * If ``type & 1 == 0``, pointers are considered to be in bounds if they point
5461 into the same storage as ``ptr`` -- that is, the same stack object, global
5462 variable, or heap allocation.
5463 * If ``type & 1 == 1``, pointers are considered to be in bounds if they point
5464 to the same subobject that ``ptr`` points to. If ``ptr`` points to an array
5465 element, other elements of the same array, but not of enclosing arrays, are
5466 considered in bounds.
5467
5468 .. code-block:: c
5469
5470 struct X { char a, b, c; } x;
5471 static_assert(__builtin_object_size(&x, 0) == 3);
5472 static_assert(__builtin_object_size(&x.b, 0) == 2);
5473 static_assert(__builtin_object_size(&x.b, 1) == 1);
5474
5475 .. code-block:: c
5476
5477 char a[10][10][10];
5478 static_assert(__builtin_object_size(&a, 1) == 1000);
5479 static_assert(__builtin_object_size(&a[1], 1) == 900);
5480 static_assert(__builtin_object_size(&a[1][1], 1) == 90);
5481 static_assert(__builtin_object_size(&a[1][1][1], 1) == 9);
5482
5483 The values returned by this builtin are a best effort conservative approximation
5484 of the correct answers. When ``type & 2 == 0``, the true value is less than or
5485 equal to the value returned by the builtin, and when ``type & 2 == 1``, the true
5486 value is greater than or equal to the value returned by the builtin.
5487
5488 For ``__builtin_object_size``, the value is determined entirely at compile time.
5489 With optimization enabled, better results will be produced, especially when the
5490 call to ``__builtin_object_size`` is in a different function from the formation
5491 of the pointer. Unlike in GCC, enabling optimization in Clang does not allow
5492 more information about subobjects to be determined, so the ``type & 1 == 1``
5493 case will often give imprecise results when used across a function call boundary
5494 even when optimization is enabled.
5495
5496 `The pass_object_size and pass_dynamic_object_size attributes <https://clang.llvm.org/docs/AttributeReference.html#pass-object-size-pass-dynamic-object-size>`_
5497 can be used to invisibly pass the object size for a pointer parameter alongside
5498 the pointer in a function call. This allows more precise object sizes to be
5499 determined both when building without optimizations and in the ``type & 1 == 1``
5500 case.
5501
5502 For ``__builtin_dynamic_object_size``, the result is not limited to being a
5503 compile time constant. Instead, a small amount of runtime evaluation is
5504 permitted to determine the size of the object, in order to give a more precise
5505 result. ``__builtin_dynamic_object_size`` is meant to be used as a drop-in
5506 replacement for ``__builtin_object_size`` in libraries that support it. For
5507 instance, here is a program that ``__builtin_dynamic_object_size`` will make
5508 safer:
5509
5510 .. code-block:: c
5511
5512 void copy_into_buffer(size_t size) {
5513 char* buffer = malloc(size);
5514 strlcpy(buffer, "some string", strlen("some string"));
5515 // Previous line preprocesses to:
5516 // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
5517 }
5518
5519 Since the size of ``buffer`` can't be known at compile time, Clang will fold
5520 ``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
5521 as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
5522 ``size``, providing some extra runtime safety.
5523
5524 Deprecating Macros
5525 ==================
5526
5527 Clang supports the pragma ``#pragma clang deprecated``, which can be used to
5528 provide deprecation warnings for macro uses. For example:
5529
5530 .. code-block:: c
5531
5532 #define MIN(x, y) x < y ? x : y
5533 #pragma clang deprecated(MIN, "use std::min instead")
5534
5535 int min(int a, int b) {
5536 return MIN(a, b); // warning: MIN is deprecated: use std::min instead
5537 }
5538
5539 ``#pragma clang deprecated`` should be preferred for this purpose over
5540 ``#pragma GCC warning`` because the warning can be controlled with
5541 ``-Wdeprecated``.
5542
5543 Restricted Expansion Macros
5544 ===========================
5545
5546 Clang supports the pragma ``#pragma clang restrict_expansion``, which can be
5547 used restrict macro expansion in headers. This can be valuable when providing
5548 headers with ABI stability requirements. Any expansion of the annotated macro
5549 processed by the preprocessor after the ``#pragma`` annotation will log a
5550 warning. Redefining the macro or undefining the macro will not be diagnosed, nor
5551 will expansion of the macro within the main source file. For example:
5552
5553 .. code-block:: c
5554
5555 #define TARGET_ARM 1
5556 #pragma clang restrict_expansion(TARGET_ARM, "<reason>")
5557
5558 /// Foo.h
5559 struct Foo {
5560 #if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason>
5561 uint32_t X;
5562 #else
5563 uint64_t X;
5564 #endif
5565 };
5566
5567 /// main.c
5568 #include "foo.h"
5569 #if TARGET_ARM // No warning in main source file
5570 X_TYPE uint32_t
5571 #else
5572 X_TYPE uint64_t
5573 #endif
5574
5575 This warning is controlled by ``-Wpedantic-macros``.
5576
5577 Final Macros
5578 ============
5579
5580 Clang supports the pragma ``#pragma clang final``, which can be used to
5581 mark macros as final, meaning they cannot be undef'd or re-defined. For example:
5582
5583 .. code-block:: c
5584
5585 #define FINAL_MACRO 1
5586 #pragma clang final(FINAL_MACRO)
5587
5588 #define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined
5589 #undef FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be undefined
5590
5591 This is useful for enforcing system-provided macros that should not be altered
5592 in user headers or code. This is controlled by ``-Wpedantic-macros``. Final
5593 macros will always warn on redefinition, including situations with identical
5594 bodies and in system headers.
5595
5596 Line Control
5597 ============
5598
5599 Clang supports an extension for source line control, which takes the
5600 form of a preprocessor directive starting with an unsigned integral
5601 constant. In addition to the standard ``#line`` directive, this form
5602 allows control of an include stack and header file type, which is used
5603 in issuing diagnostics. These lines are emitted in preprocessed
5604 output.
5605
5606 .. code-block:: c
5607
5608 # <line:number> <filename:string> <header-type:numbers>
5609
5610 The filename is optional, and if unspecified indicates no change in
5611 source filename. The header-type is an optional, whitespace-delimited,
5612 sequence of magic numbers as follows.
5613
5614 * ``1:`` Push the current source file name onto the include stack and
5615 enter a new file.
5616
5617 * ``2``: Pop the include stack and return to the specified file. If
5618 the filename is ``""``, the name popped from the include stack is
5619 used. Otherwise there is no requirement that the specified filename
5620 matches the current source when originally pushed.
5621
5622 * ``3``: Enter a system-header region. System headers often contain
5623 implementation-specific source that would normally emit a diagnostic.
5624
5625 * ``4``: Enter an implicit ``extern "C"`` region. This is not required on
5626 modern systems where system headers are C++-aware.
5627
5628 At most a single ``1`` or ``2`` can be present, and values must be in
5629 ascending order.
5630
5631 Examples are:
5632
5633 .. code-block:: c
5634
5635 # 57 // Advance (or return) to line 57 of the current source file
5636 # 57 "frob" // Set to line 57 of "frob"
5637 # 1 "foo.h" 1 // Enter "foo.h" at line 1
5638 # 59 "main.c" 2 // Leave current include and return to "main.c"
5639 # 1 "/usr/include/stdio.h" 1 3 // Enter a system header
5640 # 60 "" 2 // return to "main.c"
5641 # 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
5642
5643 Extended Integer Types
5644 ======================
5645
5646 Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
5647 and in C++. This type was previously implemented in Clang with the same
5648 semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
5649 favor of the standard type.
5650
5651 Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
5652 so this type should not yet be used in interfaces that require ABI stability.
5653
5654 Intrinsics Support within Constant Expressions
5655 ==============================================
5656
5657 The following builtin intrinsics can be used in constant expressions:
5658
5659 * ``__builtin_addcb``
5660 * ``__builtin_addcs``
5661 * ``__builtin_addc``
5662 * ``__builtin_addcl``
5663 * ``__builtin_addcll``
5664 * ``__builtin_bitreverse8``
5665 * ``__builtin_bitreverse16``
5666 * ``__builtin_bitreverse32``
5667 * ``__builtin_bitreverse64``
5668 * ``__builtin_bswap16``
5669 * ``__builtin_bswap32``
5670 * ``__builtin_bswap64``
5671 * ``__builtin_clrsb``
5672 * ``__builtin_clrsbl``
5673 * ``__builtin_clrsbll``
5674 * ``__builtin_clz``
5675 * ``__builtin_clzl``
5676 * ``__builtin_clzll``
5677 * ``__builtin_clzs``
5678 * ``__builtin_clzg``
5679 * ``__builtin_ctz``
5680 * ``__builtin_ctzl``
5681 * ``__builtin_ctzll``
5682 * ``__builtin_ctzs``
5683 * ``__builtin_ctzg``
5684 * ``__builtin_ffs``
5685 * ``__builtin_ffsl``
5686 * ``__builtin_ffsll``
5687 * ``__builtin_fmax``
5688 * ``__builtin_fmin``
5689 * ``__builtin_fpclassify``
5690 * ``__builtin_inf``
5691 * ``__builtin_isinf``
5692 * ``__builtin_isinf_sign``
5693 * ``__builtin_isfinite``
5694 * ``__builtin_isnan``
5695 * ``__builtin_isnormal``
5696 * ``__builtin_nan``
5697 * ``__builtin_nans``
5698 * ``__builtin_parity``
5699 * ``__builtin_parityl``
5700 * ``__builtin_parityll``
5701 * ``__builtin_popcount``
5702 * ``__builtin_popcountl``
5703 * ``__builtin_popcountll``
5704 * ``__builtin_popcountg``
5705 * ``__builtin_rotateleft8``
5706 * ``__builtin_rotateleft16``
5707 * ``__builtin_rotateleft32``
5708 * ``__builtin_rotateleft64``
5709 * ``__builtin_rotateright8``
5710 * ``__builtin_rotateright16``
5711 * ``__builtin_rotateright32``
5712 * ``__builtin_rotateright64``
5713 * ``__builtin_subcb``
5714 * ``__builtin_subcs``
5715 * ``__builtin_subc``
5716 * ``__builtin_subcl``
5717 * ``__builtin_subcll``
5718
5719 The following x86-specific intrinsics can be used in constant expressions:
5720
5721 * ``_bit_scan_forward``
5722 * ``_bit_scan_reverse``
5723 * ``__bsfd``
5724 * ``__bsfq``
5725 * ``__bsrd``
5726 * ``__bsrq``
5727 * ``__bswap``
5728 * ``__bswapd``
5729 * ``__bswap64``
5730 * ``__bswapq``
5731 * ``_castf32_u32``
5732 * ``_castf64_u64``
5733 * ``_castu32_f32``
5734 * ``_castu64_f64``
5735 * ``__lzcnt16``
5736 * ``__lzcnt``
5737 * ``__lzcnt64``
5738 * ``_mm_popcnt_u32``
5739 * ``_mm_popcnt_u64``
5740 * ``_popcnt32``
5741 * ``_popcnt64``
5742 * ``__popcntd``
5743 * ``__popcntq``
5744 * ``__popcnt16``
5745 * ``__popcnt``
5746 * ``__popcnt64``
5747 * ``__rolb``
5748 * ``__rolw``
5749 * ``__rold``
5750 * ``__rolq``
5751 * ``__rorb``
5752 * ``__rorw``
5753 * ``__rord``
5754 * ``__rorq``
5755 * ``_rotl``
5756 * ``_rotr``
5757 * ``_rotwl``
5758 * ``_rotwr``
5759 * ``_lrotl``
5760 * ``_lrotr``
5761
5762 Debugging the Compiler
5763 ======================
5764
5765 Clang supports a number of pragma directives that help debugging the compiler itself.
5766 Syntax is the following: `#pragma clang __debug <command> <arguments>`.
5767 Note, all of debugging pragmas are subject to change.
5768
5769 `dump`
5770 ------
5771 Accepts either a single identifier or an expression. When a single identifier is passed,
5772 the lookup results for the identifier are printed to `stderr`. When an expression is passed,
5773 the AST for the expression is printed to `stderr`. The expression is an unevaluated operand,
5774 so things like overload resolution and template instantiations are performed,
5775 but the expression has no runtime effects.
5776 Type- and value-dependent expressions are not supported yet.
5777
5778 This facility is designed to aid with testing name lookup machinery.
5779
5780 Predefined Macros
5781 =================
5782
5783 `__GCC_DESTRUCTIVE_SIZE` and `__GCC_CONSTRUCTIVE_SIZE`
5784 ------------------------------------------------------
5785 Specify the mimum offset between two objects to avoid false sharing and the
5786 maximum size of contiguous memory to promote true sharing, respectively. These
5787 macros are predefined in all C and C++ language modes, but can be redefined on
5788 the command line with ``-D`` to specify different values as needed or can be
5789 undefined on the command line with ``-U`` to disable support for the feature.
5790
5791 **Note: the values the macros expand to are not guaranteed to be stable. They
5792 are are affected by architectures and CPU tuning flags, can change between
5793 releases of Clang and will not match the values defined by other compilers such
5794 as GCC.**
5795
5796 Compiling different TUs depending on these flags (including use of
5797 ``std::hardware_constructive_interference`` or
5798 ``std::hardware_destructive_interference``) with different compilers, macro
5799 definitions, or architecture flags will lead to ODR violations and should be
5800 avoided.
5801
5802 ``#embed`` Parameters
5803 =====================
5804
5805 ``clang::offset``
5806 -----------------
5807 The ``clang::offset`` embed parameter may appear zero or one time in the
5808 embed parameter sequence. Its preprocessor argument clause shall be present and
5809 have the form:
5810
5811 ..code-block: text
5812
5813 ( constant-expression )
5814
5815 and shall be an integer constant expression. The integer constant expression
5816 shall not evaluate to a value less than 0. The token ``defined`` shall not
5817 appear within the constant expression.
5818
5819 The offset will be used when reading the contents of the embedded resource to
5820 specify the starting offset to begin embedding from. The resources is treated
5821 as being empty if the specified offset is larger than the number of bytes in
5822 the resource. The offset will be applied *before* any ``limit`` parameters are
5823 applied.