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