1//==--- AttrDocs.td - Attribute documentation ----------------------------===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===---------------------------------------------------------------------===// 8 9// To test that the documentation builds cleanly, you must run clang-tblgen to 10// convert the .td file into a .rst file, and then run sphinx to convert the 11// .rst file into an HTML file. After completing testing, you should revert the 12// generated .rst file so that the modified version does not get checked in to 13// version control. 14// 15// To run clang-tblgen to generate the .rst file: 16// clang-tblgen -gen-attr-docs -I <root>/llvm/tools/clang/include 17// <root>/llvm/tools/clang/include/clang/Basic/Attr.td -o 18// <root>/llvm/tools/clang/docs/AttributeReference.rst 19// 20// To run sphinx to generate the .html files (note that sphinx-build must be 21// available on the PATH): 22// Windows (from within the clang\docs directory): 23// make.bat html 24// Non-Windows (from within the clang\docs directory): 25// make -f Makefile.sphinx html 26 27def GlobalDocumentation { 28 code Intro =[{.. 29 ------------------------------------------------------------------- 30 NOTE: This file is automatically generated by running clang-tblgen 31 -gen-attr-docs. Do not edit this file by hand!! 32 ------------------------------------------------------------------- 33 34=================== 35Attributes in Clang 36=================== 37.. contents:: 38 :local: 39 40.. |br| raw:: html 41 42 <br/> 43 44Introduction 45============ 46 47This page lists the attributes currently supported by Clang. 48}]; 49} 50 51def SectionDocs : Documentation { 52 let Category = DocCatVariable; 53 let Content = [{ 54The ``section`` attribute allows you to specify a specific section a 55global variable or function should be in after translation. 56 }]; 57 let Heading = "section, __declspec(allocate)"; 58} 59 60def InitPriorityDocs : Documentation { 61 let Category = DocCatVariable; 62 let Content = [{ 63In C++, the order in which global variables are initialized across translation 64units is unspecified, unlike the ordering within a single translation unit. The 65``init_priority`` attribute allows you to specify a relative ordering for the 66initialization of objects declared at namespace scope in C++. The priority is 67given as an integer constant expression between 101 and 65535 (inclusive). 68Priorities outside of that range are reserved for use by the implementation. A 69lower value indicates a higher priority of initialization. Note that only the 70relative ordering of values is important. For example: 71 72.. code-block:: c++ 73 74 struct SomeType { SomeType(); }; 75 __attribute__((init_priority(200))) SomeType Obj1; 76 __attribute__((init_priority(101))) SomeType Obj2; 77 78``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of 79initialization being the opposite. 80 81This attribute is only supported for C++ and Objective-C++ and is ignored in 82other language modes. Currently, this attribute is not implemented on z/OS. 83 }]; 84} 85 86def InitSegDocs : Documentation { 87 let Category = DocCatVariable; 88 let Content = [{ 89The attribute applied by ``pragma init_seg()`` controls the section into 90which global initialization function pointers are emitted. It is only 91available with ``-fms-extensions``. Typically, this function pointer is 92emitted into ``.CRT$XCU`` on Windows. The user can change the order of 93initialization by using a different section name with the same 94``.CRT$XC`` prefix and a suffix that sorts lexicographically before or 95after the standard ``.CRT$XCU`` sections. See the init_seg_ 96documentation on MSDN for more information. 97 98.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx 99 }]; 100} 101 102def TLSModelDocs : Documentation { 103 let Category = DocCatVariable; 104 let Content = [{ 105The ``tls_model`` attribute allows you to specify which thread-local storage 106model to use. It accepts the following strings: 107 108* global-dynamic 109* local-dynamic 110* initial-exec 111* local-exec 112 113TLS models are mutually exclusive. 114 }]; 115} 116 117def DLLExportDocs : Documentation { 118 let Category = DocCatVariable; 119 let Content = [{ 120The ``__declspec(dllexport)`` attribute declares a variable, function, or 121Objective-C interface to be exported from the module. It is available under the 122``-fdeclspec`` flag for compatibility with various compilers. The primary use 123is for COFF object files which explicitly specify what interfaces are available 124for external use. See the dllexport_ documentation on MSDN for more 125information. 126 127.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 128 }]; 129} 130 131def DLLImportDocs : Documentation { 132 let Category = DocCatVariable; 133 let Content = [{ 134The ``__declspec(dllimport)`` attribute declares a variable, function, or 135Objective-C interface to be imported from an external module. It is available 136under the ``-fdeclspec`` flag for compatibility with various compilers. The 137primary use is for COFF object files which explicitly specify what interfaces 138are imported from external modules. See the dllimport_ documentation on MSDN 139for more information. 140 141.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 142 }]; 143} 144 145def ThreadDocs : Documentation { 146 let Category = DocCatVariable; 147 let Content = [{ 148The ``__declspec(thread)`` attribute declares a variable with thread local 149storage. It is available under the ``-fms-extensions`` flag for MSVC 150compatibility. See the documentation for `__declspec(thread)`_ on MSDN. 151 152.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx 153 154In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the 155GNU ``__thread`` keyword. The variable must not have a destructor and must have 156a constant initializer, if any. The attribute only applies to variables 157declared with static storage duration, such as globals, class static data 158members, and static locals. 159 }]; 160} 161 162def NoEscapeDocs : Documentation { 163 let Category = DocCatVariable; 164 let Content = [{ 165``noescape`` placed on a function parameter of a pointer type is used to inform 166the compiler that the pointer cannot escape: that is, no reference to the object 167the pointer points to that is derived from the parameter value will survive 168after the function returns. Users are responsible for making sure parameters 169annotated with ``noescape`` do not actually escape. Calling ``free()`` on such 170a parameter does not constitute an escape. 171 172For example: 173 174.. code-block:: c 175 176 int *gp; 177 178 void nonescapingFunc(__attribute__((noescape)) int *p) { 179 *p += 100; // OK. 180 } 181 182 void escapingFunc(__attribute__((noescape)) int *p) { 183 gp = p; // Not OK. 184 } 185 186Additionally, when the parameter is a `block pointer 187<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction 188applies to copies of the block. For example: 189 190.. code-block:: c 191 192 typedef void (^BlockTy)(); 193 BlockTy g0, g1; 194 195 void nonescapingFunc(__attribute__((noescape)) BlockTy block) { 196 block(); // OK. 197 } 198 199 void escapingFunc(__attribute__((noescape)) BlockTy block) { 200 g0 = block; // Not OK. 201 g1 = Block_copy(block); // Not OK either. 202 } 203 204 }]; 205} 206 207def CarriesDependencyDocs : Documentation { 208 let Category = DocCatFunction; 209 let Content = [{ 210The ``carries_dependency`` attribute specifies dependency propagation into and 211out of functions. 212 213When specified on a function or Objective-C method, the ``carries_dependency`` 214attribute means that the return value carries a dependency out of the function, 215so that the implementation need not constrain ordering upon return from that 216function. Implementations of the function and its caller may choose to preserve 217dependencies instead of emitting memory ordering instructions such as fences. 218 219Note, this attribute does not change the meaning of the program, but may result 220in generation of more efficient code. 221 }]; 222} 223 224def CPUSpecificCPUDispatchDocs : Documentation { 225 let Category = DocCatFunction; 226 let Content = [{ 227The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and 228resolve multiversioned functions. This form of multiversioning provides a 229mechanism for declaring versions across translation units and manually 230specifying the resolved function list. A specified CPU defines a set of minimum 231features that are required for the function to be called. The result of this is 232that future processors execute the most restrictive version of the function the 233new processor can execute. 234 235Function versions are defined with ``cpu_specific``, which takes one or more CPU 236names as a parameter. For example: 237 238.. code-block:: c 239 240 // Declares and defines the ivybridge version of single_cpu. 241 __attribute__((cpu_specific(ivybridge))) 242 void single_cpu(void){} 243 244 // Declares and defines the atom version of single_cpu. 245 __attribute__((cpu_specific(atom))) 246 void single_cpu(void){} 247 248 // Declares and defines both the ivybridge and atom version of multi_cpu. 249 __attribute__((cpu_specific(ivybridge, atom))) 250 void multi_cpu(void){} 251 252A dispatching (or resolving) function can be declared anywhere in a project's 253source code with ``cpu_dispatch``. This attribute takes one or more CPU names 254as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch`` 255are not expected to be defined, only declared. If such a marked function has a 256definition, any side effects of the function are ignored; trivial function 257bodies are permissible for ICC compatibility. 258 259.. code-block:: c 260 261 // Creates a resolver for single_cpu above. 262 __attribute__((cpu_dispatch(ivybridge, atom))) 263 void single_cpu(void){} 264 265 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another 266 // translation unit. 267 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge))) 268 void multi_cpu(void){} 269 270Note that it is possible to have a resolving function that dispatches based on 271more or fewer options than are present in the program. Specifying fewer will 272result in the omitted options not being considered during resolution. Specifying 273a version for resolution that isn't defined in the program will result in a 274linking failure. 275 276It is also possible to specify a CPU name of ``generic`` which will be resolved 277if the executing processor doesn't satisfy the features required in the CPU 278name. The behavior of a program executing on a processor that doesn't satisfy 279any option of a multiversioned function is undefined. 280 }]; 281} 282 283def SYCLKernelDocs : Documentation { 284 let Category = DocCatFunction; 285 let Content = [{ 286The ``sycl_kernel`` attribute specifies that a function template will be used 287to outline device code and to generate an OpenCL kernel. 288Here is a code example of the SYCL program, which demonstrates the compiler's 289outlining job: 290 291.. code-block:: c++ 292 293 int foo(int x) { return ++x; } 294 295 using namespace cl::sycl; 296 queue Q; 297 buffer<int, 1> a(range<1>{1024}); 298 Q.submit([&](handler& cgh) { 299 auto A = a.get_access<access::mode::write>(cgh); 300 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) { 301 A[index] = index[0] + foo(42); 302 }); 303 } 304 305A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel". 306A SYCL kernel defines the entry point to the "device part" of the code. The 307compiler will emit all symbols accessible from a "kernel". In this code 308example, the compiler will emit "foo" function. More details about the 309compilation of functions for the device part can be found in the SYCL 1.2.1 310specification Section 6.4. 311To show to the compiler entry point to the "device part" of the code, the SYCL 312runtime can use the ``sycl_kernel`` attribute in the following way: 313 314.. code-block:: c++ 315 316 namespace cl { 317 namespace sycl { 318 class handler { 319 template <typename KernelName, typename KernelType/*, ...*/> 320 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) { 321 // ... 322 KernelFuncObj(); 323 } 324 325 template <typename KernelName, typename KernelType, int Dims> 326 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) { 327 #ifdef __SYCL_DEVICE_ONLY__ 328 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc); 329 #else 330 // Host implementation 331 #endif 332 } 333 }; 334 } // namespace sycl 335 } // namespace cl 336 337The compiler will also generate an OpenCL kernel using the function marked with 338the ``sycl_kernel`` attribute. 339Here is the list of SYCL device compiler expectations with regard to the 340function marked with the ``sycl_kernel`` attribute: 341 342- The function must be a template with at least two type template parameters. 343 The compiler generates an OpenCL kernel and uses the first template parameter 344 as a unique name for the generated OpenCL kernel. The host application uses 345 this unique name to invoke the OpenCL kernel generated for the SYCL kernel 346 specialized by this name and second template parameter ``KernelType`` (which 347 might be an unnamed function object type). 348- The function must have at least one parameter. The first parameter is 349 required to be a function object type (named or unnamed i.e. lambda). The 350 compiler uses function object type fields to generate OpenCL kernel 351 parameters. 352- The function must return void. The compiler reuses the body of marked functions to 353 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``. 354 355The SYCL kernel in the previous code sample meets these expectations. 356 }]; 357} 358 359def C11NoReturnDocs : Documentation { 360 let Category = DocCatFunction; 361 let Content = [{ 362A function declared as ``_Noreturn`` shall not return to its caller. The 363compiler will generate a diagnostic for a function declared as ``_Noreturn`` 364that appears to be capable of returning to its caller. Despite being a type 365specifier, the ``_Noreturn`` attribute cannot be specified on a function 366pointer type. 367 }]; 368} 369 370def CXX11NoReturnDocs : Documentation { 371 let Category = DocCatFunction; 372 let Content = [{ 373A function declared as ``[[noreturn]]`` shall not return to its caller. The 374compiler will generate a diagnostic for a function declared as ``[[noreturn]]`` 375that appears to be capable of returning to its caller. 376 }]; 377} 378 379def NoMergeDocs : Documentation { 380 let Category = DocCatStmt; 381 let Content = [{ 382If a statement is marked ``nomerge`` and contains call expressions, those call 383expressions inside the statement will not be merged during optimization. This 384attribute can be used to prevent the optimizer from obscuring the source 385location of certain calls. For example, it will prevent tail merging otherwise 386identical code sequences that raise an exception or terminate the program. Tail 387merging normally reduces the precision of source location information, making 388stack traces less useful for debugging. This attribute gives the user control 389over the tradeoff between code size and debug information precision. 390 391``nomerge`` attribute can also be used as function attribute to prevent all 392calls to the specified function from merging. It has no effect on indirect 393calls. 394 }]; 395} 396 397def AssertCapabilityDocs : Documentation { 398 let Category = DocCatFunction; 399 let Heading = "assert_capability, assert_shared_capability"; 400 let Content = [{ 401Marks a function that dynamically tests whether a capability is held, and halts 402the program if it is not held. 403 }]; 404} 405 406def AcquireCapabilityDocs : Documentation { 407 let Category = DocCatFunction; 408 let Heading = "acquire_capability, acquire_shared_capability"; 409 let Content = [{ 410Marks a function as acquiring a capability. 411 }]; 412} 413 414def TryAcquireCapabilityDocs : Documentation { 415 let Category = DocCatFunction; 416 let Heading = "try_acquire_capability, try_acquire_shared_capability"; 417 let Content = [{ 418Marks a function that attempts to acquire a capability. This function may fail to 419actually acquire the capability; they accept a Boolean value determining 420whether acquiring the capability means success (true), or failing to acquire 421the capability means success (false). 422 }]; 423} 424 425def ReleaseCapabilityDocs : Documentation { 426 let Category = DocCatFunction; 427 let Heading = "release_capability, release_shared_capability"; 428 let Content = [{ 429Marks a function as releasing a capability. 430 }]; 431} 432 433def AssumeAlignedDocs : Documentation { 434 let Category = DocCatFunction; 435 let Content = [{ 436Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function 437declaration to specify that the return value of the function (which must be a 438pointer type) has the specified offset, in bytes, from an address with the 439specified alignment. The offset is taken to be zero if omitted. 440 441.. code-block:: c++ 442 443 // The returned pointer value has 32-byte alignment. 444 void *a() __attribute__((assume_aligned (32))); 445 446 // The returned pointer value is 4 bytes greater than an address having 447 // 32-byte alignment. 448 void *b() __attribute__((assume_aligned (32, 4))); 449 450Note that this attribute provides information to the compiler regarding a 451condition that the code already ensures is true. It does not cause the compiler 452to enforce the provided alignment assumption. 453 }]; 454} 455 456def AllocSizeDocs : Documentation { 457 let Category = DocCatFunction; 458 let Content = [{ 459The ``alloc_size`` attribute can be placed on functions that return pointers in 460order to hint to the compiler how many bytes of memory will be available at the 461returned pointer. ``alloc_size`` takes one or two arguments. 462 463- ``alloc_size(N)`` implies that argument number N equals the number of 464 available bytes at the returned pointer. 465- ``alloc_size(N, M)`` implies that the product of argument number N and 466 argument number M equals the number of available bytes at the returned 467 pointer. 468 469Argument numbers are 1-based. 470 471An example of how to use ``alloc_size`` 472 473.. code-block:: c 474 475 void *my_malloc(int a) __attribute__((alloc_size(1))); 476 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); 477 478 int main() { 479 void *const p = my_malloc(100); 480 assert(__builtin_object_size(p, 0) == 100); 481 void *const a = my_calloc(20, 5); 482 assert(__builtin_object_size(a, 0) == 100); 483 } 484 485.. Note:: This attribute works differently in clang than it does in GCC. 486 Specifically, clang will only trace ``const`` pointers (as above); we give up 487 on pointers that are not marked as ``const``. In the vast majority of cases, 488 this is unimportant, because LLVM has support for the ``alloc_size`` 489 attribute. However, this may cause mildly unintuitive behavior when used with 490 other attributes, such as ``enable_if``. 491 }]; 492} 493 494def CodeSegDocs : Documentation { 495 let Category = DocCatFunction; 496 let Content = [{ 497The ``__declspec(code_seg)`` attribute enables the placement of code into separate 498named segments that can be paged or locked in memory individually. This attribute 499is used to control the placement of instantiated templates and compiler-generated 500code. See the documentation for `__declspec(code_seg)`_ on MSDN. 501 502.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx 503 }]; 504} 505 506def AllocAlignDocs : Documentation { 507 let Category = DocCatFunction; 508 let Content = [{ 509Use ``__attribute__((alloc_align(<alignment>))`` on a function 510declaration to specify that the return value of the function (which must be a 511pointer type) is at least as aligned as the value of the indicated parameter. The 512parameter is given by its index in the list of formal parameters; the first 513parameter has index 1 unless the function is a C++ non-static member function, 514in which case the first parameter has index 2 to account for the implicit ``this`` 515parameter. 516 517.. code-block:: c++ 518 519 // The returned pointer has the alignment specified by the first parameter. 520 void *a(size_t align) __attribute__((alloc_align(1))); 521 522 // The returned pointer has the alignment specified by the second parameter. 523 void *b(void *v, size_t align) __attribute__((alloc_align(2))); 524 525 // The returned pointer has the alignment specified by the second visible 526 // parameter, however it must be adjusted for the implicit 'this' parameter. 527 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3))); 528 529Note that this attribute merely informs the compiler that a function always 530returns a sufficiently aligned pointer. It does not cause the compiler to 531emit code to enforce that alignment. The behavior is undefined if the returned 532pointer is not sufficiently aligned. 533 }]; 534} 535 536def EnableIfDocs : Documentation { 537 let Category = DocCatFunction; 538 let Content = [{ 539.. Note:: Some features of this attribute are experimental. The meaning of 540 multiple enable_if attributes on a single declaration is subject to change in 541 a future version of clang. Also, the ABI is not standardized and the name 542 mangling may change in future versions. To avoid that, use asm labels. 543 544The ``enable_if`` attribute can be placed on function declarations to control 545which overload is selected based on the values of the function's arguments. 546When combined with the ``overloadable`` attribute, this feature is also 547available in C. 548 549.. code-block:: c++ 550 551 int isdigit(int c); 552 int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF"))); 553 554 void foo(char c) { 555 isdigit(c); 556 isdigit(10); 557 isdigit(-10); // results in a compile-time error. 558 } 559 560The enable_if attribute takes two arguments, the first is an expression written 561in terms of the function parameters, the second is a string explaining why this 562overload candidate could not be selected to be displayed in diagnostics. The 563expression is part of the function signature for the purposes of determining 564whether it is a redeclaration (following the rules used when determining 565whether a C++ template specialization is ODR-equivalent), but is not part of 566the type. 567 568The enable_if expression is evaluated as if it were the body of a 569bool-returning constexpr function declared with the arguments of the function 570it is being applied to, then called with the parameters at the call site. If the 571result is false or could not be determined through constant expression 572evaluation, then this overload will not be chosen and the provided string may 573be used in a diagnostic if the compile fails as a result. 574 575Because the enable_if expression is an unevaluated context, there are no global 576state changes, nor the ability to pass information from the enable_if 577expression to the function body. For example, suppose we want calls to 578strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of 579strbuf) only if the size of strbuf can be determined: 580 581.. code-block:: c++ 582 583 __attribute__((always_inline)) 584 static inline size_t strnlen(const char *s, size_t maxlen) 585 __attribute__((overloadable)) 586 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))), 587 "chosen when the buffer size is known but 'maxlen' is not"))) 588 { 589 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); 590 } 591 592Multiple enable_if attributes may be applied to a single declaration. In this 593case, the enable_if expressions are evaluated from left to right in the 594following manner. First, the candidates whose enable_if expressions evaluate to 595false or cannot be evaluated are discarded. If the remaining candidates do not 596share ODR-equivalent enable_if expressions, the overload resolution is 597ambiguous. Otherwise, enable_if overload resolution continues with the next 598enable_if attribute on the candidates that have not been discarded and have 599remaining enable_if attributes. In this way, we pick the most specific 600overload out of a number of viable overloads using enable_if. 601 602.. code-block:: c++ 603 604 void f() __attribute__((enable_if(true, ""))); // #1 605 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 606 607 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 608 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 609 610In this example, a call to f() is always resolved to #2, as the first enable_if 611expression is ODR-equivalent for both declarations, but #1 does not have another 612enable_if expression to continue evaluating, so the next round of evaluation has 613only a single candidate. In a call to g(1, 1), the call is ambiguous even though 614#2 has more enable_if attributes, because the first enable_if expressions are 615not ODR-equivalent. 616 617Query for this feature with ``__has_attribute(enable_if)``. 618 619Note that functions with one or more ``enable_if`` attributes may not have 620their address taken, unless all of the conditions specified by said 621``enable_if`` are constants that evaluate to ``true``. For example: 622 623.. code-block:: c 624 625 const int TrueConstant = 1; 626 const int FalseConstant = 0; 627 int f(int a) __attribute__((enable_if(a > 0, ""))); 628 int g(int a) __attribute__((enable_if(a == 0 || a != 0, ""))); 629 int h(int a) __attribute__((enable_if(1, ""))); 630 int i(int a) __attribute__((enable_if(TrueConstant, ""))); 631 int j(int a) __attribute__((enable_if(FalseConstant, ""))); 632 633 void fn() { 634 int (*ptr)(int); 635 ptr = &f; // error: 'a > 0' is not always true 636 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant 637 ptr = &h; // OK: 1 is a truthy constant 638 ptr = &i; // OK: 'TrueConstant' is a truthy constant 639 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy 640 } 641 642Because ``enable_if`` evaluation happens during overload resolution, 643``enable_if`` may give unintuitive results when used with templates, depending 644on when overloads are resolved. In the example below, clang will emit a 645diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``: 646 647.. code-block:: c++ 648 649 double foo(int i) __attribute__((enable_if(i > 0, ""))); 650 void *foo(int i) __attribute__((enable_if(i <= 0, ""))); 651 template <int I> 652 auto bar() { return foo(I); } 653 654 template <typename T> 655 auto baz() { return foo(T::number); } 656 657 struct WithNumber { constexpr static int number = 1; }; 658 void callThem() { 659 bar<sizeof(WithNumber)>(); 660 baz<WithNumber>(); 661 } 662 663This is because, in ``bar``, ``foo`` is resolved prior to template 664instantiation, so the value for ``I`` isn't known (thus, both ``enable_if`` 665conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during 666template instantiation, so the value for ``T::number`` is known. 667 }]; 668} 669 670def DiagnoseIfDocs : Documentation { 671 let Category = DocCatFunction; 672 let Content = [{ 673The ``diagnose_if`` attribute can be placed on function declarations to emit 674warnings or errors at compile-time if calls to the attributed function meet 675certain user-defined criteria. For example: 676 677.. code-block:: c 678 679 int abs(int a) 680 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning"))); 681 int must_abs(int a) 682 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error"))); 683 684 int val = abs(1); // warning: Redundant abs call 685 int val2 = must_abs(1); // error: Redundant abs call 686 int val3 = abs(val); 687 int val4 = must_abs(val); // Because run-time checks are not emitted for 688 // diagnose_if attributes, this executes without 689 // issue. 690 691 692``diagnose_if`` is closely related to ``enable_if``, with a few key differences: 693 694* Overload resolution is not aware of ``diagnose_if`` attributes: they're 695 considered only after we select the best candidate from a given candidate set. 696* Function declarations that differ only in their ``diagnose_if`` attributes are 697 considered to be redeclarations of the same function (not overloads). 698* If the condition provided to ``diagnose_if`` cannot be evaluated, no 699 diagnostic will be emitted. 700 701Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``. 702 703As a result of bullet number two, ``diagnose_if`` attributes will stack on the 704same function. For example: 705 706.. code-block:: c 707 708 int foo() __attribute__((diagnose_if(1, "diag1", "warning"))); 709 int foo() __attribute__((diagnose_if(1, "diag2", "warning"))); 710 711 int bar = foo(); // warning: diag1 712 // warning: diag2 713 int (*fooptr)(void) = foo; // warning: diag1 714 // warning: diag2 715 716 constexpr int supportsAPILevel(int N) { return N < 5; } 717 int baz(int a) 718 __attribute__((diagnose_if(!supportsAPILevel(10), 719 "Upgrade to API level 10 to use baz", "error"))); 720 int baz(int a) 721 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning"))); 722 723 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz 724 int v = baz(0); // error: Upgrade to API level 10 to use baz 725 726Query for this feature with ``__has_attribute(diagnose_if)``. 727 }]; 728} 729 730def PassObjectSizeDocs : Documentation { 731 let Category = DocCatVariable; // Technically it's a parameter doc, but eh. 732 let Heading = "pass_object_size, pass_dynamic_object_size"; 733 let Content = [{ 734.. Note:: The mangling of functions with parameters that are annotated with 735 ``pass_object_size`` is subject to change. You can get around this by 736 using ``__asm__("foo")`` to explicitly name your functions, thus preserving 737 your ABI; also, non-overloadable C functions with ``pass_object_size`` are 738 not mangled. 739 740The ``pass_object_size(Type)`` attribute can be placed on function parameters to 741instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite 742of said function, and implicitly pass the result of this call in as an invisible 743argument of type ``size_t`` directly after the parameter annotated with 744``pass_object_size``. Clang will also replace any calls to 745``__builtin_object_size(param, Type)`` in the function by said implicit 746parameter. 747 748Example usage: 749 750.. code-block:: c 751 752 int bzero1(char *const p __attribute__((pass_object_size(0)))) 753 __attribute__((noinline)) { 754 int i = 0; 755 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) { 756 p[i] = 0; 757 } 758 return i; 759 } 760 761 int main() { 762 char chars[100]; 763 int n = bzero1(&chars[0]); 764 assert(n == sizeof(chars)); 765 return 0; 766 } 767 768If successfully evaluating ``__builtin_object_size(param, Type)`` at the 769callsite is not possible, then the "failed" value is passed in. So, using the 770definition of ``bzero1`` from above, the following code would exit cleanly: 771 772.. code-block:: c 773 774 int main2(int argc, char *argv[]) { 775 int n = bzero1(argv); 776 assert(n == -1); 777 return 0; 778 } 779 780``pass_object_size`` plays a part in overload resolution. If two overload 781candidates are otherwise equally good, then the overload with one or more 782parameters with ``pass_object_size`` is preferred. This implies that the choice 783between two identical overloads both with ``pass_object_size`` on one or more 784parameters will always be ambiguous; for this reason, having two such overloads 785is illegal. For example: 786 787.. code-block:: c++ 788 789 #define PS(N) __attribute__((pass_object_size(N))) 790 // OK 791 void Foo(char *a, char *b); // Overload A 792 // OK -- overload A has no parameters with pass_object_size. 793 void Foo(char *a PS(0), char *b PS(0)); // Overload B 794 // Error -- Same signature (sans pass_object_size) as overload B, and both 795 // overloads have one or more parameters with the pass_object_size attribute. 796 void Foo(void *a PS(0), void *b); 797 798 // OK 799 void Bar(void *a PS(0)); // Overload C 800 // OK 801 void Bar(char *c PS(1)); // Overload D 802 803 void main() { 804 char known[10], *unknown; 805 Foo(unknown, unknown); // Calls overload B 806 Foo(known, unknown); // Calls overload B 807 Foo(unknown, known); // Calls overload B 808 Foo(known, known); // Calls overload B 809 810 Bar(known); // Calls overload D 811 Bar(unknown); // Calls overload D 812 } 813 814Currently, ``pass_object_size`` is a bit restricted in terms of its usage: 815 816* Only one use of ``pass_object_size`` is allowed per parameter. 817 818* It is an error to take the address of a function with ``pass_object_size`` on 819 any of its parameters. If you wish to do this, you can create an overload 820 without ``pass_object_size`` on any parameters. 821 822* It is an error to apply the ``pass_object_size`` attribute to parameters that 823 are not pointers. Additionally, any parameter that ``pass_object_size`` is 824 applied to must be marked ``const`` at its function's definition. 825 826Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves 827identically to ``pass_object_size``, but evaluates a call to 828``__builtin_dynamic_object_size`` at the callee instead of 829``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra 830runtime checks when the object size can't be determined at compile-time. You can 831read more about ``__builtin_dynamic_object_size`` `here 832<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_. 833 834 }]; 835} 836 837def OverloadableDocs : Documentation { 838 let Category = DocCatFunction; 839 let Content = [{ 840Clang provides support for C++ function overloading in C. Function overloading 841in C is introduced using the ``overloadable`` attribute. For example, one 842might provide several overloaded versions of a ``tgsin`` function that invokes 843the appropriate standard function computing the sine of a value with ``float``, 844``double``, or ``long double`` precision: 845 846.. code-block:: c 847 848 #include <math.h> 849 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } 850 double __attribute__((overloadable)) tgsin(double x) { return sin(x); } 851 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } 852 853Given these declarations, one can call ``tgsin`` with a ``float`` value to 854receive a ``float`` result, with a ``double`` to receive a ``double`` result, 855etc. Function overloading in C follows the rules of C++ function overloading 856to pick the best overload given the call arguments, with a few C-specific 857semantics: 858 859* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a 860 floating-point promotion (per C99) rather than as a floating-point conversion 861 (as in C++). 862 863* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is 864 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are 865 compatible types. 866 867* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` 868 and ``U`` are compatible types. This conversion is given "conversion" rank. 869 870* If no viable candidates are otherwise available, we allow a conversion from a 871 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are 872 incompatible. This conversion is ranked below all other types of conversions. 873 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient 874 for ``T`` and ``U`` to be incompatible. 875 876The declaration of ``overloadable`` functions is restricted to function 877declarations and definitions. If a function is marked with the ``overloadable`` 878attribute, then all declarations and definitions of functions with that name, 879except for at most one (see the note below about unmarked overloads), must have 880the ``overloadable`` attribute. In addition, redeclarations of a function with 881the ``overloadable`` attribute must have the ``overloadable`` attribute, and 882redeclarations of a function without the ``overloadable`` attribute must *not* 883have the ``overloadable`` attribute. e.g., 884 885.. code-block:: c 886 887 int f(int) __attribute__((overloadable)); 888 float f(float); // error: declaration of "f" must have the "overloadable" attribute 889 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute 890 891 int g(int) __attribute__((overloadable)); 892 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute 893 894 int h(int); 895 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not 896 // have the "overloadable" attribute 897 898Functions marked ``overloadable`` must have prototypes. Therefore, the 899following code is ill-formed: 900 901.. code-block:: c 902 903 int h() __attribute__((overloadable)); // error: h does not have a prototype 904 905However, ``overloadable`` functions are allowed to use a ellipsis even if there 906are no named parameters (as is permitted in C++). This feature is particularly 907useful when combined with the ``unavailable`` attribute: 908 909.. code-block:: c++ 910 911 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error 912 913Functions declared with the ``overloadable`` attribute have their names mangled 914according to the same rules as C++ function names. For example, the three 915``tgsin`` functions in our motivating example get the mangled names 916``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two 917caveats to this use of name mangling: 918 919* Future versions of Clang may change the name mangling of functions overloaded 920 in C, so you should not depend on an specific mangling. To be completely 921 safe, we strongly urge the use of ``static inline`` with ``overloadable`` 922 functions. 923 924* The ``overloadable`` attribute has almost no meaning when used in C++, 925 because names will already be mangled and functions are already overloadable. 926 However, when an ``overloadable`` function occurs within an ``extern "C"`` 927 linkage specification, it's name *will* be mangled in the same way as it 928 would in C. 929 930For the purpose of backwards compatibility, at most one function with the same 931name as other ``overloadable`` functions may omit the ``overloadable`` 932attribute. In this case, the function without the ``overloadable`` attribute 933will not have its name mangled. 934 935For example: 936 937.. code-block:: c 938 939 // Notes with mangled names assume Itanium mangling. 940 int f(int); 941 int f(double) __attribute__((overloadable)); 942 void foo() { 943 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that 944 // was marked with overloadable). 945 f(1.0); // Emits a call to _Z1fd. 946 } 947 948Support for unmarked overloads is not present in some versions of clang. You may 949query for it using ``__has_extension(overloadable_unmarked)``. 950 951Query for this attribute with ``__has_attribute(overloadable)``. 952 }]; 953} 954 955def ObjCMethodFamilyDocs : Documentation { 956 let Category = DocCatFunction; 957 let Content = [{ 958Many methods in Objective-C have conventional meanings determined by their 959selectors. It is sometimes useful to be able to mark a method as having a 960particular conventional meaning despite not having the right selector, or as 961not having the conventional meaning that its selector would suggest. For these 962use cases, we provide an attribute to specifically describe the "method family" 963that a method belongs to. 964 965**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of 966``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This 967attribute can only be placed at the end of a method declaration: 968 969.. code-block:: objc 970 971 - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); 972 973Users who do not wish to change the conventional meaning of a method, and who 974merely want to document its non-standard retain and release semantics, should 975use the retaining behavior attributes (``ns_returns_retained``, 976``ns_returns_not_retained``, etc). 977 978Query for this feature with ``__has_attribute(objc_method_family)``. 979 }]; 980} 981 982def RetainBehaviorDocs : Documentation { 983 let Category = DocCatFunction; 984 let Content = [{ 985The behavior of a function with respect to reference counting for Foundation 986(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming 987convention (e.g. functions starting with "get" are assumed to return at 988``+0``). 989 990It can be overridden using a family of the following attributes. In 991Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to 992a function communicates that the object is returned at ``+1``, and the caller 993is responsible for freeing it. 994Similarly, the annotation ``__attribute__((ns_returns_not_retained))`` 995specifies that the object is returned at ``+0`` and the ownership remains with 996the callee. 997The annotation ``__attribute__((ns_consumes_self))`` specifies that 998the Objective-C method call consumes the reference to ``self``, e.g. by 999attaching it to a supplied parameter. 1000Additionally, parameters can have an annotation 1001``__attribute__((ns_consumed))``, which specifies that passing an owned object 1002as that parameter effectively transfers the ownership, and the caller is no 1003longer responsible for it. 1004These attributes affect code generation when interacting with ARC code, and 1005they are used by the Clang Static Analyzer. 1006 1007In C programs using CoreFoundation, a similar set of attributes: 1008``__attribute__((cf_returns_not_retained))``, 1009``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))`` 1010have the same respective semantics when applied to CoreFoundation objects. 1011These attributes affect code generation when interacting with ARC code, and 1012they are used by the Clang Static Analyzer. 1013 1014Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), 1015the same attribute family is present: 1016``__attribute__((os_returns_not_retained))``, 1017``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``, 1018with the same respective semantics. 1019Similar to ``__attribute__((ns_consumes_self))``, 1020``__attribute__((os_consumes_this))`` specifies that the method call consumes 1021the reference to "this" (e.g., when attaching it to a different object supplied 1022as a parameter). 1023Out parameters (parameters the function is meant to write into, 1024either via pointers-to-pointers or references-to-pointers) 1025may be annotated with ``__attribute__((os_returns_retained))`` 1026or ``__attribute__((os_returns_not_retained))`` which specifies that the object 1027written into the out parameter should (or respectively should not) be released 1028after use. 1029Since often out parameters may or may not be written depending on the exit 1030code of the function, 1031annotations ``__attribute__((os_returns_retained_on_zero))`` 1032and ``__attribute__((os_returns_retained_on_non_zero))`` specify that 1033an out parameter at ``+1`` is written if and only if the function returns a zero 1034(respectively non-zero) error code. 1035Observe that return-code-dependent out parameter annotations are only 1036available for retained out parameters, as non-retained object do not have to be 1037released by the callee. 1038These attributes are only used by the Clang Static Analyzer. 1039 1040The family of attributes ``X_returns_X_retained`` can be added to functions, 1041C++ methods, and Objective-C methods and properties. 1042Attributes ``X_consumed`` can be added to parameters of methods, functions, 1043and Objective-C methods. 1044 }]; 1045} 1046 1047def NoDebugDocs : Documentation { 1048 let Category = DocCatVariable; 1049 let Content = [{ 1050The ``nodebug`` attribute allows you to suppress debugging information for a 1051function or method, or for a variable that is not a parameter or a non-static 1052data member. 1053 }]; 1054} 1055 1056def NoDuplicateDocs : Documentation { 1057 let Category = DocCatFunction; 1058 let Content = [{ 1059The ``noduplicate`` attribute can be placed on function declarations to control 1060whether function calls to this function can be duplicated or not as a result of 1061optimizations. This is required for the implementation of functions with 1062certain special requirements, like the OpenCL "barrier" function, that might 1063need to be run concurrently by all the threads that are executing in lockstep 1064on the hardware. For example this attribute applied on the function 1065"nodupfunc" in the code below avoids that: 1066 1067.. code-block:: c 1068 1069 void nodupfunc() __attribute__((noduplicate)); 1070 // Setting it as a C++11 attribute is also valid 1071 // void nodupfunc() [[clang::noduplicate]]; 1072 void foo(); 1073 void bar(); 1074 1075 nodupfunc(); 1076 if (a > n) { 1077 foo(); 1078 } else { 1079 bar(); 1080 } 1081 1082gets possibly modified by some optimizations into code similar to this: 1083 1084.. code-block:: c 1085 1086 if (a > n) { 1087 nodupfunc(); 1088 foo(); 1089 } else { 1090 nodupfunc(); 1091 bar(); 1092 } 1093 1094where the call to "nodupfunc" is duplicated and sunk into the two branches 1095of the condition. 1096 }]; 1097} 1098 1099def ConvergentDocs : Documentation { 1100 let Category = DocCatFunction; 1101 let Content = [{ 1102The ``convergent`` attribute can be placed on a function declaration. It is 1103translated into the LLVM ``convergent`` attribute, which indicates that the call 1104instructions of a function with this attribute cannot be made control-dependent 1105on any additional values. 1106 1107In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA, 1108the call instructions of a function with this attribute must be executed by 1109all work items or threads in a work group or sub group. 1110 1111This attribute is different from ``noduplicate`` because it allows duplicating 1112function calls if it can be proved that the duplicated function calls are 1113not made control-dependent on any additional values, e.g., unrolling a loop 1114executed by all work items. 1115 1116Sample usage: 1117 1118.. code-block:: c 1119 1120 void convfunc(void) __attribute__((convergent)); 1121 // Setting it as a C++11 attribute is also valid in a C++ program. 1122 // void convfunc(void) [[clang::convergent]]; 1123 1124 }]; 1125} 1126 1127def NoSplitStackDocs : Documentation { 1128 let Category = DocCatFunction; 1129 let Content = [{ 1130The ``no_split_stack`` attribute disables the emission of the split stack 1131preamble for a particular function. It has no effect if ``-fsplit-stack`` 1132is not specified. 1133 }]; 1134} 1135 1136def NoUniqueAddressDocs : Documentation { 1137 let Category = DocCatField; 1138 let Content = [{ 1139The ``no_unique_address`` attribute allows tail padding in a non-static data 1140member to overlap other members of the enclosing class (and in the special 1141case when the type is empty, permits it to fully overlap other members). 1142The field is laid out as if a base class were encountered at the corresponding 1143point within the class (except that it does not share a vptr with the enclosing 1144object). 1145 1146Example usage: 1147 1148.. code-block:: c++ 1149 1150 template<typename T, typename Alloc> struct my_vector { 1151 T *p; 1152 [[no_unique_address]] Alloc alloc; 1153 // ... 1154 }; 1155 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*)); 1156 1157``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use 1158in C++11 onwards. 1159 }]; 1160} 1161 1162def ObjCRequiresSuperDocs : Documentation { 1163 let Category = DocCatFunction; 1164 let Content = [{ 1165Some Objective-C classes allow a subclass to override a particular method in a 1166parent class but expect that the overriding method also calls the overridden 1167method in the parent class. For these cases, we provide an attribute to 1168designate that a method requires a "call to ``super``" in the overriding 1169method in the subclass. 1170 1171**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only 1172be placed at the end of a method declaration: 1173 1174.. code-block:: objc 1175 1176 - (void)foo __attribute__((objc_requires_super)); 1177 1178This attribute can only be applied the method declarations within a class, and 1179not a protocol. Currently this attribute does not enforce any placement of 1180where the call occurs in the overriding method (such as in the case of 1181``-dealloc`` where the call must appear at the end). It checks only that it 1182exists. 1183 1184Note that on both OS X and iOS that the Foundation framework provides a 1185convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this 1186attribute: 1187 1188.. code-block:: objc 1189 1190 - (void)foo NS_REQUIRES_SUPER; 1191 1192This macro is conditionally defined depending on the compiler's support for 1193this attribute. If the compiler does not support the attribute the macro 1194expands to nothing. 1195 1196Operationally, when a method has this annotation the compiler will warn if the 1197implementation of an override in a subclass does not call super. For example: 1198 1199.. code-block:: objc 1200 1201 warning: method possibly missing a [super AnnotMeth] call 1202 - (void) AnnotMeth{}; 1203 ^ 1204 }]; 1205} 1206 1207def ObjCRuntimeNameDocs : Documentation { 1208 let Category = DocCatDecl; 1209 let Content = [{ 1210By default, the Objective-C interface or protocol identifier is used 1211in the metadata name for that object. The ``objc_runtime_name`` 1212attribute allows annotated interfaces or protocols to use the 1213specified string argument in the object's metadata name instead of the 1214default name. 1215 1216**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute 1217can only be placed before an @protocol or @interface declaration: 1218 1219.. code-block:: objc 1220 1221 __attribute__((objc_runtime_name("MyLocalName"))) 1222 @interface Message 1223 @end 1224 1225 }]; 1226} 1227 1228def ObjCRuntimeVisibleDocs : Documentation { 1229 let Category = DocCatDecl; 1230 let Content = [{ 1231This attribute specifies that the Objective-C class to which it applies is 1232visible to the Objective-C runtime but not to the linker. Classes annotated 1233with this attribute cannot be subclassed and cannot have categories defined for 1234them. 1235 }]; 1236} 1237 1238def ObjCClassStubDocs : Documentation { 1239 let Category = DocCatType; 1240 let Content = [{ 1241This attribute specifies that the Objective-C class to which it applies is 1242instantiated at runtime. 1243 1244Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute 1245still has a "class stub" that is visible to the linker. This allows categories 1246to be defined. Static message sends with the class as a receiver use a special 1247access pattern to ensure the class is lazily instantiated from the class stub. 1248 1249Classes annotated with this attribute cannot be subclassed and cannot have 1250implementations defined for them. This attribute is intended for use in 1251Swift-generated headers for classes defined in Swift. 1252 1253Adding or removing this attribute to a class is an ABI-breaking change. 1254 }]; 1255} 1256 1257def ObjCBoxableDocs : Documentation { 1258 let Category = DocCatDecl; 1259 let Content = [{ 1260Structs and unions marked with the ``objc_boxable`` attribute can be used 1261with the Objective-C boxed expression syntax, ``@(...)``. 1262 1263**Usage**: ``__attribute__((objc_boxable))``. This attribute 1264can only be placed on a declaration of a trivially-copyable struct or union: 1265 1266.. code-block:: objc 1267 1268 struct __attribute__((objc_boxable)) some_struct { 1269 int i; 1270 }; 1271 union __attribute__((objc_boxable)) some_union { 1272 int i; 1273 float f; 1274 }; 1275 typedef struct __attribute__((objc_boxable)) _some_struct some_struct; 1276 1277 // ... 1278 1279 some_struct ss; 1280 NSValue *boxed = @(ss); 1281 1282 }]; 1283} 1284 1285def AvailabilityDocs : Documentation { 1286 let Category = DocCatFunction; 1287 let Content = [{ 1288The ``availability`` attribute can be placed on declarations to describe the 1289lifecycle of that declaration relative to operating system versions. Consider 1290the function declaration for a hypothetical function ``f``: 1291 1292.. code-block:: c++ 1293 1294 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7))); 1295 1296The availability attribute states that ``f`` was introduced in macOS 10.4, 1297deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information 1298is used by Clang to determine when it is safe to use ``f``: for example, if 1299Clang is instructed to compile code for macOS 10.5, a call to ``f()`` 1300succeeds. If Clang is instructed to compile code for macOS 10.6, the call 1301succeeds but Clang emits a warning specifying that the function is deprecated. 1302Finally, if Clang is instructed to compile code for macOS 10.7, the call 1303fails because ``f()`` is no longer available. 1304 1305The availability attribute is a comma-separated list starting with the 1306platform name and then including clauses specifying important milestones in the 1307declaration's lifetime (in any order) along with additional information. Those 1308clauses can be: 1309 1310introduced=\ *version* 1311 The first version in which this declaration was introduced. 1312 1313deprecated=\ *version* 1314 The first version in which this declaration was deprecated, meaning that 1315 users should migrate away from this API. 1316 1317obsoleted=\ *version* 1318 The first version in which this declaration was obsoleted, meaning that it 1319 was removed completely and can no longer be used. 1320 1321unavailable 1322 This declaration is never available on this platform. 1323 1324message=\ *string-literal* 1325 Additional message text that Clang will provide when emitting a warning or 1326 error about use of a deprecated or obsoleted declaration. Useful to direct 1327 users to replacement APIs. 1328 1329replacement=\ *string-literal* 1330 Additional message text that Clang will use to provide Fix-It when emitting 1331 a warning about use of a deprecated declaration. The Fix-It will replace 1332 the deprecated declaration with the new declaration specified. 1333 1334Multiple availability attributes can be placed on a declaration, which may 1335correspond to different platforms. For most platforms, the availability 1336attribute with the platform corresponding to the target platform will be used; 1337any others will be ignored. However, the availability for ``watchOS`` and 1338``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute. 1339Any explicit availability attributes for those platforms are still preferred over 1340the implicitly inferred availability attributes. If no availability attribute 1341specifies availability for the current target platform, the availability 1342attributes are ignored. Supported platforms are: 1343 1344``ios`` 1345 Apple's iOS operating system. The minimum deployment target is specified by 1346 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` 1347 command-line arguments. 1348 1349``macos`` 1350 Apple's macOS operating system. The minimum deployment target is 1351 specified by the ``-mmacosx-version-min=*version*`` command-line argument. 1352 ``macosx`` is supported for backward-compatibility reasons, but it is 1353 deprecated. 1354 1355``tvos`` 1356 Apple's tvOS operating system. The minimum deployment target is specified by 1357 the ``-mtvos-version-min=*version*`` command-line argument. 1358 1359``watchos`` 1360 Apple's watchOS operating system. The minimum deployment target is specified by 1361 the ``-mwatchos-version-min=*version*`` command-line argument. 1362 1363A declaration can typically be used even when deploying back to a platform 1364version prior to when the declaration was introduced. When this happens, the 1365declaration is `weakly linked 1366<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, 1367as if the ``weak_import`` attribute were added to the declaration. A 1368weakly-linked declaration may or may not be present a run-time, and a program 1369can determine whether the declaration is present by checking whether the 1370address of that declaration is non-NULL. 1371 1372The flag ``strict`` disallows using API when deploying back to a 1373platform version prior to when the declaration was introduced. An 1374attempt to use such API before its introduction causes a hard error. 1375Weakly-linking is almost always a better API choice, since it allows 1376users to query availability at runtime. 1377 1378If there are multiple declarations of the same entity, the availability 1379attributes must either match on a per-platform basis or later 1380declarations must not have availability attributes for that 1381platform. For example: 1382 1383.. code-block:: c 1384 1385 void g(void) __attribute__((availability(macos,introduced=10.4))); 1386 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches 1387 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform 1388 void g(void); // okay, inherits both macos and ios availability from above. 1389 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch 1390 1391When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: 1392 1393.. code-block:: objc 1394 1395 @interface A 1396 - (id)method __attribute__((availability(macos,introduced=10.4))); 1397 - (id)method2 __attribute__((availability(macos,introduced=10.4))); 1398 @end 1399 1400 @interface B : A 1401 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later 1402 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4 1403 @end 1404 1405Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from 1406``<os/availability.h>`` can simplify the spelling: 1407 1408.. code-block:: objc 1409 1410 @interface A 1411 - (id)method API_AVAILABLE(macos(10.11))); 1412 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0)); 1413 @end 1414 1415Availability attributes can also be applied using a ``#pragma clang attribute``. 1416Any explicit availability attribute whose platform corresponds to the target 1417platform is applied to a declaration regardless of the availability attributes 1418specified in the pragma. For example, in the code below, 1419``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability 1420attribute that is specified with the declaration, whereas 1421``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability 1422attribute that is applied by the pragma. 1423 1424.. code-block:: c 1425 1426 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function) 1427 void getsThePragmaAvailabilityAttribute(void); 1428 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4))); 1429 #pragma clang attribute pop 1430 1431For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can 1432be implicitly inferred from an ``iOS`` availability attribute, the logic is 1433slightly more complex. The explicit and the pragma-applied availability 1434attributes whose platform corresponds to the target platform are applied as 1435described in the previous paragraph. However, the implicitly inferred attributes 1436are applied to a declaration only when there is no explicit or pragma-applied 1437availability attribute whose platform corresponds to the target platform. For 1438example, the function below will receive the ``tvOS`` availability from the 1439pragma rather than using the inferred ``iOS`` availability from the declaration: 1440 1441.. code-block:: c 1442 1443 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function) 1444 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0))); 1445 #pragma clang attribute pop 1446 1447The compiler is also able to apply implicitly inferred attributes from a pragma 1448as well. For example, when targeting ``tvOS``, the function below will receive 1449a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS`` 1450availability attribute applied by the pragma: 1451 1452.. code-block:: c 1453 1454 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function) 1455 void infersTVOSAvailabilityFromPragma(void); 1456 #pragma clang attribute pop 1457 1458The implicit attributes that are inferred from explicitly specified attributes 1459whose platform corresponds to the target platform are applied to the declaration 1460even if there is an availability attribute that can be inferred from a pragma. 1461For example, the function below will receive the ``tvOS, introduced=11.0`` 1462availability that is inferred from the attribute on the declaration rather than 1463inferring availability from the pragma: 1464 1465.. code-block:: c 1466 1467 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function) 1468 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void) 1469 __attribute__((availability(iOS,introduced=11.0))); 1470 #pragma clang attribute pop 1471 1472Also see the documentation for `@available 1473<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_ 1474 }]; 1475} 1476 1477def ExternalSourceSymbolDocs : Documentation { 1478 let Category = DocCatDecl; 1479 let Content = [{ 1480The ``external_source_symbol`` attribute specifies that a declaration originates 1481from an external source and describes the nature of that source. 1482 1483The fact that Clang is capable of recognizing declarations that were defined 1484externally can be used to provide better tooling support for mixed-language 1485projects or projects that rely on auto-generated code. For instance, an IDE that 1486uses Clang and that supports mixed-language projects can use this attribute to 1487provide a correct 'jump-to-definition' feature. For a concrete example, 1488consider a protocol that's defined in a Swift file: 1489 1490.. code-block:: swift 1491 1492 @objc public protocol SwiftProtocol { 1493 func method() 1494 } 1495 1496This protocol can be used from Objective-C code by including a header file that 1497was generated by the Swift compiler. The declarations in that header can use 1498the ``external_source_symbol`` attribute to make Clang aware of the fact 1499that ``SwiftProtocol`` actually originates from a Swift module: 1500 1501.. code-block:: objc 1502 1503 __attribute__((external_source_symbol(language="Swift",defined_in="module"))) 1504 @protocol SwiftProtocol 1505 @required 1506 - (void) method; 1507 @end 1508 1509Consequently, when 'jump-to-definition' is performed at a location that 1510references ``SwiftProtocol``, the IDE can jump to the original definition in 1511the Swift source file rather than jumping to the Objective-C declaration in the 1512auto-generated header file. 1513 1514The ``external_source_symbol`` attribute is a comma-separated list that includes 1515clauses that describe the origin and the nature of the particular declaration. 1516Those clauses can be: 1517 1518language=\ *string-literal* 1519 The name of the source language in which this declaration was defined. 1520 1521defined_in=\ *string-literal* 1522 The name of the source container in which the declaration was defined. The 1523 exact definition of source container is language-specific, e.g. Swift's 1524 source containers are modules, so ``defined_in`` should specify the Swift 1525 module name. 1526 1527generated_declaration 1528 This declaration was automatically generated by some tool. 1529 1530The clauses can be specified in any order. The clauses that are listed above are 1531all optional, but the attribute has to have at least one clause. 1532 }]; 1533} 1534 1535def ConstInitDocs : Documentation { 1536 let Category = DocCatVariable; 1537 let Heading = "require_constant_initialization, constinit (C++20)"; 1538 let Content = [{ 1539This attribute specifies that the variable to which it is attached is intended 1540to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_ 1541according to the rules of [basic.start.static]. The variable is required to 1542have static or thread storage duration. If the initialization of the variable 1543is not a constant initializer an error will be produced. This attribute may 1544only be used in C++; the ``constinit`` spelling is only accepted in C++20 1545onwards. 1546 1547Note that in C++03 strict constant expression checking is not done. Instead 1548the attribute reports if Clang can emit the variable as a constant, even if it's 1549not technically a 'constant initializer'. This behavior is non-portable. 1550 1551Static storage duration variables with constant initializers avoid hard-to-find 1552bugs caused by the indeterminate order of dynamic initialization. They can also 1553be safely used during dynamic initialization across translation units. 1554 1555This attribute acts as a compile time assertion that the requirements 1556for constant initialization have been met. Since these requirements change 1557between dialects and have subtle pitfalls it's important to fail fast instead 1558of silently falling back on dynamic initialization. 1559 1560The first use of the attribute on a variable must be part of, or precede, the 1561initializing declaration of the variable. C++20 requires the ``constinit`` 1562spelling of the attribute to be present on the initializing declaration if it 1563is used anywhere. The other spellings can be specified on a forward declaration 1564and omitted on a later initializing declaration. 1565 1566.. code-block:: c++ 1567 1568 // -std=c++14 1569 #define SAFE_STATIC [[clang::require_constant_initialization]] 1570 struct T { 1571 constexpr T(int) {} 1572 ~T(); // non-trivial 1573 }; 1574 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor. 1575 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer 1576 // copy initialization is not a constant expression on a non-literal type. 1577 }]; 1578} 1579 1580def WarnMaybeUnusedDocs : Documentation { 1581 let Category = DocCatVariable; 1582 let Heading = "maybe_unused, unused"; 1583 let Content = [{ 1584When passing the ``-Wunused`` flag to Clang, entities that are unused by the 1585program may be diagnosed. The ``[[maybe_unused]]`` (or 1586``__attribute__((unused))``) attribute can be used to silence such diagnostics 1587when the entity cannot be removed. For instance, a local variable may exist 1588solely for use in an ``assert()`` statement, which makes the local variable 1589unused when ``NDEBUG`` is defined. 1590 1591The attribute may be applied to the declaration of a class, a typedef, a 1592variable, a function or method, a function parameter, an enumeration, an 1593enumerator, a non-static data member, or a label. 1594 1595.. code-block: c++ 1596 #include <cassert> 1597 1598 [[maybe_unused]] void f([[maybe_unused]] bool thing1, 1599 [[maybe_unused]] bool thing2) { 1600 [[maybe_unused]] bool b = thing1 && thing2; 1601 assert(b); 1602 } 1603 }]; 1604} 1605 1606def WarnUnusedResultsDocs : Documentation { 1607 let Category = DocCatFunction; 1608 let Heading = "nodiscard, warn_unused_result"; 1609 let Content = [{ 1610Clang supports the ability to diagnose when the results of a function call 1611expression are discarded under suspicious circumstances. A diagnostic is 1612generated when a function or its return type is marked with ``[[nodiscard]]`` 1613(or ``__attribute__((warn_unused_result))``) and the function call appears as a 1614potentially-evaluated discarded-value expression that is not explicitly cast to 1615``void``. 1616 1617A string literal may optionally be provided to the attribute, which will be 1618reproduced in any resulting diagnostics. Redeclarations using different forms 1619of the attribute (with or without the string literal or with different string 1620literal contents) are allowed. If there are redeclarations of the entity with 1621differing string literals, it is unspecified which one will be used by Clang 1622in any resulting diagnostics. 1623 1624.. code-block: c++ 1625 struct [[nodiscard]] error_info { /*...*/ }; 1626 error_info enable_missile_safety_mode(); 1627 1628 void launch_missiles(); 1629 void test_missiles() { 1630 enable_missile_safety_mode(); // diagnoses 1631 launch_missiles(); 1632 } 1633 error_info &foo(); 1634 void f() { foo(); } // Does not diagnose, error_info is a reference. 1635 1636Additionally, discarded temporaries resulting from a call to a constructor 1637marked with ``[[nodiscard]]`` or a constructor of a type marked 1638``[[nodiscard]]`` will also diagnose. This also applies to type conversions that 1639use the annotated ``[[nodiscard]]`` constructor or result in an annotated type. 1640 1641.. code-block: c++ 1642 struct [[nodiscard]] marked_type {/*..*/ }; 1643 struct marked_ctor { 1644 [[nodiscard]] marked_ctor(); 1645 marked_ctor(int); 1646 }; 1647 1648 struct S { 1649 operator marked_type() const; 1650 [[nodiscard]] operator int() const; 1651 }; 1652 1653 void usages() { 1654 marked_type(); // diagnoses. 1655 marked_ctor(); // diagnoses. 1656 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard. 1657 1658 S s; 1659 static_cast<marked_type>(s); // diagnoses 1660 (int)s; // diagnoses 1661 } 1662 }]; 1663} 1664 1665def FallthroughDocs : Documentation { 1666 let Category = DocCatStmt; 1667 let Heading = "fallthrough"; 1668 let Content = [{ 1669The ``fallthrough`` (or ``clang::fallthrough``) attribute is used 1670to annotate intentional fall-through 1671between switch labels. It can only be applied to a null statement placed at a 1672point of execution between any statement and the next switch label. It is 1673common to mark these places with a specific comment, but this attribute is 1674meant to replace comments with a more strict annotation, which can be checked 1675by the compiler. This attribute doesn't change semantics of the code and can 1676be used wherever an intended fall-through occurs. It is designed to mimic 1677control-flow statements like ``break;``, so it can be placed in most places 1678where ``break;`` can, but only if there are no statements on the execution path 1679between it and the next switch label. 1680 1681By default, Clang does not warn on unannotated fallthrough from one ``switch`` 1682case to another. Diagnostics on fallthrough without a corresponding annotation 1683can be enabled with the ``-Wimplicit-fallthrough`` argument. 1684 1685Here is an example: 1686 1687.. code-block:: c++ 1688 1689 // compile with -Wimplicit-fallthrough 1690 switch (n) { 1691 case 22: 1692 case 33: // no warning: no statements between case labels 1693 f(); 1694 case 44: // warning: unannotated fall-through 1695 g(); 1696 [[clang::fallthrough]]; 1697 case 55: // no warning 1698 if (x) { 1699 h(); 1700 break; 1701 } 1702 else { 1703 i(); 1704 [[clang::fallthrough]]; 1705 } 1706 case 66: // no warning 1707 p(); 1708 [[clang::fallthrough]]; // warning: fallthrough annotation does not 1709 // directly precede case label 1710 q(); 1711 case 77: // warning: unannotated fall-through 1712 r(); 1713 } 1714 }]; 1715} 1716 1717def LikelihoodDocs : Documentation { 1718 let Category = DocCatStmt; 1719 let Heading = "likely and unlikely"; 1720 let Content = [{ 1721The ``likely`` and ``unlikely`` attributes are used as compiler hints. 1722The attributes are used to aid the compiler to determine which branch is 1723likely or unlikely to be taken. This is done by marking the branch substatement 1724with one of the two attributes. 1725 1726It isn't allowed to annotate a single statement with both ``likely`` and 1727``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if`` 1728statement with the same likelihood attribute will result in a diagnostic and 1729the attributes are ignored on both branches. 1730 1731In a ``switch`` statement it's allowed to annotate multiple ``case`` labels 1732or the ``default`` label with the same likelihood attribute. This makes 1733* all labels without an attribute have a neutral likelihood, 1734* all labels marked ``[[likely]]`` have an equally positive likelihood, and 1735* all labels marked ``[[unlikely]]`` have an equally negative likelihood. 1736The neutral likelihood is the more likely of path execution than the negative 1737likelihood. The positive likelihood is the more likely of path of execution 1738than the neutral likelihood. 1739 1740These attributes have no effect on the generated code when using 1741PGO (Profile-Guided Optimization) or at optimization level 0. 1742 1743In Clang, the attributes will be ignored if they're not placed on 1744* the ``case`` or ``default`` label of a ``switch`` statement, 1745* or on the substatement of an ``if`` or ``else`` statement, 1746* or on the substatement of an ``for`` or ``while`` statement. 1747The C++ Standard recommends to honor them on every statement in the 1748path of execution, but that can be confusing: 1749 1750.. code-block:: c++ 1751 1752 if (b) { 1753 [[unlikely]] --b; // In the path of execution, 1754 // this branch is considered unlikely. 1755 } 1756 1757 if (b) { 1758 --b; 1759 if(b) 1760 return; 1761 [[unlikely]] --b; // Not in the path of execution, 1762 } // the branch has no likelihood information. 1763 1764 if (b) { 1765 --b; 1766 foo(b); 1767 // Whether or not the next statement is in the path of execution depends 1768 // on the declaration of foo(): 1769 // In the path of execution: void foo(int); 1770 // Not in the path of execution: [[noreturn]] void foo(int); 1771 // This means the likelihood of the branch depends on the declaration 1772 // of foo(). 1773 [[unlikely]] --b; 1774 } 1775 1776 1777Below are some example usages of the likelihood attributes and their effects: 1778 1779.. code-block:: c++ 1780 1781 if (b) [[likely]] { // Placement on the first statement in the branch. 1782 // The compiler will optimize to execute the code here. 1783 } else { 1784 } 1785 1786 if (b) 1787 [[unlikely]] b++; // Placement on the first statement in the branch. 1788 else { 1789 // The compiler will optimize to execute the code here. 1790 } 1791 1792 if (b) { 1793 [[unlikely]] b++; // Placement on the second statement in the branch. 1794 } // The attribute will be ignored. 1795 1796 if (b) [[likely]] { 1797 [[unlikely]] b++; // No contradiction since the second attribute 1798 } // is ignored. 1799 1800 if (b) 1801 ; 1802 else [[likely]] { 1803 // The compiler will optimize to execute the code here. 1804 } 1805 1806 if (b) 1807 ; 1808 else 1809 // The compiler will optimize to execute the next statement. 1810 [[likely]] b = f(); 1811 1812 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued 1813 else [[likely]]; // and the attributes are ignored. 1814 1815 if (b) 1816 [[likely]] int i = 5; // Issues a diagnostic since the attribute 1817 // isn't allowed on a declaration. 1818 1819 switch (i) { 1820 [[likely]] case 1: // This value is likely 1821 ... 1822 break; 1823 1824 [[unlikely]] case 2: // This value is unlikely 1825 ... 1826 [[fallthrough]]; 1827 1828 case 3: // No likelihood attribute 1829 ... 1830 [[likely]] break; // No effect 1831 1832 case 4: [[likely]] { // attribute on substatement has no effect 1833 ... 1834 break; 1835 } 1836 1837 [[unlikely]] default: // All other values are unlikely 1838 ... 1839 break; 1840 } 1841 1842 switch (i) { 1843 [[likely]] case 0: // This value and code path is likely 1844 ... 1845 [[fallthrough]]; 1846 1847 case 1: // No likelihood attribute, code path is neutral 1848 break; // falling through has no effect on the likelihood 1849 1850 case 2: // No likelihood attribute, code path is neutral 1851 [[fallthrough]]; 1852 1853 [[unlikely]] default: // This value and code path are both unlikely 1854 break; 1855 } 1856 1857 for(int i = 0; i != size; ++i) [[likely]] { 1858 ... // The loop is the likely path of execution 1859 } 1860 1861 for(const auto &E : Elements) [[likely]] { 1862 ... // The loop is the likely path of execution 1863 } 1864 1865 while(i != size) [[unlikely]] { 1866 ... // The loop is the unlikely path of execution 1867 } // The generated code will optimize to skip the loop body 1868 1869 while(true) [[unlikely]] { 1870 ... // The attribute has no effect 1871 } // Clang elides the comparison and generates an infinite 1872 // loop 1873 1874 }]; 1875} 1876 1877def ARMInterruptDocs : Documentation { 1878 let Category = DocCatFunction; 1879 let Heading = "interrupt (ARM)"; 1880 let Content = [{ 1881Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on 1882ARM targets. This attribute may be attached to a function definition and 1883instructs the backend to generate appropriate function entry/exit code so that 1884it can be used directly as an interrupt service routine. 1885 1886The parameter passed to the interrupt attribute is optional, but if 1887provided it must be a string literal with one of the following values: "IRQ", 1888"FIQ", "SWI", "ABORT", "UNDEF". 1889 1890The semantics are as follows: 1891 1892- If the function is AAPCS, Clang instructs the backend to realign the stack to 1893 8 bytes on entry. This is a general requirement of the AAPCS at public 1894 interfaces, but may not hold when an exception is taken. Doing this allows 1895 other AAPCS functions to be called. 1896- If the CPU is M-class this is all that needs to be done since the architecture 1897 itself is designed in such a way that functions obeying the normal AAPCS ABI 1898 constraints are valid exception handlers. 1899- If the CPU is not M-class, the prologue and epilogue are modified to save all 1900 non-banked registers that are used, so that upon return the user-mode state 1901 will not be corrupted. Note that to avoid unnecessary overhead, only 1902 general-purpose (integer) registers are saved in this way. If VFP operations 1903 are needed, that state must be saved manually. 1904 1905 Specifically, interrupt kinds other than "FIQ" will save all core registers 1906 except "lr" and "sp". "FIQ" interrupts will save r0-r7. 1907- If the CPU is not M-class, the return instruction is changed to one of the 1908 canonical sequences permitted by the architecture for exception return. Where 1909 possible the function itself will make the necessary "lr" adjustments so that 1910 the "preferred return address" is selected. 1911 1912 Unfortunately the compiler is unable to make this guarantee for an "UNDEF" 1913 handler, where the offset from "lr" to the preferred return address depends on 1914 the execution state of the code which generated the exception. In this case 1915 a sequence equivalent to "movs pc, lr" will be used. 1916 }]; 1917} 1918 1919def BPFPreserveAccessIndexDocs : Documentation { 1920 let Category = DocCatFunction; 1921 let Content = [{ 1922Clang supports the ``__attribute__((preserve_access_index))`` 1923attribute for the BPF target. This attribute may be attached to a 1924struct or union declaration, where if -g is specified, it enables 1925preserving struct or union member access debuginfo indices of this 1926struct or union, similar to clang ``__builtin_preserve_access_index()``. 1927 }]; 1928} 1929 1930def MipsInterruptDocs : Documentation { 1931 let Category = DocCatFunction; 1932 let Heading = "interrupt (MIPS)"; 1933 let Content = [{ 1934Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on 1935MIPS targets. This attribute may be attached to a function definition and instructs 1936the backend to generate appropriate function entry/exit code so that it can be used 1937directly as an interrupt service routine. 1938 1939By default, the compiler will produce a function prologue and epilogue suitable for 1940an interrupt service routine that handles an External Interrupt Controller (eic) 1941generated interrupt. This behavior can be explicitly requested with the "eic" 1942argument. 1943 1944Otherwise, for use with vectored interrupt mode, the argument passed should be 1945of the form "vector=LEVEL" where LEVEL is one of the following values: 1946"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will 1947then set the interrupt mask to the corresponding level which will mask all 1948interrupts up to and including the argument. 1949 1950The semantics are as follows: 1951 1952- The prologue is modified so that the Exception Program Counter (EPC) and 1953 Status coprocessor registers are saved to the stack. The interrupt mask is 1954 set so that the function can only be interrupted by a higher priority 1955 interrupt. The epilogue will restore the previous values of EPC and Status. 1956 1957- The prologue and epilogue are modified to save and restore all non-kernel 1958 registers as necessary. 1959 1960- The FPU is disabled in the prologue, as the floating pointer registers are not 1961 spilled to the stack. 1962 1963- The function return sequence is changed to use an exception return instruction. 1964 1965- The parameter sets the interrupt mask for the function corresponding to the 1966 interrupt level specified. If no mask is specified the interrupt mask 1967 defaults to "eic". 1968 }]; 1969} 1970 1971def MicroMipsDocs : Documentation { 1972 let Category = DocCatFunction; 1973 let Content = [{ 1974Clang supports the GNU style ``__attribute__((micromips))`` and 1975``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes 1976may be attached to a function definition and instructs the backend to generate 1977or not to generate microMIPS code for that function. 1978 1979These attributes override the ``-mmicromips`` and ``-mno-micromips`` options 1980on the command line. 1981 }]; 1982} 1983 1984def MipsLongCallStyleDocs : Documentation { 1985 let Category = DocCatFunction; 1986 let Heading = "long_call, far"; 1987 let Content = [{ 1988Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, 1989and ``__attribute__((near))`` attributes on MIPS targets. These attributes may 1990only be added to function declarations and change the code generated 1991by the compiler when directly calling the function. The ``near`` attribute 1992allows calls to the function to be made using the ``jal`` instruction, which 1993requires the function to be located in the same naturally aligned 256MB 1994segment as the caller. The ``long_call`` and ``far`` attributes are synonyms 1995and require the use of a different call sequence that works regardless 1996of the distance between the functions. 1997 1998These attributes have no effect for position-independent code. 1999 2000These attributes take priority over command line switches such 2001as ``-mlong-calls`` and ``-mno-long-calls``. 2002 }]; 2003} 2004 2005def MipsShortCallStyleDocs : Documentation { 2006 let Category = DocCatFunction; 2007 let Heading = "short_call, near"; 2008 let Content = [{ 2009Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, 2010``__attribute__((short__call))``, and ``__attribute__((near))`` attributes 2011on MIPS targets. These attributes may only be added to function declarations 2012and change the code generated by the compiler when directly calling 2013the function. The ``short_call`` and ``near`` attributes are synonyms and 2014allow calls to the function to be made using the ``jal`` instruction, which 2015requires the function to be located in the same naturally aligned 256MB segment 2016as the caller. The ``long_call`` and ``far`` attributes are synonyms and 2017require the use of a different call sequence that works regardless 2018of the distance between the functions. 2019 2020These attributes have no effect for position-independent code. 2021 2022These attributes take priority over command line switches such 2023as ``-mlong-calls`` and ``-mno-long-calls``. 2024 }]; 2025} 2026 2027def RISCVInterruptDocs : Documentation { 2028 let Category = DocCatFunction; 2029 let Heading = "interrupt (RISCV)"; 2030 let Content = [{ 2031Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV 2032targets. This attribute may be attached to a function definition and instructs 2033the backend to generate appropriate function entry/exit code so that it can be 2034used directly as an interrupt service routine. 2035 2036Permissible values for this parameter are ``user``, ``supervisor``, 2037and ``machine``. If there is no parameter, then it defaults to machine. 2038 2039Repeated interrupt attribute on the same declaration will cause a warning 2040to be emitted. In case of repeated declarations, the last one prevails. 2041 2042Refer to: 2043https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html 2044https://riscv.org/specifications/privileged-isa/ 2045The RISC-V Instruction Set Manual Volume II: Privileged Architecture 2046Version 1.10. 2047 }]; 2048} 2049 2050def AVRInterruptDocs : Documentation { 2051 let Category = DocCatFunction; 2052 let Heading = "interrupt (AVR)"; 2053 let Content = [{ 2054Clang supports the GNU style ``__attribute__((interrupt))`` attribute on 2055AVR targets. This attribute may be attached to a function definition and instructs 2056the backend to generate appropriate function entry/exit code so that it can be used 2057directly as an interrupt service routine. 2058 2059On the AVR, the hardware globally disables interrupts when an interrupt is executed. 2060The first instruction of an interrupt handler declared with this attribute is a SEI 2061instruction to re-enable interrupts. See also the signal attribute that 2062does not insert a SEI instruction. 2063 }]; 2064} 2065 2066def AVRSignalDocs : Documentation { 2067 let Category = DocCatFunction; 2068 let Content = [{ 2069Clang supports the GNU style ``__attribute__((signal))`` attribute on 2070AVR targets. This attribute may be attached to a function definition and instructs 2071the backend to generate appropriate function entry/exit code so that it can be used 2072directly as an interrupt service routine. 2073 2074Interrupt handler functions defined with the signal attribute do not re-enable interrupts. 2075}]; 2076} 2077 2078def TargetDocs : Documentation { 2079 let Category = DocCatFunction; 2080 let Content = [{ 2081Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute. 2082This attribute may be attached to a function definition and instructs 2083the backend to use different code generation options than were passed on the 2084command line. 2085 2086The current set of options correspond to the existing "subtarget features" for 2087the target with or without a "-mno-" in front corresponding to the absence 2088of the feature, as well as ``arch="CPU"`` which will change the default "CPU" 2089for the function. 2090 2091For X86, the attribute also allows ``tune="CPU"`` to optimize the generated 2092code for the given CPU without changing the available instructions. 2093 2094For AArch64, the attribute also allows the "branch-protection=<args>" option, 2095where the permissible arguments and their effect on code generation are the same 2096as for the command-line option ``-mbranch-protection``. 2097 2098Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", 2099"avx", "xop" and largely correspond to the machine specific options handled by 2100the front end. 2101 2102Additionally, this attribute supports function multiversioning for ELF based 2103x86/x86-64 targets, which can be used to create multiple implementations of the 2104same function that will be resolved at runtime based on the priority of their 2105``target`` attribute strings. A function is considered a multiversioned function 2106if either two declarations of the function have different ``target`` attribute 2107strings, or if it has a ``target`` attribute string of ``default``. For 2108example: 2109 2110 .. code-block:: c++ 2111 2112 __attribute__((target("arch=atom"))) 2113 void foo() {} // will be called on 'atom' processors. 2114 __attribute__((target("default"))) 2115 void foo() {} // will be called on any other processors. 2116 2117All multiversioned functions must contain a ``default`` (fallback) 2118implementation, otherwise usages of the function are considered invalid. 2119Additionally, a function may not become multiversioned after its first use. 2120}]; 2121} 2122 2123def MinVectorWidthDocs : Documentation { 2124 let Category = DocCatFunction; 2125 let Content = [{ 2126Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This 2127attribute may be attached to a function and informs the backend that this 2128function desires vectors of at least this width to be generated. Target-specific 2129maximum vector widths still apply. This means even if you ask for something 2130larger than the target supports, you will only get what the target supports. 2131This attribute is meant to be a hint to control target heuristics that may 2132generate narrower vectors than what the target hardware supports. 2133 2134This is currently used by the X86 target to allow some CPUs that support 512-bit 2135vectors to be limited to using 256-bit vectors to avoid frequency penalties. 2136This is currently enabled with the ``-prefer-vector-width=256`` command line 2137option. The ``min_vector_width`` attribute can be used to prevent the backend 2138from trying to split vector operations to match the ``prefer-vector-width``. All 2139X86 vector intrinsics from x86intrin.h already set this attribute. Additionally, 2140use of any of the X86-specific vector builtins will implicitly set this 2141attribute on the calling function. The intent is that explicitly writing vector 2142code using the X86 intrinsics will prevent ``prefer-vector-width`` from 2143affecting the code. 2144}]; 2145} 2146 2147def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">; 2148 2149def AMDGPUFlatWorkGroupSizeDocs : Documentation { 2150 let Category = DocCatAMDGPUAttributes; 2151 let Content = [{ 2152The flat work-group size is the number of work-items in the work-group size 2153specified when the kernel is dispatched. It is the product of the sizes of the 2154x, y, and z dimension of the work-group. 2155 2156Clang supports the 2157``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the 2158AMDGPU target. This attribute may be attached to a kernel function definition 2159and is an optimization hint. 2160 2161``<min>`` parameter specifies the minimum flat work-group size, and ``<max>`` 2162parameter specifies the maximum flat work-group size (must be greater than 2163``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0`` 2164as ``<min>, <max>`` implies the default behavior (``128, 256``). 2165 2166If specified, the AMDGPU target backend might be able to produce better machine 2167code for barriers and perform scratch promotion by estimating available group 2168segment size. 2169 2170An error will be given if: 2171 - Specified values violate subtarget specifications; 2172 - Specified values are not compatible with values provided through other 2173 attributes. 2174 }]; 2175} 2176 2177def AMDGPUWavesPerEUDocs : Documentation { 2178 let Category = DocCatAMDGPUAttributes; 2179 let Content = [{ 2180A compute unit (CU) is responsible for executing the wavefronts of a work-group. 2181It is composed of one or more execution units (EU), which are responsible for 2182executing the wavefronts. An EU can have enough resources to maintain the state 2183of more than one executing wavefront. This allows an EU to hide latency by 2184switching between wavefronts in a similar way to symmetric multithreading on a 2185CPU. In order to allow the state for multiple wavefronts to fit on an EU, the 2186resources used by a single wavefront have to be limited. For example, the number 2187of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding, 2188but can result in having to spill some register state to memory. 2189 2190Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`` 2191attribute for the AMDGPU target. This attribute may be attached to a kernel 2192function definition and is an optimization hint. 2193 2194``<min>`` parameter specifies the requested minimum number of waves per EU, and 2195*optional* ``<max>`` parameter specifies the requested maximum number of waves 2196per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted, 2197then there is no restriction on the maximum number of waves per EU other than 2198the one dictated by the hardware for which the kernel is compiled. Passing 2199``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits). 2200 2201If specified, this attribute allows an advanced developer to tune the number of 2202wavefronts that are capable of fitting within the resources of an EU. The AMDGPU 2203target backend can use this information to limit resources, such as number of 2204SGPRs, number of VGPRs, size of available group and private memory segments, in 2205such a way that guarantees that at least ``<min>`` wavefronts and at most 2206``<max>`` wavefronts are able to fit within the resources of an EU. Requesting 2207more wavefronts can hide memory latency but limits available registers which 2208can result in spilling. Requesting fewer wavefronts can help reduce cache 2209thrashing, but can reduce memory latency hiding. 2210 2211This attribute controls the machine code generated by the AMDGPU target backend 2212to ensure it is capable of meeting the requested values. However, when the 2213kernel is executed, there may be other reasons that prevent meeting the request, 2214for example, there may be wavefronts from other kernels executing on the EU. 2215 2216An error will be given if: 2217 - Specified values violate subtarget specifications; 2218 - Specified values are not compatible with values provided through other 2219 attributes; 2220 - The AMDGPU target backend is unable to create machine code that can meet the 2221 request. 2222 }]; 2223} 2224 2225def AMDGPUNumSGPRNumVGPRDocs : Documentation { 2226 let Category = DocCatAMDGPUAttributes; 2227 let Content = [{ 2228Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and 2229``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU 2230target. These attributes may be attached to a kernel function definition and are 2231an optimization hint. 2232 2233If these attributes are specified, then the AMDGPU target backend will attempt 2234to limit the number of SGPRs and/or VGPRs used to the specified value(s). The 2235number of used SGPRs and/or VGPRs may further be rounded up to satisfy the 2236allocation requirements or constraints of the subtarget. Passing ``0`` as 2237``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits). 2238 2239These attributes can be used to test the AMDGPU target backend. It is 2240recommended that the ``amdgpu_waves_per_eu`` attribute be used to control 2241resources such as SGPRs and VGPRs since it is aware of the limits for different 2242subtargets. 2243 2244An error will be given if: 2245 - Specified values violate subtarget specifications; 2246 - Specified values are not compatible with values provided through other 2247 attributes; 2248 - The AMDGPU target backend is unable to create machine code that can meet the 2249 request. 2250 }]; 2251} 2252 2253def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> { 2254 let Content = [{ 2255Clang supports several different calling conventions, depending on the target 2256platform and architecture. The calling convention used for a function determines 2257how parameters are passed, how results are returned to the caller, and other 2258low-level details of calling a function. 2259 }]; 2260} 2261 2262def PcsDocs : Documentation { 2263 let Category = DocCatCallingConvs; 2264 let Content = [{ 2265On ARM targets, this attribute can be used to select calling conventions 2266similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and 2267"aapcs-vfp". 2268 }]; 2269} 2270 2271def AArch64VectorPcsDocs : Documentation { 2272 let Category = DocCatCallingConvs; 2273 let Content = [{ 2274On AArch64 targets, this attribute changes the calling convention of a 2275function to preserve additional floating-point and Advanced SIMD registers 2276relative to the default calling convention used for AArch64. 2277 2278This means it is more efficient to call such functions from code that performs 2279extensive floating-point and vector calculations, because fewer live SIMD and FP 2280registers need to be saved. This property makes it well-suited for e.g. 2281floating-point or vector math library functions, which are typically leaf 2282functions that require a small number of registers. 2283 2284However, using this attribute also means that it is more expensive to call 2285a function that adheres to the default calling convention from within such 2286a function. Therefore, it is recommended that this attribute is only used 2287for leaf functions. 2288 2289For more information, see the documentation for `aarch64_vector_pcs`_ on 2290the Arm Developer website. 2291 2292.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi 2293 }]; 2294} 2295 2296def RegparmDocs : Documentation { 2297 let Category = DocCatCallingConvs; 2298 let Content = [{ 2299On 32-bit x86 targets, the regparm attribute causes the compiler to pass 2300the first three integer parameters in EAX, EDX, and ECX instead of on the 2301stack. This attribute has no effect on variadic functions, and all parameters 2302are passed via the stack as normal. 2303 }]; 2304} 2305 2306def SysVABIDocs : Documentation { 2307 let Category = DocCatCallingConvs; 2308 let Content = [{ 2309On Windows x86_64 targets, this attribute changes the calling convention of a 2310function to match the default convention used on Sys V targets such as Linux, 2311Mac, and BSD. This attribute has no effect on other targets. 2312 }]; 2313} 2314 2315def MSABIDocs : Documentation { 2316 let Category = DocCatCallingConvs; 2317 let Content = [{ 2318On non-Windows x86_64 targets, this attribute changes the calling convention of 2319a function to match the default convention used on Windows x86_64. This 2320attribute has no effect on Windows targets or non-x86_64 targets. 2321 }]; 2322} 2323 2324def StdCallDocs : Documentation { 2325 let Category = DocCatCallingConvs; 2326 let Content = [{ 2327On 32-bit x86 targets, this attribute changes the calling convention of a 2328function to clear parameters off of the stack on return. This convention does 2329not support variadic calls or unprototyped functions in C, and has no effect on 2330x86_64 targets. This calling convention is used widely by the Windows API and 2331COM applications. See the documentation for `__stdcall`_ on MSDN. 2332 2333.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx 2334 }]; 2335} 2336 2337def FastCallDocs : Documentation { 2338 let Category = DocCatCallingConvs; 2339 let Content = [{ 2340On 32-bit x86 targets, this attribute changes the calling convention of a 2341function to use ECX and EDX as register parameters and clear parameters off of 2342the stack on return. This convention does not support variadic calls or 2343unprototyped functions in C, and has no effect on x86_64 targets. This calling 2344convention is supported primarily for compatibility with existing code. Users 2345seeking register parameters should use the ``regparm`` attribute, which does 2346not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN. 2347 2348.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx 2349 }]; 2350} 2351 2352def RegCallDocs : Documentation { 2353 let Category = DocCatCallingConvs; 2354 let Content = [{ 2355On x86 targets, this attribute changes the calling convention to 2356`__regcall`_ convention. This convention aims to pass as many arguments 2357as possible in registers. It also tries to utilize registers for the 2358return value whenever it is possible. 2359 2360.. _`__regcall`: https://software.intel.com/en-us/node/693069 2361 }]; 2362} 2363 2364def ThisCallDocs : Documentation { 2365 let Category = DocCatCallingConvs; 2366 let Content = [{ 2367On 32-bit x86 targets, this attribute changes the calling convention of a 2368function to use ECX for the first parameter (typically the implicit ``this`` 2369parameter of C++ methods) and clear parameters off of the stack on return. This 2370convention does not support variadic calls or unprototyped functions in C, and 2371has no effect on x86_64 targets. See the documentation for `__thiscall`_ on 2372MSDN. 2373 2374.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx 2375 }]; 2376} 2377 2378def VectorCallDocs : Documentation { 2379 let Category = DocCatCallingConvs; 2380 let Content = [{ 2381On 32-bit x86 *and* x86_64 targets, this attribute changes the calling 2382convention of a function to pass vector parameters in SSE registers. 2383 2384On 32-bit x86 targets, this calling convention is similar to ``__fastcall``. 2385The first two integer parameters are passed in ECX and EDX. Subsequent integer 2386parameters are passed in memory, and callee clears the stack. On x86_64 2387targets, the callee does *not* clear the stack, and integer parameters are 2388passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling 2389convention. 2390 2391On both 32-bit x86 and x86_64 targets, vector and floating point arguments are 2392passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are 2393passed in sequential SSE registers if enough are available. If AVX is enabled, 2394256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that 2395cannot be passed in registers for any reason is passed by reference, which 2396allows the caller to align the parameter memory. 2397 2398See the documentation for `__vectorcall`_ on MSDN for more details. 2399 2400.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx 2401 }]; 2402} 2403 2404def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> { 2405 let Content = [{ 2406Clang supports additional attributes for checking basic resource management 2407properties, specifically for unique objects that have a single owning reference. 2408The following attributes are currently supported, although **the implementation 2409for these annotations is currently in development and are subject to change.** 2410 }]; 2411} 2412 2413def SetTypestateDocs : Documentation { 2414 let Category = DocCatConsumed; 2415 let Content = [{ 2416Annotate methods that transition an object into a new state with 2417``__attribute__((set_typestate(new_state)))``. The new state must be 2418unconsumed, consumed, or unknown. 2419 }]; 2420} 2421 2422def CallableWhenDocs : Documentation { 2423 let Category = DocCatConsumed; 2424 let Content = [{ 2425Use ``__attribute__((callable_when(...)))`` to indicate what states a method 2426may be called in. Valid states are unconsumed, consumed, or unknown. Each 2427argument to this attribute must be a quoted string. E.g.: 2428 2429``__attribute__((callable_when("unconsumed", "unknown")))`` 2430 }]; 2431} 2432 2433def TestTypestateDocs : Documentation { 2434 let Category = DocCatConsumed; 2435 let Content = [{ 2436Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method 2437returns true if the object is in the specified state.. 2438 }]; 2439} 2440 2441def ParamTypestateDocs : Documentation { 2442 let Category = DocCatConsumed; 2443 let Content = [{ 2444This attribute specifies expectations about function parameters. Calls to an 2445function with annotated parameters will issue a warning if the corresponding 2446argument isn't in the expected state. The attribute is also used to set the 2447initial state of the parameter when analyzing the function's body. 2448 }]; 2449} 2450 2451def ReturnTypestateDocs : Documentation { 2452 let Category = DocCatConsumed; 2453 let Content = [{ 2454The ``return_typestate`` attribute can be applied to functions or parameters. 2455When applied to a function the attribute specifies the state of the returned 2456value. The function's body is checked to ensure that it always returns a value 2457in the specified state. On the caller side, values returned by the annotated 2458function are initialized to the given state. 2459 2460When applied to a function parameter it modifies the state of an argument after 2461a call to the function returns. The function's body is checked to ensure that 2462the parameter is in the expected state before returning. 2463 }]; 2464} 2465 2466def ConsumableDocs : Documentation { 2467 let Category = DocCatConsumed; 2468 let Content = [{ 2469Each ``class`` that uses any of the typestate annotations must first be marked 2470using the ``consumable`` attribute. Failure to do so will result in a warning. 2471 2472This attribute accepts a single parameter that must be one of the following: 2473``unknown``, ``consumed``, or ``unconsumed``. 2474 }]; 2475} 2476 2477def NoSanitizeDocs : Documentation { 2478 let Category = DocCatFunction; 2479 let Content = [{ 2480Use the ``no_sanitize`` attribute on a function or a global variable 2481declaration to specify that a particular instrumentation or set of 2482instrumentations should not be applied. The attribute takes a list of 2483string literals, which have the same meaning as values accepted by the 2484``-fno-sanitize=`` flag. For example, 2485``__attribute__((no_sanitize("address", "thread")))`` specifies that 2486AddressSanitizer and ThreadSanitizer should not be applied to the 2487function or variable. 2488 2489See :ref:`Controlling Code Generation <controlling-code-generation>` for a 2490full list of supported sanitizer flags. 2491 }]; 2492} 2493 2494def NoSanitizeAddressDocs : Documentation { 2495 let Category = DocCatFunction; 2496 // This function has multiple distinct spellings, and so it requires a custom 2497 // heading to be specified. The most common spelling is sufficient. 2498 let Heading = "no_sanitize_address, no_address_safety_analysis"; 2499 let Content = [{ 2500.. _langext-address_sanitizer: 2501 2502Use ``__attribute__((no_sanitize_address))`` on a function or a global 2503variable declaration to specify that address safety instrumentation 2504(e.g. AddressSanitizer) should not be applied. 2505 }]; 2506} 2507 2508def NoSanitizeThreadDocs : Documentation { 2509 let Category = DocCatFunction; 2510 let Heading = "no_sanitize_thread"; 2511 let Content = [{ 2512.. _langext-thread_sanitizer: 2513 2514Use ``__attribute__((no_sanitize_thread))`` on a function declaration to 2515specify that checks for data races on plain (non-atomic) memory accesses should 2516not be inserted by ThreadSanitizer. The function is still instrumented by the 2517tool to avoid false positives and provide meaningful stack traces. 2518 }]; 2519} 2520 2521def NoSanitizeMemoryDocs : Documentation { 2522 let Category = DocCatFunction; 2523 let Heading = "no_sanitize_memory"; 2524 let Content = [{ 2525.. _langext-memory_sanitizer: 2526 2527Use ``__attribute__((no_sanitize_memory))`` on a function declaration to 2528specify that checks for uninitialized memory should not be inserted 2529(e.g. by MemorySanitizer). The function may still be instrumented by the tool 2530to avoid false positives in other places. 2531 }]; 2532} 2533 2534def CFICanonicalJumpTableDocs : Documentation { 2535 let Category = DocCatFunction; 2536 let Heading = "cfi_canonical_jump_table"; 2537 let Content = [{ 2538.. _langext-cfi_canonical_jump_table: 2539 2540Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to 2541make the function's CFI jump table canonical. See :ref:`the CFI documentation 2542<cfi-canonical-jump-tables>` for more details. 2543 }]; 2544} 2545 2546def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> { 2547 let Content = [{ 2548Clang supports additional attributes to enable checking type safety properties 2549that can't be enforced by the C type system. To see warnings produced by these 2550checks, ensure that -Wtype-safety is enabled. Use cases include: 2551 2552* MPI library implementations, where these attributes enable checking that 2553 the buffer type matches the passed ``MPI_Datatype``; 2554* for HDF5 library there is a similar use case to MPI; 2555* checking types of variadic functions' arguments for functions like 2556 ``fcntl()`` and ``ioctl()``. 2557 2558You can detect support for these attributes with ``__has_attribute()``. For 2559example: 2560 2561.. code-block:: c++ 2562 2563 #if defined(__has_attribute) 2564 # if __has_attribute(argument_with_type_tag) && \ 2565 __has_attribute(pointer_with_type_tag) && \ 2566 __has_attribute(type_tag_for_datatype) 2567 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) 2568 /* ... other macros ... */ 2569 # endif 2570 #endif 2571 2572 #if !defined(ATTR_MPI_PWT) 2573 # define ATTR_MPI_PWT(buffer_idx, type_idx) 2574 #endif 2575 2576 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 2577 ATTR_MPI_PWT(1,3); 2578 }]; 2579} 2580 2581def ArgumentWithTypeTagDocs : Documentation { 2582 let Category = DocCatTypeSafety; 2583 let Heading = "argument_with_type_tag"; 2584 let Content = [{ 2585Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, 2586type_tag_idx)))`` on a function declaration to specify that the function 2587accepts a type tag that determines the type of some other argument. 2588 2589This attribute is primarily useful for checking arguments of variadic functions 2590(``pointer_with_type_tag`` can be used in most non-variadic cases). 2591 2592In the attribute prototype above: 2593 * ``arg_kind`` is an identifier that should be used when annotating all 2594 applicable type tags. 2595 * ``arg_idx`` provides the position of a function argument. The expected type of 2596 this function argument will be determined by the function argument specified 2597 by ``type_tag_idx``. In the code example below, "3" means that the type of the 2598 function's third argument will be determined by ``type_tag_idx``. 2599 * ``type_tag_idx`` provides the position of a function argument. This function 2600 argument will be a type tag. The type tag will determine the expected type of 2601 the argument specified by ``arg_idx``. In the code example below, "2" means 2602 that the type tag associated with the function's second argument should agree 2603 with the type of the argument specified by ``arg_idx``. 2604 2605For example: 2606 2607.. code-block:: c++ 2608 2609 int fcntl(int fd, int cmd, ...) 2610 __attribute__(( argument_with_type_tag(fcntl,3,2) )); 2611 // The function's second argument will be a type tag; this type tag will 2612 // determine the expected type of the function's third argument. 2613 }]; 2614} 2615 2616def PointerWithTypeTagDocs : Documentation { 2617 let Category = DocCatTypeSafety; 2618 let Heading = "pointer_with_type_tag"; 2619 let Content = [{ 2620Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` 2621on a function declaration to specify that the function accepts a type tag that 2622determines the pointee type of some other pointer argument. 2623 2624In the attribute prototype above: 2625 * ``ptr_kind`` is an identifier that should be used when annotating all 2626 applicable type tags. 2627 * ``ptr_idx`` provides the position of a function argument; this function 2628 argument will have a pointer type. The expected pointee type of this pointer 2629 type will be determined by the function argument specified by 2630 ``type_tag_idx``. In the code example below, "1" means that the pointee type 2631 of the function's first argument will be determined by ``type_tag_idx``. 2632 * ``type_tag_idx`` provides the position of a function argument; this function 2633 argument will be a type tag. The type tag will determine the expected pointee 2634 type of the pointer argument specified by ``ptr_idx``. In the code example 2635 below, "3" means that the type tag associated with the function's third 2636 argument should agree with the pointee type of the pointer argument specified 2637 by ``ptr_idx``. 2638 2639For example: 2640 2641.. code-block:: c++ 2642 2643 typedef int MPI_Datatype; 2644 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 2645 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 2646 // The function's 3rd argument will be a type tag; this type tag will 2647 // determine the expected pointee type of the function's 1st argument. 2648 }]; 2649} 2650 2651def TypeTagForDatatypeDocs : Documentation { 2652 let Category = DocCatTypeSafety; 2653 let Content = [{ 2654When declaring a variable, use 2655``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that 2656is tied to the ``type`` argument given to the attribute. 2657 2658In the attribute prototype above: 2659 * ``kind`` is an identifier that should be used when annotating all applicable 2660 type tags. 2661 * ``type`` indicates the name of the type. 2662 2663Clang supports annotating type tags of two forms. 2664 2665 * **Type tag that is a reference to a declared identifier.** 2666 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that 2667 identifier: 2668 2669 .. code-block:: c++ 2670 2671 typedef int MPI_Datatype; 2672 extern struct mpi_datatype mpi_datatype_int 2673 __attribute__(( type_tag_for_datatype(mpi,int) )); 2674 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) 2675 // &mpi_datatype_int is a type tag. It is tied to type "int". 2676 2677 * **Type tag that is an integral literal.** 2678 Declare a ``static const`` variable with an initializer value and attach 2679 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration: 2680 2681 .. code-block:: c++ 2682 2683 typedef int MPI_Datatype; 2684 static const MPI_Datatype mpi_datatype_int 2685 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42; 2686 #define MPI_INT ((MPI_Datatype) 42) 2687 // The number 42 is a type tag. It is tied to type "int". 2688 2689 2690The ``type_tag_for_datatype`` attribute also accepts an optional third argument 2691that determines how the type of the function argument specified by either 2692``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type 2693tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the 2694function argument specified by ``arg_idx`` is compared against the type 2695associated with the type tag. Also recall that for the ``pointer_with_type_tag`` 2696attribute, the pointee type of the function argument specified by ``ptr_idx`` is 2697compared against the type associated with the type tag.) There are two supported 2698values for this optional third argument: 2699 2700 * ``layout_compatible`` will cause types to be compared according to 2701 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the 2702 layout-compatibility rules for two standard-layout struct types and for two 2703 standard-layout union types). This is useful when creating a type tag 2704 associated with a struct or union type. For example: 2705 2706 .. code-block:: c++ 2707 2708 /* In mpi.h */ 2709 typedef int MPI_Datatype; 2710 struct internal_mpi_double_int { double d; int i; }; 2711 extern struct mpi_datatype mpi_datatype_double_int 2712 __attribute__(( type_tag_for_datatype(mpi, 2713 struct internal_mpi_double_int, layout_compatible) )); 2714 2715 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) 2716 2717 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) 2718 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 2719 2720 /* In user code */ 2721 struct my_pair { double a; int b; }; 2722 struct my_pair *buffer; 2723 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the 2724 // layout of my_pair is 2725 // compatible with that of 2726 // internal_mpi_double_int 2727 2728 struct my_int_pair { int a; int b; } 2729 struct my_int_pair *buffer2; 2730 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the 2731 // layout of my_int_pair 2732 // does not match that of 2733 // internal_mpi_double_int 2734 2735 * ``must_be_null`` specifies that the function argument specified by either 2736 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for 2737 the ``pointer_with_type_tag`` attribute) should be a null pointer constant. 2738 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For 2739 example: 2740 2741 .. code-block:: c++ 2742 2743 /* In mpi.h */ 2744 typedef int MPI_Datatype; 2745 extern struct mpi_datatype mpi_datatype_null 2746 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); 2747 2748 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) 2749 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) 2750 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 2751 2752 /* In user code */ 2753 struct my_pair { double a; int b; }; 2754 struct my_pair *buffer; 2755 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL 2756 // was specified but buffer 2757 // is not a null pointer 2758 }]; 2759} 2760 2761def FlattenDocs : Documentation { 2762 let Category = DocCatFunction; 2763 let Content = [{ 2764The ``flatten`` attribute causes calls within the attributed function to 2765be inlined unless it is impossible to do so, for example if the body of the 2766callee is unavailable or if the callee has the ``noinline`` attribute. 2767 }]; 2768} 2769 2770def FormatDocs : Documentation { 2771 let Category = DocCatFunction; 2772 let Content = [{ 2773 2774Clang supports the ``format`` attribute, which indicates that the function 2775accepts a ``printf`` or ``scanf``-like format string and corresponding 2776arguments or a ``va_list`` that contains these arguments. 2777 2778Please see `GCC documentation about format attribute 2779<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details 2780about attribute syntax. 2781 2782Clang implements two kinds of checks with this attribute. 2783 2784#. Clang checks that the function with the ``format`` attribute is called with 2785 a format string that uses format specifiers that are allowed, and that 2786 arguments match the format string. This is the ``-Wformat`` warning, it is 2787 on by default. 2788 2789#. Clang checks that the format string argument is a literal string. This is 2790 the ``-Wformat-nonliteral`` warning, it is off by default. 2791 2792 Clang implements this mostly the same way as GCC, but there is a difference 2793 for functions that accept a ``va_list`` argument (for example, ``vprintf``). 2794 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such 2795 functions. Clang does not warn if the format string comes from a function 2796 parameter, where the function is annotated with a compatible attribute, 2797 otherwise it warns. For example: 2798 2799 .. code-block:: c 2800 2801 __attribute__((__format__ (__scanf__, 1, 3))) 2802 void foo(const char* s, char *buf, ...) { 2803 va_list ap; 2804 va_start(ap, buf); 2805 2806 vprintf(s, ap); // warning: format string is not a string literal 2807 } 2808 2809 In this case we warn because ``s`` contains a format string for a 2810 ``scanf``-like function, but it is passed to a ``printf``-like function. 2811 2812 If the attribute is removed, clang still warns, because the format string is 2813 not a string literal. 2814 2815 Another example: 2816 2817 .. code-block:: c 2818 2819 __attribute__((__format__ (__printf__, 1, 3))) 2820 void foo(const char* s, char *buf, ...) { 2821 va_list ap; 2822 va_start(ap, buf); 2823 2824 vprintf(s, ap); // warning 2825 } 2826 2827 In this case Clang does not warn because the format string ``s`` and 2828 the corresponding arguments are annotated. If the arguments are 2829 incorrect, the caller of ``foo`` will receive a warning. 2830 }]; 2831} 2832 2833def AlignValueDocs : Documentation { 2834 let Category = DocCatType; 2835 let Content = [{ 2836The align_value attribute can be added to the typedef of a pointer type or the 2837declaration of a variable of pointer or reference type. It specifies that the 2838pointer will point to, or the reference will bind to, only objects with at 2839least the provided alignment. This alignment value must be some positive power 2840of 2. 2841 2842 .. code-block:: c 2843 2844 typedef double * aligned_double_ptr __attribute__((align_value(64))); 2845 void foo(double & x __attribute__((align_value(128)), 2846 aligned_double_ptr y) { ... } 2847 2848If the pointer value does not have the specified alignment at runtime, the 2849behavior of the program is undefined. 2850 }]; 2851} 2852 2853def FlagEnumDocs : Documentation { 2854 let Category = DocCatDecl; 2855 let Content = [{ 2856This attribute can be added to an enumerator to signal to the compiler that it 2857is intended to be used as a flag type. This will cause the compiler to assume 2858that the range of the type includes all of the values that you can get by 2859manipulating bits of the enumerator when issuing warnings. 2860 }]; 2861} 2862 2863def AsmLabelDocs : Documentation { 2864 let Category = DocCatDecl; 2865 let Content = [{ 2866This attribute can be used on a function or variable to specify its symbol name. 2867 2868On some targets, all C symbols are prefixed by default with a single character, 2869typically ``_``. This was done historically to distinguish them from symbols 2870used by other languages. (This prefix is also added to the standard Itanium 2871C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true 2872symbol name for a C++ variable declared as ``int cppvar;`` would be 2873``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the 2874symbol names specified by the ``asm`` attribute; programmers wishing to match a 2875C symbol name must compensate for this. 2876 2877For example, consider the following C code: 2878 2879.. code-block:: c 2880 2881 int var1 asm("altvar") = 1; // "altvar" in symbol table. 2882 int var2 = 1; // "_var2" in symbol table. 2883 2884 void func1(void) asm("altfunc"); 2885 void func1(void) {} // "altfunc" in symbol table. 2886 void func2(void) {} // "_func2" in symbol table. 2887 2888Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_. 2889 2890While it is possible to use this attribute to name a special symbol used 2891internally by the compiler, such as an LLVM intrinsic, this is neither 2892recommended nor supported and may cause the compiler to crash or miscompile. 2893Users who wish to gain access to intrinsic behavior are strongly encouraged to 2894request new builtin functions. 2895 }]; 2896} 2897 2898def EnumExtensibilityDocs : Documentation { 2899 let Category = DocCatDecl; 2900 let Content = [{ 2901Attribute ``enum_extensibility`` is used to distinguish between enum definitions 2902that are extensible and those that are not. The attribute can take either 2903``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the 2904enum type takes a value that corresponds to one of the enumerators listed in the 2905enum definition or, when the enum is annotated with ``flag_enum``, a value that 2906can be constructed using values corresponding to the enumerators. ``open`` 2907indicates a variable of the enum type can take any values allowed by the 2908standard and instructs clang to be more lenient when issuing warnings. 2909 2910.. code-block:: c 2911 2912 enum __attribute__((enum_extensibility(closed))) ClosedEnum { 2913 A0, A1 2914 }; 2915 2916 enum __attribute__((enum_extensibility(open))) OpenEnum { 2917 B0, B1 2918 }; 2919 2920 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum { 2921 C0 = 1 << 0, C1 = 1 << 1 2922 }; 2923 2924 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum { 2925 D0 = 1 << 0, D1 = 1 << 1 2926 }; 2927 2928 void foo1() { 2929 enum ClosedEnum ce; 2930 enum OpenEnum oe; 2931 enum ClosedFlagEnum cfe; 2932 enum OpenFlagEnum ofe; 2933 2934 ce = A1; // no warnings 2935 ce = 100; // warning issued 2936 oe = B1; // no warnings 2937 oe = 100; // no warnings 2938 cfe = C0 | C1; // no warnings 2939 cfe = C0 | C1 | 4; // warning issued 2940 ofe = D0 | D1; // no warnings 2941 ofe = D0 | D1 | 4; // no warnings 2942 } 2943 2944 }]; 2945} 2946 2947def EmptyBasesDocs : Documentation { 2948 let Category = DocCatDecl; 2949 let Content = [{ 2950The empty_bases attribute permits the compiler to utilize the 2951empty-base-optimization more frequently. 2952This attribute only applies to struct, class, and union types. 2953It is only supported when using the Microsoft C++ ABI. 2954 }]; 2955} 2956 2957def LayoutVersionDocs : Documentation { 2958 let Category = DocCatDecl; 2959 let Content = [{ 2960The layout_version attribute requests that the compiler utilize the class 2961layout rules of a particular compiler version. 2962This attribute only applies to struct, class, and union types. 2963It is only supported when using the Microsoft C++ ABI. 2964 }]; 2965} 2966 2967def LifetimeBoundDocs : Documentation { 2968 let Category = DocCatFunction; 2969 let Content = [{ 2970The ``lifetimebound`` attribute indicates that a resource owned by 2971a function parameter or implicit object parameter 2972is retained by the return value of the annotated function 2973(or, for a parameter of a constructor, in the value of the constructed object). 2974It is only supported in C++. 2975 2976This attribute provides an experimental implementation of the facility 2977described in the C++ committee paper `P0936R0 <http://wg21.link/p0936r0>`_, 2978and is subject to change as the design of the corresponding functionality 2979changes. 2980 }]; 2981} 2982 2983def TrivialABIDocs : Documentation { 2984 let Category = DocCatDecl; 2985 let Content = [{ 2986The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union. 2987It instructs the compiler to pass and return the type using the C ABI for the 2988underlying type when the type would otherwise be considered non-trivial for the 2989purpose of calls. 2990A class annotated with ``trivial_abi`` can have non-trivial destructors or 2991copy/move constructors without automatically becoming non-trivial for the 2992purposes of calls. For example: 2993 2994 .. code-block:: c++ 2995 2996 // A is trivial for the purposes of calls because ``trivial_abi`` makes the 2997 // user-provided special functions trivial. 2998 struct __attribute__((trivial_abi)) A { 2999 ~A(); 3000 A(const A &); 3001 A(A &&); 3002 int x; 3003 }; 3004 3005 // B's destructor and copy/move constructor are considered trivial for the 3006 // purpose of calls because A is trivial. 3007 struct B { 3008 A a; 3009 }; 3010 3011If a type is trivial for the purposes of calls, has a non-trivial destructor, 3012and is passed as an argument by value, the convention is that the callee will 3013destroy the object before returning. 3014 3015Attribute ``trivial_abi`` has no effect in the following cases: 3016 3017- The class directly declares a virtual base or virtual methods. 3018- Copy constructors and move constructors of the class are all deleted. 3019- The class has a base class that is non-trivial for the purposes of calls. 3020- The class has a non-static data member whose type is non-trivial for the 3021 purposes of calls, which includes: 3022 3023 - classes that are non-trivial for the purposes of calls 3024 - __weak-qualified types in Objective-C++ 3025 - arrays of any of the above 3026 }]; 3027} 3028 3029def MSInheritanceDocs : Documentation { 3030 let Category = DocCatDecl; 3031 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance"; 3032 let Content = [{ 3033This collection of keywords is enabled under ``-fms-extensions`` and controls 3034the pointer-to-member representation used on ``*-*-win32`` targets. 3035 3036The ``*-*-win32`` targets utilize a pointer-to-member representation which 3037varies in size and alignment depending on the definition of the underlying 3038class. 3039 3040However, this is problematic when a forward declaration is only available and 3041no definition has been made yet. In such cases, Clang is forced to utilize the 3042most general representation that is available to it. 3043 3044These keywords make it possible to use a pointer-to-member representation other 3045than the most general one regardless of whether or not the definition will ever 3046be present in the current translation unit. 3047 3048This family of keywords belong between the ``class-key`` and ``class-name``: 3049 3050.. code-block:: c++ 3051 3052 struct __single_inheritance S; 3053 int S::*i; 3054 struct S {}; 3055 3056This keyword can be applied to class templates but only has an effect when used 3057on full specializations: 3058 3059.. code-block:: c++ 3060 3061 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template 3062 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization 3063 template <> struct __single_inheritance A<int, float>; 3064 3065Note that choosing an inheritance model less general than strictly necessary is 3066an error: 3067 3068.. code-block:: c++ 3069 3070 struct __multiple_inheritance S; // error: inheritance model does not match definition 3071 int S::*i; 3072 struct S {}; 3073}]; 3074} 3075 3076def MSNoVTableDocs : Documentation { 3077 let Category = DocCatDecl; 3078 let Content = [{ 3079This attribute can be added to a class declaration or definition to signal to 3080the compiler that constructors and destructors will not reference the virtual 3081function table. It is only supported when using the Microsoft C++ ABI. 3082 }]; 3083} 3084 3085def OptnoneDocs : Documentation { 3086 let Category = DocCatFunction; 3087 let Content = [{ 3088The ``optnone`` attribute suppresses essentially all optimizations 3089on a function or method, regardless of the optimization level applied to 3090the compilation unit as a whole. This is particularly useful when you 3091need to debug a particular function, but it is infeasible to build the 3092entire application without optimization. Avoiding optimization on the 3093specified function can improve the quality of the debugging information 3094for that function. 3095 3096This attribute is incompatible with the ``always_inline`` and ``minsize`` 3097attributes. 3098 }]; 3099} 3100 3101def LoopHintDocs : Documentation { 3102 let Category = DocCatStmt; 3103 let Heading = "#pragma clang loop"; 3104 let Content = [{ 3105The ``#pragma clang loop`` directive allows loop optimization hints to be 3106specified for the subsequent loop. The directive allows pipelining to be 3107disabled, or vectorization, vector predication, interleaving, and unrolling to 3108be enabled or disabled. Vector width, vector predication, interleave count, 3109unrolling count, and the initiation interval for pipelining can be explicitly 3110specified. See `language extensions 3111<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 3112for details. 3113 }]; 3114} 3115 3116def UnrollHintDocs : Documentation { 3117 let Category = DocCatStmt; 3118 let Heading = "#pragma unroll, #pragma nounroll"; 3119 let Content = [{ 3120Loop unrolling optimization hints can be specified with ``#pragma unroll`` and 3121``#pragma nounroll``. The pragma is placed immediately before a for, while, 3122do-while, or c++11 range-based for loop. 3123 3124Specifying ``#pragma unroll`` without a parameter directs the loop unroller to 3125attempt to fully unroll the loop if the trip count is known at compile time and 3126attempt to partially unroll the loop if the trip count is not known at compile 3127time: 3128 3129.. code-block:: c++ 3130 3131 #pragma unroll 3132 for (...) { 3133 ... 3134 } 3135 3136Specifying the optional parameter, ``#pragma unroll _value_``, directs the 3137unroller to unroll the loop ``_value_`` times. The parameter may optionally be 3138enclosed in parentheses: 3139 3140.. code-block:: c++ 3141 3142 #pragma unroll 16 3143 for (...) { 3144 ... 3145 } 3146 3147 #pragma unroll(16) 3148 for (...) { 3149 ... 3150 } 3151 3152Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled: 3153 3154.. code-block:: c++ 3155 3156 #pragma nounroll 3157 for (...) { 3158 ... 3159 } 3160 3161``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to 3162``#pragma clang loop unroll(full)`` and 3163``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll`` 3164is equivalent to ``#pragma clang loop unroll(disable)``. See 3165`language extensions 3166<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 3167for further details including limitations of the unroll hints. 3168 }]; 3169} 3170 3171def PipelineHintDocs : Documentation { 3172 let Category = DocCatStmt; 3173 let Heading = "#pragma clang loop pipeline, #pragma clang loop pipeline_initiation_interval"; 3174 let Content = [{ 3175 Software Pipelining optimization is a technique used to optimize loops by 3176 utilizing instruction-level parallelism. It reorders loop instructions to 3177 overlap iterations. As a result, the next iteration starts before the previous 3178 iteration has finished. The module scheduling technique creates a schedule for 3179 one iteration such that when repeating at regular intervals, no inter-iteration 3180 dependencies are violated. This constant interval(in cycles) between the start 3181 of iterations is called the initiation interval. i.e. The initiation interval 3182 is the number of cycles between two iterations of an unoptimized loop in the 3183 newly created schedule. A new, optimized loop is created such that a single iteration 3184 of the loop executes in the same number of cycles as the initiation interval. 3185 For further details see <https://llvm.org/pubs/2005-06-17-LattnerMSThesis-book.pdf>. 3186 3187 ``#pragma clang loop pipeline and #pragma loop pipeline_initiation_interval`` 3188 could be used as hints for the software pipelining optimization. The pragma is 3189 placed immediately before a for, while, do-while, or a C++11 range-based for 3190 loop. 3191 3192 Using ``#pragma clang loop pipeline(disable)`` avoids the software pipelining 3193 optimization. The disable state can only be specified: 3194 3195 .. code-block:: c++ 3196 3197 #pragma clang loop pipeline(disable) 3198 for (...) { 3199 ... 3200 } 3201 3202 Using ``#pragma loop pipeline_initiation_interval`` instructs 3203 the software pipeliner to try the specified initiation interval. 3204 If a schedule was found then the resulting loop iteration would have 3205 the specified cycle count. If a schedule was not found then loop 3206 remains unchanged. The initiation interval must be a positive number 3207 greater than zero: 3208 3209 .. code-block:: c++ 3210 3211 #pragma loop pipeline_initiation_interval(10) 3212 for (...) { 3213 ... 3214 } 3215 3216 }]; 3217} 3218 3219def OpenCLUnrollHintDocs : Documentation { 3220 let Category = DocCatStmt; 3221 let Content = [{ 3222The opencl_unroll_hint attribute qualifier can be used to specify that a loop 3223(for, while and do loops) can be unrolled. This attribute qualifier can be 3224used to specify full unrolling or partial unrolling by a specified amount. 3225This is a compiler hint and the compiler may ignore this directive. See 3226`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_ 3227s6.11.5 for details. 3228 }]; 3229} 3230 3231def OpenCLIntelReqdSubGroupSizeDocs : Documentation { 3232 let Category = DocCatStmt; 3233 let Content = [{ 3234The optional attribute intel_reqd_sub_group_size can be used to indicate that 3235the kernel must be compiled and executed with the specified subgroup size. When 3236this attribute is present, get_max_sub_group_size() is guaranteed to return the 3237specified integer value. This is important for the correctness of many subgroup 3238algorithms, and in some cases may be used by the compiler to generate more optimal 3239code. See `cl_intel_required_subgroup_size 3240<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>` 3241for details. 3242 }]; 3243} 3244 3245def OpenCLAccessDocs : Documentation { 3246 let Category = DocCatStmt; 3247 let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)"; 3248 let Content = [{ 3249The access qualifiers must be used with image object arguments or pipe arguments 3250to declare if they are being read or written by a kernel or function. 3251 3252The read_only/__read_only, write_only/__write_only and read_write/__read_write 3253names are reserved for use as access qualifiers and shall not be used otherwise. 3254 3255.. code-block:: c 3256 3257 kernel void 3258 foo (read_only image2d_t imageA, 3259 write_only image2d_t imageB) { 3260 ... 3261 } 3262 3263In the above example imageA is a read-only 2D image object, and imageB is a 3264write-only 2D image object. 3265 3266The read_write (or __read_write) qualifier can not be used with pipe. 3267 3268More details can be found in the OpenCL C language Spec v2.0, Section 6.6. 3269 }]; 3270} 3271 3272def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> { 3273 let Content = [{ 3274The address space qualifier may be used to specify the region of memory that is 3275used to allocate the object. OpenCL supports the following address spaces: 3276__generic(generic), __global(global), __local(local), __private(private), 3277__constant(constant). 3278 3279 .. code-block:: c 3280 3281 __constant int c = ...; 3282 3283 __generic int* foo(global int* g) { 3284 __local int* l; 3285 private int p; 3286 ... 3287 return l; 3288 } 3289 3290More details can be found in the OpenCL C language Spec v2.0, Section 6.5. 3291 }]; 3292} 3293 3294def OpenCLAddressSpaceGenericDocs : Documentation { 3295 let Category = DocOpenCLAddressSpaces; 3296 let Heading = "__generic, generic, [[clang::opencl_generic]]"; 3297 let Content = [{ 3298The generic address space attribute is only available with OpenCL v2.0 and later. 3299It can be used with pointer types. Variables in global and local scope and 3300function parameters in non-kernel functions can have the generic address space 3301type attribute. It is intended to be a placeholder for any other address space 3302except for '__constant' in OpenCL code which can be used with multiple address 3303spaces. 3304 }]; 3305} 3306 3307def OpenCLAddressSpaceConstantDocs : Documentation { 3308 let Category = DocOpenCLAddressSpaces; 3309 let Heading = "__constant, constant, [[clang::opencl_constant]]"; 3310 let Content = [{ 3311The constant address space attribute signals that an object is located in 3312a constant (non-modifiable) memory region. It is available to all work items. 3313Any type can be annotated with the constant address space attribute. Objects 3314with the constant address space qualifier can be declared in any scope and must 3315have an initializer. 3316 }]; 3317} 3318 3319def OpenCLAddressSpaceGlobalDocs : Documentation { 3320 let Category = DocOpenCLAddressSpaces; 3321 let Heading = "__global, global, [[clang::opencl_global]]"; 3322 let Content = [{ 3323The global address space attribute specifies that an object is allocated in 3324global memory, which is accessible by all work items. The content stored in this 3325memory area persists between kernel executions. Pointer types to the global 3326address space are allowed as function parameters or local variables. Starting 3327with OpenCL v2.0, the global address space can be used with global (program 3328scope) variables and static local variable as well. 3329 }]; 3330} 3331 3332def OpenCLAddressSpaceGlobalExtDocs : Documentation { 3333 let Category = DocOpenCLAddressSpaces; 3334 let Heading = "[[clang::opencl_global_device]], [[clang::opencl_global_host]]"; 3335 let Content = [{ 3336The ``global_device`` and ``global_host`` address space attributes specify that 3337an object is allocated in global memory on the device/host. It helps to 3338distinguish USM (Unified Shared Memory) pointers that access global device 3339memory from those that access global host memory. These new address spaces are 3340a subset of the ``__global/opencl_global`` address space, the full address space 3341set model for OpenCL 2.0 with the extension looks as follows: 3342 3343 | generic->global->host 3344 | ->device 3345 | ->private 3346 | ->local 3347 | constant 3348 3349As ``global_device`` and ``global_host`` are a subset of 3350``__global/opencl_global`` address spaces it is allowed to convert 3351``global_device`` and ``global_host`` address spaces to 3352``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3 3353"Address space nesting and rules for pointers"). 3354 }]; 3355} 3356 3357def OpenCLAddressSpaceLocalDocs : Documentation { 3358 let Category = DocOpenCLAddressSpaces; 3359 let Heading = "__local, local, [[clang::opencl_local]]"; 3360 let Content = [{ 3361The local address space specifies that an object is allocated in the local (work 3362group) memory area, which is accessible to all work items in the same work 3363group. The content stored in this memory region is not accessible after 3364the kernel execution ends. In a kernel function scope, any variable can be in 3365the local address space. In other scopes, only pointer types to the local address 3366space are allowed. Local address space variables cannot have an initializer. 3367 }]; 3368} 3369 3370def OpenCLAddressSpacePrivateDocs : Documentation { 3371 let Category = DocOpenCLAddressSpaces; 3372 let Heading = "__private, private, [[clang::opencl_private]]"; 3373 let Content = [{ 3374The private address space specifies that an object is allocated in the private 3375(work item) memory. Other work items cannot access the same memory area and its 3376content is destroyed after work item execution ends. Local variables can be 3377declared in the private address space. Function arguments are always in the 3378private address space. Kernel function arguments of a pointer or an array type 3379cannot point to the private address space. 3380 }]; 3381} 3382 3383def OpenCLNoSVMDocs : Documentation { 3384 let Category = DocCatVariable; 3385 let Content = [{ 3386OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for 3387pointer variable. It informs the compiler that the pointer does not refer 3388to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details. 3389 3390Since it is not widely used and has been removed from OpenCL 2.1, it is ignored 3391by Clang. 3392 }]; 3393} 3394 3395def Ptr32Docs : Documentation { 3396 let Category = DocCatType; 3397 let Content = [{ 3398The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a 339964-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The 3400``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer 3401is sign extended or zero extended. This qualifier is enabled under 3402``-fms-extensions``. 3403 }]; 3404} 3405 3406def Ptr64Docs : Documentation { 3407 let Category = DocCatType; 3408 let Content = [{ 3409The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a 341032-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This 3411qualifier is enabled under ``-fms-extensions``. 3412 }]; 3413} 3414 3415def SPtrDocs : Documentation { 3416 let Category = DocCatType; 3417 let Content = [{ 3418The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign 3419extended when converted to a 64-bit pointer. 3420 }]; 3421} 3422 3423def UPtrDocs : Documentation { 3424 let Category = DocCatType; 3425 let Content = [{ 3426The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero 3427extended when converted to a 64-bit pointer. 3428 }]; 3429} 3430 3431 3432def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> { 3433 let Content = [{ 3434Whether a particular pointer may be "null" is an important concern when working 3435with pointers in the C family of languages. The various nullability attributes 3436indicate whether a particular pointer can be null or not, which makes APIs more 3437expressive and can help static analysis tools identify bugs involving null 3438pointers. Clang supports several kinds of nullability attributes: the 3439``nonnull`` and ``returns_nonnull`` attributes indicate which function or 3440method parameters and result types can never be null, while nullability type 3441qualifiers indicate which pointer types can be null (``_Nullable``) or cannot 3442be null (``_Nonnull``). 3443 3444The nullability (type) qualifiers express whether a value of a given pointer 3445type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning 3446for null (the ``_Nonnull`` qualifier), or for which the purpose of null is 3447unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers 3448are expressed within the type system, they are more general than the 3449``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for 3450example) a nullable pointer to an array of nonnull pointers. Nullability 3451qualifiers are written to the right of the pointer to which they apply. For 3452example: 3453 3454 .. code-block:: c 3455 3456 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior). 3457 int fetch(int * _Nonnull ptr) { return *ptr; } 3458 3459 // 'ptr' may be null. 3460 int fetch_or_zero(int * _Nullable ptr) { 3461 return ptr ? *ptr : 0; 3462 } 3463 3464 // A nullable pointer to non-null pointers to const characters. 3465 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n); 3466 3467In Objective-C, there is an alternate spelling for the nullability qualifiers 3468that can be used in Objective-C methods and properties using context-sensitive, 3469non-underscored keywords. For example: 3470 3471 .. code-block:: objective-c 3472 3473 @interface NSView : NSResponder 3474 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView; 3475 @property (assign, nullable) NSView *superview; 3476 @property (readonly, nonnull) NSArray *subviews; 3477 @end 3478 }]; 3479} 3480 3481def TypeNonNullDocs : Documentation { 3482 let Category = NullabilityDocs; 3483 let Content = [{ 3484The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful 3485value for a value of the ``_Nonnull`` pointer type. For example, given a 3486declaration such as: 3487 3488 .. code-block:: c 3489 3490 int fetch(int * _Nonnull ptr); 3491 3492a caller of ``fetch`` should not provide a null value, and the compiler will 3493produce a warning if it sees a literal null value passed to ``fetch``. Note 3494that, unlike the declaration attribute ``nonnull``, the presence of 3495``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch`` 3496is free to consider null undefined behavior or (perhaps for 3497backward-compatibility reasons) defensively handle null. 3498 }]; 3499} 3500 3501def TypeNullableDocs : Documentation { 3502 let Category = NullabilityDocs; 3503 let Content = [{ 3504The ``_Nullable`` nullability qualifier indicates that a value of the 3505``_Nullable`` pointer type can be null. For example, given: 3506 3507 .. code-block:: c 3508 3509 int fetch_or_zero(int * _Nullable ptr); 3510 3511a caller of ``fetch_or_zero`` can provide null. 3512 }]; 3513} 3514 3515def TypeNullableResultDocs : Documentation { 3516 let Category = NullabilityDocs; 3517 let Content = [{ 3518The ``_Nullable_result`` nullability qualifier means that a value of the 3519``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this 3520attribute differs from ``_Nullable`` is when it's used on a parameter to a 3521completion handler in a Swift async method. For instance, here: 3522 3523 .. code-block:: objc 3524 3525 -(void)fetchSomeDataWithID:(int)identifier 3526 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler; 3527 3528This method asynchronously calls ``completionHandler`` when the data is 3529available, or calls it with an error. ``_Nullable_result`` indicates to the 3530Swift importer that this is the uncommon case where ``result`` can get ``nil`` 3531even if no error has occured, and will therefore import it as a Swift optional 3532type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift 3533importer will assume that ``result`` will always be non-nil unless an error 3534occured. 3535}]; 3536} 3537 3538def TypeNullUnspecifiedDocs : Documentation { 3539 let Category = NullabilityDocs; 3540 let Content = [{ 3541The ``_Null_unspecified`` nullability qualifier indicates that neither the 3542``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer 3543type. It is used primarily to indicate that the role of null with specific 3544pointers in a nullability-annotated header is unclear, e.g., due to 3545overly-complex implementations or historical factors with a long-lived API. 3546 }]; 3547} 3548 3549def NonNullDocs : Documentation { 3550 let Category = NullabilityDocs; 3551 let Content = [{ 3552The ``nonnull`` attribute indicates that some function parameters must not be 3553null, and can be used in several different ways. It's original usage 3554(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_) 3555is as a function (or Objective-C method) attribute that specifies which 3556parameters of the function are nonnull in a comma-separated list. For example: 3557 3558 .. code-block:: c 3559 3560 extern void * my_memcpy (void *dest, const void *src, size_t len) 3561 __attribute__((nonnull (1, 2))); 3562 3563Here, the ``nonnull`` attribute indicates that parameters 1 and 2 3564cannot have a null value. Omitting the parenthesized list of parameter indices 3565means that all parameters of pointer type cannot be null: 3566 3567 .. code-block:: c 3568 3569 extern void * my_memcpy (void *dest, const void *src, size_t len) 3570 __attribute__((nonnull)); 3571 3572Clang also allows the ``nonnull`` attribute to be placed directly on a function 3573(or Objective-C method) parameter, eliminating the need to specify the 3574parameter index ahead of type. For example: 3575 3576 .. code-block:: c 3577 3578 extern void * my_memcpy (void *dest __attribute__((nonnull)), 3579 const void *src __attribute__((nonnull)), size_t len); 3580 3581Note that the ``nonnull`` attribute indicates that passing null to a non-null 3582parameter is undefined behavior, which the optimizer may take advantage of to, 3583e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a 3584pointer cannot be null in a more general manner (because it is part of the type 3585system) and does not imply undefined behavior, making it more widely applicable. 3586 }]; 3587} 3588 3589def ReturnsNonNullDocs : Documentation { 3590 let Category = NullabilityDocs; 3591 let Content = [{ 3592The ``returns_nonnull`` attribute indicates that a particular function (or 3593Objective-C method) always returns a non-null pointer. For example, a 3594particular system ``malloc`` might be defined to terminate a process when 3595memory is not available rather than returning a null pointer: 3596 3597 .. code-block:: c 3598 3599 extern void * malloc (size_t size) __attribute__((returns_nonnull)); 3600 3601The ``returns_nonnull`` attribute implies that returning a null pointer is 3602undefined behavior, which the optimizer may take advantage of. The ``_Nonnull`` 3603type qualifier indicates that a pointer cannot be null in a more general manner 3604(because it is part of the type system) and does not imply undefined behavior, 3605making it more widely applicable 3606}]; 3607} 3608 3609def NoAliasDocs : Documentation { 3610 let Category = DocCatFunction; 3611 let Content = [{ 3612The ``noalias`` attribute indicates that the only memory accesses inside 3613function are loads and stores from objects pointed to by its pointer-typed 3614arguments, with arbitrary offsets. 3615 }]; 3616} 3617 3618def NSErrorDomainDocs : Documentation { 3619 let Category = DocCatDecl; 3620 let Content = [{ 3621In Cocoa frameworks in Objective-C, one can group related error codes in enums 3622and categorize these enums with error domains. 3623 3624The ``ns_error_domain`` attribute indicates a global ``NSString`` or 3625``CFString`` constant representing the error domain that an error code belongs 3626to. For pointer uniqueness and code size this is a constant symbol, not a 3627literal. 3628 3629The domain and error code need to be used together. The ``ns_error_domain`` 3630attribute links error codes to their domain at the source level. 3631 3632This metadata is useful for documentation purposes, for static analysis, and for 3633improving interoperability between Objective-C and Swift. It is not used for 3634code generation in Objective-C. 3635 3636For example: 3637 3638 .. code-block:: objc 3639 3640 #define NS_ERROR_ENUM(_type, _name, _domain) \ 3641 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type 3642 3643 extern NSString *const MyErrorDomain; 3644 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) { 3645 MyErrFirst, 3646 MyErrSecond, 3647 }; 3648 }]; 3649} 3650 3651def SwiftDocs : DocumentationCategory<"Customizing Swift Import"> { 3652 let Content = [{ 3653Clang supports additional attributes for customizing how APIs are imported into 3654Swift. 3655 }]; 3656} 3657 3658def SwiftAsyncNameDocs : Documentation { 3659 let Category = SwiftDocs; 3660 let Heading = "swift_async_name"; 3661 let Content = [{ 3662The ``swift_async_name`` attribute provides the name of the ``async`` overload for 3663the given declaration in Swift. If this attribute is absent, the name is 3664transformed according to the algorithm built into the Swift compiler. 3665 3666The argument is a string literal that contains the Swift name of the function or 3667method. The name may be a compound Swift name. The function or method with such 3668an attribute must have more than zero parameters, as its last parameter is 3669assumed to be a callback that's eliminated in the Swift ``async`` name. 3670 3671 .. code-block:: objc 3672 3673 @interface URL 3674 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)"))) 3675 @end 3676 }]; 3677} 3678 3679def SwiftAttrDocs : Documentation { 3680 let Category = SwiftDocs; 3681 let Heading = "swift_attr"; 3682 let Content = [{ 3683The ``swift_attr`` provides a Swift-specific annotation for the declaration 3684to which the attribute appertains to. It can be used on any declaration 3685in Clang. This kind of annotation is ignored by Clang as it doesn't have any 3686semantic meaning in languages supported by Clang. The Swift compiler can 3687interpret these annotations according to its own rules when importing C or 3688Objective-C declarations. 3689}]; 3690} 3691 3692def SwiftBridgeDocs : Documentation { 3693 let Category = SwiftDocs; 3694 let Heading = "swift_bridge"; 3695 let Content = [{ 3696The ``swift_bridge`` attribute indicates that the declaration to which the 3697attribute appertains is bridged to the named Swift type. 3698 3699 .. code-block:: objc 3700 3701 __attribute__((__objc_root__)) 3702 @interface Base 3703 - (instancetype)init; 3704 @end 3705 3706 __attribute__((__swift_bridge__("BridgedI"))) 3707 @interface I : Base 3708 @end 3709 3710In this example, the Objective-C interface ``I`` will be made available to Swift 3711with the name ``BridgedI``. It would be possible for the compiler to refer to 3712``I`` still in order to bridge the type back to Objective-C. 3713 }]; 3714} 3715 3716def SwiftBridgedTypedefDocs : Documentation { 3717 let Category = SwiftDocs; 3718 let Heading = "swift_bridged"; 3719 let Content = [{ 3720The ``swift_bridged_typedef`` attribute indicates that when the typedef to which 3721the attribute appertains is imported into Swift, it should refer to the bridged 3722Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written 3723(e.g. ``NSString``). 3724 3725 .. code-block:: objc 3726 3727 @interface NSString; 3728 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__)); 3729 3730 extern void acceptsAliasedString(AliasedString _Nonnull parameter); 3731 3732In this case, the function ``acceptsAliasedString`` will be imported into Swift 3733as a function which accepts a ``String`` type parameter. 3734 }]; 3735} 3736 3737def SwiftObjCMembersDocs : Documentation { 3738 let Category = SwiftDocs; 3739 let Heading = "swift_objc_members"; 3740 let Content = [{ 3741This attribute indicates that Swift subclasses and members of Swift extensions 3742of this class will be implicitly marked with the ``@objcMembers`` Swift 3743attribute, exposing them back to Objective-C. 3744 }]; 3745} 3746 3747def SwiftErrorDocs : Documentation { 3748 let Category = SwiftDocs; 3749 let Heading = "swift_error"; 3750 let Content = [{ 3751The ``swift_error`` attribute controls whether a particular function (or 3752Objective-C method) is imported into Swift as a throwing function, and if so, 3753which dynamic convention it uses. 3754 3755All of these conventions except ``none`` require the function to have an error 3756parameter. Currently, the error parameter is always the last parameter of type 3757``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from 3758the imported API. When calling the API, Swift will always pass a valid address 3759initialized to a null pointer. 3760 3761* ``swift_error(none)`` means that the function should not be imported as 3762 throwing. The error parameter and result type will be imported normally. 3763 3764* ``swift_error(null_result)`` means that calls to the function should be 3765 considered to have thrown if they return a null value. The return type must be 3766 a pointer type, and it will be imported into Swift with a non-optional type. 3767 This is the default error convention for Objective-C methods that return 3768 pointers. 3769 3770* ``swift_error(zero_result)`` means that calls to the function should be 3771 considered to have thrown if they return a zero result. The return type must be 3772 an integral type. If the return type would have been imported as ``Bool``, it 3773 is instead imported as ``Void``. This is the default error convention for 3774 Objective-C methods that return a type that would be imported as ``Bool``. 3775 3776* ``swift_error(nonzero_result)`` means that calls to the function should be 3777 considered to have thrown if they return a non-zero result. The return type must 3778 be an integral type. If the return type would have been imported as ``Bool``, 3779 it is instead imported as ``Void``. 3780 3781* ``swift_error(nonnull_error)`` means that calls to the function should be 3782 considered to have thrown if they leave a non-null error in the error parameter. 3783 The return type is left unmodified. 3784 3785 }]; 3786} 3787 3788def SwiftNameDocs : Documentation { 3789 let Category = SwiftDocs; 3790 let Heading = "swift_name"; 3791 let Content = [{ 3792The ``swift_name`` attribute provides the name of the declaration in Swift. If 3793this attribute is absent, the name is transformed according to the algorithm 3794built into the Swift compiler. 3795 3796The argument is a string literal that contains the Swift name of the function, 3797variable, or type. When renaming a function, the name may be a compound Swift 3798name. For a type, enum constant, property, or variable declaration, the name 3799must be a simple or qualified identifier. 3800 3801 .. code-block:: objc 3802 3803 @interface URL 3804 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)"))) 3805 @end 3806 3807 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) { 3808 } 3809 }]; 3810} 3811 3812def SwiftNewTypeDocs : Documentation { 3813 let Category = SwiftDocs; 3814 let Heading = "swift_newtype"; 3815 let Content = [{ 3816The ``swift_newtype`` attribute indicates that the typedef to which the 3817attribute appertains is imported as a new Swift type of the typedef's name. 3818Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of 3819the attribute is identical with either spelling, ``swift_wrapper`` is 3820deprecated, only exists for compatibility purposes, and should not be used in 3821new code. 3822 3823* ``swift_newtype(struct)`` means that a Swift struct will be created for this 3824 typedef. 3825 3826* ``swift_newtype(enum)`` means that a Swift enum will be created for this 3827 typedef. 3828 3829 .. code-block:: c 3830 3831 // Import UIFontTextStyle as an enum type, with enumerated values being 3832 // constants. 3833 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum))); 3834 3835 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated 3836 // values being members of the type structure. 3837 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct))); 3838 3839 }]; 3840} 3841 3842def SwiftPrivateDocs : Documentation { 3843 let Category = SwiftDocs; 3844 let Heading = "swift_private"; 3845 let Content = [{ 3846Declarations marked with the ``swift_private`` attribute are hidden from the 3847framework client but are still made available for use within the framework or 3848Swift SDK overlay. 3849 3850The purpose of this attribute is to permit a more idomatic implementation of 3851declarations in Swift while hiding the non-idiomatic one. 3852 }]; 3853} 3854 3855def OMPDeclareSimdDocs : Documentation { 3856 let Category = DocCatFunction; 3857 let Heading = "#pragma omp declare simd"; 3858 let Content = [{ 3859The ``declare simd`` construct can be applied to a function to enable the creation 3860of one or more versions that can process multiple arguments using SIMD 3861instructions from a single invocation in a SIMD loop. The ``declare simd`` 3862directive is a declarative directive. There may be multiple ``declare simd`` 3863directives for a function. The use of a ``declare simd`` construct on a function 3864enables the creation of SIMD versions of the associated function that can be 3865used to process multiple arguments from a single invocation from a SIMD loop 3866concurrently. 3867The syntax of the ``declare simd`` construct is as follows: 3868 3869 .. code-block:: none 3870 3871 #pragma omp declare simd [clause[[,] clause] ...] new-line 3872 [#pragma omp declare simd [clause[[,] clause] ...] new-line] 3873 [...] 3874 function definition or declaration 3875 3876where clause is one of the following: 3877 3878 .. code-block:: none 3879 3880 simdlen(length) 3881 linear(argument-list[:constant-linear-step]) 3882 aligned(argument-list[:alignment]) 3883 uniform(argument-list) 3884 inbranch 3885 notinbranch 3886 3887 }]; 3888} 3889 3890def OMPDeclareTargetDocs : Documentation { 3891 let Category = DocCatFunction; 3892 let Heading = "#pragma omp declare target"; 3893 let Content = [{ 3894The ``declare target`` directive specifies that variables and functions are mapped 3895to a device for OpenMP offload mechanism. 3896 3897The syntax of the declare target directive is as follows: 3898 3899 .. code-block:: c 3900 3901 #pragma omp declare target new-line 3902 declarations-definition-seq 3903 #pragma omp end declare target new-line 3904 3905or 3906 3907 .. code-block:: c 3908 3909 #pragma omp declare target (extended-list) new-line 3910 3911or 3912 3913 .. code-block:: c 3914 3915 #pragma omp declare target clause[ [,] clause ... ] new-line 3916 3917where clause is one of the following: 3918 3919 3920 .. code-block:: c 3921 3922 to(extended-list) 3923 link(list) 3924 device_type(host | nohost | any) 3925 }]; 3926} 3927 3928def OMPDeclareVariantDocs : Documentation { 3929 let Category = DocCatFunction; 3930 let Heading = "#pragma omp declare variant"; 3931 let Content = [{ 3932The ``declare variant`` directive declares a specialized variant of a base 3933function and specifies the context in which that specialized variant is used. 3934The declare variant directive is a declarative directive. 3935The syntax of the ``declare variant`` construct is as follows: 3936 3937 .. code-block:: none 3938 3939 #pragma omp declare variant(variant-func-id) clause new-line 3940 [#pragma omp declare variant(variant-func-id) clause new-line] 3941 [...] 3942 function definition or declaration 3943 3944where clause is one of the following: 3945 3946 .. code-block:: none 3947 3948 match(context-selector-specification) 3949 3950and where ``variant-func-id`` is the name of a function variant that is either a 3951base language identifier or, for C++, a template-id. 3952 3953Clang provides the following context selector extensions, used via 3954``implementation={extension(EXTENSION)}``: 3955 3956 .. code-block:: none 3957 3958 match_all 3959 match_any 3960 match_none 3961 disable_implicit_base 3962 allow_templates 3963 3964The match extensions change when the *entire* context selector is considered a 3965match for an OpenMP context. The default is ``all``, with ``none`` no trait in the 3966selector is allowed to be in the OpenMP context, with ``any`` a single trait in 3967both the selector and OpenMP context is sufficient. Only a single match 3968extension trait is allowed per context selector. 3969The disable extensions remove default effects of the ``begin declare variant`` 3970applied to a definition. If ``disable_implicit_base`` is given, we will not 3971introduce an implicit base function for a variant if no base function was 3972found. The variant is still generated but will never be called, due to the 3973absence of a base function and consequently calls to a base function. 3974The allow extensions change when the ``begin declare variant`` effect is 3975applied to a definition. If ``allow_templates`` is given, template function 3976definitions are considered as specializations of existing or assumed template 3977declarations with the same name. The template parameters for the base functions 3978are used to instantiate the specialization. 3979 3980 }]; 3981} 3982 3983def LeafDocs : Documentation { 3984 let Category = DocCatVariable; 3985 let Content = [{ 3986 3987The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis 3988in library functions. Functions marked with the ``leaf`` attribute are not allowed 3989to jump back into the caller's translation unit, whether through invoking a 3990callback function, an external function call, use of ``longjmp``, or other means. 3991Therefore, they cannot use or modify any data that does not escape the caller function's 3992compilation unit. 3993 3994For more information see 3995`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>` 3996}]; 3997} 3998 3999def AssumptionDocs : Documentation { 4000 let Category = DocCatFunction; 4001 let Heading = "assume"; 4002 let Content = [{ 4003Clang supports the ``__attribute__((assume("assumption")))`` attribute to 4004provide additional information to the optimizer. The string-literal, here 4005"assumption", will be attached to the function declaration such that later 4006analysis and optimization passes can assume the "assumption" to hold. 4007This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but 4008instead of an expression that can be assumed to be non-zero, the assumption is 4009expressed as a string and it holds for the entire function. 4010 4011A function can have multiple assume attributes and they propagate from prior 4012declarations to later definitions. Multiple assumptions are aggregated into a 4013single comma separated string. Thus, one can provide multiple assumptions via 4014a comma separated string, i.a., 4015``__attribute__((assume("assumption1,assumption2")))``. 4016 4017While LLVM plugins might provide more assumption strings, the default LLVM 4018optimization passes are aware of the following assumptions: 4019 4020 .. code-block:: none 4021 4022 "omp_no_openmp" 4023 "omp_no_openmp_routines" 4024 "omp_no_parallelism" 4025 4026The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is 4027spelled "XYZ" in the `OpenMP 5.1 Standard`_). 4028 4029.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2 4030 4031}]; 4032} 4033 4034def NoStackProtectorDocs : Documentation { 4035 let Category = DocCatFunction; 4036 let Content = [{ 4037Clang supports the ``__attribute__((no_stack_protector))`` attribute which disables 4038the stack protector on the specified function. This attribute is useful for 4039selectively disabling the stack protector on some functions when building with 4040``-fstack-protector`` compiler option. 4041 4042For example, it disables the stack protector for the function ``foo`` but function 4043``bar`` will still be built with the stack protector with the ``-fstack-protector`` 4044option. 4045 4046.. code-block:: c 4047 4048 int __attribute__((no_stack_protector)) 4049 foo (int x); // stack protection will be disabled for foo. 4050 4051 int bar(int y); // bar can be built with the stack protector. 4052 4053 }]; 4054} 4055 4056def NotTailCalledDocs : Documentation { 4057 let Category = DocCatFunction; 4058 let Content = [{ 4059The ``not_tail_called`` attribute prevents tail-call optimization on statically 4060bound calls. It has no effect on indirect calls. Virtual functions, objective-c 4061methods, and functions marked as ``always_inline`` cannot be marked as 4062``not_tail_called``. 4063 4064For example, it prevents tail-call optimization in the following case: 4065 4066 .. code-block:: c 4067 4068 int __attribute__((not_tail_called)) foo1(int); 4069 4070 int foo2(int a) { 4071 return foo1(a); // No tail-call optimization on direct calls. 4072 } 4073 4074However, it doesn't prevent tail-call optimization in this case: 4075 4076 .. code-block:: c 4077 4078 int __attribute__((not_tail_called)) foo1(int); 4079 4080 int foo2(int a) { 4081 int (*fn)(int) = &foo1; 4082 4083 // not_tail_called has no effect on an indirect call even if the call can 4084 // be resolved at compile time. 4085 return (*fn)(a); 4086 } 4087 4088Marking virtual functions as ``not_tail_called`` is an error: 4089 4090 .. code-block:: c++ 4091 4092 class Base { 4093 public: 4094 // not_tail_called on a virtual function is an error. 4095 [[clang::not_tail_called]] virtual int foo1(); 4096 4097 virtual int foo2(); 4098 4099 // Non-virtual functions can be marked ``not_tail_called``. 4100 [[clang::not_tail_called]] int foo3(); 4101 }; 4102 4103 class Derived1 : public Base { 4104 public: 4105 int foo1() override; 4106 4107 // not_tail_called on a virtual function is an error. 4108 [[clang::not_tail_called]] int foo2() override; 4109 }; 4110 }]; 4111} 4112 4113def NoThrowDocs : Documentation { 4114 let Category = DocCatFunction; 4115 let Content = [{ 4116Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style 4117``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function 4118declarations. This attribute informs the compiler that the annotated function 4119does not throw an exception. This prevents exception-unwinding. This attribute 4120is particularly useful on functions in the C Standard Library that are 4121guaranteed to not throw an exception. 4122 }]; 4123} 4124 4125def InternalLinkageDocs : Documentation { 4126 let Category = DocCatFunction; 4127 let Content = [{ 4128The ``internal_linkage`` attribute changes the linkage type of the declaration 4129to internal. This is similar to C-style ``static``, but can be used on classes 4130and class methods. When applied to a class definition, this attribute affects 4131all methods and static data members of that class. This can be used to contain 4132the ABI of a C++ library by excluding unwanted class methods from the export 4133tables. 4134 }]; 4135} 4136 4137def ExcludeFromExplicitInstantiationDocs : Documentation { 4138 let Category = DocCatFunction; 4139 let Content = [{ 4140The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a 4141class template from being part of explicit template instantiations of that 4142class template. This means that an explicit instantiation will not instantiate 4143members of the class template marked with the attribute, but also that code 4144where an extern template declaration of the enclosing class template is visible 4145will not take for granted that an external instantiation of the class template 4146would provide those members (which would otherwise be a link error, since the 4147explicit instantiation won't provide those members). For example, let's say we 4148don't want the ``data()`` method to be part of libc++'s ABI. To make sure it 4149is not exported from the dylib, we give it hidden visibility: 4150 4151 .. code-block:: c++ 4152 4153 // in <string> 4154 template <class CharT> 4155 class basic_string { 4156 public: 4157 __attribute__((__visibility__("hidden"))) 4158 const value_type* data() const noexcept { ... } 4159 }; 4160 4161 template class basic_string<char>; 4162 4163Since an explicit template instantiation declaration for ``basic_string<char>`` 4164is provided, the compiler is free to assume that ``basic_string<char>::data()`` 4165will be provided by another translation unit, and it is free to produce an 4166external call to this function. However, since ``data()`` has hidden visibility 4167and the explicit template instantiation is provided in a shared library (as 4168opposed to simply another translation unit), ``basic_string<char>::data()`` 4169won't be found and a link error will ensue. This happens because the compiler 4170assumes that ``basic_string<char>::data()`` is part of the explicit template 4171instantiation declaration, when it really isn't. To tell the compiler that 4172``data()`` is not part of the explicit template instantiation declaration, the 4173``exclude_from_explicit_instantiation`` attribute can be used: 4174 4175 .. code-block:: c++ 4176 4177 // in <string> 4178 template <class CharT> 4179 class basic_string { 4180 public: 4181 __attribute__((__visibility__("hidden"))) 4182 __attribute__((exclude_from_explicit_instantiation)) 4183 const value_type* data() const noexcept { ... } 4184 }; 4185 4186 template class basic_string<char>; 4187 4188Now, the compiler won't assume that ``basic_string<char>::data()`` is provided 4189externally despite there being an explicit template instantiation declaration: 4190the compiler will implicitly instantiate ``basic_string<char>::data()`` in the 4191TUs where it is used. 4192 4193This attribute can be used on static and non-static member functions of class 4194templates, static data members of class templates and member classes of class 4195templates. 4196 }]; 4197} 4198 4199def DisableTailCallsDocs : Documentation { 4200 let Category = DocCatFunction; 4201 let Content = [{ 4202The ``disable_tail_calls`` attribute instructs the backend to not perform tail 4203call optimization inside the marked function. 4204 4205For example: 4206 4207 .. code-block:: c 4208 4209 int callee(int); 4210 4211 int foo(int a) __attribute__((disable_tail_calls)) { 4212 return callee(a); // This call is not tail-call optimized. 4213 } 4214 4215Marking virtual functions as ``disable_tail_calls`` is legal. 4216 4217 .. code-block:: c++ 4218 4219 int callee(int); 4220 4221 class Base { 4222 public: 4223 [[clang::disable_tail_calls]] virtual int foo1() { 4224 return callee(); // This call is not tail-call optimized. 4225 } 4226 }; 4227 4228 class Derived1 : public Base { 4229 public: 4230 int foo1() override { 4231 return callee(); // This call is tail-call optimized. 4232 } 4233 }; 4234 4235 }]; 4236} 4237 4238def AnyX86NoCallerSavedRegistersDocs : Documentation { 4239 let Category = DocCatFunction; 4240 let Content = [{ 4241Use this attribute to indicate that the specified function has no 4242caller-saved registers. That is, all registers are callee-saved except for 4243registers used for passing parameters to the function or returning parameters 4244from the function. 4245The compiler saves and restores any modified registers that were not used for 4246passing or returning arguments to the function. 4247 4248The user can call functions specified with the 'no_caller_saved_registers' 4249attribute from an interrupt handler without saving and restoring all 4250call-clobbered registers. 4251 4252Note that 'no_caller_saved_registers' attribute is not a calling convention. 4253In fact, it only overrides the decision of which registers should be saved by 4254the caller, but not how the parameters are passed from the caller to the callee. 4255 4256For example: 4257 4258 .. code-block:: c 4259 4260 __attribute__ ((no_caller_saved_registers, fastcall)) 4261 void f (int arg1, int arg2) { 4262 ... 4263 } 4264 4265 In this case parameters 'arg1' and 'arg2' will be passed in registers. 4266 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as 4267 register parameters. However, it will not assume any scratch registers and 4268 should save and restore any modified registers except for ECX and EDX. 4269 }]; 4270} 4271 4272def X86ForceAlignArgPointerDocs : Documentation { 4273 let Category = DocCatFunction; 4274 let Content = [{ 4275Use this attribute to force stack alignment. 4276 4277Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions 4278(like 'movaps') that work with the stack require operands to be 16-byte aligned. 4279This attribute realigns the stack in the function prologue to make sure the 4280stack can be used with SSE instructions. 4281 4282Note that the x86_64 ABI forces 16-byte stack alignment at the call site. 4283Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in 4284rare cases where the caller does not align the stack properly (e.g. flow 4285jumps from i386 arch code). 4286 4287 .. code-block:: c 4288 4289 __attribute__ ((force_align_arg_pointer)) 4290 void f () { 4291 ... 4292 } 4293 4294 }]; 4295} 4296 4297def AnyX86NoCfCheckDocs : Documentation { 4298 let Category = DocCatFunction; 4299 let Content = [{ 4300Jump Oriented Programming attacks rely on tampering with addresses used by 4301indirect call / jmp, e.g. redirect control-flow to non-programmer 4302intended bytes in the binary. 4303X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow 4304Enforcement Technology (CET). IBT instruments ENDBR instructions used to 4305specify valid targets of indirect call / jmp. 4306The ``nocf_check`` attribute has two roles: 43071. Appertains to a function - do not add ENDBR instruction at the beginning of 4308the function. 43092. Appertains to a function pointer - do not track the target function of this 4310pointer (by adding nocf_check prefix to the indirect-call instruction). 4311}]; 4312} 4313 4314def SwiftCallDocs : Documentation { 4315 let Category = DocCatVariable; 4316 let Content = [{ 4317The ``swiftcall`` attribute indicates that a function should be called 4318using the Swift calling convention for a function or function pointer. 4319 4320The lowering for the Swift calling convention, as described by the Swift 4321ABI documentation, occurs in multiple phases. The first, "high-level" 4322phase breaks down the formal parameters and results into innately direct 4323and indirect components, adds implicit parameters for the generic 4324signature, and assigns the context and error ABI treatments to parameters 4325where applicable. The second phase breaks down the direct parameters 4326and results from the first phase and assigns them to registers or the 4327stack. The ``swiftcall`` convention only handles this second phase of 4328lowering; the C function type must accurately reflect the results 4329of the first phase, as follows: 4330 4331- Results classified as indirect by high-level lowering should be 4332 represented as parameters with the ``swift_indirect_result`` attribute. 4333 4334- Results classified as direct by high-level lowering should be represented 4335 as follows: 4336 4337 - First, remove any empty direct results. 4338 4339 - If there are no direct results, the C result type should be ``void``. 4340 4341 - If there is one direct result, the C result type should be a type with 4342 the exact layout of that result type. 4343 4344 - If there are a multiple direct results, the C result type should be 4345 a struct type with the exact layout of a tuple of those results. 4346 4347- Parameters classified as indirect by high-level lowering should be 4348 represented as parameters of pointer type. 4349 4350- Parameters classified as direct by high-level lowering should be 4351 omitted if they are empty types; otherwise, they should be represented 4352 as a parameter type with a layout exactly matching the layout of the 4353 Swift parameter type. 4354 4355- The context parameter, if present, should be represented as a trailing 4356 parameter with the ``swift_context`` attribute. 4357 4358- The error result parameter, if present, should be represented as a 4359 trailing parameter (always following a context parameter) with the 4360 ``swift_error_result`` attribute. 4361 4362``swiftcall`` does not support variadic arguments or unprototyped functions. 4363 4364The parameter ABI treatment attributes are aspects of the function type. 4365A function type which applies an ABI treatment attribute to a 4366parameter is a different type from an otherwise-identical function type 4367that does not. A single parameter may not have multiple ABI treatment 4368attributes. 4369 4370Support for this feature is target-dependent, although it should be 4371supported on every target that Swift supports. Query for this support 4372with ``__has_attribute(swiftcall)``. This implies support for the 4373``swift_context``, ``swift_error_result``, and ``swift_indirect_result`` 4374attributes. 4375 }]; 4376} 4377 4378def SwiftContextDocs : Documentation { 4379 let Category = DocCatVariable; 4380 let Content = [{ 4381The ``swift_context`` attribute marks a parameter of a ``swiftcall`` 4382function as having the special context-parameter ABI treatment. 4383 4384This treatment generally passes the context value in a special register 4385which is normally callee-preserved. 4386 4387A ``swift_context`` parameter must either be the last parameter or must be 4388followed by a ``swift_error_result`` parameter (which itself must always be 4389the last parameter). 4390 4391A context parameter must have pointer or reference type. 4392 }]; 4393} 4394 4395def SwiftErrorResultDocs : Documentation { 4396 let Category = DocCatVariable; 4397 let Content = [{ 4398The ``swift_error_result`` attribute marks a parameter of a ``swiftcall`` 4399function as having the special error-result ABI treatment. 4400 4401This treatment generally passes the underlying error value in and out of 4402the function through a special register which is normally callee-preserved. 4403This is modeled in C by pretending that the register is addressable memory: 4404 4405- The caller appears to pass the address of a variable of pointer type. 4406 The current value of this variable is copied into the register before 4407 the call; if the call returns normally, the value is copied back into the 4408 variable. 4409 4410- The callee appears to receive the address of a variable. This address 4411 is actually a hidden location in its own stack, initialized with the 4412 value of the register upon entry. When the function returns normally, 4413 the value in that hidden location is written back to the register. 4414 4415A ``swift_error_result`` parameter must be the last parameter, and it must be 4416preceded by a ``swift_context`` parameter. 4417 4418A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some 4419type T. Note that no qualifiers are permitted on the intermediate level. 4420 4421It is undefined behavior if the caller does not pass a pointer or 4422reference to a valid object. 4423 4424The standard convention is that the error value itself (that is, the 4425value stored in the apparent argument) will be null upon function entry, 4426but this is not enforced by the ABI. 4427 }]; 4428} 4429 4430def SwiftIndirectResultDocs : Documentation { 4431 let Category = DocCatVariable; 4432 let Content = [{ 4433The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall`` 4434function as having the special indirect-result ABI treatment. 4435 4436This treatment gives the parameter the target's normal indirect-result 4437ABI treatment, which may involve passing it differently from an ordinary 4438parameter. However, only the first indirect result will receive this 4439treatment. Furthermore, low-level lowering may decide that a direct result 4440must be returned indirectly; if so, this will take priority over the 4441``swift_indirect_result`` parameters. 4442 4443A ``swift_indirect_result`` parameter must either be the first parameter or 4444follow another ``swift_indirect_result`` parameter. 4445 4446A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for 4447some object type ``T``. If ``T`` is a complete type at the point of 4448definition of a function, it is undefined behavior if the argument 4449value does not point to storage of adequate size and alignment for a 4450value of type ``T``. 4451 4452Making indirect results explicit in the signature allows C functions to 4453directly construct objects into them without relying on language 4454optimizations like C++'s named return value optimization (NRVO). 4455 }]; 4456} 4457 4458def SwiftAsyncDocs : Documentation { 4459 let Category = SwiftDocs; 4460 let Heading = "swift_async"; 4461 let Content = [{ 4462The ``swift_async`` attribute specifies if and how a particular function or 4463Objective-C method is imported into a swift async method. For instance: 4464 4465.. code-block:: objc 4466 4467 @interface MyClass : NSObject 4468 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler 4469 __attribute__((swift_async(none))); 4470 4471 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun 4472 __attribute__((swift_async(swift_private, 1))); 4473 @end 4474 4475Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as 4476``async`` (because it's last parameter's selector piece is 4477``withCompletionHandler``) if not for the ``swift_async(none)`` attribute. 4478Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as 4479``async`` if not for the ``swift_async`` attribute because it doesn't match the 4480naming convention. 4481 4482When using ``swift_async`` to enable importing, the first argument to the 4483attribute is either ``swift_private`` or ``not_swift_private`` to indicate 4484whether the function/method is private to the current framework, and the second 4485argument is the index of the completion handler parameter. 4486 }]; 4487} 4488 4489def SuppressDocs : Documentation { 4490 let Category = DocCatStmt; 4491 let Content = [{ 4492The ``[[gsl::suppress]]`` attribute suppresses specific 4493clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable 4494way. The attribute can be attached to declarations, statements, and at 4495namespace scope. 4496 4497.. code-block:: c++ 4498 4499 [[gsl::suppress("Rh-public")]] 4500 void f_() { 4501 int *p; 4502 [[gsl::suppress("type")]] { 4503 p = reinterpret_cast<int*>(7); 4504 } 4505 } 4506 namespace N { 4507 [[clang::suppress("type", "bounds")]]; 4508 ... 4509 } 4510 4511.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement 4512 }]; 4513} 4514 4515def AbiTagsDocs : Documentation { 4516 let Category = DocCatFunction; 4517 let Content = [{ 4518The ``abi_tag`` attribute can be applied to a function, variable, class or 4519inline namespace declaration to modify the mangled name of the entity. It gives 4520the ability to distinguish between different versions of the same entity but 4521with different ABI versions supported. For example, a newer version of a class 4522could have a different set of data members and thus have a different size. Using 4523the ``abi_tag`` attribute, it is possible to have different mangled names for 4524a global variable of the class type. Therefore, the old code could keep using 4525the old mangled name and the new code will use the new mangled name with tags. 4526 }]; 4527} 4528 4529def PreferredNameDocs : Documentation { 4530 let Category = DocCatDecl; 4531 let Content = [{ 4532The ``preferred_name`` attribute can be applied to a class template, and 4533specifies a preferred way of naming a specialization of the template. The 4534preferred name will be used whenever the corresponding template specialization 4535would otherwise be printed in a diagnostic or similar context. 4536 4537The preferred name must be a typedef or type alias declaration that refers to a 4538specialization of the class template (not including any type qualifiers). In 4539general this requires the template to be declared at least twice. For example: 4540 4541.. code-block:: c++ 4542 4543 template<typename T> struct basic_string; 4544 using string = basic_string<char>; 4545 using wstring = basic_string<wchar_t>; 4546 template<typename T> struct [[clang::preferred_name(string), 4547 clang::preferred_name(wstring)]] basic_string { 4548 // ... 4549 }; 4550 }]; 4551} 4552 4553def PreserveMostDocs : Documentation { 4554 let Category = DocCatCallingConvs; 4555 let Content = [{ 4556On X86-64 and AArch64 targets, this attribute changes the calling convention of 4557a function. The ``preserve_most`` calling convention attempts to make the code 4558in the caller as unintrusive as possible. This convention behaves identically 4559to the ``C`` calling convention on how arguments and return values are passed, 4560but it uses a different set of caller/callee-saved registers. This alleviates 4561the burden of saving and recovering a large register set before and after the 4562call in the caller. If the arguments are passed in callee-saved registers, 4563then they will be preserved by the callee across the call. This doesn't 4564apply for values returned in callee-saved registers. 4565 4566- On X86-64 the callee preserves all general purpose registers, except for 4567 R11. R11 can be used as a scratch register. Floating-point registers 4568 (XMMs/YMMs) are not preserved and need to be saved by the caller. 4569 4570The idea behind this convention is to support calls to runtime functions 4571that have a hot path and a cold path. The hot path is usually a small piece 4572of code that doesn't use many registers. The cold path might need to call out to 4573another function and therefore only needs to preserve the caller-saved 4574registers, which haven't already been saved by the caller. The 4575``preserve_most`` calling convention is very similar to the ``cold`` calling 4576convention in terms of caller/callee-saved registers, but they are used for 4577different types of function calls. ``coldcc`` is for function calls that are 4578rarely executed, whereas ``preserve_most`` function calls are intended to be 4579on the hot path and definitely executed a lot. Furthermore ``preserve_most`` 4580doesn't prevent the inliner from inlining the function call. 4581 4582This calling convention will be used by a future version of the Objective-C 4583runtime and should therefore still be considered experimental at this time. 4584Although this convention was created to optimize certain runtime calls to 4585the Objective-C runtime, it is not limited to this runtime and might be used 4586by other runtimes in the future too. The current implementation only 4587supports X86-64 and AArch64, but the intention is to support more architectures 4588in the future. 4589 }]; 4590} 4591 4592def PreserveAllDocs : Documentation { 4593 let Category = DocCatCallingConvs; 4594 let Content = [{ 4595On X86-64 and AArch64 targets, this attribute changes the calling convention of 4596a function. The ``preserve_all`` calling convention attempts to make the code 4597in the caller even less intrusive than the ``preserve_most`` calling convention. 4598This calling convention also behaves identical to the ``C`` calling convention 4599on how arguments and return values are passed, but it uses a different set of 4600caller/callee-saved registers. This removes the burden of saving and 4601recovering a large register set before and after the call in the caller. If 4602the arguments are passed in callee-saved registers, then they will be 4603preserved by the callee across the call. This doesn't apply for values 4604returned in callee-saved registers. 4605 4606- On X86-64 the callee preserves all general purpose registers, except for 4607 R11. R11 can be used as a scratch register. Furthermore it also preserves 4608 all floating-point registers (XMMs/YMMs). 4609 4610The idea behind this convention is to support calls to runtime functions 4611that don't need to call out to any other functions. 4612 4613This calling convention, like the ``preserve_most`` calling convention, will be 4614used by a future version of the Objective-C runtime and should be considered 4615experimental at this time. 4616 }]; 4617} 4618 4619def DeprecatedDocs : Documentation { 4620 let Category = DocCatDecl; 4621 let Content = [{ 4622The ``deprecated`` attribute can be applied to a function, a variable, or a 4623type. This is useful when identifying functions, variables, or types that are 4624expected to be removed in a future version of a program. 4625 4626Consider the function declaration for a hypothetical function ``f``: 4627 4628.. code-block:: c++ 4629 4630 void f(void) __attribute__((deprecated("message", "replacement"))); 4631 4632When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have 4633two optional string arguments. The first one is the message to display when 4634emitting the warning; the second one enables the compiler to provide a Fix-It 4635to replace the deprecated name with a new name. Otherwise, when spelled as 4636``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional 4637string argument which is the message to display when emitting the warning. 4638 }]; 4639} 4640 4641def IFuncDocs : Documentation { 4642 let Category = DocCatFunction; 4643 let Content = [{ 4644``__attribute__((ifunc("resolver")))`` is used to mark that the address of a 4645declaration should be resolved at runtime by calling a resolver function. 4646 4647The symbol name of the resolver function is given in quotes. A function with 4648this name (after mangling) must be defined in the current translation unit; it 4649may be ``static``. The resolver function should return a pointer. 4650 4651The ``ifunc`` attribute may only be used on a function declaration. A function 4652declaration with an ``ifunc`` attribute is considered to be a definition of the 4653declared entity. The entity must not have weak linkage; for example, in C++, 4654it cannot be applied to a declaration if a definition at that location would be 4655considered inline. 4656 4657Not all targets support this attribute. ELF target support depends on both the 4658linker and runtime linker, and is available in at least lld 4.0 and later, 4659binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later. 4660Non-ELF targets currently do not support this attribute. 4661 }]; 4662} 4663 4664def LTOVisibilityDocs : Documentation { 4665 let Category = DocCatDecl; 4666 let Content = [{ 4667See :doc:`LTOVisibility`. 4668 }]; 4669} 4670 4671def RenderScriptKernelAttributeDocs : Documentation { 4672 let Category = DocCatFunction; 4673 let Content = [{ 4674``__attribute__((kernel))`` is used to mark a ``kernel`` function in 4675RenderScript. 4676 4677In RenderScript, ``kernel`` functions are used to express data-parallel 4678computations. The RenderScript runtime efficiently parallelizes ``kernel`` 4679functions to run on computational resources such as multi-core CPUs and GPUs. 4680See the RenderScript_ documentation for more information. 4681 4682.. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html 4683 }]; 4684} 4685 4686def XRayDocs : Documentation { 4687 let Category = DocCatFunction; 4688 let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args"; 4689 let Content = [{ 4690``__attribute__((xray_always_instrument))`` or 4691``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), 4692methods (in Objective C), and free functions (in C, C++, and Objective C) to be 4693instrumented with XRay. This will cause the function to always have space at 4694the beginning and exit points to allow for runtime patching. 4695 4696Conversely, ``__attribute__((xray_never_instrument))`` or 4697``[[clang::xray_never_instrument]]`` will inhibit the insertion of these 4698instrumentation points. 4699 4700If a function has neither of these attributes, they become subject to the XRay 4701heuristics used to determine whether a function should be instrumented or 4702otherwise. 4703 4704``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is 4705used to preserve N function arguments for the logging function. Currently, 4706only N==1 is supported. 4707 }]; 4708} 4709 4710def PatchableFunctionEntryDocs : Documentation { 4711 let Category = DocCatFunction; 4712 let Content = [{ 4713``__attribute__((patchable_function_entry(N,M)))`` is used to generate M NOPs 4714before the function entry and N-M NOPs after the function entry. This attribute 4715takes precedence over the command line option ``-fpatchable-function-entry=N,M``. 4716``M`` defaults to 0 if omitted. 4717}]; 4718} 4719 4720def TransparentUnionDocs : Documentation { 4721 let Category = DocCatDecl; 4722 let Content = [{ 4723This attribute can be applied to a union to change the behavior of calls to 4724functions that have an argument with a transparent union type. The compiler 4725behavior is changed in the following manner: 4726 4727- A value whose type is any member of the transparent union can be passed as an 4728 argument without the need to cast that value. 4729 4730- The argument is passed to the function using the calling convention of the 4731 first member of the transparent union. Consequently, all the members of the 4732 transparent union should have the same calling convention as its first member. 4733 4734Transparent unions are not supported in C++. 4735 }]; 4736} 4737 4738def ObjCSubclassingRestrictedDocs : Documentation { 4739 let Category = DocCatDecl; 4740 let Content = [{ 4741This attribute can be added to an Objective-C ``@interface`` declaration to 4742ensure that this class cannot be subclassed. 4743 }]; 4744} 4745 4746def ObjCNonLazyClassDocs : Documentation { 4747 let Category = DocCatDecl; 4748 let Content = [{ 4749This attribute can be added to an Objective-C ``@interface`` or 4750``@implementation`` declaration to add the class to the list of non-lazily 4751initialized classes. A non-lazy class will be initialized eagerly when the 4752Objective-C runtime is loaded. This is required for certain system classes which 4753have instances allocated in non-standard ways, such as the classes for blocks 4754and constant strings. Adding this attribute is essentially equivalent to 4755providing a trivial ``+load`` method but avoids the (fairly small) load-time 4756overheads associated with defining and calling such a method. 4757 }]; 4758} 4759 4760def ObjCDirectDocs : Documentation { 4761 let Category = DocCatDecl; 4762 let Content = [{ 4763The ``objc_direct`` attribute can be used to mark an Objective-C method as 4764being *direct*. A direct method is treated statically like an ordinary method, 4765but dynamically it behaves more like a C function. This lowers some of the costs 4766associated with the method but also sacrifices some of the ordinary capabilities 4767of Objective-C methods. 4768 4769A message send of a direct method calls the implementation directly, as if it 4770were a C function, rather than using ordinary Objective-C method dispatch. This 4771is substantially faster and potentially allows the implementation to be inlined, 4772but it also means the method cannot be overridden in subclasses or replaced 4773dynamically, as ordinary Objective-C methods can. 4774 4775Furthermore, a direct method is not listed in the class's method lists. This 4776substantially reduces the code-size overhead of the method but also means it 4777cannot be called dynamically using ordinary Objective-C method dispatch at all; 4778in particular, this means that it cannot override a superclass method or satisfy 4779a protocol requirement. 4780 4781Because a direct method cannot be overridden, it is an error to perform 4782a ``super`` message send of one. 4783 4784Although a message send of a direct method causes the method to be called 4785directly as if it were a C function, it still obeys Objective-C semantics in other 4786ways: 4787 4788- If the receiver is ``nil``, the message send does nothing and returns the zero value 4789 for the return type. 4790 4791- A message send of a direct class method will cause the class to be initialized, 4792 including calling the ``+initialize`` method if present. 4793 4794- The implicit ``_cmd`` parameter containing the method's selector is still defined. 4795 In order to minimize code-size costs, the implementation will not emit a reference 4796 to the selector if the parameter is unused within the method. 4797 4798Symbols for direct method implementations are implicitly given hidden 4799visibility, meaning that they can only be called within the same linkage unit. 4800 4801It is an error to do any of the following: 4802 4803- declare a direct method in a protocol, 4804- declare an override of a direct method with a method in a subclass, 4805- declare an override of a non-direct method with a direct method in a subclass, 4806- declare a method with different directness in different class interfaces, or 4807- implement a non-direct method (as declared in any class interface) with a direct method. 4808 4809If any of these rules would be violated if every method defined in an 4810``@implementation`` within a single linkage unit were declared in an 4811appropriate class interface, the program is ill-formed with no diagnostic 4812required. If a violation of this rule is not diagnosed, behavior remains 4813well-defined; this paragraph is simply reserving the right to diagnose such 4814conflicts in the future, not to treat them as undefined behavior. 4815 4816Additionally, Clang will warn about any ``@selector`` expression that 4817names a selector that is only known to be used for direct methods. 4818 4819For the purpose of these rules, a "class interface" includes a class's primary 4820``@interface`` block, its class extensions, its categories, its declared protocols, 4821and all the class interfaces of its superclasses. 4822 4823An Objective-C property can be declared with the ``direct`` property 4824attribute. If a direct property declaration causes an implicit declaration of 4825a getter or setter method (that is, if the given method is not explicitly 4826declared elsewhere), the method is declared to be direct. 4827 4828Some programmers may wish to make many methods direct at once. In order 4829to simplify this, the ``objc_direct_members`` attribute is provided; see its 4830documentation for more information. 4831 }]; 4832} 4833 4834def ObjCDirectMembersDocs : Documentation { 4835 let Category = DocCatDecl; 4836 let Content = [{ 4837The ``objc_direct_members`` attribute can be placed on an Objective-C 4838``@interface`` or ``@implementation`` to mark that methods declared 4839therein should be considered direct by default. See the documentation 4840for ``objc_direct`` for more information about direct methods. 4841 4842When ``objc_direct_members`` is placed on an ``@interface`` block, every 4843method in the block is considered to be declared as direct. This includes any 4844implicit method declarations introduced by property declarations. If the method 4845redeclares a non-direct method, the declaration is ill-formed, exactly as if the 4846method was annotated with the ``objc_direct`` attribute. 4847 4848When ``objc_direct_members`` is placed on an ``@implementation`` block, 4849methods defined in the block are considered to be declared as direct unless 4850they have been previously declared as non-direct in any interface of the class. 4851This includes the implicit method definitions introduced by synthesized 4852properties, including auto-synthesized properties. 4853 }]; 4854} 4855 4856def ObjCNonRuntimeProtocolDocs : Documentation { 4857 let Category = DocCatDecl; 4858 let Content = [{ 4859The ``objc_non_runtime_protocol`` attribute can be used to mark that an 4860Objective-C protocol is only used during static type-checking and doesn't need 4861to be represented dynamically. This avoids several small code-size and run-time 4862overheads associated with handling the protocol's metadata. A non-runtime 4863protocol cannot be used as the operand of a ``@protocol`` expression, and 4864dynamic attempts to find it with ``objc_getProtocol`` will fail. 4865 4866If a non-runtime protocol inherits from any ordinary protocols, classes and 4867derived protocols that declare conformance to the non-runtime protocol will 4868dynamically list their conformance to those bare protocols. 4869 }]; 4870} 4871 4872def SelectAnyDocs : Documentation { 4873 let Category = DocCatDecl; 4874 let Content = [{ 4875This attribute appertains to a global symbol, causing it to have a weak 4876definition ( 4877`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_ 4878), allowing the linker to select any definition. 4879 4880For more information see 4881`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_ 4882or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_. 4883}]; } 4884 4885def WebAssemblyExportNameDocs : Documentation { 4886 let Category = DocCatFunction; 4887 let Content = [{ 4888Clang supports the ``__attribute__((export_name(<name>)))`` 4889attribute for the WebAssembly target. This attribute may be attached to a 4890function declaration, where it modifies how the symbol is to be exported 4891from the linked WebAssembly. 4892 4893WebAssembly functions are exported via string name. By default when a symbol 4894is exported, the export name for C/C++ symbols are the same as their C/C++ 4895symbol names. This attribute can be used to override the default behavior, and 4896request a specific string name be used instead. 4897 }]; 4898} 4899 4900def WebAssemblyImportModuleDocs : Documentation { 4901 let Category = DocCatFunction; 4902 let Content = [{ 4903Clang supports the ``__attribute__((import_module(<module_name>)))`` 4904attribute for the WebAssembly target. This attribute may be attached to a 4905function declaration, where it modifies how the symbol is to be imported 4906within the WebAssembly linking environment. 4907 4908WebAssembly imports use a two-level namespace scheme, consisting of a module 4909name, which typically identifies a module from which to import, and a field 4910name, which typically identifies a field from that module to import. By 4911default, module names for C/C++ symbols are assigned automatically by the 4912linker. This attribute can be used to override the default behavior, and 4913request a specific module name be used instead. 4914 }]; 4915} 4916 4917def WebAssemblyImportNameDocs : Documentation { 4918 let Category = DocCatFunction; 4919 let Content = [{ 4920Clang supports the ``__attribute__((import_name(<name>)))`` 4921attribute for the WebAssembly target. This attribute may be attached to a 4922function declaration, where it modifies how the symbol is to be imported 4923within the WebAssembly linking environment. 4924 4925WebAssembly imports use a two-level namespace scheme, consisting of a module 4926name, which typically identifies a module from which to import, and a field 4927name, which typically identifies a field from that module to import. By 4928default, field names for C/C++ symbols are the same as their C/C++ symbol 4929names. This attribute can be used to override the default behavior, and 4930request a specific field name be used instead. 4931 }]; 4932} 4933 4934def ArtificialDocs : Documentation { 4935 let Category = DocCatFunction; 4936 let Content = [{ 4937The ``artificial`` attribute can be applied to an inline function. If such a 4938function is inlined, the attribute indicates that debuggers should associate 4939the resulting instructions with the call site, rather than with the 4940corresponding line within the inlined callee. 4941 }]; 4942} 4943 4944def NoDerefDocs : Documentation { 4945 let Category = DocCatType; 4946 let Content = [{ 4947The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types. 4948This is ideally used with pointers that point to special memory which cannot be read 4949from or written to, but allowing for the pointer to be used in pointer arithmetic. 4950The following are examples of valid expressions where dereferences are diagnosed: 4951 4952.. code-block:: c 4953 4954 int __attribute__((noderef)) *p; 4955 int x = *p; // warning 4956 4957 int __attribute__((noderef)) **p2; 4958 x = **p2; // warning 4959 4960 int * __attribute__((noderef)) *p3; 4961 p = *p3; // warning 4962 4963 struct S { 4964 int a; 4965 }; 4966 struct S __attribute__((noderef)) *s; 4967 x = s->a; // warning 4968 x = (*s).a; // warning 4969 4970Not all dereferences may diagnose a warning if the value directed by the pointer may not be 4971accessed. The following are examples of valid expressions where may not be diagnosed: 4972 4973.. code-block:: c 4974 4975 int *q; 4976 int __attribute__((noderef)) *p; 4977 q = &*p; 4978 q = *&p; 4979 4980 struct S { 4981 int a; 4982 }; 4983 struct S __attribute__((noderef)) *s; 4984 p = &s->a; 4985 p = &(*s).a; 4986 4987``noderef`` is currently only supported for pointers and arrays and not usable 4988for references or Objective-C object pointers. 4989 4990.. code-block: c++ 4991 4992 int x = 2; 4993 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type 4994 4995.. code-block: objc 4996 4997 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type 4998}]; 4999} 5000 5001def ReinitializesDocs : Documentation { 5002 let Category = DocCatFunction; 5003 let Content = [{ 5004The ``reinitializes`` attribute can be applied to a non-static, non-const C++ 5005member function to indicate that this member function reinitializes the entire 5006object to a known state, independent of the previous state of the object. 5007 5008This attribute can be interpreted by static analyzers that warn about uses of an 5009object that has been left in an indeterminate state by a move operation. If a 5010member function marked with the ``reinitializes`` attribute is called on a 5011moved-from object, the analyzer can conclude that the object is no longer in an 5012indeterminate state. 5013 5014A typical example where this attribute would be used is on functions that clear 5015a container class: 5016 5017.. code-block:: c++ 5018 5019 template <class T> 5020 class Container { 5021 public: 5022 ... 5023 [[clang::reinitializes]] void Clear(); 5024 ... 5025 }; 5026 }]; 5027} 5028 5029def AlwaysDestroyDocs : Documentation { 5030 let Category = DocCatVariable; 5031 let Content = [{ 5032The ``always_destroy`` attribute specifies that a variable with static or thread 5033storage duration should have its exit-time destructor run. This attribute is the 5034default unless clang was invoked with -fno-c++-static-destructors. 5035 }]; 5036} 5037 5038def NoDestroyDocs : Documentation { 5039 let Category = DocCatVariable; 5040 let Content = [{ 5041The ``no_destroy`` attribute specifies that a variable with static or thread 5042storage duration shouldn't have its exit-time destructor run. Annotating every 5043static and thread duration variable with this attribute is equivalent to 5044invoking clang with -fno-c++-static-destructors. 5045 5046If a variable is declared with this attribute, clang doesn't access check or 5047generate the type's destructor. If you have a type that you only want to be 5048annotated with ``no_destroy``, you can therefore declare the destructor private: 5049 5050.. code-block:: c++ 5051 5052 struct only_no_destroy { 5053 only_no_destroy(); 5054 private: 5055 ~only_no_destroy(); 5056 }; 5057 5058 [[clang::no_destroy]] only_no_destroy global; // fine! 5059 5060Note that destructors are still required for subobjects of aggregates annotated 5061with this attribute. This is because previously constructed subobjects need to 5062be destroyed if an exception gets thrown before the initialization of the 5063complete object is complete. For instance: 5064 5065.. code-block:: c++ 5066 5067 void f() { 5068 try { 5069 [[clang::no_destroy]] 5070 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor. 5071 } catch (...) { 5072 // Handle the error 5073 } 5074 } 5075 5076Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]`` 5077will be destroyed, so the element's destructor needs to be accessible. 5078 }]; 5079} 5080 5081def UninitializedDocs : Documentation { 5082 let Category = DocCatVariable; 5083 let Content = [{ 5084The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to 5085initialize trivial automatic stack variables. By default, trivial automatic 5086stack variables are uninitialized. This attribute is used to override the 5087command-line parameter, forcing variables to remain uninitialized. It has no 5088semantic meaning in that using uninitialized values is undefined behavior, 5089it rather documents the programmer's intent. 5090 }]; 5091} 5092 5093def LoaderUninitializedDocs : Documentation { 5094 let Category = DocCatVariable; 5095 let Content = [{ 5096The ``loader_uninitialized`` attribute can be placed on global variables to 5097indicate that the variable does not need to be zero initialized by the loader. 5098On most targets, zero-initialization does not incur any additional cost. 5099For example, most general purpose operating systems deliberately ensure 5100that all memory is properly initialized in order to avoid leaking privileged 5101information from the kernel or other programs. However, some targets 5102do not make this guarantee, and on these targets, avoiding an unnecessary 5103zero-initialization can have a significant impact on load times and/or code 5104size. 5105 5106A declaration with this attribute is a non-tentative definition just as if it 5107provided an initializer. Variables with this attribute are considered to be 5108uninitialized in the same sense as a local variable, and the programs must 5109write to them before reading from them. If the variable's type is a C++ class 5110type with a non-trivial default constructor, or an array thereof, this attribute 5111only suppresses the static zero-initialization of the variable, not the dynamic 5112initialization provided by executing the default constructor. 5113 }]; 5114} 5115 5116def CallbackDocs : Documentation { 5117 let Category = DocCatFunction; 5118 let Content = [{ 5119The ``callback`` attribute specifies that the annotated function may invoke the 5120specified callback zero or more times. The callback, as well as the passed 5121arguments, are identified by their parameter name or position (starting with 51221!) in the annotated function. The first position in the attribute identifies 5123the callback callee, the following positions declare describe its arguments. 5124The callback callee is required to be callable with the number, and order, of 5125the specified arguments. The index ``0``, or the identifier ``this``, is used to 5126represent an implicit "this" pointer in class methods. If there is no implicit 5127"this" pointer it shall not be referenced. The index '-1', or the name "__", 5128represents an unknown callback callee argument. This can be a value which is 5129not present in the declared parameter list, or one that is, but is potentially 5130inspected, captured, or modified. Parameter names and indices can be mixed in 5131the callback attribute. 5132 5133The ``callback`` attribute, which is directly translated to ``callback`` 5134metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the 5135connection between the call to the annotated function and the callback callee. 5136This can enable interprocedural optimizations which were otherwise impossible. 5137If a function parameter is mentioned in the ``callback`` attribute, through its 5138position, it is undefined if that parameter is used for anything other than the 5139actual callback. Inspected, captured, or modified parameters shall not be 5140listed in the ``callback`` metadata. 5141 5142Example encodings for the callback performed by ``pthread_create`` are shown 5143below. The explicit attribute annotation indicates that the third parameter 5144(``start_routine``) is called zero or more times by the ``pthread_create`` function, 5145and that the fourth parameter (``arg``) is passed along. Note that the callback 5146behavior of ``pthread_create`` is automatically recognized by Clang. In addition, 5147the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for 5148``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also 5149automatically recognized as broker functions. Further functions might be added 5150in the future. 5151 5152 .. code-block:: c 5153 5154 __attribute__((callback (start_routine, arg))) 5155 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 5156 void *(*start_routine) (void *), void *arg); 5157 5158 __attribute__((callback (3, 4))) 5159 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 5160 void *(*start_routine) (void *), void *arg); 5161 5162 }]; 5163} 5164 5165def CalledOnceDocs : Documentation { 5166 let Category = DocCatVariable; 5167 let Content = [{ 5168The ``called_once`` attribute specifies that the annotated function or method 5169parameter is invoked exactly once on all execution paths. It only applies 5170to parameters with function-like types, i.e. function pointers or blocks. This 5171concept is particularly useful for asynchronous programs. 5172 5173Clang implements a check for ``called_once`` parameters, 5174``-Wcalled-once-parameter``. It is on by default and finds the following 5175violations: 5176 5177* Parameter is not called at all. 5178 5179* Parameter is called more than once. 5180 5181* Parameter is not called on one of the execution paths. 5182 5183In the latter case, Clang pinpoints the path where parameter is not invoked 5184by showing the control-flow statement where the path diverges. 5185 5186.. code-block:: objc 5187 5188 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) { 5189 if (somePredicate()) { 5190 ... 5191 callback(); 5192 } esle { 5193 callback(); // OK: callback is called on every path 5194 } 5195 } 5196 5197 void barWithCallback(void (^callback)(void) __attribute__((called_once))) { 5198 if (somePredicate()) { 5199 ... 5200 callback(); // note: previous call is here 5201 } 5202 callback(); // warning: callback is called twice 5203 } 5204 5205 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) { 5206 if (somePredicate()) { // warning: callback is not called when condition is false 5207 ... 5208 callback(); 5209 } 5210 } 5211 5212This attribute is useful for API developers who want to double-check if they 5213implemented their method correctly. 5214 5215 }]; 5216} 5217 5218def GnuInlineDocs : Documentation { 5219 let Category = DocCatFunction; 5220 let Content = [{ 5221The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline 5222semantics, meaning: 5223 5224* If any declaration that is declared ``inline`` is not declared ``extern``, 5225 then the ``inline`` keyword is just a hint. In particular, an out-of-line 5226 definition is still emitted for a function with external linkage, even if all 5227 call sites are inlined, unlike in C99 and C++ inline semantics. 5228 5229* If all declarations that are declared ``inline`` are also declared 5230 ``extern``, then the function body is present only for inlining and no 5231 out-of-line version is emitted. 5232 5233Some important consequences: ``static inline`` emits an out-of-line 5234version if needed, a plain ``inline`` definition emits an out-of-line version 5235always, and an ``extern inline`` definition (in a header) followed by a 5236(non-``extern``) ``inline`` declaration in a source file emits an out-of-line 5237version of the function in that source file but provides the function body for 5238inlining to all includers of the header. 5239 5240Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or 5241``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually 5242exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline`` 5243function attribute can be used to get GNU inline semantics on a per function 5244basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is 5245already being compiled with GNU inline semantics as the implied default. It is 5246unspecified which macro is defined in a C++ compilation. 5247 5248GNU inline semantics are the default behavior with ``-std=gnu89``, 5249``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``. 5250 }]; 5251} 5252 5253def SpeculativeLoadHardeningDocs : Documentation { 5254 let Category = DocCatFunction; 5255 let Content = [{ 5256 This attribute can be applied to a function declaration in order to indicate 5257 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_ 5258 should be enabled for the function body. This can also be applied to a method 5259 in Objective C. This attribute will take precedence over the command line flag in 5260 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified. 5261 5262 Speculative Load Hardening is a best-effort mitigation against 5263 information leak attacks that make use of control flow 5264 miss-speculation - specifically miss-speculation of whether a branch 5265 is taken or not. Typically vulnerabilities enabling such attacks are 5266 classified as "Spectre variant #1". Notably, this does not attempt to 5267 mitigate against miss-speculation of branch target, classified as 5268 "Spectre variant #2" vulnerabilities. 5269 5270 When inlining, the attribute is sticky. Inlining a function that 5271 carries this attribute will cause the caller to gain the 5272 attribute. This is intended to provide a maximally conservative model 5273 where the code in a function annotated with this attribute will always 5274 (even after inlining) end up hardened. 5275 }]; 5276} 5277 5278def NoSpeculativeLoadHardeningDocs : Documentation { 5279 let Category = DocCatFunction; 5280 let Content = [{ 5281 This attribute can be applied to a function declaration in order to indicate 5282 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_ 5283 is *not* needed for the function body. This can also be applied to a method 5284 in Objective C. This attribute will take precedence over the command line flag in 5285 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified. 5286 5287 Warning: This attribute may not prevent Speculative Load Hardening from being 5288 enabled for a function which inlines a function that has the 5289 'speculative_load_hardening' attribute. This is intended to provide a 5290 maximally conservative model where the code that is marked with the 5291 'speculative_load_hardening' attribute will always (even when inlined) 5292 be hardened. A user of this attribute may want to mark functions called by 5293 a function they do not want to be hardened with the 'noinline' attribute. 5294 5295 For example: 5296 5297 .. code-block:: c 5298 5299 __attribute__((speculative_load_hardening)) 5300 int foo(int i) { 5301 return i; 5302 } 5303 5304 // Note: bar() may still have speculative load hardening enabled if 5305 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline)) 5306 // to avoid this situation. 5307 __attribute__((no_speculative_load_hardening)) 5308 int bar(int i) { 5309 return foo(i); 5310 } 5311 }]; 5312} 5313 5314def ObjCExternallyRetainedDocs : Documentation { 5315 let Category = DocCatVariable; 5316 let Content = [{ 5317The ``objc_externally_retained`` attribute can be applied to strong local 5318variables, functions, methods, or blocks to opt into 5319`externally-retained semantics 5320<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_. 5321 5322When applied to the definition of a function, method, or block, every parameter 5323of the function with implicit strong retainable object pointer type is 5324considered externally-retained, and becomes ``const``. By explicitly annotating 5325a parameter with ``__strong``, you can opt back into the default 5326non-externally-retained behavior for that parameter. For instance, 5327``first_param`` is externally-retained below, but not ``second_param``: 5328 5329.. code-block:: objc 5330 5331 __attribute__((objc_externally_retained)) 5332 void f(NSArray *first_param, __strong NSArray *second_param) { 5333 // ... 5334 } 5335 5336Likewise, when applied to a strong local variable, that variable becomes 5337``const`` and is considered externally-retained. 5338 5339When compiled without ``-fobjc-arc``, this attribute is ignored. 5340}]; } 5341 5342def MIGConventionDocs : Documentation { 5343 let Category = DocCatFunction; 5344 let Content = [{ 5345 The Mach Interface Generator release-on-success convention dictates 5346functions that follow it to only release arguments passed to them when they 5347return "success" (a ``kern_return_t`` error code that indicates that 5348no errors have occurred). Otherwise the release is performed by the MIG client 5349that called the function. The annotation ``__attribute__((mig_server_routine))`` 5350is applied in order to specify which functions are expected to follow the 5351convention. This allows the Static Analyzer to find bugs caused by violations of 5352that convention. The attribute would normally appear on the forward declaration 5353of the actual server routine in the MIG server header, but it may also be 5354added to arbitrary functions that need to follow the same convention - for 5355example, a user can add them to auxiliary functions called by the server routine 5356that have their return value of type ``kern_return_t`` unconditionally returned 5357from the routine. The attribute can be applied to C++ methods, and in this case 5358it will be automatically applied to overrides if the method is virtual. The 5359attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``. 5360}]; 5361} 5362 5363def MSAllocatorDocs : Documentation { 5364 let Category = DocCatFunction; 5365 let Content = [{ 5366The ``__declspec(allocator)`` attribute is applied to functions that allocate 5367memory, such as operator new in C++. When CodeView debug information is emitted 5368(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to 5369record the code offset of heap allocation call sites in the debug info. It will 5370also record the type being allocated using some local heuristics. The Visual 5371Studio debugger uses this information to `profile memory usage`_. 5372 5373.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage 5374 5375This attribute does not affect optimizations in any way, unlike GCC's 5376``__attribute__((malloc))``. 5377}]; 5378} 5379 5380def CFGuardDocs : Documentation { 5381 let Category = DocCatFunction; 5382 let Content = [{ 5383Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))`` 5384attribute. This directs the compiler to not insert any CFG checks for the entire 5385function. This approach is typically used only sparingly in specific situations 5386where the programmer has manually inserted "CFG-equivalent" protection. The 5387programmer knows that they are calling through some read-only function table 5388whose address is obtained through read-only memory references and for which the 5389index is masked to the function table limit. This approach may also be applied 5390to small wrapper functions that are not inlined and that do nothing more than 5391make a call through a function pointer. Since incorrect usage of this directive 5392can compromise the security of CFG, the programmer must be very careful using 5393the directive. Typically, this usage is limited to very small functions that 5394only call one function. 5395 5396`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>` 5397}]; 5398} 5399 5400def CUDADeviceBuiltinSurfaceTypeDocs : Documentation { 5401 let Category = DocCatType; 5402 let Content = [{ 5403The ``device_builtin_surface_type`` attribute can be applied to a class 5404template when declaring the surface reference. A surface reference variable 5405could be accessed on the host side and, on the device side, might be translated 5406into an internal surface object, which is established through surface bind and 5407unbind runtime APIs. 5408 }]; 5409} 5410 5411def CUDADeviceBuiltinTextureTypeDocs : Documentation { 5412 let Category = DocCatType; 5413 let Content = [{ 5414The ``device_builtin_texture_type`` attribute can be applied to a class 5415template when declaring the texture reference. A texture reference variable 5416could be accessed on the host side and, on the device side, might be translated 5417into an internal texture object, which is established through texture bind and 5418unbind runtime APIs. 5419 }]; 5420} 5421 5422def HIPManagedAttrDocs : Documentation { 5423 let Category = DocCatDecl; 5424 let Content = [{ 5425The ``__managed__`` attribute can be applied to a global variable declaration in HIP. 5426A managed variable is emitted as an undefined global symbol in the device binary and is 5427registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates 5428managed memory and uses it to define the symbol when loading the device binary. 5429A managed variable can be accessed in both device and host code. 5430 }]; 5431} 5432 5433def LifetimeOwnerDocs : Documentation { 5434 let Category = DocCatDecl; 5435 let Content = [{ 5436.. Note:: This attribute is experimental and its effect on analysis is subject to change in 5437 a future version of clang. 5438 5439The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an 5440object of type ``T``: 5441 5442.. code:: 5443 5444 class [[gsl::Owner(int)]] IntOwner { 5445 private: 5446 int value; 5447 public: 5448 int *getInt() { return &value; } 5449 }; 5450 5451The argument ``T`` is optional and is ignored. 5452This attribute may be used by analysis tools and has no effect on code 5453generation. A ``void`` argument means that the class can own any type. 5454 5455See Pointer_ for an example. 5456}]; 5457} 5458 5459def LifetimePointerDocs : Documentation { 5460 let Category = DocCatDecl; 5461 let Content = [{ 5462.. Note:: This attribute is experimental and its effect on analysis is subject to change in 5463 a future version of clang. 5464 5465The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave 5466like pointers to an object of type ``T``: 5467 5468.. code:: 5469 5470 class [[gsl::Pointer(int)]] IntPointer { 5471 private: 5472 int *valuePointer; 5473 public: 5474 int *getInt() { return &valuePointer; } 5475 }; 5476 5477The argument ``T`` is optional and is ignored. 5478This attribute may be used by analysis tools and has no effect on code 5479generation. A ``void`` argument means that the pointer can point to any type. 5480 5481Example: 5482When constructing an instance of a class annotated like this (a Pointer) from 5483an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner), 5484then the analysis will consider the Pointer to point inside the Owner. 5485When the Owner's lifetime ends, it will consider the Pointer to be dangling. 5486 5487.. code-block:: c++ 5488 5489 int f() { 5490 IntPointer P; 5491 if (true) { 5492 IntOwner O(7); 5493 P = IntPointer(O); // P "points into" O 5494 } // P is dangling 5495 return P.get(); // error: Using a dangling Pointer. 5496 } 5497 5498}]; 5499} 5500 5501def ArmBuiltinAliasDocs : Documentation { 5502 let Category = DocCatFunction; 5503 let Content = [{ 5504This attribute is used in the implementation of the ACLE intrinsics. 5505It allows the intrinsic functions to 5506be declared using the names defined in ACLE, and still be recognized 5507as clang builtins equivalent to the underlying name. For example, 5508``arm_mve.h`` declares the function ``vaddq_u32`` with 5509``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``, 5510and similarly, one of the type-overloaded declarations of ``vaddq`` 5511will have the same attribute. This ensures that both functions are 5512recognized as that clang builtin, and in the latter case, the choice 5513of which builtin to identify the function as can be deferred until 5514after overload resolution. 5515 5516This attribute can only be used to set up the aliases for certain Arm 5517intrinsic functions; it is intended for use only inside ``arm_*.h`` 5518and is not a general mechanism for declaring arbitrary aliases for 5519clang builtin functions. 5520 }]; 5521} 5522 5523def NoBuiltinDocs : Documentation { 5524 let Category = DocCatFunction; 5525 let Content = [{ 5526.. Note:: This attribute is not yet fully implemented, it is validated but has 5527 no effect on the generated code. 5528 5529The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag 5530except it is specific to the body of a function. The attribute may also be 5531applied to a virtual function but has no effect on the behavior of overriding 5532functions in a derived class. 5533 5534It accepts one or more strings corresponding to the specific names of the 5535builtins to disable (e.g. "memcpy", "memset"). 5536If the attribute is used without parameters it will disable all buitins at 5537once. 5538 5539.. code-block:: c++ 5540 5541 // The compiler is not allowed to add any builtin to foo's body. 5542 void foo(char* data, size_t count) __attribute__((no_builtin)) { 5543 // The compiler is not allowed to convert the loop into 5544 // `__builtin_memset(data, 0xFE, count);`. 5545 for (size_t i = 0; i < count; ++i) 5546 data[i] = 0xFE; 5547 } 5548 5549 // The compiler is not allowed to add the `memcpy` builtin to bar's body. 5550 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) { 5551 // The compiler is allowed to convert the loop into 5552 // `__builtin_memset(data, 0xFE, count);` but cannot generate any 5553 // `__builtin_memcpy` 5554 for (size_t i = 0; i < count; ++i) 5555 data[i] = 0xFE; 5556 } 5557 }]; 5558} 5559 5560def HandleDocs : DocumentationCategory<"Handle Attributes"> { 5561 let Content = [{ 5562Handles are a way to identify resources like files, sockets, and processes. 5563They are more opaque than pointers and widely used in system programming. They 5564have similar risks such as never releasing a resource associated with a handle, 5565attempting to use a handle that was already released, or trying to release a 5566handle twice. Using the annotations below it is possible to make the ownership 5567of the handles clear: whose responsibility is to release them. They can also 5568aid static analysis tools to find bugs. 5569 }]; 5570} 5571 5572def AcquireHandleDocs : Documentation { 5573 let Category = HandleDocs; 5574 let Content = [{ 5575If this annotation is on a function or a function type it is assumed to return 5576a new handle. In case this annotation is on an output parameter, 5577the function is assumed to fill the corresponding argument with a new 5578handle. 5579 5580.. code-block:: c++ 5581 5582 // Output arguments from Zircon. 5583 zx_status_t zx_socket_create(uint32_t options, 5584 zx_handle_t __attribute__((acquire_handle)) * out0, 5585 zx_handle_t* out1 [[clang::acquire_handle]]); 5586 5587 5588 // Returned handle. 5589 [[clang::acquire_handle]] int open(const char *path, int oflag, ... ); 5590 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle)); 5591 }]; 5592} 5593 5594def UseHandleDocs : Documentation { 5595 let Category = HandleDocs; 5596 let Content = [{ 5597A function taking a handle by value might close the handle. If a function 5598parameter is annotated with ``use_handle`` it is assumed to not to change 5599the state of the handle. It is also assumed to require an open handle to work with. 5600 5601.. code-block:: c++ 5602 5603 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle]], 5604 zx_time_t deadline, 5605 zx_port_packet_t* packet); 5606 }]; 5607} 5608 5609def ReleaseHandleDocs : Documentation { 5610 let Category = HandleDocs; 5611 let Content = [{ 5612If a function parameter is annotated with ``release_handle`` it is assumed to 5613close the handle. It is also assumed to require an open handle to work with. 5614 5615.. code-block:: c++ 5616 5617 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle]]); 5618 }]; 5619} 5620 5621def ArmSveVectorBitsDocs : Documentation { 5622 let Category = DocCatType; 5623 let Content = [{ 5624The ``arm_sve_vector_bits(N)`` attribute is defined by the Arm C Language 5625Extensions (ACLE) for SVE. It is used to define fixed-length (VLST) variants of 5626sizeless types (VLAT). 5627 5628For example: 5629 5630.. code-block:: c 5631 5632 #include <arm_sve.h> 5633 5634 #if __ARM_FEATURE_SVE_BITS==512 5635 typedef svint32_t fixed_svint32_t __attribute__((arm_sve_vector_bits(512))); 5636 #endif 5637 5638Creates a type ``fixed_svint32_t`` that is a fixed-length variant of 5639``svint32_t`` that contains exactly 512-bits. Unlike ``svint32_t``, this type 5640can be used in globals, structs, unions, and arrays, all of which are 5641unsupported for sizeless types. 5642 5643The attribute can be attached to a single SVE vector (such as ``svint32_t``) or 5644to the SVE predicate type ``svbool_t``, this excludes tuple types such as 5645``svint32x4_t``. The behavior of the attribute is undefined unless 5646``N==__ARM_FEATURE_SVE_BITS``, the implementation defined feature macro that is 5647enabled under the ``-msve-vector-bits`` flag. 5648 5649For more information See `Arm C Language Extensions for SVE 5650<https://developer.arm.com/documentation/100987/latest>`_ for more information. 5651}]; 5652} 5653 5654def ArmMveStrictPolymorphismDocs : Documentation { 5655 let Category = DocCatType; 5656 let Content = [{ 5657This attribute is used in the implementation of the ACLE intrinsics for the Arm 5658MVE instruction set. It is used to define the vector types used by the MVE 5659intrinsics. 5660 5661Its effect is to modify the behavior of a vector type with respect to function 5662overloading. If a candidate function for overload resolution has a parameter 5663type with this attribute, then the selection of that candidate function will be 5664disallowed if the actual argument can only be converted via a lax vector 5665conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic 5666intrinsics. 5667 5668.. code-block:: c++ 5669 5670 void overloaded(uint16x8_t vector, uint16_t scalar); 5671 void overloaded(int32x4_t vector, int32_t scalar); 5672 uint16x8_t myVector; 5673 uint16_t myScalar; 5674 5675 // myScalar is promoted to int32_t as a side effect of the addition, 5676 // so if lax vector conversions are considered for myVector, then 5677 // the two overloads are equally good (one argument conversion 5678 // each). But if the vector has the __clang_arm_mve_strict_polymorphism 5679 // attribute, only the uint16x8_t,uint16_t overload will match. 5680 overloaded(myVector, myScalar + 1); 5681 5682However, this attribute does not prohibit lax vector conversions in contexts 5683other than overloading. 5684 5685.. code-block:: c++ 5686 5687 uint16x8_t function(); 5688 5689 // This is still permitted with lax vector conversion enabled, even 5690 // if the vector types have __clang_arm_mve_strict_polymorphism 5691 int32x4_t result = function(); 5692 5693 }]; 5694} 5695 5696def ArmCmseNSCallDocs : Documentation { 5697 let Category = DocCatType; 5698 let Content = [{ 5699This attribute declares a non-secure function type. When compiling for secure 5700state, a call to such a function would switch from secure to non-secure state. 5701All non-secure function calls must happen only through a function pointer, and 5702a non-secure function type should only be used as a base type of a pointer. 5703See `ARMv8-M Security Extensions: Requirements on Development 5704Tools - Engineering Specification Documentation 5705<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information. 5706 }]; 5707} 5708 5709def ArmCmseNSEntryDocs : Documentation { 5710 let Category = DocCatFunction; 5711 let Content = [{ 5712This attribute declares a function that can be called from non-secure state, or 5713from secure state. Entering from and returning to non-secure state would switch 5714to and from secure state, respectively, and prevent flow of information 5715to non-secure state, except via return values. See `ARMv8-M Security Extensions: 5716Requirements on Development Tools - Engineering Specification Documentation 5717<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information. 5718 }]; 5719} 5720 5721def AlwaysInlineDocs : Documentation { 5722 let Category = DocCatFunction; 5723 let Content = [{ 5724Inlining heuristics are disabled and inlining is always attempted regardless of 5725optimization level. 5726 5727Does not guarantee that inline substitution actually occurs. 5728 5729See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function 5730Attribute docs`_, and `the GCC Inline docs`_. 5731 5732.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp 5733.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html 5734.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html 5735 5736}]; 5737 let Heading = "always_inline, __force_inline"; 5738} 5739 5740def EnforceTCBDocs : Documentation { 5741 let Category = DocCatFunction; 5742 let Content = [{ 5743 The ``enforce_tcb`` attribute can be placed on functions to enforce that a 5744 trusted compute base (TCB) does not call out of the TCB. This generates a 5745 warning every time a function not marked with an ``enforce_tcb`` attribute is 5746 called from a function with the ``enforce_tcb`` attribute. A function may be a 5747 part of multiple TCBs. Invocations through function pointers are currently 5748 not checked. Builtins are considered to a part of every TCB. 5749 5750 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name`` 5751 }]; 5752} 5753 5754def EnforceTCBLeafDocs : Documentation { 5755 let Category = DocCatFunction; 5756 let Content = [{ 5757 The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by 5758 ``enforce_tcb`` for the marked function to be in the named TCB but does not 5759 continue to check the functions called from within the leaf function. 5760 5761 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name`` 5762 }]; 5763} 5764