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