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// sphinx-build -b html _build/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 130On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and 131``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)`` 132uses the default 65535 priority. 133 134This attribute is only supported for C++ and Objective-C++ and is ignored in 135other language modes. Currently, this attribute is not implemented on z/OS. 136 }]; 137} 138 139def InitSegDocs : Documentation { 140 let Category = DocCatVariable; 141 let Content = [{ 142The attribute applied by ``pragma init_seg()`` controls the section into 143which global initialization function pointers are emitted. It is only 144available with ``-fms-extensions``. Typically, this function pointer is 145emitted into ``.CRT$XCU`` on Windows. The user can change the order of 146initialization by using a different section name with the same 147``.CRT$XC`` prefix and a suffix that sorts lexicographically before or 148after the standard ``.CRT$XCU`` sections. See the init_seg_ 149documentation on MSDN for more information. 150 151.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx 152 }]; 153} 154 155def TLSModelDocs : Documentation { 156 let Category = DocCatVariable; 157 let Content = [{ 158The ``tls_model`` attribute allows you to specify which thread-local storage 159model to use. It accepts the following strings: 160 161* global-dynamic 162* local-dynamic 163* initial-exec 164* local-exec 165 166TLS models are mutually exclusive. 167 }]; 168} 169 170def DLLExportDocs : Documentation { 171 let Category = DocCatVariable; 172 let Content = [{ 173The ``__declspec(dllexport)`` attribute declares a variable, function, or 174Objective-C interface to be exported from the module. It is available under the 175``-fdeclspec`` flag for compatibility with various compilers. The primary use 176is for COFF object files which explicitly specify what interfaces are available 177for external use. See the dllexport_ documentation on MSDN for more 178information. 179 180.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 181 }]; 182} 183 184def DLLImportDocs : Documentation { 185 let Category = DocCatVariable; 186 let Content = [{ 187The ``__declspec(dllimport)`` attribute declares a variable, function, or 188Objective-C interface to be imported from an external module. It is available 189under the ``-fdeclspec`` flag for compatibility with various compilers. The 190primary use is for COFF object files which explicitly specify what interfaces 191are imported from external modules. See the dllimport_ documentation on MSDN 192for more information. 193 194Note that a dllimport function may still be inlined, if its definition is 195available and it doesn't reference any non-dllimport functions or global 196variables. 197 198.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 199 }]; 200} 201 202def ThreadDocs : Documentation { 203 let Category = DocCatVariable; 204 let Content = [{ 205The ``__declspec(thread)`` attribute declares a variable with thread local 206storage. It is available under the ``-fms-extensions`` flag for MSVC 207compatibility. See the documentation for `__declspec(thread)`_ on MSDN. 208 209.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx 210 211In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the 212GNU ``__thread`` keyword. The variable must not have a destructor and must have 213a constant initializer, if any. The attribute only applies to variables 214declared with static storage duration, such as globals, class static data 215members, and static locals. 216 }]; 217} 218 219def NoEscapeDocs : Documentation { 220 let Category = DocCatVariable; 221 let Content = [{ 222``noescape`` placed on a function parameter of a pointer type is used to inform 223the compiler that the pointer cannot escape: that is, no reference to the object 224the pointer points to that is derived from the parameter value will survive 225after the function returns. Users are responsible for making sure parameters 226annotated with ``noescape`` do not actually escape. Calling ``free()`` on such 227a parameter does not constitute an escape. 228 229For example: 230 231.. code-block:: c 232 233 int *gp; 234 235 void nonescapingFunc(__attribute__((noescape)) int *p) { 236 *p += 100; // OK. 237 } 238 239 void escapingFunc(__attribute__((noescape)) int *p) { 240 gp = p; // Not OK. 241 } 242 243Additionally, when the parameter is a `block pointer 244<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction 245applies to copies of the block. For example: 246 247.. code-block:: c 248 249 typedef void (^BlockTy)(); 250 BlockTy g0, g1; 251 252 void nonescapingFunc(__attribute__((noescape)) BlockTy block) { 253 block(); // OK. 254 } 255 256 void escapingFunc(__attribute__((noescape)) BlockTy block) { 257 g0 = block; // Not OK. 258 g1 = Block_copy(block); // Not OK either. 259 } 260 261 }]; 262} 263 264def MaybeUndefDocs : Documentation { 265 let Category = DocCatVariable; 266 let Content = [{ 267The ``maybe_undef`` attribute can be placed on a function parameter. It indicates 268that the parameter is allowed to use undef values. It informs the compiler 269to insert a freeze LLVM IR instruction on the function parameter. 270Please note that this is an attribute that is used as an internal 271implementation detail and not intended to be used by external users. 272 273In languages HIP, CUDA etc., some functions have multi-threaded semantics and 274it is enough for only one or some threads to provide defined arguments. 275Depending on semantics, undef arguments in some threads don't produce 276undefined results in the function call. Since, these functions accept undefined 277arguments, ``maybe_undef`` attribute can be placed. 278 279Sample usage: 280.. code-block:: c 281 282 void maybeundeffunc(int __attribute__((maybe_undef))param); 283 }]; 284} 285 286def CarriesDependencyDocs : Documentation { 287 let Category = DocCatFunction; 288 let Content = [{ 289The ``carries_dependency`` attribute specifies dependency propagation into and 290out of functions. 291 292When specified on a function or Objective-C method, the ``carries_dependency`` 293attribute means that the return value carries a dependency out of the function, 294so that the implementation need not constrain ordering upon return from that 295function. Implementations of the function and its caller may choose to preserve 296dependencies instead of emitting memory ordering instructions such as fences. 297 298Note, this attribute does not change the meaning of the program, but may result 299in generation of more efficient code. 300 }]; 301} 302 303def CPUSpecificCPUDispatchDocs : Documentation { 304 let Category = DocCatFunction; 305 let Content = [{ 306The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and 307resolve multiversioned functions. This form of multiversioning provides a 308mechanism for declaring versions across translation units and manually 309specifying the resolved function list. A specified CPU defines a set of minimum 310features that are required for the function to be called. The result of this is 311that future processors execute the most restrictive version of the function the 312new processor can execute. 313 314In addition, unlike the ICC implementation of this feature, the selection of the 315version does not consider the manufacturer or microarchitecture of the processor. 316It tests solely the list of features that are both supported by the specified 317processor and present in the compiler-rt library. This can be surprising at times, 318as the runtime processor may be from a completely different manufacturer, as long 319as it supports the same feature set. 320 321This can additionally be surprising, as some processors are indistringuishable from 322others based on the list of testable features. When this happens, the variant 323is selected in an unspecified manner. 324 325Function versions are defined with ``cpu_specific``, which takes one or more CPU 326names as a parameter. For example: 327 328.. code-block:: c 329 330 // Declares and defines the ivybridge version of single_cpu. 331 __attribute__((cpu_specific(ivybridge))) 332 void single_cpu(void){} 333 334 // Declares and defines the atom version of single_cpu. 335 __attribute__((cpu_specific(atom))) 336 void single_cpu(void){} 337 338 // Declares and defines both the ivybridge and atom version of multi_cpu. 339 __attribute__((cpu_specific(ivybridge, atom))) 340 void multi_cpu(void){} 341 342A dispatching (or resolving) function can be declared anywhere in a project's 343source code with ``cpu_dispatch``. This attribute takes one or more CPU names 344as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch`` 345are not expected to be defined, only declared. If such a marked function has a 346definition, any side effects of the function are ignored; trivial function 347bodies are permissible for ICC compatibility. 348 349.. code-block:: c 350 351 // Creates a resolver for single_cpu above. 352 __attribute__((cpu_dispatch(ivybridge, atom))) 353 void single_cpu(void){} 354 355 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another 356 // translation unit. 357 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge))) 358 void multi_cpu(void){} 359 360Note that it is possible to have a resolving function that dispatches based on 361more or fewer options than are present in the program. Specifying fewer will 362result in the omitted options not being considered during resolution. Specifying 363a version for resolution that isn't defined in the program will result in a 364linking failure. 365 366It is also possible to specify a CPU name of ``generic`` which will be resolved 367if the executing processor doesn't satisfy the features required in the CPU 368name. The behavior of a program executing on a processor that doesn't satisfy 369any option of a multiversioned function is undefined. 370 }]; 371} 372 373def SYCLKernelDocs : Documentation { 374 let Category = DocCatFunction; 375 let Content = [{ 376The ``sycl_kernel`` attribute specifies that a function template will be used 377to outline device code and to generate an OpenCL kernel. 378Here is a code example of the SYCL program, which demonstrates the compiler's 379outlining job: 380 381.. code-block:: c++ 382 383 int foo(int x) { return ++x; } 384 385 using namespace cl::sycl; 386 queue Q; 387 buffer<int, 1> a(range<1>{1024}); 388 Q.submit([&](handler& cgh) { 389 auto A = a.get_access<access::mode::write>(cgh); 390 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) { 391 A[index] = index[0] + foo(42); 392 }); 393 } 394 395A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel". 396A SYCL kernel defines the entry point to the "device part" of the code. The 397compiler will emit all symbols accessible from a "kernel". In this code 398example, the compiler will emit "foo" function. More details about the 399compilation of functions for the device part can be found in the SYCL 1.2.1 400specification Section 6.4. 401To show to the compiler entry point to the "device part" of the code, the SYCL 402runtime can use the ``sycl_kernel`` attribute in the following way: 403 404.. code-block:: c++ 405 406 namespace cl { 407 namespace sycl { 408 class handler { 409 template <typename KernelName, typename KernelType/*, ...*/> 410 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) { 411 // ... 412 KernelFuncObj(); 413 } 414 415 template <typename KernelName, typename KernelType, int Dims> 416 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) { 417 #ifdef __SYCL_DEVICE_ONLY__ 418 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc); 419 #else 420 // Host implementation 421 #endif 422 } 423 }; 424 } // namespace sycl 425 } // namespace cl 426 427The compiler will also generate an OpenCL kernel using the function marked with 428the ``sycl_kernel`` attribute. 429Here is the list of SYCL device compiler expectations with regard to the 430function marked with the ``sycl_kernel`` attribute: 431 432- The function must be a template with at least two type template parameters. 433 The compiler generates an OpenCL kernel and uses the first template parameter 434 as a unique name for the generated OpenCL kernel. The host application uses 435 this unique name to invoke the OpenCL kernel generated for the SYCL kernel 436 specialized by this name and second template parameter ``KernelType`` (which 437 might be an unnamed function object type). 438- The function must have at least one parameter. The first parameter is 439 required to be a function object type (named or unnamed i.e. lambda). The 440 compiler uses function object type fields to generate OpenCL kernel 441 parameters. 442- The function must return void. The compiler reuses the body of marked functions to 443 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``. 444 445The SYCL kernel in the previous code sample meets these expectations. 446 }]; 447} 448 449def SYCLSpecialClassDocs : Documentation { 450 let Category = DocCatStmt; 451 let Content = [{ 452SYCL defines some special classes (accessor, sampler, and stream) which require 453specific handling during the generation of the SPIR entry point. 454The ``__attribute__((sycl_special_class))`` attribute is used in SYCL 455headers to indicate that a class or a struct needs a specific handling when 456it is passed from host to device. 457Special classes will have a mandatory ``__init`` method and an optional 458``__finalize`` method (the ``__finalize`` method is used only with the 459``stream`` type). Kernel parameters types are extract from the ``__init`` method 460parameters. The kernel function arguments list is derived from the 461arguments of the ``__init`` method. The arguments of the ``__init`` method are 462copied into the kernel function argument list and the ``__init`` and 463``__finalize`` methods are called at the beginning and the end of the kernel, 464respectively. 465The ``__init`` and ``__finalize`` methods must be defined inside the 466special class. 467Please note that this is an attribute that is used as an internal 468implementation detail and not intended to be used by external users. 469 470The syntax of the attribute is as follows: 471 472.. code-block:: text 473 474 class __attribute__((sycl_special_class)) accessor {}; 475 class [[clang::sycl_special_class]] accessor {}; 476 477This is a code example that illustrates the use of the attribute: 478 479.. code-block:: c++ 480 481 class __attribute__((sycl_special_class)) SpecialType { 482 int F1; 483 int F2; 484 void __init(int f1) { 485 F1 = f1; 486 F2 = f1; 487 } 488 void __finalize() {} 489 public: 490 SpecialType() = default; 491 int getF2() const { return F2; } 492 }; 493 494 int main () { 495 SpecialType T; 496 cgh.single_task([=] { 497 T.getF2(); 498 }); 499 } 500 501This would trigger the following kernel entry point in the AST: 502 503.. code-block:: c++ 504 505 void __sycl_kernel(int f1) { 506 SpecialType T; 507 T.__init(f1); 508 ... 509 T.__finalize() 510 } 511 }]; 512} 513 514def C11NoReturnDocs : Documentation { 515 let Category = DocCatFunction; 516 let Content = [{ 517A function declared as ``_Noreturn`` shall not return to its caller. The 518compiler will generate a diagnostic for a function declared as ``_Noreturn`` 519that appears to be capable of returning to its caller. Despite being a type 520specifier, the ``_Noreturn`` attribute cannot be specified on a function 521pointer type. 522 }]; 523} 524 525def CXX11NoReturnDocs : Documentation { 526 let Category = DocCatFunction; 527 let Heading = "noreturn, _Noreturn"; 528 let Content = [{ 529A function declared as ``[[noreturn]]`` shall not return to its caller. The 530compiler will generate a diagnostic for a function declared as ``[[noreturn]]`` 531that appears to be capable of returning to its caller. 532 533The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code 534migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``. 535 }]; 536} 537 538def NoMergeDocs : Documentation { 539 let Category = DocCatStmt; 540 let Content = [{ 541If a statement is marked ``nomerge`` and contains call expressions, those call 542expressions inside the statement will not be merged during optimization. This 543attribute can be used to prevent the optimizer from obscuring the source 544location of certain calls. For example, it will prevent tail merging otherwise 545identical code sequences that raise an exception or terminate the program. Tail 546merging normally reduces the precision of source location information, making 547stack traces less useful for debugging. This attribute gives the user control 548over the tradeoff between code size and debug information precision. 549 550``nomerge`` attribute can also be used as function attribute to prevent all 551calls to the specified function from merging. It has no effect on indirect 552calls to such functions. For example: 553 554.. code-block:: c++ 555 556 [[clang::nomerge]] void foo(int) {} 557 558 void bar(int x) { 559 auto *ptr = foo; 560 if (x) foo(1); else foo(2); // will not be merged 561 if (x) ptr(1); else ptr(2); // indirect call, can be merged 562 } 563 564``nomerge`` attribute can also be used for pointers to functions to 565prevent calls through such pointer from merging. In such case the 566effect applies only to a specific function pointer. For example: 567 568.. code-block:: c++ 569 570 [[clang::nomerge]] void (*foo)(int); 571 572 void bar(int x) { 573 auto *ptr = foo; 574 if (x) foo(1); else foo(2); // will not be merged 575 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged 576 } 577 }]; 578} 579 580def NoInlineDocs : Documentation { 581 let Category = DocCatFunction; 582 let Content = [{ 583This function attribute suppresses the inlining of a function at the call sites 584of the function. 585 586``[[clang::noinline]]`` spelling can be used as a statement attribute; other 587spellings of the attribute are not supported on statements. If a statement is 588marked ``[[clang::noinline]]`` and contains calls, those calls inside the 589statement will not be inlined by the compiler. 590 591``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to 592avoid diagnostics due to usage of ``__attribute__((__noinline__))`` 593with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``. 594 595.. code-block:: c 596 597 int example(void) { 598 int r; 599 [[clang::noinline]] foo(); 600 [[clang::noinline]] r = bar(); 601 return r; 602 } 603 604 }]; 605} 606 607def MustTailDocs : Documentation { 608 let Category = DocCatStmt; 609 let Content = [{ 610If a ``return`` statement is marked ``musttail``, this indicates that the 611compiler must generate a tail call for the program to be correct, even when 612optimizations are disabled. This guarantees that the call will not cause 613unbounded stack growth if it is part of a recursive cycle in the call graph. 614 615If the callee is a virtual function that is implemented by a thunk, there is 616no guarantee in general that the thunk tail-calls the implementation of the 617virtual function, so such a call in a recursive cycle can still result in 618unbounded stack growth. 619 620``clang::musttail`` can only be applied to a ``return`` statement whose value 621is the result of a function call (even functions returning void must use 622``return``, although no value is returned). The target function must have the 623same number of arguments as the caller. The types of the return value and all 624arguments must be similar according to C++ rules (differing only in cv 625qualifiers or array size), including the implicit "this" argument, if any. 626Any variables in scope, including all arguments to the function and the 627return value must be trivially destructible. The calling convention of the 628caller and callee must match, and they must not be variadic functions or have 629old style K&R C function declarations. 630 631``clang::musttail`` provides assurances that the tail call can be optimized on 632all targets, not just one. 633 }]; 634} 635 636def AssertCapabilityDocs : Documentation { 637 let Category = DocCatFunction; 638 let Heading = "assert_capability, assert_shared_capability"; 639 let Content = [{ 640Marks a function that dynamically tests whether a capability is held, and halts 641the program if it is not held. 642 }]; 643} 644 645def AcquireCapabilityDocs : Documentation { 646 let Category = DocCatFunction; 647 let Heading = "acquire_capability, acquire_shared_capability"; 648 let Content = [{ 649Marks a function as acquiring a capability. 650 }]; 651} 652 653def TryAcquireCapabilityDocs : Documentation { 654 let Category = DocCatFunction; 655 let Heading = "try_acquire_capability, try_acquire_shared_capability"; 656 let Content = [{ 657Marks a function that attempts to acquire a capability. This function may fail to 658actually acquire the capability; they accept a Boolean value determining 659whether acquiring the capability means success (true), or failing to acquire 660the capability means success (false). 661 }]; 662} 663 664def ReleaseCapabilityDocs : Documentation { 665 let Category = DocCatFunction; 666 let Heading = "release_capability, release_shared_capability"; 667 let Content = [{ 668Marks a function as releasing a capability. 669 }]; 670} 671 672def AssumeAlignedDocs : Documentation { 673 let Category = DocCatFunction; 674 let Content = [{ 675Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function 676declaration to specify that the return value of the function (which must be a 677pointer type) has the specified offset, in bytes, from an address with the 678specified alignment. The offset is taken to be zero if omitted. 679 680.. code-block:: c++ 681 682 // The returned pointer value has 32-byte alignment. 683 void *a() __attribute__((assume_aligned (32))); 684 685 // The returned pointer value is 4 bytes greater than an address having 686 // 32-byte alignment. 687 void *b() __attribute__((assume_aligned (32, 4))); 688 689Note that this attribute provides information to the compiler regarding a 690condition that the code already ensures is true. It does not cause the compiler 691to enforce the provided alignment assumption. 692 }]; 693} 694 695def AllocSizeDocs : Documentation { 696 let Category = DocCatFunction; 697 let Content = [{ 698The ``alloc_size`` attribute can be placed on functions that return pointers in 699order to hint to the compiler how many bytes of memory will be available at the 700returned pointer. ``alloc_size`` takes one or two arguments. 701 702- ``alloc_size(N)`` implies that argument number N equals the number of 703 available bytes at the returned pointer. 704- ``alloc_size(N, M)`` implies that the product of argument number N and 705 argument number M equals the number of available bytes at the returned 706 pointer. 707 708Argument numbers are 1-based. 709 710An example of how to use ``alloc_size`` 711 712.. code-block:: c 713 714 void *my_malloc(int a) __attribute__((alloc_size(1))); 715 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); 716 717 int main() { 718 void *const p = my_malloc(100); 719 assert(__builtin_object_size(p, 0) == 100); 720 void *const a = my_calloc(20, 5); 721 assert(__builtin_object_size(a, 0) == 100); 722 } 723 724.. Note:: This attribute works differently in clang than it does in GCC. 725 Specifically, clang will only trace ``const`` pointers (as above); we give up 726 on pointers that are not marked as ``const``. In the vast majority of cases, 727 this is unimportant, because LLVM has support for the ``alloc_size`` 728 attribute. However, this may cause mildly unintuitive behavior when used with 729 other attributes, such as ``enable_if``. 730 }]; 731} 732 733def CodeSegDocs : Documentation { 734 let Category = DocCatFunction; 735 let Content = [{ 736The ``__declspec(code_seg)`` attribute enables the placement of code into separate 737named segments that can be paged or locked in memory individually. This attribute 738is used to control the placement of instantiated templates and compiler-generated 739code. See the documentation for `__declspec(code_seg)`_ on MSDN. 740 741.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx 742 }]; 743} 744 745def AllocAlignDocs : Documentation { 746 let Category = DocCatFunction; 747 let Content = [{ 748Use ``__attribute__((alloc_align(<alignment>))`` on a function 749declaration to specify that the return value of the function (which must be a 750pointer type) is at least as aligned as the value of the indicated parameter. The 751parameter is given by its index in the list of formal parameters; the first 752parameter has index 1 unless the function is a C++ non-static member function, 753in which case the first parameter has index 2 to account for the implicit ``this`` 754parameter. 755 756.. code-block:: c++ 757 758 // The returned pointer has the alignment specified by the first parameter. 759 void *a(size_t align) __attribute__((alloc_align(1))); 760 761 // The returned pointer has the alignment specified by the second parameter. 762 void *b(void *v, size_t align) __attribute__((alloc_align(2))); 763 764 // The returned pointer has the alignment specified by the second visible 765 // parameter, however it must be adjusted for the implicit 'this' parameter. 766 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3))); 767 768Note that this attribute merely informs the compiler that a function always 769returns a sufficiently aligned pointer. It does not cause the compiler to 770emit code to enforce that alignment. The behavior is undefined if the returned 771pointer is not sufficiently aligned. 772 }]; 773} 774 775def EnableIfDocs : Documentation { 776 let Category = DocCatFunction; 777 let Content = [{ 778.. Note:: Some features of this attribute are experimental. The meaning of 779 multiple enable_if attributes on a single declaration is subject to change in 780 a future version of clang. Also, the ABI is not standardized and the name 781 mangling may change in future versions. To avoid that, use asm labels. 782 783The ``enable_if`` attribute can be placed on function declarations to control 784which overload is selected based on the values of the function's arguments. 785When combined with the ``overloadable`` attribute, this feature is also 786available in C. 787 788.. code-block:: c++ 789 790 int isdigit(int c); 791 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"))); 792 793 void foo(char c) { 794 isdigit(c); 795 isdigit(10); 796 isdigit(-10); // results in a compile-time error. 797 } 798 799The enable_if attribute takes two arguments, the first is an expression written 800in terms of the function parameters, the second is a string explaining why this 801overload candidate could not be selected to be displayed in diagnostics. The 802expression is part of the function signature for the purposes of determining 803whether it is a redeclaration (following the rules used when determining 804whether a C++ template specialization is ODR-equivalent), but is not part of 805the type. 806 807The enable_if expression is evaluated as if it were the body of a 808bool-returning constexpr function declared with the arguments of the function 809it is being applied to, then called with the parameters at the call site. If the 810result is false or could not be determined through constant expression 811evaluation, then this overload will not be chosen and the provided string may 812be used in a diagnostic if the compile fails as a result. 813 814Because the enable_if expression is an unevaluated context, there are no global 815state changes, nor the ability to pass information from the enable_if 816expression to the function body. For example, suppose we want calls to 817strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of 818strbuf) only if the size of strbuf can be determined: 819 820.. code-block:: c++ 821 822 __attribute__((always_inline)) 823 static inline size_t strnlen(const char *s, size_t maxlen) 824 __attribute__((overloadable)) 825 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))), 826 "chosen when the buffer size is known but 'maxlen' is not"))) 827 { 828 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); 829 } 830 831Multiple enable_if attributes may be applied to a single declaration. In this 832case, the enable_if expressions are evaluated from left to right in the 833following manner. First, the candidates whose enable_if expressions evaluate to 834false or cannot be evaluated are discarded. If the remaining candidates do not 835share ODR-equivalent enable_if expressions, the overload resolution is 836ambiguous. Otherwise, enable_if overload resolution continues with the next 837enable_if attribute on the candidates that have not been discarded and have 838remaining enable_if attributes. In this way, we pick the most specific 839overload out of a number of viable overloads using enable_if. 840 841.. code-block:: c++ 842 843 void f() __attribute__((enable_if(true, ""))); // #1 844 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 845 846 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 847 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 848 849In this example, a call to f() is always resolved to #2, as the first enable_if 850expression is ODR-equivalent for both declarations, but #1 does not have another 851enable_if expression to continue evaluating, so the next round of evaluation has 852only a single candidate. In a call to g(1, 1), the call is ambiguous even though 853#2 has more enable_if attributes, because the first enable_if expressions are 854not ODR-equivalent. 855 856Query for this feature with ``__has_attribute(enable_if)``. 857 858Note that functions with one or more ``enable_if`` attributes may not have 859their address taken, unless all of the conditions specified by said 860``enable_if`` are constants that evaluate to ``true``. For example: 861 862.. code-block:: c 863 864 const int TrueConstant = 1; 865 const int FalseConstant = 0; 866 int f(int a) __attribute__((enable_if(a > 0, ""))); 867 int g(int a) __attribute__((enable_if(a == 0 || a != 0, ""))); 868 int h(int a) __attribute__((enable_if(1, ""))); 869 int i(int a) __attribute__((enable_if(TrueConstant, ""))); 870 int j(int a) __attribute__((enable_if(FalseConstant, ""))); 871 872 void fn() { 873 int (*ptr)(int); 874 ptr = &f; // error: 'a > 0' is not always true 875 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant 876 ptr = &h; // OK: 1 is a truthy constant 877 ptr = &i; // OK: 'TrueConstant' is a truthy constant 878 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy 879 } 880 881Because ``enable_if`` evaluation happens during overload resolution, 882``enable_if`` may give unintuitive results when used with templates, depending 883on when overloads are resolved. In the example below, clang will emit a 884diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``: 885 886.. code-block:: c++ 887 888 double foo(int i) __attribute__((enable_if(i > 0, ""))); 889 void *foo(int i) __attribute__((enable_if(i <= 0, ""))); 890 template <int I> 891 auto bar() { return foo(I); } 892 893 template <typename T> 894 auto baz() { return foo(T::number); } 895 896 struct WithNumber { constexpr static int number = 1; }; 897 void callThem() { 898 bar<sizeof(WithNumber)>(); 899 baz<WithNumber>(); 900 } 901 902This is because, in ``bar``, ``foo`` is resolved prior to template 903instantiation, so the value for ``I`` isn't known (thus, both ``enable_if`` 904conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during 905template instantiation, so the value for ``T::number`` is known. 906 }]; 907} 908 909def DiagnoseIfDocs : Documentation { 910 let Category = DocCatFunction; 911 let Content = [{ 912The ``diagnose_if`` attribute can be placed on function declarations to emit 913warnings or errors at compile-time if calls to the attributed function meet 914certain user-defined criteria. For example: 915 916.. code-block:: c 917 918 int abs(int a) 919 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning"))); 920 int must_abs(int a) 921 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error"))); 922 923 int val = abs(1); // warning: Redundant abs call 924 int val2 = must_abs(1); // error: Redundant abs call 925 int val3 = abs(val); 926 int val4 = must_abs(val); // Because run-time checks are not emitted for 927 // diagnose_if attributes, this executes without 928 // issue. 929 930 931``diagnose_if`` is closely related to ``enable_if``, with a few key differences: 932 933* Overload resolution is not aware of ``diagnose_if`` attributes: they're 934 considered only after we select the best candidate from a given candidate set. 935* Function declarations that differ only in their ``diagnose_if`` attributes are 936 considered to be redeclarations of the same function (not overloads). 937* If the condition provided to ``diagnose_if`` cannot be evaluated, no 938 diagnostic will be emitted. 939 940Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``. 941 942As a result of bullet number two, ``diagnose_if`` attributes will stack on the 943same function. For example: 944 945.. code-block:: c 946 947 int foo() __attribute__((diagnose_if(1, "diag1", "warning"))); 948 int foo() __attribute__((diagnose_if(1, "diag2", "warning"))); 949 950 int bar = foo(); // warning: diag1 951 // warning: diag2 952 int (*fooptr)(void) = foo; // warning: diag1 953 // warning: diag2 954 955 constexpr int supportsAPILevel(int N) { return N < 5; } 956 int baz(int a) 957 __attribute__((diagnose_if(!supportsAPILevel(10), 958 "Upgrade to API level 10 to use baz", "error"))); 959 int baz(int a) 960 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning"))); 961 962 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz 963 int v = baz(0); // error: Upgrade to API level 10 to use baz 964 965Query for this feature with ``__has_attribute(diagnose_if)``. 966 }]; 967} 968 969def PassObjectSizeDocs : Documentation { 970 let Category = DocCatVariable; // Technically it's a parameter doc, but eh. 971 let Heading = "pass_object_size, pass_dynamic_object_size"; 972 let Content = [{ 973.. Note:: The mangling of functions with parameters that are annotated with 974 ``pass_object_size`` is subject to change. You can get around this by 975 using ``__asm__("foo")`` to explicitly name your functions, thus preserving 976 your ABI; also, non-overloadable C functions with ``pass_object_size`` are 977 not mangled. 978 979The ``pass_object_size(Type)`` attribute can be placed on function parameters to 980instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite 981of said function, and implicitly pass the result of this call in as an invisible 982argument of type ``size_t`` directly after the parameter annotated with 983``pass_object_size``. Clang will also replace any calls to 984``__builtin_object_size(param, Type)`` in the function by said implicit 985parameter. 986 987Example usage: 988 989.. code-block:: c 990 991 int bzero1(char *const p __attribute__((pass_object_size(0)))) 992 __attribute__((noinline)) { 993 int i = 0; 994 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) { 995 p[i] = 0; 996 } 997 return i; 998 } 999 1000 int main() { 1001 char chars[100]; 1002 int n = bzero1(&chars[0]); 1003 assert(n == sizeof(chars)); 1004 return 0; 1005 } 1006 1007If successfully evaluating ``__builtin_object_size(param, Type)`` at the 1008callsite is not possible, then the "failed" value is passed in. So, using the 1009definition of ``bzero1`` from above, the following code would exit cleanly: 1010 1011.. code-block:: c 1012 1013 int main2(int argc, char *argv[]) { 1014 int n = bzero1(argv); 1015 assert(n == -1); 1016 return 0; 1017 } 1018 1019``pass_object_size`` plays a part in overload resolution. If two overload 1020candidates are otherwise equally good, then the overload with one or more 1021parameters with ``pass_object_size`` is preferred. This implies that the choice 1022between two identical overloads both with ``pass_object_size`` on one or more 1023parameters will always be ambiguous; for this reason, having two such overloads 1024is illegal. For example: 1025 1026.. code-block:: c++ 1027 1028 #define PS(N) __attribute__((pass_object_size(N))) 1029 // OK 1030 void Foo(char *a, char *b); // Overload A 1031 // OK -- overload A has no parameters with pass_object_size. 1032 void Foo(char *a PS(0), char *b PS(0)); // Overload B 1033 // Error -- Same signature (sans pass_object_size) as overload B, and both 1034 // overloads have one or more parameters with the pass_object_size attribute. 1035 void Foo(void *a PS(0), void *b); 1036 1037 // OK 1038 void Bar(void *a PS(0)); // Overload C 1039 // OK 1040 void Bar(char *c PS(1)); // Overload D 1041 1042 void main() { 1043 char known[10], *unknown; 1044 Foo(unknown, unknown); // Calls overload B 1045 Foo(known, unknown); // Calls overload B 1046 Foo(unknown, known); // Calls overload B 1047 Foo(known, known); // Calls overload B 1048 1049 Bar(known); // Calls overload D 1050 Bar(unknown); // Calls overload D 1051 } 1052 1053Currently, ``pass_object_size`` is a bit restricted in terms of its usage: 1054 1055* Only one use of ``pass_object_size`` is allowed per parameter. 1056 1057* It is an error to take the address of a function with ``pass_object_size`` on 1058 any of its parameters. If you wish to do this, you can create an overload 1059 without ``pass_object_size`` on any parameters. 1060 1061* It is an error to apply the ``pass_object_size`` attribute to parameters that 1062 are not pointers. Additionally, any parameter that ``pass_object_size`` is 1063 applied to must be marked ``const`` at its function's definition. 1064 1065Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves 1066identically to ``pass_object_size``, but evaluates a call to 1067``__builtin_dynamic_object_size`` at the callee instead of 1068``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra 1069runtime checks when the object size can't be determined at compile-time. You can 1070read more about ``__builtin_dynamic_object_size`` `here 1071<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_. 1072 1073 }]; 1074} 1075 1076def OverloadableDocs : Documentation { 1077 let Category = DocCatFunction; 1078 let Content = [{ 1079Clang provides support for C++ function overloading in C. Function overloading 1080in C is introduced using the ``overloadable`` attribute. For example, one 1081might provide several overloaded versions of a ``tgsin`` function that invokes 1082the appropriate standard function computing the sine of a value with ``float``, 1083``double``, or ``long double`` precision: 1084 1085.. code-block:: c 1086 1087 #include <math.h> 1088 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } 1089 double __attribute__((overloadable)) tgsin(double x) { return sin(x); } 1090 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } 1091 1092Given these declarations, one can call ``tgsin`` with a ``float`` value to 1093receive a ``float`` result, with a ``double`` to receive a ``double`` result, 1094etc. Function overloading in C follows the rules of C++ function overloading 1095to pick the best overload given the call arguments, with a few C-specific 1096semantics: 1097 1098* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a 1099 floating-point promotion (per C99) rather than as a floating-point conversion 1100 (as in C++). 1101 1102* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is 1103 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are 1104 compatible types. 1105 1106* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` 1107 and ``U`` are compatible types. This conversion is given "conversion" rank. 1108 1109* If no viable candidates are otherwise available, we allow a conversion from a 1110 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are 1111 incompatible. This conversion is ranked below all other types of conversions. 1112 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient 1113 for ``T`` and ``U`` to be incompatible. 1114 1115The declaration of ``overloadable`` functions is restricted to function 1116declarations and definitions. If a function is marked with the ``overloadable`` 1117attribute, then all declarations and definitions of functions with that name, 1118except for at most one (see the note below about unmarked overloads), must have 1119the ``overloadable`` attribute. In addition, redeclarations of a function with 1120the ``overloadable`` attribute must have the ``overloadable`` attribute, and 1121redeclarations of a function without the ``overloadable`` attribute must *not* 1122have the ``overloadable`` attribute. e.g., 1123 1124.. code-block:: c 1125 1126 int f(int) __attribute__((overloadable)); 1127 float f(float); // error: declaration of "f" must have the "overloadable" attribute 1128 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute 1129 1130 int g(int) __attribute__((overloadable)); 1131 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute 1132 1133 int h(int); 1134 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not 1135 // have the "overloadable" attribute 1136 1137Functions marked ``overloadable`` must have prototypes. Therefore, the 1138following code is ill-formed: 1139 1140.. code-block:: c 1141 1142 int h() __attribute__((overloadable)); // error: h does not have a prototype 1143 1144However, ``overloadable`` functions are allowed to use a ellipsis even if there 1145are no named parameters (as is permitted in C++). This feature is particularly 1146useful when combined with the ``unavailable`` attribute: 1147 1148.. code-block:: c++ 1149 1150 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error 1151 1152Functions declared with the ``overloadable`` attribute have their names mangled 1153according to the same rules as C++ function names. For example, the three 1154``tgsin`` functions in our motivating example get the mangled names 1155``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two 1156caveats to this use of name mangling: 1157 1158* Future versions of Clang may change the name mangling of functions overloaded 1159 in C, so you should not depend on an specific mangling. To be completely 1160 safe, we strongly urge the use of ``static inline`` with ``overloadable`` 1161 functions. 1162 1163* The ``overloadable`` attribute has almost no meaning when used in C++, 1164 because names will already be mangled and functions are already overloadable. 1165 However, when an ``overloadable`` function occurs within an ``extern "C"`` 1166 linkage specification, its name *will* be mangled in the same way as it 1167 would in C. 1168 1169For the purpose of backwards compatibility, at most one function with the same 1170name as other ``overloadable`` functions may omit the ``overloadable`` 1171attribute. In this case, the function without the ``overloadable`` attribute 1172will not have its name mangled. 1173 1174For example: 1175 1176.. code-block:: c 1177 1178 // Notes with mangled names assume Itanium mangling. 1179 int f(int); 1180 int f(double) __attribute__((overloadable)); 1181 void foo() { 1182 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that 1183 // was marked with overloadable). 1184 f(1.0); // Emits a call to _Z1fd. 1185 } 1186 1187Support for unmarked overloads is not present in some versions of clang. You may 1188query for it using ``__has_extension(overloadable_unmarked)``. 1189 1190Query for this attribute with ``__has_attribute(overloadable)``. 1191 }]; 1192} 1193 1194def ObjCMethodFamilyDocs : Documentation { 1195 let Category = DocCatFunction; 1196 let Content = [{ 1197Many methods in Objective-C have conventional meanings determined by their 1198selectors. It is sometimes useful to be able to mark a method as having a 1199particular conventional meaning despite not having the right selector, or as 1200not having the conventional meaning that its selector would suggest. For these 1201use cases, we provide an attribute to specifically describe the "method family" 1202that a method belongs to. 1203 1204**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of 1205``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This 1206attribute can only be placed at the end of a method declaration: 1207 1208.. code-block:: objc 1209 1210 - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); 1211 1212Users who do not wish to change the conventional meaning of a method, and who 1213merely want to document its non-standard retain and release semantics, should 1214use the retaining behavior attributes (``ns_returns_retained``, 1215``ns_returns_not_retained``, etc). 1216 1217Query for this feature with ``__has_attribute(objc_method_family)``. 1218 }]; 1219} 1220 1221def RetainBehaviorDocs : Documentation { 1222 let Category = DocCatFunction; 1223 let Content = [{ 1224The behavior of a function with respect to reference counting for Foundation 1225(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming 1226convention (e.g. functions starting with "get" are assumed to return at 1227``+0``). 1228 1229It can be overridden using a family of the following attributes. In 1230Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to 1231a function communicates that the object is returned at ``+1``, and the caller 1232is responsible for freeing it. 1233Similarly, the annotation ``__attribute__((ns_returns_not_retained))`` 1234specifies that the object is returned at ``+0`` and the ownership remains with 1235the callee. 1236The annotation ``__attribute__((ns_consumes_self))`` specifies that 1237the Objective-C method call consumes the reference to ``self``, e.g. by 1238attaching it to a supplied parameter. 1239Additionally, parameters can have an annotation 1240``__attribute__((ns_consumed))``, which specifies that passing an owned object 1241as that parameter effectively transfers the ownership, and the caller is no 1242longer responsible for it. 1243These attributes affect code generation when interacting with ARC code, and 1244they are used by the Clang Static Analyzer. 1245 1246In C programs using CoreFoundation, a similar set of attributes: 1247``__attribute__((cf_returns_not_retained))``, 1248``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))`` 1249have the same respective semantics when applied to CoreFoundation objects. 1250These attributes affect code generation when interacting with ARC code, and 1251they are used by the Clang Static Analyzer. 1252 1253Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), 1254the same attribute family is present: 1255``__attribute__((os_returns_not_retained))``, 1256``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``, 1257with the same respective semantics. 1258Similar to ``__attribute__((ns_consumes_self))``, 1259``__attribute__((os_consumes_this))`` specifies that the method call consumes 1260the reference to "this" (e.g., when attaching it to a different object supplied 1261as a parameter). 1262Out parameters (parameters the function is meant to write into, 1263either via pointers-to-pointers or references-to-pointers) 1264may be annotated with ``__attribute__((os_returns_retained))`` 1265or ``__attribute__((os_returns_not_retained))`` which specifies that the object 1266written into the out parameter should (or respectively should not) be released 1267after use. 1268Since often out parameters may or may not be written depending on the exit 1269code of the function, 1270annotations ``__attribute__((os_returns_retained_on_zero))`` 1271and ``__attribute__((os_returns_retained_on_non_zero))`` specify that 1272an out parameter at ``+1`` is written if and only if the function returns a zero 1273(respectively non-zero) error code. 1274Observe that return-code-dependent out parameter annotations are only 1275available for retained out parameters, as non-retained object do not have to be 1276released by the callee. 1277These attributes are only used by the Clang Static Analyzer. 1278 1279The family of attributes ``X_returns_X_retained`` can be added to functions, 1280C++ methods, and Objective-C methods and properties. 1281Attributes ``X_consumed`` can be added to parameters of methods, functions, 1282and Objective-C methods. 1283 }]; 1284} 1285 1286def NoDebugDocs : Documentation { 1287 let Category = DocCatVariable; 1288 let Content = [{ 1289The ``nodebug`` attribute allows you to suppress debugging information for a 1290function or method, for a variable that is not a parameter or a non-static 1291data member, or for a typedef or using declaration. 1292 }]; 1293} 1294 1295def StandaloneDebugDocs : Documentation { 1296 let Category = DocCatVariable; 1297 let Content = [{ 1298The ``standalone_debug`` attribute causes debug info to be emitted for a record 1299type regardless of the debug info optimizations that are enabled with 1300-fno-standalone-debug. This attribute only has an effect when debug info 1301optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only. 1302 }]; 1303} 1304 1305def NoDuplicateDocs : Documentation { 1306 let Category = DocCatFunction; 1307 let Content = [{ 1308The ``noduplicate`` attribute can be placed on function declarations to control 1309whether function calls to this function can be duplicated or not as a result of 1310optimizations. This is required for the implementation of functions with 1311certain special requirements, like the OpenCL "barrier" function, that might 1312need to be run concurrently by all the threads that are executing in lockstep 1313on the hardware. For example this attribute applied on the function 1314"nodupfunc" in the code below avoids that: 1315 1316.. code-block:: c 1317 1318 void nodupfunc() __attribute__((noduplicate)); 1319 // Setting it as a C++11 attribute is also valid 1320 // void nodupfunc() [[clang::noduplicate]]; 1321 void foo(); 1322 void bar(); 1323 1324 nodupfunc(); 1325 if (a > n) { 1326 foo(); 1327 } else { 1328 bar(); 1329 } 1330 1331gets possibly modified by some optimizations into code similar to this: 1332 1333.. code-block:: c 1334 1335 if (a > n) { 1336 nodupfunc(); 1337 foo(); 1338 } else { 1339 nodupfunc(); 1340 bar(); 1341 } 1342 1343where the call to "nodupfunc" is duplicated and sunk into the two branches 1344of the condition. 1345 }]; 1346} 1347 1348def ConvergentDocs : Documentation { 1349 let Category = DocCatFunction; 1350 let Content = [{ 1351The ``convergent`` attribute can be placed on a function declaration. It is 1352translated into the LLVM ``convergent`` attribute, which indicates that the call 1353instructions of a function with this attribute cannot be made control-dependent 1354on any additional values. 1355 1356In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA, 1357the call instructions of a function with this attribute must be executed by 1358all work items or threads in a work group or sub group. 1359 1360This attribute is different from ``noduplicate`` because it allows duplicating 1361function calls if it can be proved that the duplicated function calls are 1362not made control-dependent on any additional values, e.g., unrolling a loop 1363executed by all work items. 1364 1365Sample usage: 1366 1367.. code-block:: c 1368 1369 void convfunc(void) __attribute__((convergent)); 1370 // Setting it as a C++11 attribute is also valid in a C++ program. 1371 // void convfunc(void) [[clang::convergent]]; 1372 1373 }]; 1374} 1375 1376def NoSplitStackDocs : Documentation { 1377 let Category = DocCatFunction; 1378 let Content = [{ 1379The ``no_split_stack`` attribute disables the emission of the split stack 1380preamble for a particular function. It has no effect if ``-fsplit-stack`` 1381is not specified. 1382 }]; 1383} 1384 1385def NoUniqueAddressDocs : Documentation { 1386 let Category = DocCatField; 1387 let Content = [{ 1388The ``no_unique_address`` attribute allows tail padding in a non-static data 1389member to overlap other members of the enclosing class (and in the special 1390case when the type is empty, permits it to fully overlap other members). 1391The field is laid out as if a base class were encountered at the corresponding 1392point within the class (except that it does not share a vptr with the enclosing 1393object). 1394 1395Example usage: 1396 1397.. code-block:: c++ 1398 1399 template<typename T, typename Alloc> struct my_vector { 1400 T *p; 1401 [[no_unique_address]] Alloc alloc; 1402 // ... 1403 }; 1404 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*)); 1405 1406``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use 1407in C++11 onwards. 1408 1409On MSVC targets, ``[[no_unique_address]]`` is ignored; use 1410``[[msvc::no_unique_address]]`` instead. Currently there is no guarantee of ABI 1411compatibility or stability with MSVC. 1412 }]; 1413} 1414 1415def ObjCRequiresSuperDocs : Documentation { 1416 let Category = DocCatFunction; 1417 let Content = [{ 1418Some Objective-C classes allow a subclass to override a particular method in a 1419parent class but expect that the overriding method also calls the overridden 1420method in the parent class. For these cases, we provide an attribute to 1421designate that a method requires a "call to ``super``" in the overriding 1422method in the subclass. 1423 1424**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only 1425be placed at the end of a method declaration: 1426 1427.. code-block:: objc 1428 1429 - (void)foo __attribute__((objc_requires_super)); 1430 1431This attribute can only be applied the method declarations within a class, and 1432not a protocol. Currently this attribute does not enforce any placement of 1433where the call occurs in the overriding method (such as in the case of 1434``-dealloc`` where the call must appear at the end). It checks only that it 1435exists. 1436 1437Note that on both OS X and iOS that the Foundation framework provides a 1438convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this 1439attribute: 1440 1441.. code-block:: objc 1442 1443 - (void)foo NS_REQUIRES_SUPER; 1444 1445This macro is conditionally defined depending on the compiler's support for 1446this attribute. If the compiler does not support the attribute the macro 1447expands to nothing. 1448 1449Operationally, when a method has this annotation the compiler will warn if the 1450implementation of an override in a subclass does not call super. For example: 1451 1452.. code-block:: objc 1453 1454 warning: method possibly missing a [super AnnotMeth] call 1455 - (void) AnnotMeth{}; 1456 ^ 1457 }]; 1458} 1459 1460def ObjCRuntimeNameDocs : Documentation { 1461 let Category = DocCatDecl; 1462 let Content = [{ 1463By default, the Objective-C interface or protocol identifier is used 1464in the metadata name for that object. The ``objc_runtime_name`` 1465attribute allows annotated interfaces or protocols to use the 1466specified string argument in the object's metadata name instead of the 1467default name. 1468 1469**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute 1470can only be placed before an @protocol or @interface declaration: 1471 1472.. code-block:: objc 1473 1474 __attribute__((objc_runtime_name("MyLocalName"))) 1475 @interface Message 1476 @end 1477 1478 }]; 1479} 1480 1481def ObjCRuntimeVisibleDocs : Documentation { 1482 let Category = DocCatDecl; 1483 let Content = [{ 1484This attribute specifies that the Objective-C class to which it applies is 1485visible to the Objective-C runtime but not to the linker. Classes annotated 1486with this attribute cannot be subclassed and cannot have categories defined for 1487them. 1488 }]; 1489} 1490 1491def ObjCClassStubDocs : Documentation { 1492 let Category = DocCatType; 1493 let Content = [{ 1494This attribute specifies that the Objective-C class to which it applies is 1495instantiated at runtime. 1496 1497Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute 1498still has a "class stub" that is visible to the linker. This allows categories 1499to be defined. Static message sends with the class as a receiver use a special 1500access pattern to ensure the class is lazily instantiated from the class stub. 1501 1502Classes annotated with this attribute cannot be subclassed and cannot have 1503implementations defined for them. This attribute is intended for use in 1504Swift-generated headers for classes defined in Swift. 1505 1506Adding or removing this attribute to a class is an ABI-breaking change. 1507 }]; 1508} 1509 1510def ObjCBoxableDocs : Documentation { 1511 let Category = DocCatDecl; 1512 let Content = [{ 1513Structs and unions marked with the ``objc_boxable`` attribute can be used 1514with the Objective-C boxed expression syntax, ``@(...)``. 1515 1516**Usage**: ``__attribute__((objc_boxable))``. This attribute 1517can only be placed on a declaration of a trivially-copyable struct or union: 1518 1519.. code-block:: objc 1520 1521 struct __attribute__((objc_boxable)) some_struct { 1522 int i; 1523 }; 1524 union __attribute__((objc_boxable)) some_union { 1525 int i; 1526 float f; 1527 }; 1528 typedef struct __attribute__((objc_boxable)) _some_struct some_struct; 1529 1530 // ... 1531 1532 some_struct ss; 1533 NSValue *boxed = @(ss); 1534 1535 }]; 1536} 1537 1538def AvailabilityDocs : Documentation { 1539 let Category = DocCatFunction; 1540 let Content = [{ 1541The ``availability`` attribute can be placed on declarations to describe the 1542lifecycle of that declaration relative to operating system versions. Consider 1543the function declaration for a hypothetical function ``f``: 1544 1545.. code-block:: c++ 1546 1547 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7))); 1548 1549The availability attribute states that ``f`` was introduced in macOS 10.4, 1550deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information 1551is used by Clang to determine when it is safe to use ``f``: for example, if 1552Clang is instructed to compile code for macOS 10.5, a call to ``f()`` 1553succeeds. If Clang is instructed to compile code for macOS 10.6, the call 1554succeeds but Clang emits a warning specifying that the function is deprecated. 1555Finally, if Clang is instructed to compile code for macOS 10.7, the call 1556fails because ``f()`` is no longer available. 1557 1558The availability attribute is a comma-separated list starting with the 1559platform name and then including clauses specifying important milestones in the 1560declaration's lifetime (in any order) along with additional information. Those 1561clauses can be: 1562 1563introduced=\ *version* 1564 The first version in which this declaration was introduced. 1565 1566deprecated=\ *version* 1567 The first version in which this declaration was deprecated, meaning that 1568 users should migrate away from this API. 1569 1570obsoleted=\ *version* 1571 The first version in which this declaration was obsoleted, meaning that it 1572 was removed completely and can no longer be used. 1573 1574unavailable 1575 This declaration is never available on this platform. 1576 1577message=\ *string-literal* 1578 Additional message text that Clang will provide when emitting a warning or 1579 error about use of a deprecated or obsoleted declaration. Useful to direct 1580 users to replacement APIs. 1581 1582replacement=\ *string-literal* 1583 Additional message text that Clang will use to provide Fix-It when emitting 1584 a warning about use of a deprecated declaration. The Fix-It will replace 1585 the deprecated declaration with the new declaration specified. 1586 1587Multiple availability attributes can be placed on a declaration, which may 1588correspond to different platforms. For most platforms, the availability 1589attribute with the platform corresponding to the target platform will be used; 1590any others will be ignored. However, the availability for ``watchOS`` and 1591``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute. 1592Any explicit availability attributes for those platforms are still preferred over 1593the implicitly inferred availability attributes. If no availability attribute 1594specifies availability for the current target platform, the availability 1595attributes are ignored. Supported platforms are: 1596 1597``ios`` 1598 Apple's iOS operating system. The minimum deployment target is specified by 1599 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` 1600 command-line arguments. 1601 1602``macos`` 1603 Apple's macOS operating system. The minimum deployment target is 1604 specified by the ``-mmacosx-version-min=*version*`` command-line argument. 1605 ``macosx`` is supported for backward-compatibility reasons, but it is 1606 deprecated. 1607 1608``tvos`` 1609 Apple's tvOS operating system. The minimum deployment target is specified by 1610 the ``-mtvos-version-min=*version*`` command-line argument. 1611 1612``watchos`` 1613 Apple's watchOS operating system. The minimum deployment target is specified by 1614 the ``-mwatchos-version-min=*version*`` command-line argument. 1615 1616``driverkit`` 1617 Apple's DriverKit userspace kernel extensions. The minimum deployment target 1618 is specified as part of the triple. 1619 1620A declaration can typically be used even when deploying back to a platform 1621version prior to when the declaration was introduced. When this happens, the 1622declaration is `weakly linked 1623<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, 1624as if the ``weak_import`` attribute were added to the declaration. A 1625weakly-linked declaration may or may not be present a run-time, and a program 1626can determine whether the declaration is present by checking whether the 1627address of that declaration is non-NULL. 1628 1629The flag ``strict`` disallows using API when deploying back to a 1630platform version prior to when the declaration was introduced. An 1631attempt to use such API before its introduction causes a hard error. 1632Weakly-linking is almost always a better API choice, since it allows 1633users to query availability at runtime. 1634 1635If there are multiple declarations of the same entity, the availability 1636attributes must either match on a per-platform basis or later 1637declarations must not have availability attributes for that 1638platform. For example: 1639 1640.. code-block:: c 1641 1642 void g(void) __attribute__((availability(macos,introduced=10.4))); 1643 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches 1644 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform 1645 void g(void); // okay, inherits both macos and ios availability from above. 1646 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch 1647 1648When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: 1649 1650.. code-block:: objc 1651 1652 @interface A 1653 - (id)method __attribute__((availability(macos,introduced=10.4))); 1654 - (id)method2 __attribute__((availability(macos,introduced=10.4))); 1655 @end 1656 1657 @interface B : A 1658 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later 1659 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4 1660 @end 1661 1662Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from 1663``<os/availability.h>`` can simplify the spelling: 1664 1665.. code-block:: objc 1666 1667 @interface A 1668 - (id)method API_AVAILABLE(macos(10.11))); 1669 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0)); 1670 @end 1671 1672Availability attributes can also be applied using a ``#pragma clang attribute``. 1673Any explicit availability attribute whose platform corresponds to the target 1674platform is applied to a declaration regardless of the availability attributes 1675specified in the pragma. For example, in the code below, 1676``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability 1677attribute that is specified with the declaration, whereas 1678``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability 1679attribute that is applied by the pragma. 1680 1681.. code-block:: c 1682 1683 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function) 1684 void getsThePragmaAvailabilityAttribute(void); 1685 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4))); 1686 #pragma clang attribute pop 1687 1688For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can 1689be implicitly inferred from an ``iOS`` availability attribute, the logic is 1690slightly more complex. The explicit and the pragma-applied availability 1691attributes whose platform corresponds to the target platform are applied as 1692described in the previous paragraph. However, the implicitly inferred attributes 1693are applied to a declaration only when there is no explicit or pragma-applied 1694availability attribute whose platform corresponds to the target platform. For 1695example, the function below will receive the ``tvOS`` availability from the 1696pragma rather than using the inferred ``iOS`` availability from the declaration: 1697 1698.. code-block:: c 1699 1700 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function) 1701 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0))); 1702 #pragma clang attribute pop 1703 1704The compiler is also able to apply implicitly inferred attributes from a pragma 1705as well. For example, when targeting ``tvOS``, the function below will receive 1706a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS`` 1707availability attribute applied by the pragma: 1708 1709.. code-block:: c 1710 1711 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function) 1712 void infersTVOSAvailabilityFromPragma(void); 1713 #pragma clang attribute pop 1714 1715The implicit attributes that are inferred from explicitly specified attributes 1716whose platform corresponds to the target platform are applied to the declaration 1717even if there is an availability attribute that can be inferred from a pragma. 1718For example, the function below will receive the ``tvOS, introduced=11.0`` 1719availability that is inferred from the attribute on the declaration rather than 1720inferring availability from the pragma: 1721 1722.. code-block:: c 1723 1724 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function) 1725 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void) 1726 __attribute__((availability(iOS,introduced=11.0))); 1727 #pragma clang attribute pop 1728 1729Also see the documentation for `@available 1730<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_ 1731 }]; 1732} 1733 1734def ExternalSourceSymbolDocs : Documentation { 1735 let Category = DocCatDecl; 1736 let Content = [{ 1737The ``external_source_symbol`` attribute specifies that a declaration originates 1738from an external source and describes the nature of that source. 1739 1740The fact that Clang is capable of recognizing declarations that were defined 1741externally can be used to provide better tooling support for mixed-language 1742projects or projects that rely on auto-generated code. For instance, an IDE that 1743uses Clang and that supports mixed-language projects can use this attribute to 1744provide a correct 'jump-to-definition' feature. For a concrete example, 1745consider a protocol that's defined in a Swift file: 1746 1747.. code-block:: swift 1748 1749 @objc public protocol SwiftProtocol { 1750 func method() 1751 } 1752 1753This protocol can be used from Objective-C code by including a header file that 1754was generated by the Swift compiler. The declarations in that header can use 1755the ``external_source_symbol`` attribute to make Clang aware of the fact 1756that ``SwiftProtocol`` actually originates from a Swift module: 1757 1758.. code-block:: objc 1759 1760 __attribute__((external_source_symbol(language="Swift",defined_in="module"))) 1761 @protocol SwiftProtocol 1762 @required 1763 - (void) method; 1764 @end 1765 1766Consequently, when 'jump-to-definition' is performed at a location that 1767references ``SwiftProtocol``, the IDE can jump to the original definition in 1768the Swift source file rather than jumping to the Objective-C declaration in the 1769auto-generated header file. 1770 1771The ``external_source_symbol`` attribute is a comma-separated list that includes 1772clauses that describe the origin and the nature of the particular declaration. 1773Those clauses can be: 1774 1775language=\ *string-literal* 1776 The name of the source language in which this declaration was defined. 1777 1778defined_in=\ *string-literal* 1779 The name of the source container in which the declaration was defined. The 1780 exact definition of source container is language-specific, e.g. Swift's 1781 source containers are modules, so ``defined_in`` should specify the Swift 1782 module name. 1783 1784USR=\ *string-literal* 1785 String that specifies a unified symbol resolution (USR) value for this 1786 declaration. USR string uniquely identifies this particular declaration, and 1787 is typically used when constructing an index of a codebase. 1788 The USR value in this attribute is expected to be generated by an external 1789 compiler that compiled the native declaration using its original source 1790 language. The exact format of the USR string and its other attributes 1791 are determined by the specification of this declaration's source language. 1792 When not specified, Clang's indexer will use the Clang USR for this symbol. 1793 User can query to see if Clang supports the use of the ``USR`` clause in 1794 the ``external_source_symbol`` attribute with 1795 ``__has_attribute(external_source_symbol) >= 20230206``. 1796 1797generated_declaration 1798 This declaration was automatically generated by some tool. 1799 1800The clauses can be specified in any order. The clauses that are listed above are 1801all optional, but the attribute has to have at least one clause. 1802 }]; 1803} 1804 1805def ConstInitDocs : Documentation { 1806 let Category = DocCatVariable; 1807 let Heading = "require_constant_initialization, constinit (C++20)"; 1808 let Content = [{ 1809This attribute specifies that the variable to which it is attached is intended 1810to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_ 1811according to the rules of [basic.start.static]. The variable is required to 1812have static or thread storage duration. If the initialization of the variable 1813is not a constant initializer an error will be produced. This attribute may 1814only be used in C++; the ``constinit`` spelling is only accepted in C++20 1815onwards. 1816 1817Note that in C++03 strict constant expression checking is not done. Instead 1818the attribute reports if Clang can emit the variable as a constant, even if it's 1819not technically a 'constant initializer'. This behavior is non-portable. 1820 1821Static storage duration variables with constant initializers avoid hard-to-find 1822bugs caused by the indeterminate order of dynamic initialization. They can also 1823be safely used during dynamic initialization across translation units. 1824 1825This attribute acts as a compile time assertion that the requirements 1826for constant initialization have been met. Since these requirements change 1827between dialects and have subtle pitfalls it's important to fail fast instead 1828of silently falling back on dynamic initialization. 1829 1830The first use of the attribute on a variable must be part of, or precede, the 1831initializing declaration of the variable. C++20 requires the ``constinit`` 1832spelling of the attribute to be present on the initializing declaration if it 1833is used anywhere. The other spellings can be specified on a forward declaration 1834and omitted on a later initializing declaration. 1835 1836.. code-block:: c++ 1837 1838 // -std=c++14 1839 #define SAFE_STATIC [[clang::require_constant_initialization]] 1840 struct T { 1841 constexpr T(int) {} 1842 ~T(); // non-trivial 1843 }; 1844 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor. 1845 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer 1846 // copy initialization is not a constant expression on a non-literal type. 1847 }]; 1848} 1849 1850def WarnMaybeUnusedDocs : Documentation { 1851 let Category = DocCatVariable; 1852 let Heading = "maybe_unused, unused"; 1853 let Content = [{ 1854When passing the ``-Wunused`` flag to Clang, entities that are unused by the 1855program may be diagnosed. The ``[[maybe_unused]]`` (or 1856``__attribute__((unused))``) attribute can be used to silence such diagnostics 1857when the entity cannot be removed. For instance, a local variable may exist 1858solely for use in an ``assert()`` statement, which makes the local variable 1859unused when ``NDEBUG`` is defined. 1860 1861The attribute may be applied to the declaration of a class, a typedef, a 1862variable, a function or method, a function parameter, an enumeration, an 1863enumerator, a non-static data member, or a label. 1864 1865.. code-block:: c++ 1866 1867 #include <cassert> 1868 1869 [[maybe_unused]] void f([[maybe_unused]] bool thing1, 1870 [[maybe_unused]] bool thing2) { 1871 [[maybe_unused]] bool b = thing1 && thing2; 1872 assert(b); 1873 } 1874 }]; 1875} 1876 1877def WarnUnusedResultsDocs : Documentation { 1878 let Category = DocCatFunction; 1879 let Heading = "nodiscard, warn_unused_result"; 1880 let Content = [{ 1881Clang supports the ability to diagnose when the results of a function call 1882expression are discarded under suspicious circumstances. A diagnostic is 1883generated when a function or its return type is marked with ``[[nodiscard]]`` 1884(or ``__attribute__((warn_unused_result))``) and the function call appears as a 1885potentially-evaluated discarded-value expression that is not explicitly cast to 1886``void``. 1887 1888A string literal may optionally be provided to the attribute, which will be 1889reproduced in any resulting diagnostics. Redeclarations using different forms 1890of the attribute (with or without the string literal or with different string 1891literal contents) are allowed. If there are redeclarations of the entity with 1892differing string literals, it is unspecified which one will be used by Clang 1893in any resulting diagnostics. 1894 1895.. code-block:: c++ 1896 1897 struct [[nodiscard]] error_info { /*...*/ }; 1898 error_info enable_missile_safety_mode(); 1899 1900 void launch_missiles(); 1901 void test_missiles() { 1902 enable_missile_safety_mode(); // diagnoses 1903 launch_missiles(); 1904 } 1905 error_info &foo(); 1906 void f() { foo(); } // Does not diagnose, error_info is a reference. 1907 1908Additionally, discarded temporaries resulting from a call to a constructor 1909marked with ``[[nodiscard]]`` or a constructor of a type marked 1910``[[nodiscard]]`` will also diagnose. This also applies to type conversions that 1911use the annotated ``[[nodiscard]]`` constructor or result in an annotated type. 1912 1913.. code-block:: c++ 1914 1915 struct [[nodiscard]] marked_type {/*..*/ }; 1916 struct marked_ctor { 1917 [[nodiscard]] marked_ctor(); 1918 marked_ctor(int); 1919 }; 1920 1921 struct S { 1922 operator marked_type() const; 1923 [[nodiscard]] operator int() const; 1924 }; 1925 1926 void usages() { 1927 marked_type(); // diagnoses. 1928 marked_ctor(); // diagnoses. 1929 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard. 1930 1931 S s; 1932 static_cast<marked_type>(s); // diagnoses 1933 (int)s; // diagnoses 1934 } 1935 }]; 1936} 1937 1938def FallthroughDocs : Documentation { 1939 let Category = DocCatStmt; 1940 let Heading = "fallthrough"; 1941 let Content = [{ 1942The ``fallthrough`` (or ``clang::fallthrough``) attribute is used 1943to annotate intentional fall-through 1944between switch labels. It can only be applied to a null statement placed at a 1945point of execution between any statement and the next switch label. It is 1946common to mark these places with a specific comment, but this attribute is 1947meant to replace comments with a more strict annotation, which can be checked 1948by the compiler. This attribute doesn't change semantics of the code and can 1949be used wherever an intended fall-through occurs. It is designed to mimic 1950control-flow statements like ``break;``, so it can be placed in most places 1951where ``break;`` can, but only if there are no statements on the execution path 1952between it and the next switch label. 1953 1954By default, Clang does not warn on unannotated fallthrough from one ``switch`` 1955case to another. Diagnostics on fallthrough without a corresponding annotation 1956can be enabled with the ``-Wimplicit-fallthrough`` argument. 1957 1958Here is an example: 1959 1960.. code-block:: c++ 1961 1962 // compile with -Wimplicit-fallthrough 1963 switch (n) { 1964 case 22: 1965 case 33: // no warning: no statements between case labels 1966 f(); 1967 case 44: // warning: unannotated fall-through 1968 g(); 1969 [[clang::fallthrough]]; 1970 case 55: // no warning 1971 if (x) { 1972 h(); 1973 break; 1974 } 1975 else { 1976 i(); 1977 [[clang::fallthrough]]; 1978 } 1979 case 66: // no warning 1980 p(); 1981 [[clang::fallthrough]]; // warning: fallthrough annotation does not 1982 // directly precede case label 1983 q(); 1984 case 77: // warning: unannotated fall-through 1985 r(); 1986 } 1987 }]; 1988} 1989 1990def LikelihoodDocs : Documentation { 1991 let Category = DocCatStmt; 1992 let Heading = "likely and unlikely"; 1993 let Content = [{ 1994The ``likely`` and ``unlikely`` attributes are used as compiler hints. 1995The attributes are used to aid the compiler to determine which branch is 1996likely or unlikely to be taken. This is done by marking the branch substatement 1997with one of the two attributes. 1998 1999It isn't allowed to annotate a single statement with both ``likely`` and 2000``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if`` 2001statement with the same likelihood attribute will result in a diagnostic and 2002the attributes are ignored on both branches. 2003 2004In a ``switch`` statement it's allowed to annotate multiple ``case`` labels 2005or the ``default`` label with the same likelihood attribute. This makes 2006* all labels without an attribute have a neutral likelihood, 2007* all labels marked ``[[likely]]`` have an equally positive likelihood, and 2008* all labels marked ``[[unlikely]]`` have an equally negative likelihood. 2009The neutral likelihood is the more likely of path execution than the negative 2010likelihood. The positive likelihood is the more likely of path of execution 2011than the neutral likelihood. 2012 2013These attributes have no effect on the generated code when using 2014PGO (Profile-Guided Optimization) or at optimization level 0. 2015 2016In Clang, the attributes will be ignored if they're not placed on 2017* the ``case`` or ``default`` label of a ``switch`` statement, 2018* or on the substatement of an ``if`` or ``else`` statement, 2019* or on the substatement of an ``for`` or ``while`` statement. 2020The C++ Standard recommends to honor them on every statement in the 2021path of execution, but that can be confusing: 2022 2023.. code-block:: c++ 2024 2025 if (b) { 2026 [[unlikely]] --b; // In the path of execution, 2027 // this branch is considered unlikely. 2028 } 2029 2030 if (b) { 2031 --b; 2032 if(b) 2033 return; 2034 [[unlikely]] --b; // Not in the path of execution, 2035 } // the branch has no likelihood information. 2036 2037 if (b) { 2038 --b; 2039 foo(b); 2040 // Whether or not the next statement is in the path of execution depends 2041 // on the declaration of foo(): 2042 // In the path of execution: void foo(int); 2043 // Not in the path of execution: [[noreturn]] void foo(int); 2044 // This means the likelihood of the branch depends on the declaration 2045 // of foo(). 2046 [[unlikely]] --b; 2047 } 2048 2049 2050Below are some example usages of the likelihood attributes and their effects: 2051 2052.. code-block:: c++ 2053 2054 if (b) [[likely]] { // Placement on the first statement in the branch. 2055 // The compiler will optimize to execute the code here. 2056 } else { 2057 } 2058 2059 if (b) 2060 [[unlikely]] b++; // Placement on the first statement in the branch. 2061 else { 2062 // The compiler will optimize to execute the code here. 2063 } 2064 2065 if (b) { 2066 [[unlikely]] b++; // Placement on the second statement in the branch. 2067 } // The attribute will be ignored. 2068 2069 if (b) [[likely]] { 2070 [[unlikely]] b++; // No contradiction since the second attribute 2071 } // is ignored. 2072 2073 if (b) 2074 ; 2075 else [[likely]] { 2076 // The compiler will optimize to execute the code here. 2077 } 2078 2079 if (b) 2080 ; 2081 else 2082 // The compiler will optimize to execute the next statement. 2083 [[likely]] b = f(); 2084 2085 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued 2086 else [[likely]]; // and the attributes are ignored. 2087 2088 if (b) 2089 [[likely]] int i = 5; // Issues a diagnostic since the attribute 2090 // isn't allowed on a declaration. 2091 2092 switch (i) { 2093 [[likely]] case 1: // This value is likely 2094 ... 2095 break; 2096 2097 [[unlikely]] case 2: // This value is unlikely 2098 ... 2099 [[fallthrough]]; 2100 2101 case 3: // No likelihood attribute 2102 ... 2103 [[likely]] break; // No effect 2104 2105 case 4: [[likely]] { // attribute on substatement has no effect 2106 ... 2107 break; 2108 } 2109 2110 [[unlikely]] default: // All other values are unlikely 2111 ... 2112 break; 2113 } 2114 2115 switch (i) { 2116 [[likely]] case 0: // This value and code path is likely 2117 ... 2118 [[fallthrough]]; 2119 2120 case 1: // No likelihood attribute, code path is neutral 2121 break; // falling through has no effect on the likelihood 2122 2123 case 2: // No likelihood attribute, code path is neutral 2124 [[fallthrough]]; 2125 2126 [[unlikely]] default: // This value and code path are both unlikely 2127 break; 2128 } 2129 2130 for(int i = 0; i != size; ++i) [[likely]] { 2131 ... // The loop is the likely path of execution 2132 } 2133 2134 for(const auto &E : Elements) [[likely]] { 2135 ... // The loop is the likely path of execution 2136 } 2137 2138 while(i != size) [[unlikely]] { 2139 ... // The loop is the unlikely path of execution 2140 } // The generated code will optimize to skip the loop body 2141 2142 while(true) [[unlikely]] { 2143 ... // The attribute has no effect 2144 } // Clang elides the comparison and generates an infinite 2145 // loop 2146 2147 }]; 2148} 2149 2150def ARMInterruptDocs : Documentation { 2151 let Category = DocCatFunction; 2152 let Heading = "interrupt (ARM)"; 2153 let Content = [{ 2154Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on 2155ARM targets. This attribute may be attached to a function definition and 2156instructs the backend to generate appropriate function entry/exit code so that 2157it can be used directly as an interrupt service routine. 2158 2159The parameter passed to the interrupt attribute is optional, but if 2160provided it must be a string literal with one of the following values: "IRQ", 2161"FIQ", "SWI", "ABORT", "UNDEF". 2162 2163The semantics are as follows: 2164 2165- If the function is AAPCS, Clang instructs the backend to realign the stack to 2166 8 bytes on entry. This is a general requirement of the AAPCS at public 2167 interfaces, but may not hold when an exception is taken. Doing this allows 2168 other AAPCS functions to be called. 2169- If the CPU is M-class this is all that needs to be done since the architecture 2170 itself is designed in such a way that functions obeying the normal AAPCS ABI 2171 constraints are valid exception handlers. 2172- If the CPU is not M-class, the prologue and epilogue are modified to save all 2173 non-banked registers that are used, so that upon return the user-mode state 2174 will not be corrupted. Note that to avoid unnecessary overhead, only 2175 general-purpose (integer) registers are saved in this way. If VFP operations 2176 are needed, that state must be saved manually. 2177 2178 Specifically, interrupt kinds other than "FIQ" will save all core registers 2179 except "lr" and "sp". "FIQ" interrupts will save r0-r7. 2180- If the CPU is not M-class, the return instruction is changed to one of the 2181 canonical sequences permitted by the architecture for exception return. Where 2182 possible the function itself will make the necessary "lr" adjustments so that 2183 the "preferred return address" is selected. 2184 2185 Unfortunately the compiler is unable to make this guarantee for an "UNDEF" 2186 handler, where the offset from "lr" to the preferred return address depends on 2187 the execution state of the code which generated the exception. In this case 2188 a sequence equivalent to "movs pc, lr" will be used. 2189 }]; 2190} 2191 2192def BPFPreserveAccessIndexDocs : Documentation { 2193 let Category = DocCatFunction; 2194 let Content = [{ 2195Clang supports the ``__attribute__((preserve_access_index))`` 2196attribute for the BPF target. This attribute may be attached to a 2197struct or union declaration, where if -g is specified, it enables 2198preserving struct or union member access debuginfo indices of this 2199struct or union, similar to clang ``__builtin_preserve_access_index()``. 2200 }]; 2201} 2202 2203def BPFPreserveStaticOffsetDocs : Documentation { 2204 let Category = DocCatFunction; 2205 let Content = [{ 2206Clang supports the ``__attribute__((preserve_static_offset))`` 2207attribute for the BPF target. This attribute may be attached to a 2208struct or union declaration. Reading or writing fields of types having 2209such annotation is guaranteed to generate LDX/ST/STX instruction with 2210offset corresponding to the field. 2211 2212For example: 2213 2214.. code-block:: c 2215 2216 struct foo { 2217 int a; 2218 int b; 2219 }; 2220 2221 struct bar { 2222 int a; 2223 struct foo b; 2224 } __attribute__((preserve_static_offset)); 2225 2226 void buz(struct bar *g) { 2227 g->b.a = 42; 2228 } 2229 2230The assignment to ``g``'s field would produce an ST instruction with 2231offset 8: ``*(u32)(r1 + 8) = 42;``. 2232 2233Without this attribute generated instructions might be different, 2234depending on optimizations behavior. E.g. the example above could be 2235rewritten as ``r1 += 8; *(u32)(r1 + 0) = 42;``. 2236 }]; 2237} 2238 2239def BTFDeclTagDocs : Documentation { 2240 let Category = DocCatFunction; 2241 let Content = [{ 2242Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for 2243all targets. This attribute may be attached to a struct/union, struct/union 2244field, function, function parameter, variable or typedef declaration. If -g is 2245specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to 2246dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF 2247section too. 2248 }]; 2249} 2250 2251def BTFTypeTagDocs : Documentation { 2252 let Category = DocCatType; 2253 let Content = [{ 2254Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for 2255all targets. It only has effect when ``-g`` is specified on the command line and 2256is currently silently ignored when not applied to a pointer type (note: this 2257scenario may be diagnosed in the future). 2258 2259The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the 2260types used in variable declarations, function declarations, or typedef 2261declarations. 2262 2263For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF 2264section. 2265 }]; 2266} 2267 2268def MipsInterruptDocs : Documentation { 2269 let Category = DocCatFunction; 2270 let Heading = "interrupt (MIPS)"; 2271 let Content = [{ 2272Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on 2273MIPS targets. This attribute may be attached to a function definition and instructs 2274the backend to generate appropriate function entry/exit code so that it can be used 2275directly as an interrupt service routine. 2276 2277By default, the compiler will produce a function prologue and epilogue suitable for 2278an interrupt service routine that handles an External Interrupt Controller (eic) 2279generated interrupt. This behavior can be explicitly requested with the "eic" 2280argument. 2281 2282Otherwise, for use with vectored interrupt mode, the argument passed should be 2283of the form "vector=LEVEL" where LEVEL is one of the following values: 2284"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will 2285then set the interrupt mask to the corresponding level which will mask all 2286interrupts up to and including the argument. 2287 2288The semantics are as follows: 2289 2290- The prologue is modified so that the Exception Program Counter (EPC) and 2291 Status coprocessor registers are saved to the stack. The interrupt mask is 2292 set so that the function can only be interrupted by a higher priority 2293 interrupt. The epilogue will restore the previous values of EPC and Status. 2294 2295- The prologue and epilogue are modified to save and restore all non-kernel 2296 registers as necessary. 2297 2298- The FPU is disabled in the prologue, as the floating pointer registers are not 2299 spilled to the stack. 2300 2301- The function return sequence is changed to use an exception return instruction. 2302 2303- The parameter sets the interrupt mask for the function corresponding to the 2304 interrupt level specified. If no mask is specified the interrupt mask 2305 defaults to "eic". 2306 }]; 2307} 2308 2309def MicroMipsDocs : Documentation { 2310 let Category = DocCatFunction; 2311 let Content = [{ 2312Clang supports the GNU style ``__attribute__((micromips))`` and 2313``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes 2314may be attached to a function definition and instructs the backend to generate 2315or not to generate microMIPS code for that function. 2316 2317These attributes override the ``-mmicromips`` and ``-mno-micromips`` options 2318on the command line. 2319 }]; 2320} 2321 2322def MipsLongCallStyleDocs : Documentation { 2323 let Category = DocCatFunction; 2324 let Heading = "long_call, far"; 2325 let Content = [{ 2326Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, 2327and ``__attribute__((near))`` attributes on MIPS targets. These attributes may 2328only be added to function declarations and change the code generated 2329by the compiler when directly calling the function. The ``near`` attribute 2330allows calls to the function to be made using the ``jal`` instruction, which 2331requires the function to be located in the same naturally aligned 256MB 2332segment as the caller. The ``long_call`` and ``far`` attributes are synonyms 2333and require the use of a different call sequence that works regardless 2334of the distance between the functions. 2335 2336These attributes have no effect for position-independent code. 2337 2338These attributes take priority over command line switches such 2339as ``-mlong-calls`` and ``-mno-long-calls``. 2340 }]; 2341} 2342 2343def MipsShortCallStyleDocs : Documentation { 2344 let Category = DocCatFunction; 2345 let Heading = "short_call, near"; 2346 let Content = [{ 2347Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, 2348``__attribute__((short__call))``, and ``__attribute__((near))`` attributes 2349on MIPS targets. These attributes may only be added to function declarations 2350and change the code generated by the compiler when directly calling 2351the function. The ``short_call`` and ``near`` attributes are synonyms and 2352allow calls to the function to be made using the ``jal`` instruction, which 2353requires the function to be located in the same naturally aligned 256MB segment 2354as the caller. The ``long_call`` and ``far`` attributes are synonyms and 2355require the use of a different call sequence that works regardless 2356of the distance between the functions. 2357 2358These attributes have no effect for position-independent code. 2359 2360These attributes take priority over command line switches such 2361as ``-mlong-calls`` and ``-mno-long-calls``. 2362 }]; 2363} 2364 2365def RISCVInterruptDocs : Documentation { 2366 let Category = DocCatFunction; 2367 let Heading = "interrupt (RISC-V)"; 2368 let Content = [{ 2369Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV 2370targets. This attribute may be attached to a function definition and instructs 2371the backend to generate appropriate function entry/exit code so that it can be 2372used directly as an interrupt service routine. 2373 2374Permissible values for this parameter are ``user``, ``supervisor``, 2375and ``machine``. If there is no parameter, then it defaults to machine. 2376 2377Repeated interrupt attribute on the same declaration will cause a warning 2378to be emitted. In case of repeated declarations, the last one prevails. 2379 2380Refer to: 2381https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html 2382https://riscv.org/specifications/privileged-isa/ 2383The RISC-V Instruction Set Manual Volume II: Privileged Architecture 2384Version 1.10. 2385 }]; 2386} 2387 2388def RISCVRVVVectorBitsDocs : Documentation { 2389 let Category = DocCatType; 2390 let Content = [{ 2391On RISC-V targets, the ``riscv_rvv_vector_bits(N)`` attribute is used to define 2392fixed-length variants of sizeless types. 2393 2394For example: 2395 2396.. code-block:: c 2397 2398 #include <riscv_vector.h> 2399 2400 #if defined(__riscv_v_fixed_vlen) 2401 typedef vint8m1_t fixed_vint8m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen))); 2402 #endif 2403 2404Creates a type ``fixed_vint8m1_t_t`` that is a fixed-length variant of 2405``vint8m1_t`` that contains exactly 512 bits. Unlike ``vint8m1_t``, this type 2406can be used in globals, structs, unions, and arrays, all of which are 2407unsupported for sizeless types. 2408 2409The attribute can be attached to a single RVV vector (such as ``vint8m1_t``). 2410The attribute will be rejected unless 2411``N==(__riscv_v_fixed_vlen*LMUL)``, the implementation defined feature macro that 2412is enabled under the ``-mrvv-vector-bits`` flag. ``__riscv_v_fixed_vlen`` can 2413only be a power of 2 between 64 and 65536. 2414 2415For types where LMUL!=1, ``__riscv_v_fixed_vlen`` needs to be scaled by the LMUL 2416of the type before passing to the attribute. 2417 2418``vbool*_t`` types are not supported at this time. 2419}]; 2420} 2421 2422def AVRInterruptDocs : Documentation { 2423 let Category = DocCatFunction; 2424 let Heading = "interrupt (AVR)"; 2425 let Content = [{ 2426Clang supports the GNU style ``__attribute__((interrupt))`` attribute on 2427AVR targets. This attribute may be attached to a function definition and instructs 2428the backend to generate appropriate function entry/exit code so that it can be used 2429directly as an interrupt service routine. 2430 2431On the AVR, the hardware globally disables interrupts when an interrupt is executed. 2432The first instruction of an interrupt handler declared with this attribute is a SEI 2433instruction to re-enable interrupts. See also the signal attribute that 2434does not insert a SEI instruction. 2435 }]; 2436} 2437 2438def AVRSignalDocs : Documentation { 2439 let Category = DocCatFunction; 2440 let Content = [{ 2441Clang supports the GNU style ``__attribute__((signal))`` attribute on 2442AVR targets. This attribute may be attached to a function definition and instructs 2443the backend to generate appropriate function entry/exit code so that it can be used 2444directly as an interrupt service routine. 2445 2446Interrupt handler functions defined with the signal attribute do not re-enable interrupts. 2447}]; 2448} 2449 2450def TargetDocs : Documentation { 2451 let Category = DocCatFunction; 2452 let Content = [{ 2453Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute. 2454This attribute may be attached to a function definition and instructs 2455the backend to use different code generation options than were passed on the 2456command line. 2457 2458The current set of options correspond to the existing "subtarget features" for 2459the target with or without a "-mno-" in front corresponding to the absence 2460of the feature, as well as ``arch="CPU"`` which will change the default "CPU" 2461for the function. 2462 2463For X86, the attribute also allows ``tune="CPU"`` to optimize the generated 2464code for the given CPU without changing the available instructions. 2465 2466For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march 2467command line options. ``cpu="CPU"`` can be used to select a specific cpu, 2468as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the 2469"branch-protection=<args>" option, where the permissible arguments and their 2470effect on code generation are the same as for the command-line option 2471``-mbranch-protection``. 2472 2473Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", 2474"avx", "xop" and largely correspond to the machine specific options handled by 2475the front end. 2476 2477Additionally, this attribute supports function multiversioning for ELF based 2478x86/x86-64 targets, which can be used to create multiple implementations of the 2479same function that will be resolved at runtime based on the priority of their 2480``target`` attribute strings. A function is considered a multiversioned function 2481if either two declarations of the function have different ``target`` attribute 2482strings, or if it has a ``target`` attribute string of ``default``. For 2483example: 2484 2485 .. code-block:: c++ 2486 2487 __attribute__((target("arch=atom"))) 2488 void foo() {} // will be called on 'atom' processors. 2489 __attribute__((target("default"))) 2490 void foo() {} // will be called on any other processors. 2491 2492All multiversioned functions must contain a ``default`` (fallback) 2493implementation, otherwise usages of the function are considered invalid. 2494Additionally, a function may not become multiversioned after its first use. 2495}]; 2496} 2497 2498def TargetVersionDocs : Documentation { 2499 let Category = DocCatFunction; 2500 let Content = [{ 2501For AArch64 target clang supports function multiversioning by 2502``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a 2503function it instructs compiler to emit multiple function versions based on 2504``target_version`` attribute strings, which resolved at runtime depend on their 2505priority and target features availability. One of the versions is always 2506( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can 2507contain dependent features names joined by the "+" sign. 2508}]; 2509} 2510 2511def TargetClonesDocs : Documentation { 2512 let Category = DocCatFunction; 2513 let Content = [{ 2514Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be 2515attached to a function declaration and causes function multiversioning, where 2516multiple versions of the function will be emitted with different code 2517generation options. Additionally, these versions will be resolved at runtime 2518based on the priority of their attribute options. All ``target_clone`` functions 2519are considered multiversioned functions. 2520 2521For AArch64 target: 2522The attribute contains comma-separated strings of target features joined by "+" 2523sign. For example: 2524 2525 .. code-block:: c++ 2526 2527 __attribute__((target_clones("sha2+memtag2", "fcma+sve2-pmull128"))) 2528 void foo() {} 2529 2530For every multiversioned function a ``default`` (fallback) implementation 2531always generated if not specified directly. 2532 2533For x86/x86-64 targets: 2534All multiversioned functions must contain a ``default`` (fallback) 2535implementation, otherwise usages of the function are considered invalid. 2536Additionally, a function may not become multiversioned after its first use. 2537 2538The options to ``target_clones`` can either be a target-specific architecture 2539(specified as ``arch=CPU``), or one of a list of subtarget features. 2540 2541Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", 2542"avx", "xop" and largely correspond to the machine specific options handled by 2543the front end. 2544 2545The versions can either be listed as a comma-separated sequence of string 2546literals or as a single string literal containing a comma-separated list of 2547versions. For compatibility with GCC, the two formats can be mixed. For 2548example, the following will emit 4 versions of the function: 2549 2550 .. code-block:: c++ 2551 2552 __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default"))) 2553 void foo() {} 2554 2555For targets that support the GNU indirect function (IFUNC) feature, dispatch 2556is performed by emitting an indirect function that is resolved to the appropriate 2557target clone at load time. The indirect function is given the name the 2558multiversioned function would have if it had been declared without the attribute. 2559For backward compatibility with earlier Clang releases, a function alias with an 2560``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated 2561feature and support for it may be removed in the future. 2562}]; 2563} 2564 2565def MinVectorWidthDocs : Documentation { 2566 let Category = DocCatFunction; 2567 let Content = [{ 2568Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This 2569attribute may be attached to a function and informs the backend that this 2570function desires vectors of at least this width to be generated. Target-specific 2571maximum vector widths still apply. This means even if you ask for something 2572larger than the target supports, you will only get what the target supports. 2573This attribute is meant to be a hint to control target heuristics that may 2574generate narrower vectors than what the target hardware supports. 2575 2576This is currently used by the X86 target to allow some CPUs that support 512-bit 2577vectors to be limited to using 256-bit vectors to avoid frequency penalties. 2578This is currently enabled with the ``-prefer-vector-width=256`` command line 2579option. The ``min_vector_width`` attribute can be used to prevent the backend 2580from trying to split vector operations to match the ``prefer-vector-width``. All 2581X86 vector intrinsics from x86intrin.h already set this attribute. Additionally, 2582use of any of the X86-specific vector builtins will implicitly set this 2583attribute on the calling function. The intent is that explicitly writing vector 2584code using the X86 intrinsics will prevent ``prefer-vector-width`` from 2585affecting the code. 2586}]; 2587} 2588 2589def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">; 2590 2591def AMDGPUFlatWorkGroupSizeDocs : Documentation { 2592 let Category = DocCatAMDGPUAttributes; 2593 let Content = [{ 2594The flat work-group size is the number of work-items in the work-group size 2595specified when the kernel is dispatched. It is the product of the sizes of the 2596x, y, and z dimension of the work-group. 2597 2598Clang supports the 2599``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the 2600AMDGPU target. This attribute may be attached to a kernel function definition 2601and is an optimization hint. 2602 2603``<min>`` parameter specifies the minimum flat work-group size, and ``<max>`` 2604parameter specifies the maximum flat work-group size (must be greater than 2605``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0`` 2606as ``<min>, <max>`` implies the default behavior (``128, 256``). 2607 2608If specified, the AMDGPU target backend might be able to produce better machine 2609code for barriers and perform scratch promotion by estimating available group 2610segment size. 2611 2612An error will be given if: 2613 - Specified values violate subtarget specifications; 2614 - Specified values are not compatible with values provided through other 2615 attributes. 2616 }]; 2617} 2618 2619def AMDGPUWavesPerEUDocs : Documentation { 2620 let Category = DocCatAMDGPUAttributes; 2621 let Content = [{ 2622A compute unit (CU) is responsible for executing the wavefronts of a work-group. 2623It is composed of one or more execution units (EU), which are responsible for 2624executing the wavefronts. An EU can have enough resources to maintain the state 2625of more than one executing wavefront. This allows an EU to hide latency by 2626switching between wavefronts in a similar way to symmetric multithreading on a 2627CPU. In order to allow the state for multiple wavefronts to fit on an EU, the 2628resources used by a single wavefront have to be limited. For example, the number 2629of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding, 2630but can result in having to spill some register state to memory. 2631 2632Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`` 2633attribute for the AMDGPU target. This attribute may be attached to a kernel 2634function definition and is an optimization hint. 2635 2636``<min>`` parameter specifies the requested minimum number of waves per EU, and 2637*optional* ``<max>`` parameter specifies the requested maximum number of waves 2638per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted, 2639then there is no restriction on the maximum number of waves per EU other than 2640the one dictated by the hardware for which the kernel is compiled. Passing 2641``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits). 2642 2643If specified, this attribute allows an advanced developer to tune the number of 2644wavefronts that are capable of fitting within the resources of an EU. The AMDGPU 2645target backend can use this information to limit resources, such as number of 2646SGPRs, number of VGPRs, size of available group and private memory segments, in 2647such a way that guarantees that at least ``<min>`` wavefronts and at most 2648``<max>`` wavefronts are able to fit within the resources of an EU. Requesting 2649more wavefronts can hide memory latency but limits available registers which 2650can result in spilling. Requesting fewer wavefronts can help reduce cache 2651thrashing, but can reduce memory latency hiding. 2652 2653This attribute controls the machine code generated by the AMDGPU target backend 2654to ensure it is capable of meeting the requested values. However, when the 2655kernel is executed, there may be other reasons that prevent meeting the request, 2656for example, there may be wavefronts from other kernels executing on the EU. 2657 2658An error will be given if: 2659 - Specified values violate subtarget specifications; 2660 - Specified values are not compatible with values provided through other 2661 attributes; 2662 2663The AMDGPU target backend will emit a warning whenever it is unable to 2664create machine code that meets the request. 2665 }]; 2666} 2667 2668def AMDGPUNumSGPRNumVGPRDocs : Documentation { 2669 let Category = DocCatAMDGPUAttributes; 2670 let Content = [{ 2671Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and 2672``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU 2673target. These attributes may be attached to a kernel function definition and are 2674an optimization hint. 2675 2676If these attributes are specified, then the AMDGPU target backend will attempt 2677to limit the number of SGPRs and/or VGPRs used to the specified value(s). The 2678number of used SGPRs and/or VGPRs may further be rounded up to satisfy the 2679allocation requirements or constraints of the subtarget. Passing ``0`` as 2680``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits). 2681 2682These attributes can be used to test the AMDGPU target backend. It is 2683recommended that the ``amdgpu_waves_per_eu`` attribute be used to control 2684resources such as SGPRs and VGPRs since it is aware of the limits for different 2685subtargets. 2686 2687An error will be given if: 2688 - Specified values violate subtarget specifications; 2689 - Specified values are not compatible with values provided through other 2690 attributes; 2691 - The AMDGPU target backend is unable to create machine code that can meet the 2692 request. 2693 }]; 2694} 2695 2696def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> { 2697 let Content = [{ 2698Clang supports several different calling conventions, depending on the target 2699platform and architecture. The calling convention used for a function determines 2700how parameters are passed, how results are returned to the caller, and other 2701low-level details of calling a function. 2702 }]; 2703} 2704 2705def PcsDocs : Documentation { 2706 let Category = DocCatCallingConvs; 2707 let Content = [{ 2708On ARM targets, this attribute can be used to select calling conventions 2709similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and 2710"aapcs-vfp". 2711 }]; 2712} 2713 2714def AArch64VectorPcsDocs : Documentation { 2715 let Category = DocCatCallingConvs; 2716 let Content = [{ 2717On AArch64 targets, this attribute changes the calling convention of a 2718function to preserve additional floating-point and Advanced SIMD registers 2719relative to the default calling convention used for AArch64. 2720 2721This means it is more efficient to call such functions from code that performs 2722extensive floating-point and vector calculations, because fewer live SIMD and FP 2723registers need to be saved. This property makes it well-suited for e.g. 2724floating-point or vector math library functions, which are typically leaf 2725functions that require a small number of registers. 2726 2727However, using this attribute also means that it is more expensive to call 2728a function that adheres to the default calling convention from within such 2729a function. Therefore, it is recommended that this attribute is only used 2730for leaf functions. 2731 2732For more information, see the documentation for `aarch64_vector_pcs`_ on 2733the Arm Developer website. 2734 2735.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi 2736 }]; 2737} 2738 2739def AArch64SVEPcsDocs : Documentation { 2740 let Category = DocCatCallingConvs; 2741 let Content = [{ 2742On AArch64 targets, this attribute changes the calling convention of a 2743function to preserve additional Scalable Vector registers and Scalable 2744Predicate registers relative to the default calling convention used for 2745AArch64. 2746 2747This means it is more efficient to call such functions from code that performs 2748extensive scalable vector and scalable predicate calculations, because fewer 2749live SVE registers need to be saved. This property makes it well-suited for SVE 2750math library functions, which are typically leaf functions that require a small 2751number of registers. 2752 2753However, using this attribute also means that it is more expensive to call 2754a function that adheres to the default calling convention from within such 2755a function. Therefore, it is recommended that this attribute is only used 2756for leaf functions. 2757 2758For more information, see the documentation for `aarch64_sve_pcs` in the 2759ARM C Language Extension (ACLE) documentation. 2760 2761.. _`aarch64_sve_pcs`: https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute 2762 }]; 2763} 2764 2765def RegparmDocs : Documentation { 2766 let Category = DocCatCallingConvs; 2767 let Content = [{ 2768On 32-bit x86 targets, the regparm attribute causes the compiler to pass 2769the first three integer parameters in EAX, EDX, and ECX instead of on the 2770stack. This attribute has no effect on variadic functions, and all parameters 2771are passed via the stack as normal. 2772 }]; 2773} 2774 2775def SysVABIDocs : Documentation { 2776 let Category = DocCatCallingConvs; 2777 let Content = [{ 2778On Windows x86_64 targets, this attribute changes the calling convention of a 2779function to match the default convention used on Sys V targets such as Linux, 2780Mac, and BSD. This attribute has no effect on other targets. 2781 }]; 2782} 2783 2784def MSABIDocs : Documentation { 2785 let Category = DocCatCallingConvs; 2786 let Content = [{ 2787On non-Windows x86_64 targets, this attribute changes the calling convention of 2788a function to match the default convention used on Windows x86_64. This 2789attribute has no effect on Windows targets or non-x86_64 targets. 2790 }]; 2791} 2792 2793def StdCallDocs : Documentation { 2794 let Category = DocCatCallingConvs; 2795 let Content = [{ 2796On 32-bit x86 targets, this attribute changes the calling convention of a 2797function to clear parameters off of the stack on return. This convention does 2798not support variadic calls or unprototyped functions in C, and has no effect on 2799x86_64 targets. This calling convention is used widely by the Windows API and 2800COM applications. See the documentation for `__stdcall`_ on MSDN. 2801 2802.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx 2803 }]; 2804} 2805 2806def FastCallDocs : Documentation { 2807 let Category = DocCatCallingConvs; 2808 let Content = [{ 2809On 32-bit x86 targets, this attribute changes the calling convention of a 2810function to use ECX and EDX as register parameters and clear parameters off of 2811the stack on return. This convention does not support variadic calls or 2812unprototyped functions in C, and has no effect on x86_64 targets. This calling 2813convention is supported primarily for compatibility with existing code. Users 2814seeking register parameters should use the ``regparm`` attribute, which does 2815not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN. 2816 2817.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx 2818 }]; 2819} 2820 2821def RegCallDocs : Documentation { 2822 let Category = DocCatCallingConvs; 2823 let Content = [{ 2824On x86 targets, this attribute changes the calling convention to 2825`__regcall`_ convention. This convention aims to pass as many arguments 2826as possible in registers. It also tries to utilize registers for the 2827return value whenever it is possible. 2828 2829.. _`__regcall`: https://www.intel.com/content/www/us/en/docs/dpcpp-cpp-compiler/developer-guide-reference/2023-2/c-c-sycl-calling-conventions.html 2830 }]; 2831} 2832 2833def ThisCallDocs : Documentation { 2834 let Category = DocCatCallingConvs; 2835 let Content = [{ 2836On 32-bit x86 targets, this attribute changes the calling convention of a 2837function to use ECX for the first parameter (typically the implicit ``this`` 2838parameter of C++ methods) and clear parameters off of the stack on return. This 2839convention does not support variadic calls or unprototyped functions in C, and 2840has no effect on x86_64 targets. See the documentation for `__thiscall`_ on 2841MSDN. 2842 2843.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx 2844 }]; 2845} 2846 2847def VectorCallDocs : Documentation { 2848 let Category = DocCatCallingConvs; 2849 let Content = [{ 2850On 32-bit x86 *and* x86_64 targets, this attribute changes the calling 2851convention of a function to pass vector parameters in SSE registers. 2852 2853On 32-bit x86 targets, this calling convention is similar to ``__fastcall``. 2854The first two integer parameters are passed in ECX and EDX. Subsequent integer 2855parameters are passed in memory, and callee clears the stack. On x86_64 2856targets, the callee does *not* clear the stack, and integer parameters are 2857passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling 2858convention. 2859 2860On both 32-bit x86 and x86_64 targets, vector and floating point arguments are 2861passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are 2862passed in sequential SSE registers if enough are available. If AVX is enabled, 2863256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that 2864cannot be passed in registers for any reason is passed by reference, which 2865allows the caller to align the parameter memory. 2866 2867See the documentation for `__vectorcall`_ on MSDN for more details. 2868 2869.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx 2870 }]; 2871} 2872 2873def M68kRTDDocs : Documentation { 2874 let Category = DocCatCallingConvs; 2875 let Content = [{ 2876On M68k targets, this attribute changes the calling convention of a function 2877to clear parameters off the stack on return. In other words, callee is 2878responsible for cleaning out the stack space allocated for incoming paramters. 2879This convention does not support variadic calls or unprototyped functions in C. 2880When targeting M68010 or newer CPUs, this calling convention is implemented 2881using the `rtd` instruction. 2882 }]; 2883} 2884 2885def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> { 2886 let Content = [{ 2887Clang supports additional attributes for checking basic resource management 2888properties, specifically for unique objects that have a single owning reference. 2889The following attributes are currently supported, although **the implementation 2890for these annotations is currently in development and are subject to change.** 2891 }]; 2892} 2893 2894def SetTypestateDocs : Documentation { 2895 let Category = DocCatConsumed; 2896 let Content = [{ 2897Annotate methods that transition an object into a new state with 2898``__attribute__((set_typestate(new_state)))``. The new state must be 2899unconsumed, consumed, or unknown. 2900 }]; 2901} 2902 2903def CallableWhenDocs : Documentation { 2904 let Category = DocCatConsumed; 2905 let Content = [{ 2906Use ``__attribute__((callable_when(...)))`` to indicate what states a method 2907may be called in. Valid states are unconsumed, consumed, or unknown. Each 2908argument to this attribute must be a quoted string. E.g.: 2909 2910``__attribute__((callable_when("unconsumed", "unknown")))`` 2911 }]; 2912} 2913 2914def TestTypestateDocs : Documentation { 2915 let Category = DocCatConsumed; 2916 let Content = [{ 2917Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method 2918returns true if the object is in the specified state.. 2919 }]; 2920} 2921 2922def ParamTypestateDocs : Documentation { 2923 let Category = DocCatConsumed; 2924 let Content = [{ 2925This attribute specifies expectations about function parameters. Calls to an 2926function with annotated parameters will issue a warning if the corresponding 2927argument isn't in the expected state. The attribute is also used to set the 2928initial state of the parameter when analyzing the function's body. 2929 }]; 2930} 2931 2932def ReturnTypestateDocs : Documentation { 2933 let Category = DocCatConsumed; 2934 let Content = [{ 2935The ``return_typestate`` attribute can be applied to functions or parameters. 2936When applied to a function the attribute specifies the state of the returned 2937value. The function's body is checked to ensure that it always returns a value 2938in the specified state. On the caller side, values returned by the annotated 2939function are initialized to the given state. 2940 2941When applied to a function parameter it modifies the state of an argument after 2942a call to the function returns. The function's body is checked to ensure that 2943the parameter is in the expected state before returning. 2944 }]; 2945} 2946 2947def ConsumableDocs : Documentation { 2948 let Category = DocCatConsumed; 2949 let Content = [{ 2950Each ``class`` that uses any of the typestate annotations must first be marked 2951using the ``consumable`` attribute. Failure to do so will result in a warning. 2952 2953This attribute accepts a single parameter that must be one of the following: 2954``unknown``, ``consumed``, or ``unconsumed``. 2955 }]; 2956} 2957 2958def NoProfileInstrumentFunctionDocs : Documentation { 2959 let Category = DocCatFunction; 2960 let Content = [{ 2961Use the ``no_profile_instrument_function`` attribute on a function declaration 2962to denote that the compiler should not instrument the function with 2963profile-related instrumentation, such as via the 2964``-fprofile-generate`` / ``-fprofile-instr-generate`` / 2965``-fcs-profile-generate`` / ``-fprofile-arcs`` flags. 2966}]; 2967} 2968 2969def NoSanitizeDocs : Documentation { 2970 let Category = DocCatFunction; 2971 let Content = [{ 2972Use the ``no_sanitize`` attribute on a function or a global variable 2973declaration to specify that a particular instrumentation or set of 2974instrumentations should not be applied. 2975 2976The attribute takes a list of string literals with the following accepted 2977values: 2978* all values accepted by ``-fno-sanitize=``; 2979* ``coverage``, to disable SanitizerCoverage instrumentation. 2980 2981For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies 2982that AddressSanitizer and ThreadSanitizer should not be applied to the function 2983or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that 2984SanitizerCoverage should not be applied to the function. 2985 2986See :ref:`Controlling Code Generation <controlling-code-generation>` for a 2987full list of supported sanitizer flags. 2988 }]; 2989} 2990 2991def DisableSanitizerInstrumentationDocs : Documentation { 2992 let Category = DocCatFunction; 2993 let Content = [{ 2994Use the ``disable_sanitizer_instrumentation`` attribute on a function, 2995Objective-C method, or global variable, to specify that no sanitizer 2996instrumentation should be applied. 2997 2998This is not the same as ``__attribute__((no_sanitize(...)))``, which depending 2999on the tool may still insert instrumentation to prevent false positive reports. 3000 }]; 3001} 3002 3003def NoSanitizeAddressDocs : Documentation { 3004 let Category = DocCatFunction; 3005 // This function has multiple distinct spellings, and so it requires a custom 3006 // heading to be specified. The most common spelling is sufficient. 3007 let Heading = "no_sanitize_address, no_address_safety_analysis"; 3008 let Content = [{ 3009.. _langext-address_sanitizer: 3010 3011Use ``__attribute__((no_sanitize_address))`` on a function or a global 3012variable declaration to specify that address safety instrumentation 3013(e.g. AddressSanitizer) should not be applied. 3014 }]; 3015} 3016 3017def NoSanitizeThreadDocs : Documentation { 3018 let Category = DocCatFunction; 3019 let Heading = "no_sanitize_thread"; 3020 let Content = [{ 3021.. _langext-thread_sanitizer: 3022 3023Use ``__attribute__((no_sanitize_thread))`` on a function declaration to 3024specify that checks for data races on plain (non-atomic) memory accesses should 3025not be inserted by ThreadSanitizer. The function is still instrumented by the 3026tool to avoid false positives and provide meaningful stack traces. 3027 }]; 3028} 3029 3030def NoSanitizeMemoryDocs : Documentation { 3031 let Category = DocCatFunction; 3032 let Heading = "no_sanitize_memory"; 3033 let Content = [{ 3034.. _langext-memory_sanitizer: 3035 3036Use ``__attribute__((no_sanitize_memory))`` on a function declaration to 3037specify that checks for uninitialized memory should not be inserted 3038(e.g. by MemorySanitizer). The function may still be instrumented by the tool 3039to avoid false positives in other places. 3040 }]; 3041} 3042 3043def CFICanonicalJumpTableDocs : Documentation { 3044 let Category = DocCatFunction; 3045 let Heading = "cfi_canonical_jump_table"; 3046 let Content = [{ 3047.. _langext-cfi_canonical_jump_table: 3048 3049Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to 3050make the function's CFI jump table canonical. See :ref:`the CFI documentation 3051<cfi-canonical-jump-tables>` for more details. 3052 }]; 3053} 3054 3055def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> { 3056 let Content = [{ 3057Clang supports additional attributes to enable checking type safety properties 3058that can't be enforced by the C type system. To see warnings produced by these 3059checks, ensure that -Wtype-safety is enabled. Use cases include: 3060 3061* MPI library implementations, where these attributes enable checking that 3062 the buffer type matches the passed ``MPI_Datatype``; 3063* for HDF5 library there is a similar use case to MPI; 3064* checking types of variadic functions' arguments for functions like 3065 ``fcntl()`` and ``ioctl()``. 3066 3067You can detect support for these attributes with ``__has_attribute()``. For 3068example: 3069 3070.. code-block:: c++ 3071 3072 #if defined(__has_attribute) 3073 # if __has_attribute(argument_with_type_tag) && \ 3074 __has_attribute(pointer_with_type_tag) && \ 3075 __has_attribute(type_tag_for_datatype) 3076 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) 3077 /* ... other macros ... */ 3078 # endif 3079 #endif 3080 3081 #if !defined(ATTR_MPI_PWT) 3082 # define ATTR_MPI_PWT(buffer_idx, type_idx) 3083 #endif 3084 3085 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 3086 ATTR_MPI_PWT(1,3); 3087 }]; 3088} 3089 3090def ArgumentWithTypeTagDocs : Documentation { 3091 let Category = DocCatTypeSafety; 3092 let Heading = "argument_with_type_tag"; 3093 let Content = [{ 3094Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, 3095type_tag_idx)))`` on a function declaration to specify that the function 3096accepts a type tag that determines the type of some other argument. 3097 3098This attribute is primarily useful for checking arguments of variadic functions 3099(``pointer_with_type_tag`` can be used in most non-variadic cases). 3100 3101In the attribute prototype above: 3102 * ``arg_kind`` is an identifier that should be used when annotating all 3103 applicable type tags. 3104 * ``arg_idx`` provides the position of a function argument. The expected type of 3105 this function argument will be determined by the function argument specified 3106 by ``type_tag_idx``. In the code example below, "3" means that the type of the 3107 function's third argument will be determined by ``type_tag_idx``. 3108 * ``type_tag_idx`` provides the position of a function argument. This function 3109 argument will be a type tag. The type tag will determine the expected type of 3110 the argument specified by ``arg_idx``. In the code example below, "2" means 3111 that the type tag associated with the function's second argument should agree 3112 with the type of the argument specified by ``arg_idx``. 3113 3114For example: 3115 3116.. code-block:: c++ 3117 3118 int fcntl(int fd, int cmd, ...) 3119 __attribute__(( argument_with_type_tag(fcntl,3,2) )); 3120 // The function's second argument will be a type tag; this type tag will 3121 // determine the expected type of the function's third argument. 3122 }]; 3123} 3124 3125def PointerWithTypeTagDocs : Documentation { 3126 let Category = DocCatTypeSafety; 3127 let Heading = "pointer_with_type_tag"; 3128 let Content = [{ 3129Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` 3130on a function declaration to specify that the function accepts a type tag that 3131determines the pointee type of some other pointer argument. 3132 3133In the attribute prototype above: 3134 * ``ptr_kind`` is an identifier that should be used when annotating all 3135 applicable type tags. 3136 * ``ptr_idx`` provides the position of a function argument; this function 3137 argument will have a pointer type. The expected pointee type of this pointer 3138 type will be determined by the function argument specified by 3139 ``type_tag_idx``. In the code example below, "1" means that the pointee type 3140 of the function's first argument will be determined by ``type_tag_idx``. 3141 * ``type_tag_idx`` provides the position of a function argument; this function 3142 argument will be a type tag. The type tag will determine the expected pointee 3143 type of the pointer argument specified by ``ptr_idx``. In the code example 3144 below, "3" means that the type tag associated with the function's third 3145 argument should agree with the pointee type of the pointer argument specified 3146 by ``ptr_idx``. 3147 3148For example: 3149 3150.. code-block:: c++ 3151 3152 typedef int MPI_Datatype; 3153 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 3154 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 3155 // The function's 3rd argument will be a type tag; this type tag will 3156 // determine the expected pointee type of the function's 1st argument. 3157 }]; 3158} 3159 3160def TypeTagForDatatypeDocs : Documentation { 3161 let Category = DocCatTypeSafety; 3162 let Content = [{ 3163When declaring a variable, use 3164``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that 3165is tied to the ``type`` argument given to the attribute. 3166 3167In the attribute prototype above: 3168 * ``kind`` is an identifier that should be used when annotating all applicable 3169 type tags. 3170 * ``type`` indicates the name of the type. 3171 3172Clang supports annotating type tags of two forms. 3173 3174 * **Type tag that is a reference to a declared identifier.** 3175 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that 3176 identifier: 3177 3178 .. code-block:: c++ 3179 3180 typedef int MPI_Datatype; 3181 extern struct mpi_datatype mpi_datatype_int 3182 __attribute__(( type_tag_for_datatype(mpi,int) )); 3183 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) 3184 // &mpi_datatype_int is a type tag. It is tied to type "int". 3185 3186 * **Type tag that is an integral literal.** 3187 Declare a ``static const`` variable with an initializer value and attach 3188 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration: 3189 3190 .. code-block:: c++ 3191 3192 typedef int MPI_Datatype; 3193 static const MPI_Datatype mpi_datatype_int 3194 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42; 3195 #define MPI_INT ((MPI_Datatype) 42) 3196 // The number 42 is a type tag. It is tied to type "int". 3197 3198 3199The ``type_tag_for_datatype`` attribute also accepts an optional third argument 3200that determines how the type of the function argument specified by either 3201``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type 3202tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the 3203function argument specified by ``arg_idx`` is compared against the type 3204associated with the type tag. Also recall that for the ``pointer_with_type_tag`` 3205attribute, the pointee type of the function argument specified by ``ptr_idx`` is 3206compared against the type associated with the type tag.) There are two supported 3207values for this optional third argument: 3208 3209 * ``layout_compatible`` will cause types to be compared according to 3210 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the 3211 layout-compatibility rules for two standard-layout struct types and for two 3212 standard-layout union types). This is useful when creating a type tag 3213 associated with a struct or union type. For example: 3214 3215 .. code-block:: c++ 3216 3217 /* In mpi.h */ 3218 typedef int MPI_Datatype; 3219 struct internal_mpi_double_int { double d; int i; }; 3220 extern struct mpi_datatype mpi_datatype_double_int 3221 __attribute__(( type_tag_for_datatype(mpi, 3222 struct internal_mpi_double_int, layout_compatible) )); 3223 3224 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) 3225 3226 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) 3227 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 3228 3229 /* In user code */ 3230 struct my_pair { double a; int b; }; 3231 struct my_pair *buffer; 3232 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the 3233 // layout of my_pair is 3234 // compatible with that of 3235 // internal_mpi_double_int 3236 3237 struct my_int_pair { int a; int b; } 3238 struct my_int_pair *buffer2; 3239 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the 3240 // layout of my_int_pair 3241 // does not match that of 3242 // internal_mpi_double_int 3243 3244 * ``must_be_null`` specifies that the function argument specified by either 3245 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for 3246 the ``pointer_with_type_tag`` attribute) should be a null pointer constant. 3247 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For 3248 example: 3249 3250 .. code-block:: c++ 3251 3252 /* In mpi.h */ 3253 typedef int MPI_Datatype; 3254 extern struct mpi_datatype mpi_datatype_null 3255 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); 3256 3257 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) 3258 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) 3259 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 3260 3261 /* In user code */ 3262 struct my_pair { double a; int b; }; 3263 struct my_pair *buffer; 3264 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL 3265 // was specified but buffer 3266 // is not a null pointer 3267 }]; 3268} 3269 3270def FlattenDocs : Documentation { 3271 let Category = DocCatFunction; 3272 let Content = [{ 3273The ``flatten`` attribute causes calls within the attributed function to 3274be inlined unless it is impossible to do so, for example if the body of the 3275callee is unavailable or if the callee has the ``noinline`` attribute. 3276 }]; 3277} 3278 3279def FormatDocs : Documentation { 3280 let Category = DocCatFunction; 3281 let Content = [{ 3282 3283Clang supports the ``format`` attribute, which indicates that the function 3284accepts (among other possibilities) a ``printf`` or ``scanf``-like format string 3285and corresponding arguments or a ``va_list`` that contains these arguments. 3286 3287Please see `GCC documentation about format attribute 3288<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details 3289about attribute syntax. 3290 3291Clang implements two kinds of checks with this attribute. 3292 3293#. Clang checks that the function with the ``format`` attribute is called with 3294 a format string that uses format specifiers that are allowed, and that 3295 arguments match the format string. This is the ``-Wformat`` warning, it is 3296 on by default. 3297 3298#. Clang checks that the format string argument is a literal string. This is 3299 the ``-Wformat-nonliteral`` warning, it is off by default. 3300 3301 Clang implements this mostly the same way as GCC, but there is a difference 3302 for functions that accept a ``va_list`` argument (for example, ``vprintf``). 3303 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such 3304 functions. Clang does not warn if the format string comes from a function 3305 parameter, where the function is annotated with a compatible attribute, 3306 otherwise it warns. For example: 3307 3308 .. code-block:: c 3309 3310 __attribute__((__format__ (__scanf__, 1, 3))) 3311 void foo(const char* s, char *buf, ...) { 3312 va_list ap; 3313 va_start(ap, buf); 3314 3315 vprintf(s, ap); // warning: format string is not a string literal 3316 } 3317 3318 In this case we warn because ``s`` contains a format string for a 3319 ``scanf``-like function, but it is passed to a ``printf``-like function. 3320 3321 If the attribute is removed, clang still warns, because the format string is 3322 not a string literal. 3323 3324 Another example: 3325 3326 .. code-block:: c 3327 3328 __attribute__((__format__ (__printf__, 1, 3))) 3329 void foo(const char* s, char *buf, ...) { 3330 va_list ap; 3331 va_start(ap, buf); 3332 3333 vprintf(s, ap); // warning 3334 } 3335 3336 In this case Clang does not warn because the format string ``s`` and 3337 the corresponding arguments are annotated. If the arguments are 3338 incorrect, the caller of ``foo`` will receive a warning. 3339 3340As an extension to GCC's behavior, Clang accepts the ``format`` attribute on 3341non-variadic functions. Clang checks non-variadic format functions for the same 3342classes of issues that can be found on variadic functions, as controlled by the 3343same warning flags, except that the types of formatted arguments is forced by 3344the function signature. For example: 3345 3346.. code-block:: c 3347 3348 __attribute__((__format__(__printf__, 1, 2))) 3349 void fmt(const char *s, const char *a, int b); 3350 3351 void bar(void) { 3352 fmt("%s %i", "hello", 123); // OK 3353 fmt("%i %g", "hello", 123); // warning: arguments don't match format 3354 extern const char *fmt; 3355 fmt(fmt, "hello", 123); // warning: format string is not a string literal 3356 } 3357 3358When using the format attribute on a variadic function, the first data parameter 3359_must_ be the index of the ellipsis in the parameter list. Clang will generate 3360a diagnostic otherwise, as it wouldn't be possible to forward that argument list 3361to `printf`-family functions. For instance, this is an error: 3362 3363.. code-block:: c 3364 3365 __attribute__((__format__(__printf__, 1, 2))) 3366 void fmt(const char *s, int b, ...); 3367 // ^ error: format attribute parameter 3 is out of bounds 3368 // (must be __printf__, 1, 3) 3369 3370Using the ``format`` attribute on a non-variadic function emits a GCC 3371compatibility diagnostic. 3372 }]; 3373} 3374 3375def AlignValueDocs : Documentation { 3376 let Category = DocCatType; 3377 let Content = [{ 3378The align_value attribute can be added to the typedef of a pointer type or the 3379declaration of a variable of pointer or reference type. It specifies that the 3380pointer will point to, or the reference will bind to, only objects with at 3381least the provided alignment. This alignment value must be some positive power 3382of 2. 3383 3384 .. code-block:: c 3385 3386 typedef double * aligned_double_ptr __attribute__((align_value(64))); 3387 void foo(double & x __attribute__((align_value(128)), 3388 aligned_double_ptr y) { ... } 3389 3390If the pointer value does not have the specified alignment at runtime, the 3391behavior of the program is undefined. 3392 }]; 3393} 3394 3395def FlagEnumDocs : Documentation { 3396 let Category = DocCatDecl; 3397 let Content = [{ 3398This attribute can be added to an enumerator to signal to the compiler that it 3399is intended to be used as a flag type. This will cause the compiler to assume 3400that the range of the type includes all of the values that you can get by 3401manipulating bits of the enumerator when issuing warnings. 3402 }]; 3403} 3404 3405def AsmLabelDocs : Documentation { 3406 let Category = DocCatDecl; 3407 let Content = [{ 3408This attribute can be used on a function or variable to specify its symbol name. 3409 3410On some targets, all C symbols are prefixed by default with a single character, 3411typically ``_``. This was done historically to distinguish them from symbols 3412used by other languages. (This prefix is also added to the standard Itanium 3413C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true 3414symbol name for a C++ variable declared as ``int cppvar;`` would be 3415``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the 3416symbol names specified by the ``asm`` attribute; programmers wishing to match a 3417C symbol name must compensate for this. 3418 3419For example, consider the following C code: 3420 3421.. code-block:: c 3422 3423 int var1 asm("altvar") = 1; // "altvar" in symbol table. 3424 int var2 = 1; // "_var2" in symbol table. 3425 3426 void func1(void) asm("altfunc"); 3427 void func1(void) {} // "altfunc" in symbol table. 3428 void func2(void) {} // "_func2" in symbol table. 3429 3430Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_. 3431 3432While it is possible to use this attribute to name a special symbol used 3433internally by the compiler, such as an LLVM intrinsic, this is neither 3434recommended nor supported and may cause the compiler to crash or miscompile. 3435Users who wish to gain access to intrinsic behavior are strongly encouraged to 3436request new builtin functions. 3437 }]; 3438} 3439 3440def EnumExtensibilityDocs : Documentation { 3441 let Category = DocCatDecl; 3442 let Content = [{ 3443Attribute ``enum_extensibility`` is used to distinguish between enum definitions 3444that are extensible and those that are not. The attribute can take either 3445``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the 3446enum type takes a value that corresponds to one of the enumerators listed in the 3447enum definition or, when the enum is annotated with ``flag_enum``, a value that 3448can be constructed using values corresponding to the enumerators. ``open`` 3449indicates a variable of the enum type can take any values allowed by the 3450standard and instructs clang to be more lenient when issuing warnings. 3451 3452.. code-block:: c 3453 3454 enum __attribute__((enum_extensibility(closed))) ClosedEnum { 3455 A0, A1 3456 }; 3457 3458 enum __attribute__((enum_extensibility(open))) OpenEnum { 3459 B0, B1 3460 }; 3461 3462 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum { 3463 C0 = 1 << 0, C1 = 1 << 1 3464 }; 3465 3466 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum { 3467 D0 = 1 << 0, D1 = 1 << 1 3468 }; 3469 3470 void foo1() { 3471 enum ClosedEnum ce; 3472 enum OpenEnum oe; 3473 enum ClosedFlagEnum cfe; 3474 enum OpenFlagEnum ofe; 3475 3476 ce = A1; // no warnings 3477 ce = 100; // warning issued 3478 oe = B1; // no warnings 3479 oe = 100; // no warnings 3480 cfe = C0 | C1; // no warnings 3481 cfe = C0 | C1 | 4; // warning issued 3482 ofe = D0 | D1; // no warnings 3483 ofe = D0 | D1 | 4; // no warnings 3484 } 3485 3486 }]; 3487} 3488 3489def EmptyBasesDocs : Documentation { 3490 let Category = DocCatDecl; 3491 let Content = [{ 3492The empty_bases attribute permits the compiler to utilize the 3493empty-base-optimization more frequently. 3494This attribute only applies to struct, class, and union types. 3495It is only supported when using the Microsoft C++ ABI. 3496 }]; 3497} 3498 3499def LayoutVersionDocs : Documentation { 3500 let Category = DocCatDecl; 3501 let Content = [{ 3502The layout_version attribute requests that the compiler utilize the class 3503layout rules of a particular compiler version. 3504This attribute only applies to struct, class, and union types. 3505It is only supported when using the Microsoft C++ ABI. 3506 }]; 3507} 3508 3509def LifetimeBoundDocs : Documentation { 3510 let Category = DocCatFunction; 3511 let Content = [{ 3512The ``lifetimebound`` attribute on a function parameter or implicit object 3513parameter indicates that objects that are referred to by that parameter may 3514also be referred to by the return value of the annotated function (or, for a 3515parameter of a constructor, by the value of the constructed object). It is only 3516supported in C++. 3517 3518By default, a reference is considered to refer to its referenced object, a 3519pointer is considered to refer to its pointee, a ``std::initializer_list<T>`` 3520is considered to refer to its underlying array, and aggregates (arrays and 3521simple ``struct``\s) are considered to refer to all objects that their 3522transitive subobjects refer to. 3523 3524Clang warns if it is able to detect that an object or reference refers to 3525another object with a shorter lifetime. For example, Clang will warn if a 3526function returns a reference to a local variable, or if a reference is bound to 3527a temporary object whose lifetime is not extended. By using the 3528``lifetimebound`` attribute, this determination can be extended to look through 3529user-declared functions. For example: 3530 3531.. code-block:: c++ 3532 3533 // Returns m[key] if key is present, or default_value if not. 3534 template<typename T, typename U> 3535 const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]], 3536 const T &key, /* note, not lifetimebound */ 3537 const U &default_value [[clang::lifetimebound]]); 3538 3539 std::map<std::string, std::string> m; 3540 // warning: temporary "bar"s that might be bound to local reference 'val' 3541 // will be destroyed at the end of the full-expression 3542 const std::string &val = get_or_default(m, "foo"s, "bar"s); 3543 3544 // No warning in this case. 3545 std::string def_val = "bar"s; 3546 const std::string &val = get_or_default(m, "foo"s, def_val); 3547 3548The attribute can be applied to the implicit ``this`` parameter of a member 3549function by writing the attribute after the function type: 3550 3551.. code-block:: c++ 3552 3553 struct string { 3554 // The returned pointer should not outlive ``*this``. 3555 const char *data() const [[clang::lifetimebound]]; 3556 }; 3557 3558This attribute is inspired by the C++ committee paper `P0936R0 3559<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects 3560have their lifetimes extended. 3561 }]; 3562} 3563 3564def TrivialABIDocs : Documentation { 3565 let Category = DocCatDecl; 3566 let Content = [{ 3567The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union. 3568It instructs the compiler to pass and return the type using the C ABI for the 3569underlying type when the type would otherwise be considered non-trivial for the 3570purpose of calls. 3571A class annotated with ``trivial_abi`` can have non-trivial destructors or 3572copy/move constructors without automatically becoming non-trivial for the 3573purposes of calls. For example: 3574 3575 .. code-block:: c++ 3576 3577 // A is trivial for the purposes of calls because ``trivial_abi`` makes the 3578 // user-provided special functions trivial. 3579 struct __attribute__((trivial_abi)) A { 3580 ~A(); 3581 A(const A &); 3582 A(A &&); 3583 int x; 3584 }; 3585 3586 // B's destructor and copy/move constructor are considered trivial for the 3587 // purpose of calls because A is trivial. 3588 struct B { 3589 A a; 3590 }; 3591 3592If a type is trivial for the purposes of calls, has a non-trivial destructor, 3593and is passed as an argument by value, the convention is that the callee will 3594destroy the object before returning. 3595 3596If a type is trivial for the purpose of calls, it is assumed to be trivially 3597relocatable for the purpose of ``__is_trivially_relocatable``. 3598 3599Attribute ``trivial_abi`` has no effect in the following cases: 3600 3601- The class directly declares a virtual base or virtual methods. 3602- Copy constructors and move constructors of the class are all deleted. 3603- The class has a base class that is non-trivial for the purposes of calls. 3604- The class has a non-static data member whose type is non-trivial for the 3605 purposes of calls, which includes: 3606 3607 - classes that are non-trivial for the purposes of calls 3608 - __weak-qualified types in Objective-C++ 3609 - arrays of any of the above 3610 }]; 3611} 3612 3613def MSInheritanceDocs : Documentation { 3614 let Category = DocCatDecl; 3615 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance"; 3616 let Content = [{ 3617This collection of keywords is enabled under ``-fms-extensions`` and controls 3618the pointer-to-member representation used on ``*-*-win32`` targets. 3619 3620The ``*-*-win32`` targets utilize a pointer-to-member representation which 3621varies in size and alignment depending on the definition of the underlying 3622class. 3623 3624However, this is problematic when a forward declaration is only available and 3625no definition has been made yet. In such cases, Clang is forced to utilize the 3626most general representation that is available to it. 3627 3628These keywords make it possible to use a pointer-to-member representation other 3629than the most general one regardless of whether or not the definition will ever 3630be present in the current translation unit. 3631 3632This family of keywords belong between the ``class-key`` and ``class-name``: 3633 3634.. code-block:: c++ 3635 3636 struct __single_inheritance S; 3637 int S::*i; 3638 struct S {}; 3639 3640This keyword can be applied to class templates but only has an effect when used 3641on full specializations: 3642 3643.. code-block:: c++ 3644 3645 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template 3646 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization 3647 template <> struct __single_inheritance A<int, float>; 3648 3649Note that choosing an inheritance model less general than strictly necessary is 3650an error: 3651 3652.. code-block:: c++ 3653 3654 struct __multiple_inheritance S; // error: inheritance model does not match definition 3655 int S::*i; 3656 struct S {}; 3657}]; 3658} 3659 3660def MSConstexprDocs : Documentation { 3661 let Category = DocCatStmt; 3662 let Content = [{ 3663The ``[[msvc::constexpr]]`` attribute can be applied only to a function 3664definition or a ``return`` statement. It does not impact function declarations. 3665A ``[[msvc::constexpr]]`` function cannot be ``constexpr`` or ``consteval``. 3666A ``[[msvc::constexpr]]`` function is treated as if it were a ``constexpr`` function 3667when it is evaluated in a constant context of ``[[msvc::constexpr]] return`` statement. 3668Otherwise, it is treated as a regular function. 3669 3670Semantics of this attribute are enabled only under MSVC compatibility 3671(``-fms-compatibility-version``) 19.33 and later. 3672 }]; 3673} 3674 3675def MSNoVTableDocs : Documentation { 3676 let Category = DocCatDecl; 3677 let Content = [{ 3678This attribute can be added to a class declaration or definition to signal to 3679the compiler that constructors and destructors will not reference the virtual 3680function table. It is only supported when using the Microsoft C++ ABI. 3681 }]; 3682} 3683 3684def OptnoneDocs : Documentation { 3685 let Category = DocCatFunction; 3686 let Content = [{ 3687The ``optnone`` attribute suppresses essentially all optimizations 3688on a function or method, regardless of the optimization level applied to 3689the compilation unit as a whole. This is particularly useful when you 3690need to debug a particular function, but it is infeasible to build the 3691entire application without optimization. Avoiding optimization on the 3692specified function can improve the quality of the debugging information 3693for that function. 3694 3695This attribute is incompatible with the ``always_inline`` and ``minsize`` 3696attributes. 3697 }]; 3698} 3699 3700def LoopHintDocs : Documentation { 3701 let Category = DocCatStmt; 3702 let Heading = "#pragma clang loop"; 3703 let Content = [{ 3704The ``#pragma clang loop`` directive allows loop optimization hints to be 3705specified for the subsequent loop. The directive allows pipelining to be 3706disabled, or vectorization, vector predication, interleaving, and unrolling to 3707be enabled or disabled. Vector width, vector predication, interleave count, 3708unrolling count, and the initiation interval for pipelining can be explicitly 3709specified. See `language extensions 3710<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 3711for details. 3712 }]; 3713} 3714 3715def UnrollHintDocs : Documentation { 3716 let Category = DocCatStmt; 3717 let Heading = "#pragma unroll, #pragma nounroll"; 3718 let Content = [{ 3719Loop unrolling optimization hints can be specified with ``#pragma unroll`` and 3720``#pragma nounroll``. The pragma is placed immediately before a for, while, 3721do-while, or c++11 range-based for loop. GCC's loop unrolling hints 3722``#pragma GCC unroll`` and ``#pragma GCC nounroll`` are also supported and have 3723identical semantics to ``#pragma unroll`` and ``#pragma nounroll``. 3724 3725Specifying ``#pragma unroll`` without a parameter directs the loop unroller to 3726attempt to fully unroll the loop if the trip count is known at compile time and 3727attempt to partially unroll the loop if the trip count is not known at compile 3728time: 3729 3730.. code-block:: c++ 3731 3732 #pragma unroll 3733 for (...) { 3734 ... 3735 } 3736 3737Specifying the optional parameter, ``#pragma unroll _value_``, directs the 3738unroller to unroll the loop ``_value_`` times. The parameter may optionally be 3739enclosed in parentheses: 3740 3741.. code-block:: c++ 3742 3743 #pragma unroll 16 3744 for (...) { 3745 ... 3746 } 3747 3748 #pragma unroll(16) 3749 for (...) { 3750 ... 3751 } 3752 3753Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled: 3754 3755.. code-block:: c++ 3756 3757 #pragma nounroll 3758 for (...) { 3759 ... 3760 } 3761 3762``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to 3763``#pragma clang loop unroll(enable)`` and 3764``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll`` 3765is equivalent to ``#pragma clang loop unroll(disable)``. See 3766`language extensions 3767<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 3768for further details including limitations of the unroll hints. 3769 }]; 3770} 3771 3772def PipelineHintDocs : Documentation { 3773 let Category = DocCatStmt; 3774 let Heading = "#pragma clang loop pipeline, #pragma clang loop pipeline_initiation_interval"; 3775 let Content = [{ 3776 Software Pipelining optimization is a technique used to optimize loops by 3777 utilizing instruction-level parallelism. It reorders loop instructions to 3778 overlap iterations. As a result, the next iteration starts before the previous 3779 iteration has finished. The module scheduling technique creates a schedule for 3780 one iteration such that when repeating at regular intervals, no inter-iteration 3781 dependencies are violated. This constant interval(in cycles) between the start 3782 of iterations is called the initiation interval. i.e. The initiation interval 3783 is the number of cycles between two iterations of an unoptimized loop in the 3784 newly created schedule. A new, optimized loop is created such that a single iteration 3785 of the loop executes in the same number of cycles as the initiation interval. 3786 For further details see <https://llvm.org/pubs/2005-06-17-LattnerMSThesis-book.pdf>. 3787 3788 ``#pragma clang loop pipeline and #pragma loop pipeline_initiation_interval`` 3789 could be used as hints for the software pipelining optimization. The pragma is 3790 placed immediately before a for, while, do-while, or a C++11 range-based for 3791 loop. 3792 3793 Using ``#pragma clang loop pipeline(disable)`` avoids the software pipelining 3794 optimization. The disable state can only be specified: 3795 3796 .. code-block:: c++ 3797 3798 #pragma clang loop pipeline(disable) 3799 for (...) { 3800 ... 3801 } 3802 3803 Using ``#pragma loop pipeline_initiation_interval`` instructs 3804 the software pipeliner to try the specified initiation interval. 3805 If a schedule was found then the resulting loop iteration would have 3806 the specified cycle count. If a schedule was not found then loop 3807 remains unchanged. The initiation interval must be a positive number 3808 greater than zero: 3809 3810 .. code-block:: c++ 3811 3812 #pragma loop pipeline_initiation_interval(10) 3813 for (...) { 3814 ... 3815 } 3816 3817 }]; 3818} 3819 3820def OpenCLUnrollHintDocs : Documentation { 3821 let Category = DocCatStmt; 3822 let Content = [{ 3823The opencl_unroll_hint attribute qualifier can be used to specify that a loop 3824(for, while and do loops) can be unrolled. This attribute qualifier can be 3825used to specify full unrolling or partial unrolling by a specified amount. 3826This is a compiler hint and the compiler may ignore this directive. See 3827`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_ 3828s6.11.5 for details. 3829 }]; 3830} 3831 3832def OpenCLIntelReqdSubGroupSizeDocs : Documentation { 3833 let Category = DocCatStmt; 3834 let Content = [{ 3835The optional attribute intel_reqd_sub_group_size can be used to indicate that 3836the kernel must be compiled and executed with the specified subgroup size. When 3837this attribute is present, get_max_sub_group_size() is guaranteed to return the 3838specified integer value. This is important for the correctness of many subgroup 3839algorithms, and in some cases may be used by the compiler to generate more optimal 3840code. See `cl_intel_required_subgroup_size 3841<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>` 3842for details. 3843 }]; 3844} 3845 3846def OpenCLAccessDocs : Documentation { 3847 let Category = DocCatStmt; 3848 let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)"; 3849 let Content = [{ 3850The access qualifiers must be used with image object arguments or pipe arguments 3851to declare if they are being read or written by a kernel or function. 3852 3853The read_only/__read_only, write_only/__write_only and read_write/__read_write 3854names are reserved for use as access qualifiers and shall not be used otherwise. 3855 3856.. code-block:: c 3857 3858 kernel void 3859 foo (read_only image2d_t imageA, 3860 write_only image2d_t imageB) { 3861 ... 3862 } 3863 3864In the above example imageA is a read-only 2D image object, and imageB is a 3865write-only 2D image object. 3866 3867The read_write (or __read_write) qualifier can not be used with pipe. 3868 3869More details can be found in the OpenCL C language Spec v2.0, Section 6.6. 3870 }]; 3871} 3872 3873def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> { 3874 let Content = [{ 3875The address space qualifier may be used to specify the region of memory that is 3876used to allocate the object. OpenCL supports the following address spaces: 3877__generic(generic), __global(global), __local(local), __private(private), 3878__constant(constant). 3879 3880 .. code-block:: c 3881 3882 __constant int c = ...; 3883 3884 __generic int* foo(global int* g) { 3885 __local int* l; 3886 private int p; 3887 ... 3888 return l; 3889 } 3890 3891More details can be found in the OpenCL C language Spec v2.0, Section 6.5. 3892 }]; 3893} 3894 3895def OpenCLAddressSpaceGenericDocs : Documentation { 3896 let Category = DocOpenCLAddressSpaces; 3897 let Heading = "__generic, generic, [[clang::opencl_generic]]"; 3898 let Content = [{ 3899The generic address space attribute is only available with OpenCL v2.0 and later. 3900It can be used with pointer types. Variables in global and local scope and 3901function parameters in non-kernel functions can have the generic address space 3902type attribute. It is intended to be a placeholder for any other address space 3903except for '__constant' in OpenCL code which can be used with multiple address 3904spaces. 3905 }]; 3906} 3907 3908def OpenCLAddressSpaceConstantDocs : Documentation { 3909 let Category = DocOpenCLAddressSpaces; 3910 let Heading = "__constant, constant, [[clang::opencl_constant]]"; 3911 let Content = [{ 3912The constant address space attribute signals that an object is located in 3913a constant (non-modifiable) memory region. It is available to all work items. 3914Any type can be annotated with the constant address space attribute. Objects 3915with the constant address space qualifier can be declared in any scope and must 3916have an initializer. 3917 }]; 3918} 3919 3920def OpenCLAddressSpaceGlobalDocs : Documentation { 3921 let Category = DocOpenCLAddressSpaces; 3922 let Heading = "__global, global, [[clang::opencl_global]]"; 3923 let Content = [{ 3924The global address space attribute specifies that an object is allocated in 3925global memory, which is accessible by all work items. The content stored in this 3926memory area persists between kernel executions. Pointer types to the global 3927address space are allowed as function parameters or local variables. Starting 3928with OpenCL v2.0, the global address space can be used with global (program 3929scope) variables and static local variable as well. 3930 }]; 3931} 3932 3933def OpenCLAddressSpaceGlobalExtDocs : Documentation { 3934 let Category = DocOpenCLAddressSpaces; 3935 let Heading = "[[clang::opencl_global_device]], [[clang::opencl_global_host]]"; 3936 let Content = [{ 3937The ``global_device`` and ``global_host`` address space attributes specify that 3938an object is allocated in global memory on the device/host. It helps to 3939distinguish USM (Unified Shared Memory) pointers that access global device 3940memory from those that access global host memory. These new address spaces are 3941a subset of the ``__global/opencl_global`` address space, the full address space 3942set model for OpenCL 2.0 with the extension looks as follows: 3943 3944 | generic->global->host 3945 | ->device 3946 | ->private 3947 | ->local 3948 | constant 3949 3950As ``global_device`` and ``global_host`` are a subset of 3951``__global/opencl_global`` address spaces it is allowed to convert 3952``global_device`` and ``global_host`` address spaces to 3953``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3 3954"Address space nesting and rules for pointers"). 3955 }]; 3956} 3957 3958def OpenCLAddressSpaceLocalDocs : Documentation { 3959 let Category = DocOpenCLAddressSpaces; 3960 let Heading = "__local, local, [[clang::opencl_local]]"; 3961 let Content = [{ 3962The local address space specifies that an object is allocated in the local (work 3963group) memory area, which is accessible to all work items in the same work 3964group. The content stored in this memory region is not accessible after 3965the kernel execution ends. In a kernel function scope, any variable can be in 3966the local address space. In other scopes, only pointer types to the local address 3967space are allowed. Local address space variables cannot have an initializer. 3968 }]; 3969} 3970 3971def OpenCLAddressSpacePrivateDocs : Documentation { 3972 let Category = DocOpenCLAddressSpaces; 3973 let Heading = "__private, private, [[clang::opencl_private]]"; 3974 let Content = [{ 3975The private address space specifies that an object is allocated in the private 3976(work item) memory. Other work items cannot access the same memory area and its 3977content is destroyed after work item execution ends. Local variables can be 3978declared in the private address space. Function arguments are always in the 3979private address space. Kernel function arguments of a pointer or an array type 3980cannot point to the private address space. 3981 }]; 3982} 3983 3984def OpenCLNoSVMDocs : Documentation { 3985 let Category = DocCatVariable; 3986 let Content = [{ 3987OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for 3988pointer variable. It informs the compiler that the pointer does not refer 3989to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details. 3990 3991Since it is not widely used and has been removed from OpenCL 2.1, it is ignored 3992by Clang. 3993 }]; 3994} 3995 3996def Ptr32Docs : Documentation { 3997 let Category = DocCatType; 3998 let Content = [{ 3999The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a 400064-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The 4001``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer 4002is sign extended or zero extended. This qualifier is enabled under 4003``-fms-extensions``. 4004 }]; 4005} 4006 4007def Ptr64Docs : Documentation { 4008 let Category = DocCatType; 4009 let Content = [{ 4010The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a 401132-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This 4012qualifier is enabled under ``-fms-extensions``. 4013 }]; 4014} 4015 4016def SPtrDocs : Documentation { 4017 let Category = DocCatType; 4018 let Content = [{ 4019The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign 4020extended when converted to a 64-bit pointer. 4021 }]; 4022} 4023 4024def UPtrDocs : Documentation { 4025 let Category = DocCatType; 4026 let Content = [{ 4027The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero 4028extended when converted to a 64-bit pointer. 4029 }]; 4030} 4031 4032 4033def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> { 4034 let Content = [{ 4035Whether a particular pointer may be "null" is an important concern when working 4036with pointers in the C family of languages. The various nullability attributes 4037indicate whether a particular pointer can be null or not, which makes APIs more 4038expressive and can help static analysis tools identify bugs involving null 4039pointers. Clang supports several kinds of nullability attributes: the 4040``nonnull`` and ``returns_nonnull`` attributes indicate which function or 4041method parameters and result types can never be null, while nullability type 4042qualifiers indicate which pointer types can be null (``_Nullable``) or cannot 4043be null (``_Nonnull``). 4044 4045The nullability (type) qualifiers express whether a value of a given pointer 4046type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning 4047for null (the ``_Nonnull`` qualifier), or for which the purpose of null is 4048unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers 4049are expressed within the type system, they are more general than the 4050``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for 4051example) a nullable pointer to an array of nonnull pointers. Nullability 4052qualifiers are written to the right of the pointer to which they apply. For 4053example: 4054 4055 .. code-block:: c 4056 4057 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior). 4058 int fetch(int * _Nonnull ptr) { return *ptr; } 4059 4060 // 'ptr' may be null. 4061 int fetch_or_zero(int * _Nullable ptr) { 4062 return ptr ? *ptr : 0; 4063 } 4064 4065 // A nullable pointer to non-null pointers to const characters. 4066 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n); 4067 4068In Objective-C, there is an alternate spelling for the nullability qualifiers 4069that can be used in Objective-C methods and properties using context-sensitive, 4070non-underscored keywords. For example: 4071 4072 .. code-block:: objective-c 4073 4074 @interface NSView : NSResponder 4075 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView; 4076 @property (assign, nullable) NSView *superview; 4077 @property (readonly, nonnull) NSArray *subviews; 4078 @end 4079 }]; 4080} 4081 4082def TypeNonNullDocs : Documentation { 4083 let Category = NullabilityDocs; 4084 let Content = [{ 4085The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful 4086value for a value of the ``_Nonnull`` pointer type. For example, given a 4087declaration such as: 4088 4089 .. code-block:: c 4090 4091 int fetch(int * _Nonnull ptr); 4092 4093a caller of ``fetch`` should not provide a null value, and the compiler will 4094produce a warning if it sees a literal null value passed to ``fetch``. Note 4095that, unlike the declaration attribute ``nonnull``, the presence of 4096``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch`` 4097is free to consider null undefined behavior or (perhaps for 4098backward-compatibility reasons) defensively handle null. 4099 }]; 4100} 4101 4102def TypeNullableDocs : Documentation { 4103 let Category = NullabilityDocs; 4104 let Content = [{ 4105The ``_Nullable`` nullability qualifier indicates that a value of the 4106``_Nullable`` pointer type can be null. For example, given: 4107 4108 .. code-block:: c 4109 4110 int fetch_or_zero(int * _Nullable ptr); 4111 4112a caller of ``fetch_or_zero`` can provide null. 4113 }]; 4114} 4115 4116def TypeNullableResultDocs : Documentation { 4117 let Category = NullabilityDocs; 4118 let Content = [{ 4119The ``_Nullable_result`` nullability qualifier means that a value of the 4120``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this 4121attribute differs from ``_Nullable`` is when it's used on a parameter to a 4122completion handler in a Swift async method. For instance, here: 4123 4124 .. code-block:: objc 4125 4126 -(void)fetchSomeDataWithID:(int)identifier 4127 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler; 4128 4129This method asynchronously calls ``completionHandler`` when the data is 4130available, or calls it with an error. ``_Nullable_result`` indicates to the 4131Swift importer that this is the uncommon case where ``result`` can get ``nil`` 4132even if no error has occurred, and will therefore import it as a Swift optional 4133type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift 4134importer will assume that ``result`` will always be non-nil unless an error 4135occurred. 4136}]; 4137} 4138 4139def TypeNullUnspecifiedDocs : Documentation { 4140 let Category = NullabilityDocs; 4141 let Content = [{ 4142The ``_Null_unspecified`` nullability qualifier indicates that neither the 4143``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer 4144type. It is used primarily to indicate that the role of null with specific 4145pointers in a nullability-annotated header is unclear, e.g., due to 4146overly-complex implementations or historical factors with a long-lived API. 4147 }]; 4148} 4149 4150def NonNullDocs : Documentation { 4151 let Category = NullabilityDocs; 4152 let Content = [{ 4153The ``nonnull`` attribute indicates that some function parameters must not be 4154null, and can be used in several different ways. It's original usage 4155(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_) 4156is as a function (or Objective-C method) attribute that specifies which 4157parameters of the function are nonnull in a comma-separated list. For example: 4158 4159 .. code-block:: c 4160 4161 extern void * my_memcpy (void *dest, const void *src, size_t len) 4162 __attribute__((nonnull (1, 2))); 4163 4164Here, the ``nonnull`` attribute indicates that parameters 1 and 2 4165cannot have a null value. Omitting the parenthesized list of parameter indices 4166means that all parameters of pointer type cannot be null: 4167 4168 .. code-block:: c 4169 4170 extern void * my_memcpy (void *dest, const void *src, size_t len) 4171 __attribute__((nonnull)); 4172 4173Clang also allows the ``nonnull`` attribute to be placed directly on a function 4174(or Objective-C method) parameter, eliminating the need to specify the 4175parameter index ahead of type. For example: 4176 4177 .. code-block:: c 4178 4179 extern void * my_memcpy (void *dest __attribute__((nonnull)), 4180 const void *src __attribute__((nonnull)), size_t len); 4181 4182Note that the ``nonnull`` attribute indicates that passing null to a non-null 4183parameter is undefined behavior, which the optimizer may take advantage of to, 4184e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a 4185pointer cannot be null in a more general manner (because it is part of the type 4186system) and does not imply undefined behavior, making it more widely applicable. 4187 }]; 4188} 4189 4190def RestrictDocs : Documentation { 4191 let Category = DocCatFunction; 4192 let Heading = "malloc"; 4193 let Content = [{ 4194The ``malloc`` attribute indicates that the function acts like a system memory 4195allocation function, returning a pointer to allocated storage disjoint from the 4196storage for any other object accessible to the caller. 4197 }]; 4198} 4199 4200def ReturnsNonNullDocs : Documentation { 4201 let Category = NullabilityDocs; 4202 let Content = [{ 4203The ``returns_nonnull`` attribute indicates that a particular function (or 4204Objective-C method) always returns a non-null pointer. For example, a 4205particular system ``malloc`` might be defined to terminate a process when 4206memory is not available rather than returning a null pointer: 4207 4208 .. code-block:: c 4209 4210 extern void * malloc (size_t size) __attribute__((returns_nonnull)); 4211 4212The ``returns_nonnull`` attribute implies that returning a null pointer is 4213undefined behavior, which the optimizer may take advantage of. The ``_Nonnull`` 4214type qualifier indicates that a pointer cannot be null in a more general manner 4215(because it is part of the type system) and does not imply undefined behavior, 4216making it more widely applicable 4217}]; 4218} 4219 4220def NoAliasDocs : Documentation { 4221 let Category = DocCatFunction; 4222 let Content = [{ 4223The ``noalias`` attribute indicates that the only memory accesses inside 4224function are loads and stores from objects pointed to by its pointer-typed 4225arguments, with arbitrary offsets. 4226 }]; 4227} 4228 4229def NSErrorDomainDocs : Documentation { 4230 let Category = DocCatDecl; 4231 let Content = [{ 4232In Cocoa frameworks in Objective-C, one can group related error codes in enums 4233and categorize these enums with error domains. 4234 4235The ``ns_error_domain`` attribute indicates a global ``NSString`` or 4236``CFString`` constant representing the error domain that an error code belongs 4237to. For pointer uniqueness and code size this is a constant symbol, not a 4238literal. 4239 4240The domain and error code need to be used together. The ``ns_error_domain`` 4241attribute links error codes to their domain at the source level. 4242 4243This metadata is useful for documentation purposes, for static analysis, and for 4244improving interoperability between Objective-C and Swift. It is not used for 4245code generation in Objective-C. 4246 4247For example: 4248 4249 .. code-block:: objc 4250 4251 #define NS_ERROR_ENUM(_type, _name, _domain) \ 4252 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type 4253 4254 extern NSString *const MyErrorDomain; 4255 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) { 4256 MyErrFirst, 4257 MyErrSecond, 4258 }; 4259 }]; 4260} 4261 4262def SwiftDocs : DocumentationCategory<"Customizing Swift Import"> { 4263 let Content = [{ 4264Clang supports additional attributes for customizing how APIs are imported into 4265Swift. 4266 }]; 4267} 4268 4269def SwiftAsyncNameDocs : Documentation { 4270 let Category = SwiftDocs; 4271 let Heading = "swift_async_name"; 4272 let Content = [{ 4273The ``swift_async_name`` attribute provides the name of the ``async`` overload for 4274the given declaration in Swift. If this attribute is absent, the name is 4275transformed according to the algorithm built into the Swift compiler. 4276 4277The argument is a string literal that contains the Swift name of the function or 4278method. The name may be a compound Swift name. The function or method with such 4279an attribute must have more than zero parameters, as its last parameter is 4280assumed to be a callback that's eliminated in the Swift ``async`` name. 4281 4282 .. code-block:: objc 4283 4284 @interface URL 4285 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)"))) 4286 @end 4287 }]; 4288} 4289 4290def SwiftAttrDocs : Documentation { 4291 let Category = SwiftDocs; 4292 let Heading = "swift_attr"; 4293 let Content = [{ 4294The ``swift_attr`` provides a Swift-specific annotation for the declaration 4295to which the attribute appertains to. It can be used on any declaration 4296in Clang. This kind of annotation is ignored by Clang as it doesn't have any 4297semantic meaning in languages supported by Clang. The Swift compiler can 4298interpret these annotations according to its own rules when importing C or 4299Objective-C declarations. 4300}]; 4301} 4302 4303def SwiftBridgeDocs : Documentation { 4304 let Category = SwiftDocs; 4305 let Heading = "swift_bridge"; 4306 let Content = [{ 4307The ``swift_bridge`` attribute indicates that the declaration to which the 4308attribute appertains is bridged to the named Swift type. 4309 4310 .. code-block:: objc 4311 4312 __attribute__((__objc_root__)) 4313 @interface Base 4314 - (instancetype)init; 4315 @end 4316 4317 __attribute__((__swift_bridge__("BridgedI"))) 4318 @interface I : Base 4319 @end 4320 4321In this example, the Objective-C interface ``I`` will be made available to Swift 4322with the name ``BridgedI``. It would be possible for the compiler to refer to 4323``I`` still in order to bridge the type back to Objective-C. 4324 }]; 4325} 4326 4327def SwiftBridgedTypedefDocs : Documentation { 4328 let Category = SwiftDocs; 4329 let Heading = "swift_bridged"; 4330 let Content = [{ 4331The ``swift_bridged_typedef`` attribute indicates that when the typedef to which 4332the attribute appertains is imported into Swift, it should refer to the bridged 4333Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written 4334(e.g. ``NSString``). 4335 4336 .. code-block:: objc 4337 4338 @interface NSString; 4339 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__)); 4340 4341 extern void acceptsAliasedString(AliasedString _Nonnull parameter); 4342 4343In this case, the function ``acceptsAliasedString`` will be imported into Swift 4344as a function which accepts a ``String`` type parameter. 4345 }]; 4346} 4347 4348def SwiftObjCMembersDocs : Documentation { 4349 let Category = SwiftDocs; 4350 let Heading = "swift_objc_members"; 4351 let Content = [{ 4352This attribute indicates that Swift subclasses and members of Swift extensions 4353of this class will be implicitly marked with the ``@objcMembers`` Swift 4354attribute, exposing them back to Objective-C. 4355 }]; 4356} 4357 4358def SwiftErrorDocs : Documentation { 4359 let Category = SwiftDocs; 4360 let Heading = "swift_error"; 4361 let Content = [{ 4362The ``swift_error`` attribute controls whether a particular function (or 4363Objective-C method) is imported into Swift as a throwing function, and if so, 4364which dynamic convention it uses. 4365 4366All of these conventions except ``none`` require the function to have an error 4367parameter. Currently, the error parameter is always the last parameter of type 4368``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from 4369the imported API. When calling the API, Swift will always pass a valid address 4370initialized to a null pointer. 4371 4372* ``swift_error(none)`` means that the function should not be imported as 4373 throwing. The error parameter and result type will be imported normally. 4374 4375* ``swift_error(null_result)`` means that calls to the function should be 4376 considered to have thrown if they return a null value. The return type must be 4377 a pointer type, and it will be imported into Swift with a non-optional type. 4378 This is the default error convention for Objective-C methods that return 4379 pointers. 4380 4381* ``swift_error(zero_result)`` means that calls to the function should be 4382 considered to have thrown if they return a zero result. The return type must be 4383 an integral type. If the return type would have been imported as ``Bool``, it 4384 is instead imported as ``Void``. This is the default error convention for 4385 Objective-C methods that return a type that would be imported as ``Bool``. 4386 4387* ``swift_error(nonzero_result)`` means that calls to the function should be 4388 considered to have thrown if they return a non-zero result. The return type must 4389 be an integral type. If the return type would have been imported as ``Bool``, 4390 it is instead imported as ``Void``. 4391 4392* ``swift_error(nonnull_error)`` means that calls to the function should be 4393 considered to have thrown if they leave a non-null error in the error parameter. 4394 The return type is left unmodified. 4395 4396 }]; 4397} 4398 4399def SwiftNameDocs : Documentation { 4400 let Category = SwiftDocs; 4401 let Heading = "swift_name"; 4402 let Content = [{ 4403The ``swift_name`` attribute provides the name of the declaration in Swift. If 4404this attribute is absent, the name is transformed according to the algorithm 4405built into the Swift compiler. 4406 4407The argument is a string literal that contains the Swift name of the function, 4408variable, or type. When renaming a function, the name may be a compound Swift 4409name. For a type, enum constant, property, or variable declaration, the name 4410must be a simple or qualified identifier. 4411 4412 .. code-block:: objc 4413 4414 @interface URL 4415 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)"))) 4416 @end 4417 4418 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) { 4419 } 4420 }]; 4421} 4422 4423def SwiftNewTypeDocs : Documentation { 4424 let Category = SwiftDocs; 4425 let Heading = "swift_newtype"; 4426 let Content = [{ 4427The ``swift_newtype`` attribute indicates that the typedef to which the 4428attribute appertains is imported as a new Swift type of the typedef's name. 4429Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of 4430the attribute is identical with either spelling, ``swift_wrapper`` is 4431deprecated, only exists for compatibility purposes, and should not be used in 4432new code. 4433 4434* ``swift_newtype(struct)`` means that a Swift struct will be created for this 4435 typedef. 4436 4437* ``swift_newtype(enum)`` means that a Swift enum will be created for this 4438 typedef. 4439 4440 .. code-block:: c 4441 4442 // Import UIFontTextStyle as an enum type, with enumerated values being 4443 // constants. 4444 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum))); 4445 4446 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated 4447 // values being members of the type structure. 4448 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct))); 4449 4450 }]; 4451} 4452 4453def SwiftPrivateDocs : Documentation { 4454 let Category = SwiftDocs; 4455 let Heading = "swift_private"; 4456 let Content = [{ 4457Declarations marked with the ``swift_private`` attribute are hidden from the 4458framework client but are still made available for use within the framework or 4459Swift SDK overlay. 4460 4461The purpose of this attribute is to permit a more idomatic implementation of 4462declarations in Swift while hiding the non-idiomatic one. 4463 }]; 4464} 4465 4466def OMPDeclareSimdDocs : Documentation { 4467 let Category = DocCatFunction; 4468 let Heading = "#pragma omp declare simd"; 4469 let Content = [{ 4470The ``declare simd`` construct can be applied to a function to enable the creation 4471of one or more versions that can process multiple arguments using SIMD 4472instructions from a single invocation in a SIMD loop. The ``declare simd`` 4473directive is a declarative directive. There may be multiple ``declare simd`` 4474directives for a function. The use of a ``declare simd`` construct on a function 4475enables the creation of SIMD versions of the associated function that can be 4476used to process multiple arguments from a single invocation from a SIMD loop 4477concurrently. 4478The syntax of the ``declare simd`` construct is as follows: 4479 4480 .. code-block:: none 4481 4482 #pragma omp declare simd [clause[[,] clause] ...] new-line 4483 [#pragma omp declare simd [clause[[,] clause] ...] new-line] 4484 [...] 4485 function definition or declaration 4486 4487where clause is one of the following: 4488 4489 .. code-block:: none 4490 4491 simdlen(length) 4492 linear(argument-list[:constant-linear-step]) 4493 aligned(argument-list[:alignment]) 4494 uniform(argument-list) 4495 inbranch 4496 notinbranch 4497 4498 }]; 4499} 4500 4501def OMPDeclareTargetDocs : Documentation { 4502 let Category = DocCatFunction; 4503 let Heading = "#pragma omp declare target"; 4504 let Content = [{ 4505The ``declare target`` directive specifies that variables and functions are mapped 4506to a device for OpenMP offload mechanism. 4507 4508The syntax of the declare target directive is as follows: 4509 4510 .. code-block:: c 4511 4512 #pragma omp declare target new-line 4513 declarations-definition-seq 4514 #pragma omp end declare target new-line 4515 4516or 4517 4518 .. code-block:: c 4519 4520 #pragma omp declare target (extended-list) new-line 4521 4522or 4523 4524 .. code-block:: c 4525 4526 #pragma omp declare target clause[ [,] clause ... ] new-line 4527 4528where clause is one of the following: 4529 4530 4531 .. code-block:: c 4532 4533 to(extended-list) 4534 link(list) 4535 device_type(host | nohost | any) 4536 }]; 4537} 4538 4539def OMPDeclareVariantDocs : Documentation { 4540 let Category = DocCatFunction; 4541 let Heading = "#pragma omp declare variant"; 4542 let Content = [{ 4543The ``declare variant`` directive declares a specialized variant of a base 4544function and specifies the context in which that specialized variant is used. 4545The declare variant directive is a declarative directive. 4546The syntax of the ``declare variant`` construct is as follows: 4547 4548 .. code-block:: none 4549 4550 #pragma omp declare variant(variant-func-id) clause new-line 4551 [#pragma omp declare variant(variant-func-id) clause new-line] 4552 [...] 4553 function definition or declaration 4554 4555where clause is one of the following: 4556 4557 .. code-block:: none 4558 4559 match(context-selector-specification) 4560 4561and where ``variant-func-id`` is the name of a function variant that is either a 4562base language identifier or, for C++, a template-id. 4563 4564Clang provides the following context selector extensions, used via 4565``implementation={extension(EXTENSION)}``: 4566 4567 .. code-block:: none 4568 4569 match_all 4570 match_any 4571 match_none 4572 disable_implicit_base 4573 allow_templates 4574 bind_to_declaration 4575 4576The match extensions change when the *entire* context selector is considered a 4577match for an OpenMP context. The default is ``all``, with ``none`` no trait in the 4578selector is allowed to be in the OpenMP context, with ``any`` a single trait in 4579both the selector and OpenMP context is sufficient. Only a single match 4580extension trait is allowed per context selector. 4581The disable extensions remove default effects of the ``begin declare variant`` 4582applied to a definition. If ``disable_implicit_base`` is given, we will not 4583introduce an implicit base function for a variant if no base function was 4584found. The variant is still generated but will never be called, due to the 4585absence of a base function and consequently calls to a base function. 4586The allow extensions change when the ``begin declare variant`` effect is 4587applied to a definition. If ``allow_templates`` is given, template function 4588definitions are considered as specializations of existing or assumed template 4589declarations with the same name. The template parameters for the base functions 4590are used to instantiate the specialization. If ``bind_to_declaration`` is given, 4591apply the same variant rules to function declarations. This allows the user to 4592override declarations with only a function declaration. 4593 }]; 4594} 4595 4596def LeafDocs : Documentation { 4597 let Category = DocCatVariable; 4598 let Content = [{ 4599 4600The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis 4601in library functions. Functions marked with the ``leaf`` attribute are not allowed 4602to jump back into the caller's translation unit, whether through invoking a 4603callback function, an external function call, use of ``longjmp``, or other means. 4604Therefore, they cannot use or modify any data that does not escape the caller function's 4605compilation unit. 4606 4607For more information see 4608`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>` 4609}]; 4610} 4611 4612def AssumptionDocs : Documentation { 4613 let Category = DocCatFunction; 4614 let Heading = "assume"; 4615 let Content = [{ 4616Clang supports the ``__attribute__((assume("assumption")))`` attribute to 4617provide additional information to the optimizer. The string-literal, here 4618"assumption", will be attached to the function declaration such that later 4619analysis and optimization passes can assume the "assumption" to hold. 4620This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but 4621instead of an expression that can be assumed to be non-zero, the assumption is 4622expressed as a string and it holds for the entire function. 4623 4624A function can have multiple assume attributes and they propagate from prior 4625declarations to later definitions. Multiple assumptions are aggregated into a 4626single comma separated string. Thus, one can provide multiple assumptions via 4627a comma separated string, i.a., 4628``__attribute__((assume("assumption1,assumption2")))``. 4629 4630While LLVM plugins might provide more assumption strings, the default LLVM 4631optimization passes are aware of the following assumptions: 4632 4633 .. code-block:: none 4634 4635 "omp_no_openmp" 4636 "omp_no_openmp_routines" 4637 "omp_no_parallelism" 4638 4639The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is 4640spelled "XYZ" in the `OpenMP 5.1 Standard`_). 4641 4642.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2 4643 4644}]; 4645} 4646 4647def NoStackProtectorDocs : Documentation { 4648 let Category = DocCatFunction; 4649 let Heading = "no_stack_protector, safebuffers"; 4650 let Content = [{ 4651Clang supports the GNU style ``__attribute__((no_stack_protector))`` and Microsoft 4652style ``__declspec(safebuffers)`` attribute which disables 4653the stack protector on the specified function. This attribute is useful for 4654selectively disabling the stack protector on some functions when building with 4655``-fstack-protector`` compiler option. 4656 4657For example, it disables the stack protector for the function ``foo`` but function 4658``bar`` will still be built with the stack protector with the ``-fstack-protector`` 4659option. 4660 4661.. code-block:: c 4662 4663 int __attribute__((no_stack_protector)) 4664 foo (int x); // stack protection will be disabled for foo. 4665 4666 int bar(int y); // bar can be built with the stack protector. 4667 4668 }]; 4669} 4670 4671def StrictGuardStackCheckDocs : Documentation { 4672 let Category = DocCatFunction; 4673 let Content = [{ 4674Clang supports the Microsoft style ``__declspec((strict_gs_check))`` attribute 4675which upgrades the stack protector check from ``-fstack-protector`` to 4676``-fstack-protector-strong``. 4677 4678For example, it upgrades the stack protector for the function ``foo`` to 4679``-fstack-protector-strong`` but function ``bar`` will still be built with the 4680stack protector with the ``-fstack-protector`` option. 4681 4682.. code-block:: c 4683 4684 __declspec((strict_gs_check)) 4685 int foo(int x); // stack protection will be upgraded for foo. 4686 4687 int bar(int y); // bar can be built with the standard stack protector checks. 4688 4689 }]; 4690} 4691 4692def NotTailCalledDocs : Documentation { 4693 let Category = DocCatFunction; 4694 let Content = [{ 4695The ``not_tail_called`` attribute prevents tail-call optimization on statically 4696bound calls. Objective-c methods, and functions marked as ``always_inline`` 4697cannot be marked as ``not_tail_called``. 4698 4699For example, it prevents tail-call optimization in the following case: 4700 4701 .. code-block:: c 4702 4703 int __attribute__((not_tail_called)) foo1(int); 4704 4705 int foo2(int a) { 4706 return foo1(a); // No tail-call optimization on direct calls. 4707 } 4708 4709However, it doesn't prevent tail-call optimization in this case: 4710 4711 .. code-block:: c 4712 4713 int __attribute__((not_tail_called)) foo1(int); 4714 4715 int foo2(int a) { 4716 int (*fn)(int) = &foo1; 4717 4718 // not_tail_called has no effect on an indirect call even if the call can 4719 // be resolved at compile time. 4720 return (*fn)(a); 4721 } 4722 4723Generally, marking an overriding virtual function as ``not_tail_called`` is 4724not useful, because this attribute is a property of the static type. Calls 4725made through a pointer or reference to the base class type will respect 4726the ``not_tail_called`` attribute of the base class's member function, 4727regardless of the runtime destination of the call: 4728 4729 .. code-block:: c++ 4730 4731 struct Foo { virtual void f(); }; 4732 struct Bar : Foo { 4733 [[clang::not_tail_called]] void f() override; 4734 }; 4735 void callera(Bar& bar) { 4736 Foo& foo = bar; 4737 // not_tail_called has no effect on here, even though the 4738 // underlying method is f from Bar. 4739 foo.f(); 4740 bar.f(); // No tail-call optimization on here. 4741 } 4742 }]; 4743} 4744 4745def NoThrowDocs : Documentation { 4746 let Category = DocCatFunction; 4747 let Content = [{ 4748Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style 4749``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function 4750declarations. This attribute informs the compiler that the annotated function 4751does not throw an exception. This prevents exception-unwinding. This attribute 4752is particularly useful on functions in the C Standard Library that are 4753guaranteed to not throw an exception. 4754 }]; 4755} 4756 4757def NoUwtableDocs : Documentation { 4758 let Category = DocCatFunction; 4759 let Content = [{ 4760Clang supports the ``nouwtable`` attribute which skips emitting 4761the unwind table entry for the specified function. This attribute is useful for 4762selectively emitting the unwind table entry on some functions when building with 4763``-funwind-tables`` compiler option. 4764 }]; 4765} 4766 4767def InternalLinkageDocs : Documentation { 4768 let Category = DocCatFunction; 4769 let Content = [{ 4770The ``internal_linkage`` attribute changes the linkage type of the declaration 4771to internal. This is similar to C-style ``static``, but can be used on classes 4772and class methods. When applied to a class definition, this attribute affects 4773all methods and static data members of that class. This can be used to contain 4774the ABI of a C++ library by excluding unwanted class methods from the export 4775tables. 4776 }]; 4777} 4778 4779def ExcludeFromExplicitInstantiationDocs : Documentation { 4780 let Category = DocCatFunction; 4781 let Content = [{ 4782The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a 4783class template from being part of explicit template instantiations of that 4784class template. This means that an explicit instantiation will not instantiate 4785members of the class template marked with the attribute, but also that code 4786where an extern template declaration of the enclosing class template is visible 4787will not take for granted that an external instantiation of the class template 4788would provide those members (which would otherwise be a link error, since the 4789explicit instantiation won't provide those members). For example, let's say we 4790don't want the ``data()`` method to be part of libc++'s ABI. To make sure it 4791is not exported from the dylib, we give it hidden visibility: 4792 4793 .. code-block:: c++ 4794 4795 // in <string> 4796 template <class CharT> 4797 class basic_string { 4798 public: 4799 __attribute__((__visibility__("hidden"))) 4800 const value_type* data() const noexcept { ... } 4801 }; 4802 4803 template class basic_string<char>; 4804 4805Since an explicit template instantiation declaration for ``basic_string<char>`` 4806is provided, the compiler is free to assume that ``basic_string<char>::data()`` 4807will be provided by another translation unit, and it is free to produce an 4808external call to this function. However, since ``data()`` has hidden visibility 4809and the explicit template instantiation is provided in a shared library (as 4810opposed to simply another translation unit), ``basic_string<char>::data()`` 4811won't be found and a link error will ensue. This happens because the compiler 4812assumes that ``basic_string<char>::data()`` is part of the explicit template 4813instantiation declaration, when it really isn't. To tell the compiler that 4814``data()`` is not part of the explicit template instantiation declaration, the 4815``exclude_from_explicit_instantiation`` attribute can be used: 4816 4817 .. code-block:: c++ 4818 4819 // in <string> 4820 template <class CharT> 4821 class basic_string { 4822 public: 4823 __attribute__((__visibility__("hidden"))) 4824 __attribute__((exclude_from_explicit_instantiation)) 4825 const value_type* data() const noexcept { ... } 4826 }; 4827 4828 template class basic_string<char>; 4829 4830Now, the compiler won't assume that ``basic_string<char>::data()`` is provided 4831externally despite there being an explicit template instantiation declaration: 4832the compiler will implicitly instantiate ``basic_string<char>::data()`` in the 4833TUs where it is used. 4834 4835This attribute can be used on static and non-static member functions of class 4836templates, static data members of class templates and member classes of class 4837templates. 4838 }]; 4839} 4840 4841def DisableTailCallsDocs : Documentation { 4842 let Category = DocCatFunction; 4843 let Content = [{ 4844The ``disable_tail_calls`` attribute instructs the backend to not perform tail 4845call optimization inside the marked function. 4846 4847For example: 4848 4849 .. code-block:: c 4850 4851 int callee(int); 4852 4853 int foo(int a) __attribute__((disable_tail_calls)) { 4854 return callee(a); // This call is not tail-call optimized. 4855 } 4856 4857Marking virtual functions as ``disable_tail_calls`` is legal. 4858 4859 .. code-block:: c++ 4860 4861 int callee(int); 4862 4863 class Base { 4864 public: 4865 [[clang::disable_tail_calls]] virtual int foo1() { 4866 return callee(); // This call is not tail-call optimized. 4867 } 4868 }; 4869 4870 class Derived1 : public Base { 4871 public: 4872 int foo1() override { 4873 return callee(); // This call is tail-call optimized. 4874 } 4875 }; 4876 4877 }]; 4878} 4879 4880def AnyX86InterruptDocs : Documentation { 4881 let Category = DocCatFunction; 4882 let Heading = "interrupt (X86)"; 4883 let Content = [{ 4884Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86 4885targets. This attribute may be attached to a function definition and instructs 4886the backend to generate appropriate function entry/exit code so that it can be 4887used directly as an interrupt service routine. 4888 4889Interrupt handlers have access to the stack frame pushed onto the stack by the processor, 4890and return using the ``IRET`` instruction. All registers in an interrupt handler are callee-saved. 4891Exception handlers also have access to the error code pushed onto the stack by the processor, 4892when applicable. 4893 4894An interrupt handler must take the following arguments: 4895 4896 .. code-block:: c 4897 4898 __attribute__ ((interrupt)) 4899 void f (struct stack_frame *frame) { 4900 ... 4901 } 4902 4903 Where ``struct stack_frame`` is a suitable struct matching the stack frame pushed by the 4904 processor. 4905 4906An exception handler must take the following arguments: 4907 4908 .. code-block:: c 4909 4910 __attribute__ ((interrupt)) 4911 void g (struct stack_frame *frame, unsigned long code) { 4912 ... 4913 } 4914 4915 On 32-bit targets, the ``code`` argument should be of type ``unsigned int``. 4916 4917Exception handlers should only be used when an error code is pushed by the processor. 4918Using the incorrect handler type will crash the system. 4919 4920Interrupt and exception handlers cannot be called by other functions and must have return type ``void``. 4921 4922Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers' 4923attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused 4924non-GPR registers. 4925 }]; 4926} 4927 4928def AnyX86NoCallerSavedRegistersDocs : Documentation { 4929 let Category = DocCatFunction; 4930 let Content = [{ 4931Use this attribute to indicate that the specified function has no 4932caller-saved registers. That is, all registers are callee-saved except for 4933registers used for passing parameters to the function or returning parameters 4934from the function. 4935The compiler saves and restores any modified registers that were not used for 4936passing or returning arguments to the function. 4937 4938The user can call functions specified with the 'no_caller_saved_registers' 4939attribute from an interrupt handler without saving and restoring all 4940call-clobbered registers. 4941 4942Functions specified with the 'no_caller_saved_registers' attribute should only 4943call other functions with the 'no_caller_saved_registers' attribute, or should be 4944compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers. 4945 4946Note that 'no_caller_saved_registers' attribute is not a calling convention. 4947In fact, it only overrides the decision of which registers should be saved by 4948the caller, but not how the parameters are passed from the caller to the callee. 4949 4950For example: 4951 4952 .. code-block:: c 4953 4954 __attribute__ ((no_caller_saved_registers, fastcall)) 4955 void f (int arg1, int arg2) { 4956 ... 4957 } 4958 4959 In this case parameters 'arg1' and 'arg2' will be passed in registers. 4960 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as 4961 register parameters. However, it will not assume any scratch registers and 4962 should save and restore any modified registers except for ECX and EDX. 4963 }]; 4964} 4965 4966def X86ForceAlignArgPointerDocs : Documentation { 4967 let Category = DocCatFunction; 4968 let Content = [{ 4969Use this attribute to force stack alignment. 4970 4971Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions 4972(like 'movaps') that work with the stack require operands to be 16-byte aligned. 4973This attribute realigns the stack in the function prologue to make sure the 4974stack can be used with SSE instructions. 4975 4976Note that the x86_64 ABI forces 16-byte stack alignment at the call site. 4977Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in 4978rare cases where the caller does not align the stack properly (e.g. flow 4979jumps from i386 arch code). 4980 4981 .. code-block:: c 4982 4983 __attribute__ ((force_align_arg_pointer)) 4984 void f () { 4985 ... 4986 } 4987 4988 }]; 4989} 4990 4991def AnyX86NoCfCheckDocs : Documentation { 4992 let Category = DocCatFunction; 4993 let Content = [{ 4994Jump Oriented Programming attacks rely on tampering with addresses used by 4995indirect call / jmp, e.g. redirect control-flow to non-programmer 4996intended bytes in the binary. 4997X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow 4998Enforcement Technology (CET). IBT instruments ENDBR instructions used to 4999specify valid targets of indirect call / jmp. 5000The ``nocf_check`` attribute has two roles: 50011. Appertains to a function - do not add ENDBR instruction at the beginning of 5002the function. 50032. Appertains to a function pointer - do not track the target function of this 5004pointer (by adding nocf_check prefix to the indirect-call instruction). 5005}]; 5006} 5007 5008def SwiftCallDocs : Documentation { 5009 let Category = DocCatVariable; 5010 let Content = [{ 5011The ``swiftcall`` attribute indicates that a function should be called 5012using the Swift calling convention for a function or function pointer. 5013 5014The lowering for the Swift calling convention, as described by the Swift 5015ABI documentation, occurs in multiple phases. The first, "high-level" 5016phase breaks down the formal parameters and results into innately direct 5017and indirect components, adds implicit parameters for the generic 5018signature, and assigns the context and error ABI treatments to parameters 5019where applicable. The second phase breaks down the direct parameters 5020and results from the first phase and assigns them to registers or the 5021stack. The ``swiftcall`` convention only handles this second phase of 5022lowering; the C function type must accurately reflect the results 5023of the first phase, as follows: 5024 5025- Results classified as indirect by high-level lowering should be 5026 represented as parameters with the ``swift_indirect_result`` attribute. 5027 5028- Results classified as direct by high-level lowering should be represented 5029 as follows: 5030 5031 - First, remove any empty direct results. 5032 5033 - If there are no direct results, the C result type should be ``void``. 5034 5035 - If there is one direct result, the C result type should be a type with 5036 the exact layout of that result type. 5037 5038 - If there are a multiple direct results, the C result type should be 5039 a struct type with the exact layout of a tuple of those results. 5040 5041- Parameters classified as indirect by high-level lowering should be 5042 represented as parameters of pointer type. 5043 5044- Parameters classified as direct by high-level lowering should be 5045 omitted if they are empty types; otherwise, they should be represented 5046 as a parameter type with a layout exactly matching the layout of the 5047 Swift parameter type. 5048 5049- The context parameter, if present, should be represented as a trailing 5050 parameter with the ``swift_context`` attribute. 5051 5052- The error result parameter, if present, should be represented as a 5053 trailing parameter (always following a context parameter) with the 5054 ``swift_error_result`` attribute. 5055 5056``swiftcall`` does not support variadic arguments or unprototyped functions. 5057 5058The parameter ABI treatment attributes are aspects of the function type. 5059A function type which applies an ABI treatment attribute to a 5060parameter is a different type from an otherwise-identical function type 5061that does not. A single parameter may not have multiple ABI treatment 5062attributes. 5063 5064Support for this feature is target-dependent, although it should be 5065supported on every target that Swift supports. Query for this support 5066with ``__has_attribute(swiftcall)``. This implies support for the 5067``swift_context``, ``swift_error_result``, and ``swift_indirect_result`` 5068attributes. 5069 }]; 5070} 5071 5072def SwiftContextDocs : Documentation { 5073 let Category = DocCatVariable; 5074 let Content = [{ 5075The ``swift_context`` attribute marks a parameter of a ``swiftcall`` 5076or ``swiftasynccall`` function as having the special context-parameter 5077ABI treatment. 5078 5079This treatment generally passes the context value in a special register 5080which is normally callee-preserved. 5081 5082A ``swift_context`` parameter must either be the last parameter or must be 5083followed by a ``swift_error_result`` parameter (which itself must always be 5084the last parameter). 5085 5086A context parameter must have pointer or reference type. 5087 }]; 5088} 5089 5090def SwiftAsyncCallDocs : Documentation { 5091 let Category = DocCatVariable; 5092 let Content = [{ 5093The ``swiftasynccall`` attribute indicates that a function is 5094compatible with the low-level conventions of Swift async functions, 5095provided it declares the right formal arguments. 5096 5097In most respects, this is similar to the ``swiftcall`` attribute, except for 5098the following: 5099 5100- A parameter may be marked ``swift_async_context``, ``swift_context`` 5101 or ``swift_indirect_result`` (with the same restrictions on parameter 5102 ordering as ``swiftcall``) but the parameter attribute 5103 ``swift_error_result`` is not permitted. 5104 5105- A ``swiftasynccall`` function must have return type ``void``. 5106 5107- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall`` 5108 function that is the immediate operand of a ``return`` statement is 5109 guaranteed to be performed as a tail call. This syntax is allowed even 5110 in C as an extension (a call to a void-returning function cannot be a 5111 return operand in standard C). If something in the calling function would 5112 semantically be performed after a guaranteed tail call, such as the 5113 non-trivial destruction of a local variable or temporary, 5114 then the program is ill-formed. 5115 }]; 5116} 5117 5118def SwiftAsyncContextDocs : Documentation { 5119 let Category = DocCatVariable; 5120 let Content = [{ 5121The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall`` 5122function as having the special asynchronous context-parameter ABI treatment. 5123 5124If the function is not ``swiftasynccall``, this attribute only generates 5125extended frame information. 5126 5127A context parameter must have pointer or reference type. 5128 }]; 5129} 5130 5131def SwiftErrorResultDocs : Documentation { 5132 let Category = DocCatVariable; 5133 let Content = [{ 5134The ``swift_error_result`` attribute marks a parameter of a ``swiftcall`` 5135function as having the special error-result ABI treatment. 5136 5137This treatment generally passes the underlying error value in and out of 5138the function through a special register which is normally callee-preserved. 5139This is modeled in C by pretending that the register is addressable memory: 5140 5141- The caller appears to pass the address of a variable of pointer type. 5142 The current value of this variable is copied into the register before 5143 the call; if the call returns normally, the value is copied back into the 5144 variable. 5145 5146- The callee appears to receive the address of a variable. This address 5147 is actually a hidden location in its own stack, initialized with the 5148 value of the register upon entry. When the function returns normally, 5149 the value in that hidden location is written back to the register. 5150 5151A ``swift_error_result`` parameter must be the last parameter, and it must be 5152preceded by a ``swift_context`` parameter. 5153 5154A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some 5155type T. Note that no qualifiers are permitted on the intermediate level. 5156 5157It is undefined behavior if the caller does not pass a pointer or 5158reference to a valid object. 5159 5160The standard convention is that the error value itself (that is, the 5161value stored in the apparent argument) will be null upon function entry, 5162but this is not enforced by the ABI. 5163 }]; 5164} 5165 5166def SwiftIndirectResultDocs : Documentation { 5167 let Category = DocCatVariable; 5168 let Content = [{ 5169The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall`` 5170or ``swiftasynccall`` function as having the special indirect-result ABI 5171treatment. 5172 5173This treatment gives the parameter the target's normal indirect-result 5174ABI treatment, which may involve passing it differently from an ordinary 5175parameter. However, only the first indirect result will receive this 5176treatment. Furthermore, low-level lowering may decide that a direct result 5177must be returned indirectly; if so, this will take priority over the 5178``swift_indirect_result`` parameters. 5179 5180A ``swift_indirect_result`` parameter must either be the first parameter or 5181follow another ``swift_indirect_result`` parameter. 5182 5183A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for 5184some object type ``T``. If ``T`` is a complete type at the point of 5185definition of a function, it is undefined behavior if the argument 5186value does not point to storage of adequate size and alignment for a 5187value of type ``T``. 5188 5189Making indirect results explicit in the signature allows C functions to 5190directly construct objects into them without relying on language 5191optimizations like C++'s named return value optimization (NRVO). 5192 }]; 5193} 5194 5195def SwiftAsyncDocs : Documentation { 5196 let Category = SwiftDocs; 5197 let Heading = "swift_async"; 5198 let Content = [{ 5199The ``swift_async`` attribute specifies if and how a particular function or 5200Objective-C method is imported into a swift async method. For instance: 5201 5202.. code-block:: objc 5203 5204 @interface MyClass : NSObject 5205 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler 5206 __attribute__((swift_async(none))); 5207 5208 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun 5209 __attribute__((swift_async(swift_private, 1))); 5210 @end 5211 5212Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as 5213``async`` (because it's last parameter's selector piece is 5214``withCompletionHandler``) if not for the ``swift_async(none)`` attribute. 5215Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as 5216``async`` if not for the ``swift_async`` attribute because it doesn't match the 5217naming convention. 5218 5219When using ``swift_async`` to enable importing, the first argument to the 5220attribute is either ``swift_private`` or ``not_swift_private`` to indicate 5221whether the function/method is private to the current framework, and the second 5222argument is the index of the completion handler parameter. 5223 }]; 5224} 5225 5226def SwiftAsyncErrorDocs : Documentation { 5227 let Category = SwiftDocs; 5228 let Heading = "swift_async_error"; 5229 let Content = [{ 5230The ``swift_async_error`` attribute specifies how an error state will be 5231represented in a swift async method. It's a bit analogous to the ``swift_error`` 5232attribute for the generated async method. The ``swift_async_error`` attribute 5233can indicate a variety of different ways of representing an error. 5234 5235- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the 5236 async method is considered to have failed if the Nth argument to the 5237 completion handler is zero. 5238 5239- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that 5240 the async method is considered to have failed if the Nth argument to the 5241 completion handler is non-zero. 5242 5243- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the 5244 async method is considered to have failed if the ``NSError *`` argument to the 5245 completion handler is non-null. 5246 5247- ``__attribute__((swift_async_error(none)))``, specifies that the async method 5248 cannot fail. 5249 5250 5251For instance: 5252 5253.. code-block:: objc 5254 5255 @interface MyClass : NSObject 5256 -(void)asyncMethod:(void (^)(char, int, float))handler 5257 __attribute__((swift_async(swift_private, 1))) 5258 __attribute__((swift_async_error(zero_argument, 2))); 5259 @end 5260 5261Here, the ``swift_async`` attribute specifies that ``handler`` is the completion 5262handler for this method, and the ``swift_async_error`` attribute specifies that 5263the ``int`` parameter is the one that represents the error. 5264}]; 5265} 5266 5267def SuppressDocs : Documentation { 5268 let Category = DocCatStmt; 5269 let Content = [{ 5270The ``suppress`` attribute suppresses unwanted warnings coming from static 5271analysis tools such as the Clang Static Analyzer. The tool will not report 5272any issues in source code annotated with the attribute. 5273 5274The attribute cannot be used to suppress traditional Clang warnings, because 5275many such warnings are emitted before the attribute is fully parsed. 5276Consider using ``#pragma clang diagnostic`` to control such diagnostics, 5277as described in `Controlling Diagnostics via Pragmas 5278<https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas>`_. 5279 5280The ``suppress`` attribute can be placed on an individual statement in order to 5281suppress warnings about undesirable behavior occurring at that statement: 5282 5283.. code-block:: c++ 5284 5285 int foo() { 5286 int *x = nullptr; 5287 ... 5288 [[clang::suppress]] 5289 return *x; // null pointer dereference warning suppressed here 5290 } 5291 5292Putting the attribute on a compound statement suppresses all warnings in scope: 5293 5294.. code-block:: c++ 5295 5296 int foo() { 5297 [[clang::suppress]] { 5298 int *x = nullptr; 5299 ... 5300 return *x; // warnings suppressed in the entire scope 5301 } 5302 } 5303 5304Some static analysis warnings are accompanied by one or more notes, and the 5305line of code against which the warning is emitted isn't necessarily the best 5306for suppression purposes. In such cases the tools are allowed to implement 5307additional ways to suppress specific warnings based on the attribute attached 5308to a note location. 5309 5310For example, the Clang Static Analyzer suppresses memory leak warnings when 5311the suppression attribute is placed at the allocation site (highlited by 5312a "note: memory is allocated"), which may be different from the line of code 5313at which the program "loses track" of the pointer (where the warning 5314is ultimately emitted): 5315 5316.. code-block:: c 5317 5318 int bar1(bool coin_flip) { 5319 __attribute__((suppress)) 5320 int *result = (int *)malloc(sizeof(int)); 5321 if (coin_flip) 5322 return 1; // warning about this leak path is suppressed 5323 5324 return *result; // warning about this leak path is also suppressed 5325 } 5326 5327 int bar2(bool coin_flip) { 5328 int *result = (int *)malloc(sizeof(int)); 5329 if (coin_flip) 5330 return 1; // leak warning on this path NOT suppressed 5331 5332 __attribute__((suppress)) 5333 return *result; // leak warning is suppressed only on this path 5334 } 5335 5336 5337When written as ``[[gsl::suppress]]``, this attribute suppresses specific 5338clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable 5339way. The attribute can be attached to declarations, statements, and at 5340namespace scope. 5341 5342.. code-block:: c++ 5343 5344 [[gsl::suppress("Rh-public")]] 5345 void f_() { 5346 int *p; 5347 [[gsl::suppress("type")]] { 5348 p = reinterpret_cast<int*>(7); 5349 } 5350 } 5351 namespace N { 5352 [[clang::suppress("type", "bounds")]]; 5353 ... 5354 } 5355 5356.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement 5357 }]; 5358} 5359 5360def AbiTagsDocs : Documentation { 5361 let Category = DocCatFunction; 5362 let Content = [{ 5363The ``abi_tag`` attribute can be applied to a function, variable, class or 5364inline namespace declaration to modify the mangled name of the entity. It gives 5365the ability to distinguish between different versions of the same entity but 5366with different ABI versions supported. For example, a newer version of a class 5367could have a different set of data members and thus have a different size. Using 5368the ``abi_tag`` attribute, it is possible to have different mangled names for 5369a global variable of the class type. Therefore, the old code could keep using 5370the old mangled name and the new code will use the new mangled name with tags. 5371 }]; 5372} 5373 5374def BuiltinAliasDocs : Documentation { 5375 let Category = DocCatFunction; 5376 let Heading = "clang::builtin_alias, clang_builtin_alias"; 5377 let Content = [{ 5378This attribute is used in the implementation of the C intrinsics. 5379It allows the C intrinsic functions to be declared using the names defined 5380in target builtins, and still be recognized as clang builtins equivalent to the 5381underlying name. For example, ``riscv_vector.h`` declares the function ``vadd`` 5382with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``. 5383This ensures that both functions are recognized as that clang builtin, 5384and in the latter case, the choice of which builtin to identify the 5385function as can be deferred until after overload resolution. 5386 5387This attribute can only be used to set up the aliases for certain ARM/RISC-V 5388C intrinsic functions; it is intended for use only inside ``arm_*.h`` and 5389``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases 5390for clang builtin functions. 5391 }]; 5392} 5393 5394def PreferredNameDocs : Documentation { 5395 let Category = DocCatDecl; 5396 let Content = [{ 5397The ``preferred_name`` attribute can be applied to a class template, and 5398specifies a preferred way of naming a specialization of the template. The 5399preferred name will be used whenever the corresponding template specialization 5400would otherwise be printed in a diagnostic or similar context. 5401 5402The preferred name must be a typedef or type alias declaration that refers to a 5403specialization of the class template (not including any type qualifiers). In 5404general this requires the template to be declared at least twice. For example: 5405 5406.. code-block:: c++ 5407 5408 template<typename T> struct basic_string; 5409 using string = basic_string<char>; 5410 using wstring = basic_string<wchar_t>; 5411 template<typename T> struct [[clang::preferred_name(string), 5412 clang::preferred_name(wstring)]] basic_string { 5413 // ... 5414 }; 5415 5416 5417Note that the ``preferred_name`` attribute will be ignored when the compiler 5418writes a C++20 Module interface now. This is due to a compiler issue 5419(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize 5420declarations with `preferred_name`. This is intended to be fixed in the future. 5421 }]; 5422} 5423 5424def PreserveMostDocs : Documentation { 5425 let Category = DocCatCallingConvs; 5426 let Content = [{ 5427On X86-64 and AArch64 targets, this attribute changes the calling convention of 5428a function. The ``preserve_most`` calling convention attempts to make the code 5429in the caller as unintrusive as possible. This convention behaves identically 5430to the ``C`` calling convention on how arguments and return values are passed, 5431but it uses a different set of caller/callee-saved registers. This alleviates 5432the burden of saving and recovering a large register set before and after the 5433call in the caller. If the arguments are passed in callee-saved registers, 5434then they will be preserved by the callee across the call. This doesn't 5435apply for values returned in callee-saved registers. 5436 5437- On X86-64 the callee preserves all general purpose registers, except for 5438 R11. R11 can be used as a scratch register. Floating-point registers 5439 (XMMs/YMMs) are not preserved and need to be saved by the caller. 5440 5441- On AArch64 the callee preserve all general purpose registers, except X0-X8 and 5442 X16-X18. 5443 5444The idea behind this convention is to support calls to runtime functions 5445that have a hot path and a cold path. The hot path is usually a small piece 5446of code that doesn't use many registers. The cold path might need to call out to 5447another function and therefore only needs to preserve the caller-saved 5448registers, which haven't already been saved by the caller. The 5449``preserve_most`` calling convention is very similar to the ``cold`` calling 5450convention in terms of caller/callee-saved registers, but they are used for 5451different types of function calls. ``coldcc`` is for function calls that are 5452rarely executed, whereas ``preserve_most`` function calls are intended to be 5453on the hot path and definitely executed a lot. Furthermore ``preserve_most`` 5454doesn't prevent the inliner from inlining the function call. 5455 5456This calling convention will be used by a future version of the Objective-C 5457runtime and should therefore still be considered experimental at this time. 5458Although this convention was created to optimize certain runtime calls to 5459the Objective-C runtime, it is not limited to this runtime and might be used 5460by other runtimes in the future too. The current implementation only 5461supports X86-64 and AArch64, but the intention is to support more architectures 5462in the future. 5463 }]; 5464} 5465 5466def PreserveAllDocs : Documentation { 5467 let Category = DocCatCallingConvs; 5468 let Content = [{ 5469On X86-64 and AArch64 targets, this attribute changes the calling convention of 5470a function. The ``preserve_all`` calling convention attempts to make the code 5471in the caller even less intrusive than the ``preserve_most`` calling convention. 5472This calling convention also behaves identical to the ``C`` calling convention 5473on how arguments and return values are passed, but it uses a different set of 5474caller/callee-saved registers. This removes the burden of saving and 5475recovering a large register set before and after the call in the caller. If 5476the arguments are passed in callee-saved registers, then they will be 5477preserved by the callee across the call. This doesn't apply for values 5478returned in callee-saved registers. 5479 5480- On X86-64 the callee preserves all general purpose registers, except for 5481 R11. R11 can be used as a scratch register. Furthermore it also preserves 5482 all floating-point registers (XMMs/YMMs). 5483 5484- On AArch64 the callee preserve all general purpose registers, except X0-X8 and 5485 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating 5486 point registers. 5487 5488The idea behind this convention is to support calls to runtime functions 5489that don't need to call out to any other functions. 5490 5491This calling convention, like the ``preserve_most`` calling convention, will be 5492used by a future version of the Objective-C runtime and should be considered 5493experimental at this time. 5494 }]; 5495} 5496 5497def DeprecatedDocs : Documentation { 5498 let Category = DocCatDecl; 5499 let Content = [{ 5500The ``deprecated`` attribute can be applied to a function, a variable, or a 5501type. This is useful when identifying functions, variables, or types that are 5502expected to be removed in a future version of a program. 5503 5504Consider the function declaration for a hypothetical function ``f``: 5505 5506.. code-block:: c++ 5507 5508 void f(void) __attribute__((deprecated("message", "replacement"))); 5509 5510When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have 5511two optional string arguments. The first one is the message to display when 5512emitting the warning; the second one enables the compiler to provide a Fix-It 5513to replace the deprecated name with a new name. Otherwise, when spelled as 5514``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional 5515string argument which is the message to display when emitting the warning. 5516 }]; 5517} 5518 5519def IFuncDocs : Documentation { 5520 let Category = DocCatFunction; 5521 let Content = [{ 5522``__attribute__((ifunc("resolver")))`` is used to mark that the address of a 5523declaration should be resolved at runtime by calling a resolver function. 5524 5525The symbol name of the resolver function is given in quotes. A function with 5526this name (after mangling) must be defined in the current translation unit; it 5527may be ``static``. The resolver function should return a pointer. 5528 5529The ``ifunc`` attribute may only be used on a function declaration. A function 5530declaration with an ``ifunc`` attribute is considered to be a definition of the 5531declared entity. The entity must not have weak linkage; for example, in C++, 5532it cannot be applied to a declaration if a definition at that location would be 5533considered inline. 5534 5535Not all targets support this attribute. ELF target support depends on both the 5536linker and runtime linker, and is available in at least lld 4.0 and later, 5537binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later. 5538Mach-O targets support it, but with slightly different semantics: the resolver 5539is run at first call, instead of at load time by the runtime linker. Targets 5540other than ELF and Mach-O currently do not support this attribute. 5541 }]; 5542} 5543 5544def LTOVisibilityDocs : Documentation { 5545 let Category = DocCatDecl; 5546 let Content = [{ 5547See :doc:`LTOVisibility`. 5548 }]; 5549} 5550 5551def RenderScriptKernelAttributeDocs : Documentation { 5552 let Category = DocCatFunction; 5553 let Content = [{ 5554``__attribute__((kernel))`` is used to mark a ``kernel`` function in 5555RenderScript. 5556 5557In RenderScript, ``kernel`` functions are used to express data-parallel 5558computations. The RenderScript runtime efficiently parallelizes ``kernel`` 5559functions to run on computational resources such as multi-core CPUs and GPUs. 5560See the RenderScript_ documentation for more information. 5561 5562.. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html 5563 }]; 5564} 5565 5566def XRayDocs : Documentation { 5567 let Category = DocCatFunction; 5568 let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args"; 5569 let Content = [{ 5570``__attribute__((xray_always_instrument))`` or 5571``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), 5572methods (in Objective C), and free functions (in C, C++, and Objective C) to be 5573instrumented with XRay. This will cause the function to always have space at 5574the beginning and exit points to allow for runtime patching. 5575 5576Conversely, ``__attribute__((xray_never_instrument))`` or 5577``[[clang::xray_never_instrument]]`` will inhibit the insertion of these 5578instrumentation points. 5579 5580If a function has neither of these attributes, they become subject to the XRay 5581heuristics used to determine whether a function should be instrumented or 5582otherwise. 5583 5584``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is 5585used to preserve N function arguments for the logging function. Currently, 5586only N==1 is supported. 5587 }]; 5588} 5589 5590def PatchableFunctionEntryDocs : Documentation { 5591 let Category = DocCatFunction; 5592 let Content = [{ 5593``__attribute__((patchable_function_entry(N,M)))`` is used to generate M NOPs 5594before the function entry and N-M NOPs after the function entry. This attribute 5595takes precedence over the command line option ``-fpatchable-function-entry=N,M``. 5596``M`` defaults to 0 if omitted. 5597 5598This attribute is only supported on 5599aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64 targets. 5600}]; 5601} 5602 5603def HotFunctionEntryDocs : Documentation { 5604 let Category = DocCatFunction; 5605 let Content = [{ 5606``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data. 5607If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``). 5608}]; 5609} 5610 5611def ColdFunctionEntryDocs : Documentation { 5612 let Category = DocCatFunction; 5613 let Content = [{ 5614``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data. 5615If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``). 5616}]; 5617} 5618def TransparentUnionDocs : Documentation { 5619 let Category = DocCatDecl; 5620 let Content = [{ 5621This attribute can be applied to a union to change the behavior of calls to 5622functions that have an argument with a transparent union type. The compiler 5623behavior is changed in the following manner: 5624 5625- A value whose type is any member of the transparent union can be passed as an 5626 argument without the need to cast that value. 5627 5628- The argument is passed to the function using the calling convention of the 5629 first member of the transparent union. Consequently, all the members of the 5630 transparent union should have the same calling convention as its first member. 5631 5632Transparent unions are not supported in C++. 5633 }]; 5634} 5635 5636def ObjCSubclassingRestrictedDocs : Documentation { 5637 let Category = DocCatDecl; 5638 let Content = [{ 5639This attribute can be added to an Objective-C ``@interface`` declaration to 5640ensure that this class cannot be subclassed. 5641 }]; 5642} 5643 5644def ObjCNonLazyClassDocs : Documentation { 5645 let Category = DocCatDecl; 5646 let Content = [{ 5647This attribute can be added to an Objective-C ``@interface`` or 5648``@implementation`` declaration to add the class to the list of non-lazily 5649initialized classes. A non-lazy class will be initialized eagerly when the 5650Objective-C runtime is loaded. This is required for certain system classes which 5651have instances allocated in non-standard ways, such as the classes for blocks 5652and constant strings. Adding this attribute is essentially equivalent to 5653providing a trivial ``+load`` method but avoids the (fairly small) load-time 5654overheads associated with defining and calling such a method. 5655 }]; 5656} 5657 5658def ObjCDirectDocs : Documentation { 5659 let Category = DocCatDecl; 5660 let Content = [{ 5661The ``objc_direct`` attribute can be used to mark an Objective-C method as 5662being *direct*. A direct method is treated statically like an ordinary method, 5663but dynamically it behaves more like a C function. This lowers some of the costs 5664associated with the method but also sacrifices some of the ordinary capabilities 5665of Objective-C methods. 5666 5667A message send of a direct method calls the implementation directly, as if it 5668were a C function, rather than using ordinary Objective-C method dispatch. This 5669is substantially faster and potentially allows the implementation to be inlined, 5670but it also means the method cannot be overridden in subclasses or replaced 5671dynamically, as ordinary Objective-C methods can. 5672 5673Furthermore, a direct method is not listed in the class's method lists. This 5674substantially reduces the code-size overhead of the method but also means it 5675cannot be called dynamically using ordinary Objective-C method dispatch at all; 5676in particular, this means that it cannot override a superclass method or satisfy 5677a protocol requirement. 5678 5679Because a direct method cannot be overridden, it is an error to perform 5680a ``super`` message send of one. 5681 5682Although a message send of a direct method causes the method to be called 5683directly as if it were a C function, it still obeys Objective-C semantics in other 5684ways: 5685 5686- If the receiver is ``nil``, the message send does nothing and returns the zero value 5687 for the return type. 5688 5689- A message send of a direct class method will cause the class to be initialized, 5690 including calling the ``+initialize`` method if present. 5691 5692- The implicit ``_cmd`` parameter containing the method's selector is still defined. 5693 In order to minimize code-size costs, the implementation will not emit a reference 5694 to the selector if the parameter is unused within the method. 5695 5696Symbols for direct method implementations are implicitly given hidden 5697visibility, meaning that they can only be called within the same linkage unit. 5698 5699It is an error to do any of the following: 5700 5701- declare a direct method in a protocol, 5702- declare an override of a direct method with a method in a subclass, 5703- declare an override of a non-direct method with a direct method in a subclass, 5704- declare a method with different directness in different class interfaces, or 5705- implement a non-direct method (as declared in any class interface) with a direct method. 5706 5707If any of these rules would be violated if every method defined in an 5708``@implementation`` within a single linkage unit were declared in an 5709appropriate class interface, the program is ill-formed with no diagnostic 5710required. If a violation of this rule is not diagnosed, behavior remains 5711well-defined; this paragraph is simply reserving the right to diagnose such 5712conflicts in the future, not to treat them as undefined behavior. 5713 5714Additionally, Clang will warn about any ``@selector`` expression that 5715names a selector that is only known to be used for direct methods. 5716 5717For the purpose of these rules, a "class interface" includes a class's primary 5718``@interface`` block, its class extensions, its categories, its declared protocols, 5719and all the class interfaces of its superclasses. 5720 5721An Objective-C property can be declared with the ``direct`` property 5722attribute. If a direct property declaration causes an implicit declaration of 5723a getter or setter method (that is, if the given method is not explicitly 5724declared elsewhere), the method is declared to be direct. 5725 5726Some programmers may wish to make many methods direct at once. In order 5727to simplify this, the ``objc_direct_members`` attribute is provided; see its 5728documentation for more information. 5729 }]; 5730} 5731 5732def ObjCDirectMembersDocs : Documentation { 5733 let Category = DocCatDecl; 5734 let Content = [{ 5735The ``objc_direct_members`` attribute can be placed on an Objective-C 5736``@interface`` or ``@implementation`` to mark that methods declared 5737therein should be considered direct by default. See the documentation 5738for ``objc_direct`` for more information about direct methods. 5739 5740When ``objc_direct_members`` is placed on an ``@interface`` block, every 5741method in the block is considered to be declared as direct. This includes any 5742implicit method declarations introduced by property declarations. If the method 5743redeclares a non-direct method, the declaration is ill-formed, exactly as if the 5744method was annotated with the ``objc_direct`` attribute. 5745 5746When ``objc_direct_members`` is placed on an ``@implementation`` block, 5747methods defined in the block are considered to be declared as direct unless 5748they have been previously declared as non-direct in any interface of the class. 5749This includes the implicit method definitions introduced by synthesized 5750properties, including auto-synthesized properties. 5751 }]; 5752} 5753 5754def ObjCNonRuntimeProtocolDocs : Documentation { 5755 let Category = DocCatDecl; 5756 let Content = [{ 5757The ``objc_non_runtime_protocol`` attribute can be used to mark that an 5758Objective-C protocol is only used during static type-checking and doesn't need 5759to be represented dynamically. This avoids several small code-size and run-time 5760overheads associated with handling the protocol's metadata. A non-runtime 5761protocol cannot be used as the operand of a ``@protocol`` expression, and 5762dynamic attempts to find it with ``objc_getProtocol`` will fail. 5763 5764If a non-runtime protocol inherits from any ordinary protocols, classes and 5765derived protocols that declare conformance to the non-runtime protocol will 5766dynamically list their conformance to those bare protocols. 5767 }]; 5768} 5769 5770def SelectAnyDocs : Documentation { 5771 let Category = DocCatDecl; 5772 let Content = [{ 5773This attribute appertains to a global symbol, causing it to have a weak 5774definition ( 5775`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_ 5776), allowing the linker to select any definition. 5777 5778For more information see 5779`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_ 5780or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_. 5781}]; } 5782 5783def WebAssemblyExportNameDocs : Documentation { 5784 let Category = DocCatFunction; 5785 let Content = [{ 5786Clang supports the ``__attribute__((export_name(<name>)))`` 5787attribute for the WebAssembly target. This attribute may be attached to a 5788function declaration, where it modifies how the symbol is to be exported 5789from the linked WebAssembly. 5790 5791WebAssembly functions are exported via string name. By default when a symbol 5792is exported, the export name for C/C++ symbols are the same as their C/C++ 5793symbol names. This attribute can be used to override the default behavior, and 5794request a specific string name be used instead. 5795 }]; 5796} 5797 5798def WebAssemblyImportModuleDocs : Documentation { 5799 let Category = DocCatFunction; 5800 let Content = [{ 5801Clang supports the ``__attribute__((import_module(<module_name>)))`` 5802attribute for the WebAssembly target. This attribute may be attached to a 5803function declaration, where it modifies how the symbol is to be imported 5804within the WebAssembly linking environment. 5805 5806WebAssembly imports use a two-level namespace scheme, consisting of a module 5807name, which typically identifies a module from which to import, and a field 5808name, which typically identifies a field from that module to import. By 5809default, module names for C/C++ symbols are assigned automatically by the 5810linker. This attribute can be used to override the default behavior, and 5811request a specific module name be used instead. 5812 }]; 5813} 5814 5815def WebAssemblyImportNameDocs : Documentation { 5816 let Category = DocCatFunction; 5817 let Content = [{ 5818Clang supports the ``__attribute__((import_name(<name>)))`` 5819attribute for the WebAssembly target. This attribute may be attached to a 5820function declaration, where it modifies how the symbol is to be imported 5821within the WebAssembly linking environment. 5822 5823WebAssembly imports use a two-level namespace scheme, consisting of a module 5824name, which typically identifies a module from which to import, and a field 5825name, which typically identifies a field from that module to import. By 5826default, field names for C/C++ symbols are the same as their C/C++ symbol 5827names. This attribute can be used to override the default behavior, and 5828request a specific field name be used instead. 5829 }]; 5830} 5831 5832def ArtificialDocs : Documentation { 5833 let Category = DocCatFunction; 5834 let Content = [{ 5835The ``artificial`` attribute can be applied to an inline function. If such a 5836function is inlined, the attribute indicates that debuggers should associate 5837the resulting instructions with the call site, rather than with the 5838corresponding line within the inlined callee. 5839 }]; 5840} 5841 5842def NoDerefDocs : Documentation { 5843 let Category = DocCatType; 5844 let Content = [{ 5845The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types. 5846This is ideally used with pointers that point to special memory which cannot be read 5847from or written to, but allowing for the pointer to be used in pointer arithmetic. 5848The following are examples of valid expressions where dereferences are diagnosed: 5849 5850.. code-block:: c 5851 5852 int __attribute__((noderef)) *p; 5853 int x = *p; // warning 5854 5855 int __attribute__((noderef)) **p2; 5856 x = **p2; // warning 5857 5858 int * __attribute__((noderef)) *p3; 5859 p = *p3; // warning 5860 5861 struct S { 5862 int a; 5863 }; 5864 struct S __attribute__((noderef)) *s; 5865 x = s->a; // warning 5866 x = (*s).a; // warning 5867 5868Not all dereferences may diagnose a warning if the value directed by the pointer may not be 5869accessed. The following are examples of valid expressions where may not be diagnosed: 5870 5871.. code-block:: c 5872 5873 int *q; 5874 int __attribute__((noderef)) *p; 5875 q = &*p; 5876 q = *&p; 5877 5878 struct S { 5879 int a; 5880 }; 5881 struct S __attribute__((noderef)) *s; 5882 p = &s->a; 5883 p = &(*s).a; 5884 5885``noderef`` is currently only supported for pointers and arrays and not usable 5886for references or Objective-C object pointers. 5887 5888.. code-block:: c++ 5889 5890 int x = 2; 5891 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type 5892 5893.. code-block:: objc 5894 5895 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type 5896}]; 5897} 5898 5899def ReinitializesDocs : Documentation { 5900 let Category = DocCatFunction; 5901 let Content = [{ 5902The ``reinitializes`` attribute can be applied to a non-static, non-const C++ 5903member function to indicate that this member function reinitializes the entire 5904object to a known state, independent of the previous state of the object. 5905 5906This attribute can be interpreted by static analyzers that warn about uses of an 5907object that has been left in an indeterminate state by a move operation. If a 5908member function marked with the ``reinitializes`` attribute is called on a 5909moved-from object, the analyzer can conclude that the object is no longer in an 5910indeterminate state. 5911 5912A typical example where this attribute would be used is on functions that clear 5913a container class: 5914 5915.. code-block:: c++ 5916 5917 template <class T> 5918 class Container { 5919 public: 5920 ... 5921 [[clang::reinitializes]] void Clear(); 5922 ... 5923 }; 5924 }]; 5925} 5926 5927def AlwaysDestroyDocs : Documentation { 5928 let Category = DocCatVariable; 5929 let Content = [{ 5930The ``always_destroy`` attribute specifies that a variable with static or thread 5931storage duration should have its exit-time destructor run. This attribute is the 5932default unless clang was invoked with -fno-c++-static-destructors. 5933 }]; 5934} 5935 5936def NoDestroyDocs : Documentation { 5937 let Category = DocCatVariable; 5938 let Content = [{ 5939The ``no_destroy`` attribute specifies that a variable with static or thread 5940storage duration shouldn't have its exit-time destructor run. Annotating every 5941static and thread duration variable with this attribute is equivalent to 5942invoking clang with -fno-c++-static-destructors. 5943 5944If a variable is declared with this attribute, clang doesn't access check or 5945generate the type's destructor. If you have a type that you only want to be 5946annotated with ``no_destroy``, you can therefore declare the destructor private: 5947 5948.. code-block:: c++ 5949 5950 struct only_no_destroy { 5951 only_no_destroy(); 5952 private: 5953 ~only_no_destroy(); 5954 }; 5955 5956 [[clang::no_destroy]] only_no_destroy global; // fine! 5957 5958Note that destructors are still required for subobjects of aggregates annotated 5959with this attribute. This is because previously constructed subobjects need to 5960be destroyed if an exception gets thrown before the initialization of the 5961complete object is complete. For instance: 5962 5963.. code-block:: c++ 5964 5965 void f() { 5966 try { 5967 [[clang::no_destroy]] 5968 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor. 5969 } catch (...) { 5970 // Handle the error 5971 } 5972 } 5973 5974Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]`` 5975will be destroyed, so the element's destructor needs to be accessible. 5976 }]; 5977} 5978 5979def UninitializedDocs : Documentation { 5980 let Category = DocCatVariable; 5981 let Content = [{ 5982The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to 5983initialize trivial automatic stack variables. By default, trivial automatic 5984stack variables are uninitialized. This attribute is used to override the 5985command-line parameter, forcing variables to remain uninitialized. It has no 5986semantic meaning in that using uninitialized values is undefined behavior, 5987it rather documents the programmer's intent. 5988 }]; 5989} 5990 5991def LoaderUninitializedDocs : Documentation { 5992 let Category = DocCatVariable; 5993 let Content = [{ 5994The ``loader_uninitialized`` attribute can be placed on global variables to 5995indicate that the variable does not need to be zero initialized by the loader. 5996On most targets, zero-initialization does not incur any additional cost. 5997For example, most general purpose operating systems deliberately ensure 5998that all memory is properly initialized in order to avoid leaking privileged 5999information from the kernel or other programs. However, some targets 6000do not make this guarantee, and on these targets, avoiding an unnecessary 6001zero-initialization can have a significant impact on load times and/or code 6002size. 6003 6004A declaration with this attribute is a non-tentative definition just as if it 6005provided an initializer. Variables with this attribute are considered to be 6006uninitialized in the same sense as a local variable, and the programs must 6007write to them before reading from them. If the variable's type is a C++ class 6008type with a non-trivial default constructor, or an array thereof, this attribute 6009only suppresses the static zero-initialization of the variable, not the dynamic 6010initialization provided by executing the default constructor. 6011 }]; 6012} 6013 6014def CallbackDocs : Documentation { 6015 let Category = DocCatFunction; 6016 let Content = [{ 6017The ``callback`` attribute specifies that the annotated function may invoke the 6018specified callback zero or more times. The callback, as well as the passed 6019arguments, are identified by their parameter name or position (starting with 60201!) in the annotated function. The first position in the attribute identifies 6021the callback callee, the following positions declare describe its arguments. 6022The callback callee is required to be callable with the number, and order, of 6023the specified arguments. The index ``0``, or the identifier ``this``, is used to 6024represent an implicit "this" pointer in class methods. If there is no implicit 6025"this" pointer it shall not be referenced. The index '-1', or the name "__", 6026represents an unknown callback callee argument. This can be a value which is 6027not present in the declared parameter list, or one that is, but is potentially 6028inspected, captured, or modified. Parameter names and indices can be mixed in 6029the callback attribute. 6030 6031The ``callback`` attribute, which is directly translated to ``callback`` 6032metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the 6033connection between the call to the annotated function and the callback callee. 6034This can enable interprocedural optimizations which were otherwise impossible. 6035If a function parameter is mentioned in the ``callback`` attribute, through its 6036position, it is undefined if that parameter is used for anything other than the 6037actual callback. Inspected, captured, or modified parameters shall not be 6038listed in the ``callback`` metadata. 6039 6040Example encodings for the callback performed by ``pthread_create`` are shown 6041below. The explicit attribute annotation indicates that the third parameter 6042(``start_routine``) is called zero or more times by the ``pthread_create`` function, 6043and that the fourth parameter (``arg``) is passed along. Note that the callback 6044behavior of ``pthread_create`` is automatically recognized by Clang. In addition, 6045the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for 6046``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also 6047automatically recognized as broker functions. Further functions might be added 6048in the future. 6049 6050 .. code-block:: c 6051 6052 __attribute__((callback (start_routine, arg))) 6053 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 6054 void *(*start_routine) (void *), void *arg); 6055 6056 __attribute__((callback (3, 4))) 6057 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 6058 void *(*start_routine) (void *), void *arg); 6059 6060 }]; 6061} 6062 6063def CalledOnceDocs : Documentation { 6064 let Category = DocCatVariable; 6065 let Content = [{ 6066The ``called_once`` attribute specifies that the annotated function or method 6067parameter is invoked exactly once on all execution paths. It only applies 6068to parameters with function-like types, i.e. function pointers or blocks. This 6069concept is particularly useful for asynchronous programs. 6070 6071Clang implements a check for ``called_once`` parameters, 6072``-Wcalled-once-parameter``. It is on by default and finds the following 6073violations: 6074 6075* Parameter is not called at all. 6076 6077* Parameter is called more than once. 6078 6079* Parameter is not called on one of the execution paths. 6080 6081In the latter case, Clang pinpoints the path where parameter is not invoked 6082by showing the control-flow statement where the path diverges. 6083 6084.. code-block:: objc 6085 6086 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) { 6087 if (somePredicate()) { 6088 ... 6089 callback(); 6090 } else { 6091 callback(); // OK: callback is called on every path 6092 } 6093 } 6094 6095 void barWithCallback(void (^callback)(void) __attribute__((called_once))) { 6096 if (somePredicate()) { 6097 ... 6098 callback(); // note: previous call is here 6099 } 6100 callback(); // warning: callback is called twice 6101 } 6102 6103 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) { 6104 if (somePredicate()) { // warning: callback is not called when condition is false 6105 ... 6106 callback(); 6107 } 6108 } 6109 6110This attribute is useful for API developers who want to double-check if they 6111implemented their method correctly. 6112 6113 }]; 6114} 6115 6116def GnuInlineDocs : Documentation { 6117 let Category = DocCatFunction; 6118 let Content = [{ 6119The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline 6120semantics, meaning: 6121 6122* If any declaration that is declared ``inline`` is not declared ``extern``, 6123 then the ``inline`` keyword is just a hint. In particular, an out-of-line 6124 definition is still emitted for a function with external linkage, even if all 6125 call sites are inlined, unlike in C99 and C++ inline semantics. 6126 6127* If all declarations that are declared ``inline`` are also declared 6128 ``extern``, then the function body is present only for inlining and no 6129 out-of-line version is emitted. 6130 6131Some important consequences: ``static inline`` emits an out-of-line 6132version if needed, a plain ``inline`` definition emits an out-of-line version 6133always, and an ``extern inline`` definition (in a header) followed by a 6134(non-``extern``) ``inline`` declaration in a source file emits an out-of-line 6135version of the function in that source file but provides the function body for 6136inlining to all includers of the header. 6137 6138Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or 6139``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually 6140exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline`` 6141function attribute can be used to get GNU inline semantics on a per function 6142basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is 6143already being compiled with GNU inline semantics as the implied default. It is 6144unspecified which macro is defined in a C++ compilation. 6145 6146GNU inline semantics are the default behavior with ``-std=gnu89``, 6147``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``. 6148 }]; 6149} 6150 6151def SpeculativeLoadHardeningDocs : Documentation { 6152 let Category = DocCatFunction; 6153 let Content = [{ 6154 This attribute can be applied to a function declaration in order to indicate 6155 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_ 6156 should be enabled for the function body. This can also be applied to a method 6157 in Objective C. This attribute will take precedence over the command line flag in 6158 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified. 6159 6160 Speculative Load Hardening is a best-effort mitigation against 6161 information leak attacks that make use of control flow 6162 miss-speculation - specifically miss-speculation of whether a branch 6163 is taken or not. Typically vulnerabilities enabling such attacks are 6164 classified as "Spectre variant #1". Notably, this does not attempt to 6165 mitigate against miss-speculation of branch target, classified as 6166 "Spectre variant #2" vulnerabilities. 6167 6168 When inlining, the attribute is sticky. Inlining a function that 6169 carries this attribute will cause the caller to gain the 6170 attribute. This is intended to provide a maximally conservative model 6171 where the code in a function annotated with this attribute will always 6172 (even after inlining) end up hardened. 6173 }]; 6174} 6175 6176def NoSpeculativeLoadHardeningDocs : Documentation { 6177 let Category = DocCatFunction; 6178 let Content = [{ 6179 This attribute can be applied to a function declaration in order to indicate 6180 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_ 6181 is *not* needed for the function body. This can also be applied to a method 6182 in Objective C. This attribute will take precedence over the command line flag in 6183 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified. 6184 6185 Warning: This attribute may not prevent Speculative Load Hardening from being 6186 enabled for a function which inlines a function that has the 6187 'speculative_load_hardening' attribute. This is intended to provide a 6188 maximally conservative model where the code that is marked with the 6189 'speculative_load_hardening' attribute will always (even when inlined) 6190 be hardened. A user of this attribute may want to mark functions called by 6191 a function they do not want to be hardened with the 'noinline' attribute. 6192 6193 For example: 6194 6195 .. code-block:: c 6196 6197 __attribute__((speculative_load_hardening)) 6198 int foo(int i) { 6199 return i; 6200 } 6201 6202 // Note: bar() may still have speculative load hardening enabled if 6203 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline)) 6204 // to avoid this situation. 6205 __attribute__((no_speculative_load_hardening)) 6206 int bar(int i) { 6207 return foo(i); 6208 } 6209 }]; 6210} 6211 6212def ObjCExternallyRetainedDocs : Documentation { 6213 let Category = DocCatVariable; 6214 let Content = [{ 6215The ``objc_externally_retained`` attribute can be applied to strong local 6216variables, functions, methods, or blocks to opt into 6217`externally-retained semantics 6218<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_. 6219 6220When applied to the definition of a function, method, or block, every parameter 6221of the function with implicit strong retainable object pointer type is 6222considered externally-retained, and becomes ``const``. By explicitly annotating 6223a parameter with ``__strong``, you can opt back into the default 6224non-externally-retained behavior for that parameter. For instance, 6225``first_param`` is externally-retained below, but not ``second_param``: 6226 6227.. code-block:: objc 6228 6229 __attribute__((objc_externally_retained)) 6230 void f(NSArray *first_param, __strong NSArray *second_param) { 6231 // ... 6232 } 6233 6234Likewise, when applied to a strong local variable, that variable becomes 6235``const`` and is considered externally-retained. 6236 6237When compiled without ``-fobjc-arc``, this attribute is ignored. 6238}]; } 6239 6240def MIGConventionDocs : Documentation { 6241 let Category = DocCatFunction; 6242 let Content = [{ 6243 The Mach Interface Generator release-on-success convention dictates 6244functions that follow it to only release arguments passed to them when they 6245return "success" (a ``kern_return_t`` error code that indicates that 6246no errors have occurred). Otherwise the release is performed by the MIG client 6247that called the function. The annotation ``__attribute__((mig_server_routine))`` 6248is applied in order to specify which functions are expected to follow the 6249convention. This allows the Static Analyzer to find bugs caused by violations of 6250that convention. The attribute would normally appear on the forward declaration 6251of the actual server routine in the MIG server header, but it may also be 6252added to arbitrary functions that need to follow the same convention - for 6253example, a user can add them to auxiliary functions called by the server routine 6254that have their return value of type ``kern_return_t`` unconditionally returned 6255from the routine. The attribute can be applied to C++ methods, and in this case 6256it will be automatically applied to overrides if the method is virtual. The 6257attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``. 6258}]; 6259} 6260 6261def MinSizeDocs : Documentation { 6262 let Category = DocCatFunction; 6263 let Content = [{ 6264This function attribute indicates that optimization passes and code generator passes 6265make choices that keep the function code size as small as possible. Optimizations may 6266also sacrifice runtime performance in order to minimize the size of the generated code. 6267 }]; 6268} 6269 6270def MSAllocatorDocs : Documentation { 6271 let Category = DocCatFunction; 6272 let Content = [{ 6273The ``__declspec(allocator)`` attribute is applied to functions that allocate 6274memory, such as operator new in C++. When CodeView debug information is emitted 6275(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to 6276record the code offset of heap allocation call sites in the debug info. It will 6277also record the type being allocated using some local heuristics. The Visual 6278Studio debugger uses this information to `profile memory usage`_. 6279 6280.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage 6281 6282This attribute does not affect optimizations in any way, unlike GCC's 6283``__attribute__((malloc))``. 6284}]; 6285} 6286 6287def CFGuardDocs : Documentation { 6288 let Category = DocCatFunction; 6289 let Content = [{ 6290Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))`` 6291attribute. This directs the compiler to not insert any CFG checks for the entire 6292function. This approach is typically used only sparingly in specific situations 6293where the programmer has manually inserted "CFG-equivalent" protection. The 6294programmer knows that they are calling through some read-only function table 6295whose address is obtained through read-only memory references and for which the 6296index is masked to the function table limit. This approach may also be applied 6297to small wrapper functions that are not inlined and that do nothing more than 6298make a call through a function pointer. Since incorrect usage of this directive 6299can compromise the security of CFG, the programmer must be very careful using 6300the directive. Typically, this usage is limited to very small functions that 6301only call one function. 6302 6303`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>` 6304}]; 6305} 6306 6307def CUDADeviceBuiltinSurfaceTypeDocs : Documentation { 6308 let Category = DocCatType; 6309 let Content = [{ 6310The ``device_builtin_surface_type`` attribute can be applied to a class 6311template when declaring the surface reference. A surface reference variable 6312could be accessed on the host side and, on the device side, might be translated 6313into an internal surface object, which is established through surface bind and 6314unbind runtime APIs. 6315 }]; 6316} 6317 6318def CUDADeviceBuiltinTextureTypeDocs : Documentation { 6319 let Category = DocCatType; 6320 let Content = [{ 6321The ``device_builtin_texture_type`` attribute can be applied to a class 6322template when declaring the texture reference. A texture reference variable 6323could be accessed on the host side and, on the device side, might be translated 6324into an internal texture object, which is established through texture bind and 6325unbind runtime APIs. 6326 }]; 6327} 6328 6329def HIPManagedAttrDocs : Documentation { 6330 let Category = DocCatDecl; 6331 let Content = [{ 6332The ``__managed__`` attribute can be applied to a global variable declaration in HIP. 6333A managed variable is emitted as an undefined global symbol in the device binary and is 6334registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates 6335managed memory and uses it to define the symbol when loading the device binary. 6336A managed variable can be accessed in both device and host code. 6337 }]; 6338} 6339 6340def LifetimeOwnerDocs : Documentation { 6341 let Category = DocCatDecl; 6342 let Content = [{ 6343.. Note:: This attribute is experimental and its effect on analysis is subject to change in 6344 a future version of clang. 6345 6346The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an 6347object of type ``T``: 6348 6349.. code:: 6350 6351 class [[gsl::Owner(int)]] IntOwner { 6352 private: 6353 int value; 6354 public: 6355 int *getInt() { return &value; } 6356 }; 6357 6358The argument ``T`` is optional and is ignored. 6359This attribute may be used by analysis tools and has no effect on code 6360generation. A ``void`` argument means that the class can own any type. 6361 6362See Pointer_ for an example. 6363}]; 6364} 6365 6366def LifetimePointerDocs : Documentation { 6367 let Category = DocCatDecl; 6368 let Content = [{ 6369.. Note:: This attribute is experimental and its effect on analysis is subject to change in 6370 a future version of clang. 6371 6372The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave 6373like pointers to an object of type ``T``: 6374 6375.. code:: 6376 6377 class [[gsl::Pointer(int)]] IntPointer { 6378 private: 6379 int *valuePointer; 6380 public: 6381 int *getInt() { return &valuePointer; } 6382 }; 6383 6384The argument ``T`` is optional and is ignored. 6385This attribute may be used by analysis tools and has no effect on code 6386generation. A ``void`` argument means that the pointer can point to any type. 6387 6388Example: 6389When constructing an instance of a class annotated like this (a Pointer) from 6390an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner), 6391then the analysis will consider the Pointer to point inside the Owner. 6392When the Owner's lifetime ends, it will consider the Pointer to be dangling. 6393 6394.. code-block:: c++ 6395 6396 int f() { 6397 IntPointer P; 6398 if (true) { 6399 IntOwner O(7); 6400 P = IntPointer(O); // P "points into" O 6401 } // P is dangling 6402 return P.get(); // error: Using a dangling Pointer. 6403 } 6404 6405}]; 6406} 6407 6408def ArmBuiltinAliasDocs : Documentation { 6409 let Category = DocCatFunction; 6410 let Content = [{ 6411This attribute is used in the implementation of the ACLE intrinsics. 6412It allows the intrinsic functions to 6413be declared using the names defined in ACLE, and still be recognized 6414as clang builtins equivalent to the underlying name. For example, 6415``arm_mve.h`` declares the function ``vaddq_u32`` with 6416``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``, 6417and similarly, one of the type-overloaded declarations of ``vaddq`` 6418will have the same attribute. This ensures that both functions are 6419recognized as that clang builtin, and in the latter case, the choice 6420of which builtin to identify the function as can be deferred until 6421after overload resolution. 6422 6423This attribute can only be used to set up the aliases for certain Arm 6424intrinsic functions; it is intended for use only inside ``arm_*.h`` 6425and is not a general mechanism for declaring arbitrary aliases for 6426clang builtin functions. 6427 6428In order to avoid duplicating the attribute definitions for similar 6429purpose for other architecture, there is a general form for the 6430attribute `clang_builtin_alias`. 6431 }]; 6432} 6433 6434def NoBuiltinDocs : Documentation { 6435 let Category = DocCatFunction; 6436 let Content = [{ 6437The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag 6438except it is specific to the body of a function. The attribute may also be 6439applied to a virtual function but has no effect on the behavior of overriding 6440functions in a derived class. 6441 6442It accepts one or more strings corresponding to the specific names of the 6443builtins to disable (e.g. "memcpy", "memset"). 6444If the attribute is used without parameters it will disable all buitins at 6445once. 6446 6447.. code-block:: c++ 6448 6449 // The compiler is not allowed to add any builtin to foo's body. 6450 void foo(char* data, size_t count) __attribute__((no_builtin)) { 6451 // The compiler is not allowed to convert the loop into 6452 // `__builtin_memset(data, 0xFE, count);`. 6453 for (size_t i = 0; i < count; ++i) 6454 data[i] = 0xFE; 6455 } 6456 6457 // The compiler is not allowed to add the `memcpy` builtin to bar's body. 6458 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) { 6459 // The compiler is allowed to convert the loop into 6460 // `__builtin_memset(data, 0xFE, count);` but cannot generate any 6461 // `__builtin_memcpy` 6462 for (size_t i = 0; i < count; ++i) 6463 data[i] = 0xFE; 6464 } 6465 }]; 6466} 6467 6468def UsingIfExistsDocs : Documentation { 6469 let Category = DocCatDecl; 6470 let Content = [{ 6471The ``using_if_exists`` attribute applies to a using-declaration. It allows 6472programmers to import a declaration that potentially does not exist, instead 6473deferring any errors to the point of use. For instance: 6474 6475.. code-block:: c++ 6476 6477 namespace empty_namespace {}; 6478 __attribute__((using_if_exists)) 6479 using empty_namespace::does_not_exist; // no error! 6480 6481 does_not_exist x; // error: use of unresolved 'using_if_exists' 6482 6483The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also 6484supported as a clang extension, since ISO C++ doesn't support attributes in this 6485position. If the entity referred to by the using-declaration is found by name 6486lookup, the attribute has no effect. This attribute is useful for libraries 6487(primarily, libc++) that wish to redeclare a set of declarations in another 6488namespace, when the availability of those declarations is difficult or 6489impossible to detect at compile time with the preprocessor. 6490 }]; 6491} 6492 6493def HandleDocs : DocumentationCategory<"Handle Attributes"> { 6494 let Content = [{ 6495Handles are a way to identify resources like files, sockets, and processes. 6496They are more opaque than pointers and widely used in system programming. They 6497have similar risks such as never releasing a resource associated with a handle, 6498attempting to use a handle that was already released, or trying to release a 6499handle twice. Using the annotations below it is possible to make the ownership 6500of the handles clear: whose responsibility is to release them. They can also 6501aid static analysis tools to find bugs. 6502 }]; 6503} 6504 6505def AcquireHandleDocs : Documentation { 6506 let Category = HandleDocs; 6507 let Content = [{ 6508If this annotation is on a function or a function type it is assumed to return 6509a new handle. In case this annotation is on an output parameter, 6510the function is assumed to fill the corresponding argument with a new 6511handle. The attribute requires a string literal argument which used to 6512identify the handle with later uses of ``use_handle`` or 6513``release_handle``. 6514 6515.. code-block:: c++ 6516 6517 // Output arguments from Zircon. 6518 zx_status_t zx_socket_create(uint32_t options, 6519 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0, 6520 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]); 6521 6522 6523 // Returned handle. 6524 [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... ); 6525 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag"))); 6526 }]; 6527} 6528 6529def UseHandleDocs : Documentation { 6530 let Category = HandleDocs; 6531 let Content = [{ 6532A function taking a handle by value might close the handle. If a function 6533parameter is annotated with ``use_handle(tag)`` it is assumed to not to change 6534the state of the handle. It is also assumed to require an open handle to work with. 6535The attribute requires a string literal argument to identify the handle being used. 6536 6537.. code-block:: c++ 6538 6539 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]], 6540 zx_time_t deadline, 6541 zx_port_packet_t* packet); 6542 }]; 6543} 6544 6545def ReleaseHandleDocs : Documentation { 6546 let Category = HandleDocs; 6547 let Content = [{ 6548If a function parameter is annotated with ``release_handle(tag)`` it is assumed to 6549close the handle. It is also assumed to require an open handle to work with. The 6550attribute requires a string literal argument to identify the handle being released. 6551 6552.. code-block:: c++ 6553 6554 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]); 6555 }]; 6556} 6557 6558def UnsafeBufferUsageDocs : Documentation { 6559 let Category = DocCatFunction; 6560 let Content = [{ 6561The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions 6562that need to be avoided as they are prone to buffer overflows. It is designed to 6563work together with the off-by-default compiler warning ``-Wunsafe-buffer-usage`` 6564to help codebases transition away from raw pointer based buffer management, 6565in favor of safer abstractions such as C++20 ``std::span``. The attribute causes 6566``-Wunsafe-buffer-usage`` to warn on every use of the function, and it may 6567enable ``-Wunsafe-buffer-usage`` to emit automatic fix-it hints 6568which would help the user replace such unsafe functions with safe 6569alternatives, though the attribute can be used even when the fix can't be automated. 6570 6571The attribute does not suppress ``-Wunsafe-buffer-usage`` inside the function 6572to which it is attached. These warnings still need to be addressed. 6573 6574The attribute is warranted even if the only way a function can overflow 6575the buffer is by violating the function's preconditions. For example, it 6576would make sense to put the attribute on function ``foo()`` below because 6577passing an incorrect size parameter would cause a buffer overflow: 6578 6579.. code-block:: c++ 6580 6581 [[clang::unsafe_buffer_usage]] 6582 void foo(int *buf, size_t size) { 6583 for (size_t i = 0; i < size; ++i) { 6584 buf[i] = i; 6585 } 6586 } 6587 6588The attribute is NOT warranted when the function uses safe abstractions, 6589assuming that these abstractions weren't misused outside the function. 6590For example, function ``bar()`` below doesn't need the attribute, 6591because assuming that the container ``buf`` is well-formed (has size that 6592fits the original buffer it refers to), overflow cannot occur: 6593 6594.. code-block:: c++ 6595 6596 void bar(std::span<int> buf) { 6597 for (size_t i = 0; i < buf.size(); ++i) { 6598 buf[i] = i; 6599 } 6600 } 6601 6602In this case function ``bar()`` enables the user to keep the buffer 6603"containerized" in a span for as long as possible. On the other hand, 6604Function ``foo()`` in the previous example may have internal 6605consistency, but by accepting a raw buffer it requires the user to unwrap 6606their span, which is undesirable according to the programming model 6607behind ``-Wunsafe-buffer-usage``. 6608 6609The attribute is warranted when a function accepts a raw buffer only to 6610immediately put it into a span: 6611 6612.. code-block:: c++ 6613 6614 [[clang::unsafe_buffer_usage]] 6615 void baz(int *buf, size_t size) { 6616 std::span<int> sp{ buf, size }; 6617 for (size_t i = 0; i < sp.size(); ++i) { 6618 sp[i] = i; 6619 } 6620 } 6621 6622In this case ``baz()`` does not contain any unsafe operations, but the awkward 6623parameter type causes the caller to unwrap the span unnecessarily. 6624Note that regardless of the attribute, code inside ``baz()`` isn't flagged 6625by ``-Wunsafe-buffer-usage`` as unsafe. It is definitely undesirable, 6626but if ``baz()`` is on an API surface, there is no way to improve it 6627to make it as safe as ``bar()`` without breaking the source and binary 6628compatibility with existing users of the function. In such cases 6629the proper solution would be to create a different function (possibly 6630an overload of ``baz()``) that accepts a safe container like ``bar()``, 6631and then use the attribute on the original ``baz()`` to help the users 6632update their code to use the new function. 6633 }]; 6634} 6635 6636def DiagnoseAsBuiltinDocs : Documentation { 6637 let Category = DocCatFunction; 6638 let Content = [{ 6639The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to 6640be applied to the declared function as if it were the function specified by the 6641attribute. The builtin function whose diagnostics are to be mimicked should be 6642given. In addition, the order in which arguments should be applied must also 6643be given. 6644 6645For example, the attribute can be used as follows. 6646 6647.. code-block:: c 6648 6649 __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1))) 6650 void *mymemset(int n, int c, void *s) { 6651 // ... 6652 } 6653 6654This indicates that calls to ``mymemset`` should be diagnosed as if they were 6655calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the 6656order in which arguments of ``mymemset`` should be applied to 6657``__builtin_memset``. The third argument should be applied first, then the 6658second, and then the first. Thus (when Fortify warnings are enabled) the call 6659``mymemset(n, c, s)`` will diagnose overflows as if it were the call 6660``__builtin_memset(s, c, n)``. 6661 6662For variadic functions, the variadic arguments must come in the same order as 6663they would to the builtin function, after all normal arguments. For instance, 6664to diagnose a new function as if it were `sscanf`, we can use the attribute as 6665follows. 6666 6667.. code-block:: c 6668 6669 __attribute__((diagnose_as_builtin(sscanf, 1, 2))) 6670 int mysscanf(const char *str, const char *format, ...) { 6671 // ... 6672 } 6673 6674Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as 6675if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`. 6676 6677This attribute cannot be applied to non-static member functions. 6678}]; 6679} 6680 6681def ArmSveVectorBitsDocs : Documentation { 6682 let Category = DocCatType; 6683 let Content = [{ 6684The ``arm_sve_vector_bits(N)`` attribute is defined by the Arm C Language 6685Extensions (ACLE) for SVE. It is used to define fixed-length (VLST) variants of 6686sizeless types (VLAT). 6687 6688For example: 6689 6690.. code-block:: c 6691 6692 #include <arm_sve.h> 6693 6694 #if __ARM_FEATURE_SVE_BITS==512 6695 typedef svint32_t fixed_svint32_t __attribute__((arm_sve_vector_bits(512))); 6696 #endif 6697 6698Creates a type ``fixed_svint32_t`` that is a fixed-length variant of 6699``svint32_t`` that contains exactly 512-bits. Unlike ``svint32_t``, this type 6700can be used in globals, structs, unions, and arrays, all of which are 6701unsupported for sizeless types. 6702 6703The attribute can be attached to a single SVE vector (such as ``svint32_t``) or 6704to the SVE predicate type ``svbool_t``, this excludes tuple types such as 6705``svint32x4_t``. The behavior of the attribute is undefined unless 6706``N==__ARM_FEATURE_SVE_BITS``, the implementation defined feature macro that is 6707enabled under the ``-msve-vector-bits`` flag. 6708 6709For more information See `Arm C Language Extensions for SVE 6710<https://developer.arm.com/documentation/100987/latest>`_ for more information. 6711}]; 6712} 6713 6714def ArmMveStrictPolymorphismDocs : Documentation { 6715 let Category = DocCatType; 6716 let Content = [{ 6717This attribute is used in the implementation of the ACLE intrinsics for the Arm 6718MVE instruction set. It is used to define the vector types used by the MVE 6719intrinsics. 6720 6721Its effect is to modify the behavior of a vector type with respect to function 6722overloading. If a candidate function for overload resolution has a parameter 6723type with this attribute, then the selection of that candidate function will be 6724disallowed if the actual argument can only be converted via a lax vector 6725conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic 6726intrinsics. 6727 6728.. code-block:: c++ 6729 6730 void overloaded(uint16x8_t vector, uint16_t scalar); 6731 void overloaded(int32x4_t vector, int32_t scalar); 6732 uint16x8_t myVector; 6733 uint16_t myScalar; 6734 6735 // myScalar is promoted to int32_t as a side effect of the addition, 6736 // so if lax vector conversions are considered for myVector, then 6737 // the two overloads are equally good (one argument conversion 6738 // each). But if the vector has the __clang_arm_mve_strict_polymorphism 6739 // attribute, only the uint16x8_t,uint16_t overload will match. 6740 overloaded(myVector, myScalar + 1); 6741 6742However, this attribute does not prohibit lax vector conversions in contexts 6743other than overloading. 6744 6745.. code-block:: c++ 6746 6747 uint16x8_t function(); 6748 6749 // This is still permitted with lax vector conversion enabled, even 6750 // if the vector types have __clang_arm_mve_strict_polymorphism 6751 int32x4_t result = function(); 6752 6753 }]; 6754} 6755 6756def ArmCmseNSCallDocs : Documentation { 6757 let Category = DocCatType; 6758 let Content = [{ 6759This attribute declares a non-secure function type. When compiling for secure 6760state, a call to such a function would switch from secure to non-secure state. 6761All non-secure function calls must happen only through a function pointer, and 6762a non-secure function type should only be used as a base type of a pointer. 6763See `ARMv8-M Security Extensions: Requirements on Development 6764Tools - Engineering Specification Documentation 6765<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information. 6766 }]; 6767} 6768 6769def ArmCmseNSEntryDocs : Documentation { 6770 let Category = DocCatFunction; 6771 let Content = [{ 6772This attribute declares a function that can be called from non-secure state, or 6773from secure state. Entering from and returning to non-secure state would switch 6774to and from secure state, respectively, and prevent flow of information 6775to non-secure state, except via return values. See `ARMv8-M Security Extensions: 6776Requirements on Development Tools - Engineering Specification Documentation 6777<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information. 6778 }]; 6779} 6780 6781def DocCatArmSmeAttributes : DocumentationCategory<"AArch64 SME Attributes"> { 6782 let Content = [{ 6783Clang supports a number of AArch64-specific attributes to manage state 6784added by the Scalable Matrix Extension (SME). This state includes the 6785runtime mode that the processor is in (e.g. non-streaming or streaming) 6786as well as the state of the ``ZA`` Matrix Storage. 6787 6788The attributes come in the form of type- and declaration attributes: 6789 6790* The SME declaration attributes can appear anywhere that a standard 6791 ``[[...]]`` declaration attribute can appear. 6792 6793* The SME type attributes apply only to prototyped functions and can appear 6794 anywhere that a standard ``[[...]]`` type attribute can appear. The SME 6795 type attributes do not apply to functions having a K&R-style 6796 unprototyped function type. 6797 6798See `Arm C Language Extensions <https://github.com/ARM-software/acle>`_ 6799for more details about the features related to the SME extension. 6800 6801See `Procedure Call Standard for the Arm® 64-bit Architecture (AArch64) 6802<https://github.com/ARM-software/abi-aa>`_ for more details about 6803streaming-interface functions and shared/private-ZA interface functions. 6804 }]; 6805} 6806 6807def ArmSmeStreamingDocs : Documentation { 6808 let Category = DocCatArmSmeAttributes; 6809 let Content = [{ 6810The ``__arm_streaming`` keyword applies to prototyped function types and specifies 6811that the function has a "streaming interface". This means that: 6812 6813* the function requires that the processor implements the Scalable Matrix 6814 Extension (SME). 6815 6816* the function must be entered in streaming mode (that is, with PSTATE.SM 6817 set to 1) 6818 6819* the function must return in streaming mode 6820 6821Clang manages PSTATE.SM automatically; it is not the source code's 6822responsibility to do this. For example, if a non-streaming 6823function calls an ``__arm_streaming`` function, Clang generates code 6824that switches into streaming mode before calling the function and 6825switches back to non-streaming mode on return. 6826 }]; 6827} 6828 6829def ArmSmeStreamingCompatibleDocs : Documentation { 6830 let Category = DocCatArmSmeAttributes; 6831 let Content = [{ 6832The ``__arm_streaming_compatible`` keyword applies to prototyped function types and 6833specifies that the function has a "streaming compatible interface". This 6834means that: 6835 6836* the function may be entered in either non-streaming mode (PSTATE.SM=0) or 6837 in streaming mode (PSTATE.SM=1). 6838 6839* the function must return in the same mode as it was entered. 6840 6841* the code executed in the function is compatible with either mode. 6842 6843Clang manages PSTATE.SM automatically; it is not the source code's 6844responsibility to do this. Clang will ensure that the generated code in 6845streaming-compatible functions is valid in either mode (PSTATE.SM=0 or 6846PSTATE.SM=1). For example, if an ``__arm_streaming_compatible`` function calls a 6847non-streaming function, Clang generates code to temporarily switch out of streaming 6848mode before calling the function and switch back to streaming-mode on return if 6849``PSTATE.SM`` is ``1`` on entry of the caller. If ``PSTATE.SM`` is ``0`` on 6850entry to the ``__arm_streaming_compatible`` function, the call will be executed 6851without changing modes. 6852 }]; 6853} 6854 6855def ArmSmeSharedZADocs : Documentation { 6856 let Category = DocCatArmSmeAttributes; 6857 let Content = [{ 6858The ``__arm_shared_za`` keyword applies to prototyped function types and specifies 6859that the function shares SME's matrix storage (ZA) with its caller. This 6860means that: 6861 6862* the function requires that the processor implements the Scalable Matrix 6863 Extension (SME). 6864 6865* the function enters with ZA in an active state. 6866 6867* the function returns with ZA in an active state. 6868 }]; 6869} 6870 6871def ArmSmePreservesZADocs : Documentation { 6872 let Category = DocCatArmSmeAttributes; 6873 let Content = [{ 6874The ``__arm_preserves_za`` keyword applies to prototyped function types and 6875specifies that the function does not modify ZA state. 6876 }]; 6877} 6878 6879 6880def ArmSmeLocallyStreamingDocs : Documentation { 6881 let Category = DocCatArmSmeAttributes; 6882 let Content = [{ 6883The ``__arm_locally_streaming`` keyword applies to function declarations 6884and specifies that all the statements in the function are executed in 6885streaming mode. This means that: 6886 6887* the function requires that the target processor implements the Scalable Matrix 6888 Extension (SME). 6889 6890* the program automatically puts the machine into streaming mode before 6891 executing the statements and automatically restores the previous mode 6892 afterwards. 6893 6894Clang manages PSTATE.SM automatically; it is not the source code's 6895responsibility to do this. For example, Clang will emit code to enable 6896streaming mode at the start of the function, and disable streaming mode 6897at the end of the function. 6898 }]; 6899} 6900 6901def ArmSmeNewZADocs : Documentation { 6902 let Category = DocCatArmSmeAttributes; 6903 let Content = [{ 6904The ``__arm_new_za`` keyword applies to function declarations and specifies 6905that the function will be set up with a fresh ZA context. 6906 6907This means that: 6908 6909* the function requires that the target processor implements the Scalable Matrix 6910 Extension (SME). 6911 6912* the function will commit any lazily saved ZA data. 6913 6914* the function will create a new ZA context and enable PSTATE.ZA. 6915 6916* the function will disable PSTATE.ZA (by setting it to 0) before returning. 6917 6918For ``__arm_new_za`` functions Clang will set up the ZA context automatically 6919on entry to the function, and disable it before returning. For example, if ZA is 6920in a dormant state Clang will generate the code to commit a lazy-save and set up 6921a new ZA state before executing user code. 6922 }]; 6923} 6924 6925def AlwaysInlineDocs : Documentation { 6926 let Category = DocCatFunction; 6927 let Content = [{ 6928Inlining heuristics are disabled and inlining is always attempted regardless of 6929optimization level. 6930 6931``[[clang::always_inline]]`` spelling can be used as a statement attribute; other 6932spellings of the attribute are not supported on statements. If a statement is 6933marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts 6934to inline those calls. 6935 6936.. code-block:: c 6937 6938 int example(void) { 6939 int i; 6940 [[clang::always_inline]] foo(); // attempts to inline foo 6941 [[clang::always_inline]] i = bar(); // attempts to inline bar 6942 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything 6943 } 6944 6945A declaration statement, which is a statement, is not a statement that can have an 6946attribute associated with it (the attribute applies to the declaration, not the 6947statement in that case). So this use case will not work: 6948 6949.. code-block:: c 6950 6951 int example(void) { 6952 [[clang::always_inline]] int i = bar(); 6953 return i; 6954 } 6955 6956This attribute does not guarantee that inline substitution actually occurs. 6957 6958<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level 6959has no effect; other optimization levels may only partially inline and result in a 6960diagnostic.</ins> 6961 6962See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function 6963Attribute docs`_, and `the GCC Inline docs`_. 6964 6965.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp 6966.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html 6967.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html 6968 6969}]; 6970 let Heading = "always_inline, __force_inline"; 6971} 6972 6973def EnforceTCBDocs : Documentation { 6974 let Category = DocCatFunction; 6975 let Content = [{ 6976 The ``enforce_tcb`` attribute can be placed on functions to enforce that a 6977 trusted compute base (TCB) does not call out of the TCB. This generates a 6978 warning every time a function not marked with an ``enforce_tcb`` attribute is 6979 called from a function with the ``enforce_tcb`` attribute. A function may be a 6980 part of multiple TCBs. Invocations through function pointers are currently 6981 not checked. Builtins are considered to a part of every TCB. 6982 6983 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name`` 6984 }]; 6985} 6986 6987def EnforceTCBLeafDocs : Documentation { 6988 let Category = DocCatFunction; 6989 let Content = [{ 6990 The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by 6991 ``enforce_tcb`` for the marked function to be in the named TCB but does not 6992 continue to check the functions called from within the leaf function. 6993 6994 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name`` 6995 }]; 6996} 6997 6998def ErrorAttrDocs : Documentation { 6999 let Category = DocCatFunction; 7000 let Heading = "error, warning"; 7001 let Content = [{ 7002The ``error`` and ``warning`` function attributes can be used to specify a 7003custom diagnostic to be emitted when a call to such a function is not 7004eliminated via optimizations. This can be used to create compile time 7005assertions that depend on optimizations, while providing diagnostics 7006pointing to precise locations of the call site in the source. 7007 7008.. code-block:: c++ 7009 7010 __attribute__((warning("oh no"))) void dontcall(); 7011 void foo() { 7012 if (someCompileTimeAssertionThatsTrue) 7013 dontcall(); // Warning 7014 7015 dontcall(); // Warning 7016 7017 if (someCompileTimeAssertionThatsFalse) 7018 dontcall(); // No Warning 7019 sizeof(dontcall()); // No Warning 7020 } 7021 }]; 7022} 7023 7024def ZeroCallUsedRegsDocs : Documentation { 7025 let Category = DocCatFunction; 7026 let Content = [{ 7027This attribute, when attached to a function, causes the compiler to zero a 7028subset of all call-used registers before the function returns. It's used to 7029increase program security by either mitigating `Return-Oriented Programming`_ 7030(ROP) attacks or preventing information leakage through registers. 7031 7032The term "call-used" means registers which are not guaranteed to be preserved 7033unchanged for the caller by the current calling convention. This could also be 7034described as "caller-saved" or "not callee-saved". 7035 7036The `choice` parameters gives the programmer flexibility to choose the subset 7037of the call-used registers to be zeroed: 7038 7039- ``skip`` doesn't zero any call-used registers. This choice overrides any 7040 command-line arguments. 7041- ``used`` only zeros call-used registers used in the function. By ``used``, we 7042 mean a register whose contents have been set or referenced in the function. 7043- ``used-gpr`` only zeros call-used GPR registers used in the function. 7044- ``used-arg`` only zeros call-used registers used to pass arguments to the 7045 function. 7046- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to 7047 the function. 7048- ``all`` zeros all call-used registers. 7049- ``all-gpr`` zeros all call-used GPR registers. 7050- ``all-arg`` zeros all call-used registers used to pass arguments to the 7051 function. 7052- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to 7053 the function. 7054 7055The default for the attribute is controlled by the ``-fzero-call-used-regs`` 7056flag. 7057 7058.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming 7059 }]; 7060} 7061 7062def NumThreadsDocs : Documentation { 7063 let Category = DocCatFunction; 7064 let Content = [{ 7065The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts 7066are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute 7067dictate the thread id. Total number of threads executed is ``X * Y * Z``. 7068 7069The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads 7070 }]; 7071} 7072 7073def HLSLSV_ShaderTypeAttrDocs : Documentation { 7074 let Category = DocCatFunction; 7075 let Content = [{ 7076The ``shader`` type attribute applies to HLSL shader entry functions to 7077identify the shader type for the entry function. 7078The syntax is: 7079 7080.. code-block:: text 7081 7082 ``[shader(string-literal)]`` 7083 7084where the string literal is one of: "pixel", "vertex", "geometry", "hull", 7085"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit", 7086"miss", "callable", "mesh", "amplification". Normally the shader type is set 7087by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a 7088library target like ``lib_6_3``, the shader type attribute can help the 7089compiler to identify the shader type. It is mostly used by Raytracing shaders 7090where shaders must be compiled into a library and linked at runtime. 7091 }]; 7092} 7093 7094def ClangRandomizeLayoutDocs : Documentation { 7095 let Category = DocCatDecl; 7096 let Heading = "randomize_layout, no_randomize_layout"; 7097 let Content = [{ 7098The attribute ``randomize_layout``, when attached to a C structure, selects it 7099for structure layout field randomization; a compile-time hardening technique. A 7100"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag. 7101For example: 7102 7103.. code-block:: bash 7104 7105 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'` 7106 make ... CFLAGS="-frandomize-layout-seed=$SEED" ... 7107 7108You can also supply the seed in a file with ``-frandomize-layout-seed-file=``. 7109For example: 7110 7111.. code-block:: bash 7112 7113 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt 7114 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ... 7115 7116The randomization is deterministic based for a given seed, so the entire 7117program should be compiled with the same seed, but keep the seed safe 7118otherwise. 7119 7120The attribute ``no_randomize_layout``, when attached to a C structure, 7121instructs the compiler that this structure should not have its field layout 7122randomized. 7123 }]; 7124} 7125 7126def HLSLSV_GroupIndexDocs : Documentation { 7127 let Category = DocCatFunction; 7128 let Content = [{ 7129The ``SV_GroupIndex`` semantic, when applied to an input parameter, specifies a 7130data binding to map the group index to the specified parameter. This attribute 7131is only supported in compute shaders. 7132 7133The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex 7134 }]; 7135} 7136 7137def HLSLResourceBindingDocs : Documentation { 7138 let Category = DocCatFunction; 7139 let Content = [{ 7140The resource binding attribute sets the virtual register and logical register space for a resource. 7141Attribute spelling in HLSL is: ``register(slot [, space])``. 7142``slot`` takes the format ``[type][number]``, 7143where ``type`` is a single character specifying the resource type and ``number`` is the virtual register number. 7144 7145Register types are: 7146t for shader resource views (SRV), 7147s for samplers, 7148u for unordered access views (UAV), 7149b for constant buffer views (CBV). 7150 7151Register space is specified in the format ``space[number]`` and defaults to ``space0`` if omitted. 7152Here're resource binding examples with and without space: 7153.. code-block:: c++ 7154 7155 RWBuffer<float> Uav : register(u3, space1); 7156 Buffer<float> Buf : register(t1); 7157 7158The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl 7159 }]; 7160} 7161 7162def HLSLSV_DispatchThreadIDDocs : Documentation { 7163 let Category = DocCatFunction; 7164 let Content = [{ 7165The ``SV_DispatchThreadID`` semantic, when applied to an input parameter, 7166specifies a data binding to map the global thread offset within the Dispatch 7167call (per dimension of the group) to the specified parameter. 7168When applied to a field of a struct, the data binding is specified to the field 7169when the struct is used as a parameter type. 7170The semantic on the field is ignored when not used as a parameter. 7171This attribute is only supported in compute shaders. 7172 7173The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-dispatchthreadid 7174 }]; 7175} 7176 7177def HLSLGroupSharedAddressSpaceDocs : Documentation { 7178 let Category = DocCatVariable; 7179 let Content = [{ 7180HLSL enables threads of a compute shader to exchange values via shared memory. 7181HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync, 7182and so on to ensure the correct ordering of reads and writes to shared memory 7183in the shader and to avoid data races. 7184Here's an example to declare a groupshared variable. 7185.. code-block:: c++ 7186 7187 groupshared GSData data[5*5*1]; 7188 7189The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared 7190 }]; 7191} 7192 7193def HLSLParamQualifierDocs : Documentation { 7194 let Category = DocCatVariable; 7195 let Heading = "HLSL Parameter Modifiers"; 7196 let Content = [{ 7197HLSL function parameters are passed by value. Parameter declarations support 7198three qualifiers to denote parameter passing behavior. The three qualifiers are 7199`in`, `out` and `inout`. 7200 7201Parameters annotated with `in` or with no annotation are passed by value from 7202the caller to the callee. 7203 7204Parameters annotated with `out` are written to the argument after the callee 7205returns (Note: arguments values passed into `out` parameters *are not* copied 7206into the callee). 7207 7208Parameters annotated with `inout` are copied into the callee via a temporary, 7209and copied back to the argument after the callee returns. 7210 }]; 7211} 7212 7213def AnnotateTypeDocs : Documentation { 7214 let Category = DocCatType; 7215 let Heading = "annotate_type"; 7216 let Content = [{ 7217This attribute is used to add annotations to types, typically for use by static 7218analysis tools that are not integrated into the core Clang compiler (e.g., 7219Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the 7220`annotate` attribute, which serves the same purpose, but for declarations. 7221 7222The attribute takes a mandatory string literal argument specifying the 7223annotation category and an arbitrary number of optional arguments that provide 7224additional information specific to the annotation category. The optional 7225arguments must be constant expressions of arbitrary type. 7226 7227For example: 7228 7229.. code-block:: c++ 7230 7231 int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *); 7232 7233The attribute does not have any effect on the semantics of the type system, 7234neither type checking rules, nor runtime semantics. In particular: 7235 7236- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types 7237 ``T``. 7238 7239- It is not permissible for overloaded functions or template specializations 7240 to differ merely by an ``annotate_type`` attribute. 7241 7242- The presence of an ``annotate_type`` attribute will not affect name 7243 mangling. 7244 }]; 7245} 7246 7247def WeakDocs : Documentation { 7248 let Category = DocCatDecl; 7249 let Content = [{ 7250 7251In supported output formats the ``weak`` attribute can be used to 7252specify that a variable or function should be emitted as a symbol with 7253``weak`` (if a definition) or ``extern_weak`` (if a declaration of an 7254external symbol) `linkage 7255<https://llvm.org/docs/LangRef.html#linkage-types>`_. 7256 7257If there is a non-weak definition of the symbol the linker will select 7258that over the weak. They must have same type and alignment (variables 7259must also have the same size), but may have a different value. 7260 7261If there are multiple weak definitions of same symbol, but no non-weak 7262definition, they should have same type, size, alignment and value, the 7263linker will select one of them (see also selectany_ attribute). 7264 7265If the ``weak`` attribute is applied to a ``const`` qualified variable 7266definition that variable is no longer consider a compiletime constant 7267as its value can change during linking (or dynamic linking). This 7268means that it can e.g no longer be part of an initializer expression. 7269 7270.. code-block:: c 7271 7272 const int ANSWER __attribute__ ((weak)) = 42; 7273 7274 /* This function may be replaced link-time */ 7275 __attribute__ ((weak)) void debug_log(const char *msg) 7276 { 7277 fprintf(stderr, "DEBUG: %s\n", msg); 7278 } 7279 7280 int main(int argc, const char **argv) 7281 { 7282 debug_log ("Starting up..."); 7283 7284 /* This may print something else than "6 * 7 = 42", 7285 if there is a non-weak definition of "ANSWER" in 7286 an object linked in */ 7287 printf("6 * 7 = %d\n", ANSWER); 7288 7289 return 0; 7290 } 7291 7292If an external declaration is marked weak and that symbol does not 7293exist during linking (possibly dynamic) the address of the symbol will 7294evaluate to NULL. 7295 7296.. code-block:: c 7297 7298 void may_not_exist(void) __attribute__ ((weak)); 7299 7300 int main(int argc, const char **argv) 7301 { 7302 if (may_not_exist) { 7303 may_not_exist(); 7304 } else { 7305 printf("Function did not exist\n"); 7306 } 7307 return 0; 7308 } 7309 }]; 7310} 7311 7312def FunctionReturnThunksDocs : Documentation { 7313 let Category = DocCatFunction; 7314 let Content = [{ 7315The attribute ``function_return`` can replace return instructions with jumps to 7316target-specific symbols. This attribute supports 2 possible values, 7317corresponding to the values supported by the ``-mfunction-return=`` command 7318line flag: 7319 7320* ``__attribute__((function_return("keep")))`` to disable related transforms. 7321 This is useful for undoing global setting from ``-mfunction-return=`` locally 7322 for individual functions. 7323* ``__attribute__((function_return("thunk-extern")))`` to replace returns with 7324 jumps, while NOT emitting the thunk. 7325 7326The values ``thunk`` and ``thunk-inline`` from GCC are not supported. 7327 7328The symbol used for ``thunk-extern`` is target specific: 7329* X86: ``__x86_return_thunk`` 7330 7331As such, this function attribute is currently only supported on X86 targets. 7332 }]; 7333} 7334 7335def ReadOnlyPlacementDocs : Documentation { 7336 let Category = DocCatType; 7337 let Content = [{This attribute is attached to a structure, class or union declaration. 7338 When attached to a record declaration/definition, it checks if all instances 7339 of this type can be placed in the read-only data segment of the program. If it 7340 finds an instance that can not be placed in a read-only segment, the compiler 7341 emits a warning at the source location where the type was used. 7342 7343 Examples: 7344 * ``struct __attribute__((enforce_read_only_placement)) Foo;`` 7345 * ``struct __attribute__((enforce_read_only_placement)) Bar { ... };`` 7346 7347 Both ``Foo`` and ``Bar`` types have the ``enforce_read_only_placement`` attribute. 7348 7349 The goal of introducing this attribute is to assist developers with writing secure 7350 code. A ``const``-qualified global is generally placed in the read-only section 7351 of the memory that has additional run time protection from malicious writes. By 7352 attaching this attribute to a declaration, the developer can express the intent 7353 to place all instances of the annotated type in the read-only program memory. 7354 7355 Note 1: The attribute doesn't guarantee that the object will be placed in the 7356 read-only data segment as it does not instruct the compiler to ensure such 7357 a placement. It emits a warning if something in the code can be proven to prevent 7358 an instance from being placed in the read-only data segment. 7359 7360 Note 2: Currently, clang only checks if all global declarations of a given type 'T' 7361 are ``const``-qualified. The following conditions would also prevent the data to be 7362 put into read only segment, but the corresponding warnings are not yet implemented. 7363 7364 1. An instance of type ``T`` is allocated on the heap/stack. 7365 2. Type ``T`` defines/inherits a mutable field. 7366 3. Type ``T`` defines/inherits non-constexpr constructor(s) for initialization. 7367 4. A field of type ``T`` is defined by type ``Q``, which does not bear the 7368 ``enforce_read_only_placement`` attribute. 7369 5. A type ``Q`` inherits from type ``T`` and it does not have the 7370 ``enforce_read_only_placement`` attribute. 7371 }]; 7372} 7373 7374def WebAssemblyFuncrefDocs : Documentation { 7375 let Category = DocCatType; 7376 let Content = [{ 7377Clang supports the ``__funcref`` attribute for the WebAssembly target. 7378This attribute may be attached to a function pointer type, where it modifies 7379its underlying representation to be a WebAssembly ``funcref``. 7380 }]; 7381} 7382 7383def PreferredTypeDocumentation : Documentation { 7384 let Category = DocCatField; 7385 let Content = [{ 7386This attribute allows adjusting the type of a bit-field in debug information. 7387This can be helpful when a bit-field is intended to store an enumeration value, 7388but has to be specified as having the enumeration's underlying type in order to 7389facilitate compiler optimizations or bit-field packing behavior. Normally, the 7390underlying type is what is emitted in debug information, which can make it hard 7391for debuggers to know to map a bit-field's value back to a particular enumeration. 7392 7393.. code-block:: c++ 7394 7395 enum Colors { Red, Green, Blue }; 7396 7397 struct S { 7398 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2; 7399 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1; 7400 } s = { Green, false }; 7401 7402Without the attribute, a debugger is likely to display the value ``1`` for ``ColorVal`` 7403and ``0`` for ``UseAlternateColorSpace``. With the attribute, the debugger may now 7404display ``Green`` and ``false`` instead. 7405 7406This can be used to map a bit-field to an arbitrary type that isn't integral 7407or an enumeration type. For example: 7408 7409.. code-block:: c++ 7410 7411 struct A { 7412 short a1; 7413 short a2; 7414 }; 7415 7416 struct B { 7417 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C; 7418 }; 7419 7420will associate the type ``A`` with the ``b1`` bit-field and is intended to display 7421something like this in the debugger: 7422 7423.. code-block:: text 7424 7425 Process 2755547 stopped 7426 * thread #1, name = 'test-preferred-', stop reason = step in 7427 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14 7428 10 int main() 7429 11 { 7430 12 B b; 7431 -> 13 return b.b1; 7432 14 } 7433 (lldb) v -T 7434 (B) b = { 7435 (A:32) b1 = { 7436 (short) a1 = 12 7437 (short) a2 = 15 7438 } 7439 } 7440 7441Note that debuggers may not be able to handle more complex mappings, and so 7442this usage is debugger-dependent. 7443 }]; 7444} 7445 7446def CleanupDocs : Documentation { 7447 let Category = DocCatVariable; 7448 let Content = [{ 7449This attribute allows a function to be run when a local variable goes out of 7450scope. The attribute takes the identifier of a function with a parameter type 7451that is a pointer to the type with the attribute. 7452 7453.. code-block:: c 7454 7455 static void foo (int *) { ... } 7456 static void bar (int *) { ... } 7457 void baz (void) { 7458 int x __attribute__((cleanup(foo))); 7459 { 7460 int y __attribute__((cleanup(bar))); 7461 } 7462 } 7463 7464The above example will result in a call to ``bar`` being passed the address of 7465`y`` when ``y`` goes out of scope, then a call to ``foo`` being passed the 7466address of ``x`` when ``x`` goes out of scope. If two or more variables share 7467the same scope, their ``cleanup`` callbacks are invoked in the reverse order 7468the variables were declared in. It is not possible to check the return value 7469(if any) of these ``cleanup`` callback functions. 7470}]; 7471} 7472 7473def CtorDtorDocs : Documentation { 7474 let Category = DocCatFunction; 7475 let Content = [{ 7476The ``constructor`` attribute causes the function to be called before entering 7477``main()``, and the ``destructor`` attribute causes the function to be called 7478after returning from ``main()`` or when the ``exit()`` function has been 7479called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function 7480marked ``destructor`` from being called. 7481 7482The constructor or destructor function should not accept any arguments and its 7483return type should be ``void``. 7484 7485The attributes accept an optional argument used to specify the priority order 7486in which to execute constructor and destructor functions. The priority is 7487given as an integer constant expression between 101 and 65535 (inclusive). 7488Priorities outside of that range are reserved for use by the implementation. A 7489lower value indicates a higher priority of initialization. Note that only the 7490relative ordering of values is important. For example: 7491 7492.. code-block:: c++ 7493 7494 __attribute__((constructor(200))) void foo(void); 7495 __attribute__((constructor(101))) void bar(void); 7496 7497``bar()`` will be called before ``foo()``, and both will be called before 7498``main()``. If no argument is given to the ``constructor`` or ``destructor`` 7499attribute, they default to the value ``65535``. 7500}]; 7501} 7502 7503def CoroOnlyDestroyWhenCompleteDocs : Documentation { 7504 let Category = DocCatDecl; 7505 let Content = [{ 7506The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines 7507whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has 7508reached the final suspend point. 7509 7510This is helpful for the optimizers to reduce the size of the destroy function for the coroutines. 7511 7512For example, 7513 7514.. code-block:: c++ 7515 7516 A foo() { 7517 dtor d; 7518 co_await something(); 7519 dtor d1; 7520 co_await something(); 7521 dtor d2; 7522 co_return 43; 7523 } 7524 7525The compiler may generate the following pseudocode: 7526 7527.. code-block:: c++ 7528 7529 void foo.destroy(foo.Frame *frame) { 7530 switch(frame->suspend_index()) { 7531 case 1: 7532 frame->d.~dtor(); 7533 break; 7534 case 2: 7535 frame->d.~dtor(); 7536 frame->d1.~dtor(); 7537 break; 7538 case 3: 7539 frame->d.~dtor(); 7540 frame->d1.~dtor(); 7541 frame->d2.~dtor(); 7542 break; 7543 default: // coroutine completed or haven't started 7544 break; 7545 } 7546 7547 frame->promise.~promise_type(); 7548 delete frame; 7549 } 7550 7551The `foo.destroy()` function's purpose is to release all of the resources 7552initialized for the coroutine when it is destroyed in a suspended state. 7553However, if the coroutine is only ever destroyed at the final suspend state, 7554the rest of the conditions are superfluous. 7555 7556The user can use the `coro_only_destroy_when_complete` attributo suppress 7557generation of the other destruction cases, optimizing the above `foo.destroy` to: 7558 7559.. code-block:: c++ 7560 7561 void foo.destroy(foo.Frame *frame) { 7562 frame->promise.~promise_type(); 7563 delete frame; 7564 } 7565 7566 }]; 7567} 7568 7569def CoroReturnTypeAndWrapperDoc : Documentation { 7570 let Category = DocCatDecl; 7571 let Content = [{ 7572The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize 7573coroutines from the function signatures. 7574 7575The ``coro_return_type`` attribute should be marked on a C++ class to mark it as 7576a **coroutine return type (CRT)**. 7577 7578A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R`` 7579is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it 7580(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type). 7581 7582If the return type of a function is a ``CRT`` then the function must be a coroutine. 7583Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT`` 7584if the function is marked with ``[[clang::coro_wrapper]]``. 7585 7586The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as 7587a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``, 7588is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``. 7589 7590Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked 7591with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error. 7592 7593From a language perspective, it is not possible to differentiate between a coroutine and a 7594function returning a CRT by merely looking at the function signature. 7595 7596Coroutine wrappers, in particular, are susceptible to capturing 7597references to temporaries and other lifetime issues. This allows to avoid such lifetime 7598issues with coroutine wrappers. 7599 7600For example, 7601 7602.. code-block:: c++ 7603 7604 // This is a CRT. 7605 template <typename T> struct [[clang::coro_return_type]] Task { 7606 using promise_type = some_promise_type; 7607 }; 7608 7609 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine. 7610 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine. 7611 7612 // Fine for a coroutine wrapper to return a CRT. 7613 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); } 7614 7615 void bar() { 7616 // Invalid. This intantiates a function which returns a CRT but is not marked as 7617 // a coroutine wrapper. 7618 std::function<Task<int>(int)> f = increment; 7619 } 7620 7621Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary 7622implementation detail of any coroutine library. 7623}]; 7624} 7625 7626def CodeAlignAttrDocs : Documentation { 7627 let Category = DocCatVariable; 7628 let Heading = "clang::code_align"; 7629 let Content = [{ 7630The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte 7631alignment for a loop. The attribute accepts a positive integer constant 7632initialization expression indicating the number of bytes for the minimum 7633alignment boundary. Its value must be a power of 2, between 1 and 4096 7634(inclusive). 7635 7636.. code-block:: c++ 7637 7638 void foo() { 7639 int var = 0; 7640 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++; 7641 } 7642 7643 void Array(int *array, size_t n) { 7644 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0; 7645 } 7646 7647 void count () { 7648 int a1[10], int i = 0; 7649 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; } 7650 } 7651 7652 void check() { 7653 int a = 10; 7654 [[clang::code_align(8)]] do { 7655 a = a + 1; 7656 } while (a < 20); 7657 } 7658 7659 template<int A> 7660 void func() { 7661 [[clang::code_align(A)]] for(;;) { } 7662 } 7663 7664 }]; 7665} 7666 7667def CoroLifetimeBoundDoc : Documentation { 7668 let Category = DocCatDecl; 7669 let Content = [{ 7670The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied 7671to a coroutine return type (`CRT`_) (i.e. 7672it should also be annotated with ``[[clang::coro_return_type]]``). 7673 7674All parameters of a function are considered to be lifetime bound. See `documentation`_ 7675of ``[[clang::lifetimebound]]`` for more details. 7676if the function returns a coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``. 7677 7678Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables. 7679 7680For example, 7681 7682.. code-block:: c++ 7683 7684 task<int> coro(const int& a) { co_return a + 1; } 7685 task<int> dangling_refs(int a) { 7686 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`. 7687 auto foo = coro(1); 7688 // `coro` captures reference to local variable `a` which is destroyed after the return. 7689 return coro(a); 7690 } 7691 7692Lifetime bound static analysis can be used to detect such instances when coroutines capture references 7693which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with 7694``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to 7695temporaries or return address of a local variable. 7696 7697Both coroutines and coroutine wrappers are part of this analysis. 7698 7699.. code-block:: c++ 7700 7701 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task { 7702 using promise_type = some_promise_type; 7703 }; 7704 7705 Task<int> coro(const int& a) { co_return a + 1; } 7706 Task<int> [[clang::coro_wrapper]] coro_wrapper(const int& a, const int& b) { 7707 return a > b ? coro(a) : coro(b); 7708 } 7709 Task<int> temporary_reference() { 7710 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression. 7711 7712 int a = 1; 7713 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary. 7714 7715 co_return co_await coro(1); // fine. 7716 } 7717 [[clang::coro_wrapper]] Task<int> stack_reference(int a) { 7718 return coro(a); // warning: returning address of stack variable `a`. 7719 } 7720 7721.. _`documentation`: https://clang.llvm.org/docs/AttributeReference.html#lifetimebound 7722.. _`CRT`: https://clang.llvm.org/docs/AttributeReference.html#coro-return-type 7723}]; 7724} 7725