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