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