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