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