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