1//==--- AttrDocs.td - Attribute documentation ----------------------------===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===---------------------------------------------------------------------===// 8 9// To test that the documentation builds cleanly, you must run clang-tblgen to 10// convert the .td file into a .rst file, and then run sphinx to convert the 11// .rst file into an HTML file. After completing testing, you should revert the 12// generated .rst file so that the modified version does not get checked in to 13// version control. 14// 15// To run clang-tblgen to generate the .rst file: 16// clang-tblgen -gen-attr-docs -I <root>/llvm/tools/clang/include 17// <root>/llvm/tools/clang/include/clang/Basic/Attr.td -o 18// <root>/llvm/tools/clang/docs/AttributeReference.rst 19// 20// To run sphinx to generate the .html files (note that sphinx-build must be 21// available on the PATH): 22// Windows (from within the clang\docs directory): 23// make.bat html 24// Non-Windows (from within the clang\docs directory): 25// make -f Makefile.sphinx html 26 27def GlobalDocumentation { 28 code Intro =[{.. 29 ------------------------------------------------------------------- 30 NOTE: This file is automatically generated by running clang-tblgen 31 -gen-attr-docs. Do not edit this file by hand!! 32 ------------------------------------------------------------------- 33 34=================== 35Attributes in Clang 36=================== 37.. contents:: 38 :local: 39 40.. |br| raw:: html 41 42 <br/> 43 44Introduction 45============ 46 47This page lists the attributes currently supported by Clang. 48}]; 49} 50 51def SectionDocs : Documentation { 52 let Category = DocCatVariable; 53 let Content = [{ 54The ``section`` attribute allows you to specify a specific section a 55global variable or function should be in after translation. 56 }]; 57 let Heading = "section, __declspec(allocate)"; 58} 59 60def InitSegDocs : Documentation { 61 let Category = DocCatVariable; 62 let Content = [{ 63The attribute applied by ``pragma init_seg()`` controls the section into 64which global initialization function pointers are emitted. It is only 65available with ``-fms-extensions``. Typically, this function pointer is 66emitted into ``.CRT$XCU`` on Windows. The user can change the order of 67initialization by using a different section name with the same 68``.CRT$XC`` prefix and a suffix that sorts lexicographically before or 69after the standard ``.CRT$XCU`` sections. See the init_seg_ 70documentation on MSDN for more information. 71 72.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx 73 }]; 74} 75 76def TLSModelDocs : Documentation { 77 let Category = DocCatVariable; 78 let Content = [{ 79The ``tls_model`` attribute allows you to specify which thread-local storage 80model to use. It accepts the following strings: 81 82* global-dynamic 83* local-dynamic 84* initial-exec 85* local-exec 86 87TLS models are mutually exclusive. 88 }]; 89} 90 91def DLLExportDocs : Documentation { 92 let Category = DocCatVariable; 93 let Content = [{ 94The ``__declspec(dllexport)`` attribute declares a variable, function, or 95Objective-C interface to be exported from the module. It is available under the 96``-fdeclspec`` flag for compatibility with various compilers. The primary use 97is for COFF object files which explicitly specify what interfaces are available 98for external use. See the dllexport_ documentation on MSDN for more 99information. 100 101.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 102 }]; 103} 104 105def DLLImportDocs : Documentation { 106 let Category = DocCatVariable; 107 let Content = [{ 108The ``__declspec(dllimport)`` attribute declares a variable, function, or 109Objective-C interface to be imported from an external module. It is available 110under the ``-fdeclspec`` flag for compatibility with various compilers. The 111primary use is for COFF object files which explicitly specify what interfaces 112are imported from external modules. See the dllimport_ documentation on MSDN 113for more information. 114 115.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 116 }]; 117} 118 119def ThreadDocs : Documentation { 120 let Category = DocCatVariable; 121 let Content = [{ 122The ``__declspec(thread)`` attribute declares a variable with thread local 123storage. It is available under the ``-fms-extensions`` flag for MSVC 124compatibility. See the documentation for `__declspec(thread)`_ on MSDN. 125 126.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx 127 128In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the 129GNU ``__thread`` keyword. The variable must not have a destructor and must have 130a constant initializer, if any. The attribute only applies to variables 131declared with static storage duration, such as globals, class static data 132members, and static locals. 133 }]; 134} 135 136def NoEscapeDocs : Documentation { 137 let Category = DocCatVariable; 138 let Content = [{ 139``noescape`` placed on a function parameter of a pointer type is used to inform 140the compiler that the pointer cannot escape: that is, no reference to the object 141the pointer points to that is derived from the parameter value will survive 142after the function returns. Users are responsible for making sure parameters 143annotated with ``noescape`` do not actuallly escape. 144 145For example: 146 147.. code-block:: c 148 149 int *gp; 150 151 void nonescapingFunc(__attribute__((noescape)) int *p) { 152 *p += 100; // OK. 153 } 154 155 void escapingFunc(__attribute__((noescape)) int *p) { 156 gp = p; // Not OK. 157 } 158 159Additionally, when the parameter is a `block pointer 160<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction 161applies to copies of the block. For example: 162 163.. code-block:: c 164 165 typedef void (^BlockTy)(); 166 BlockTy g0, g1; 167 168 void nonescapingFunc(__attribute__((noescape)) BlockTy block) { 169 block(); // OK. 170 } 171 172 void escapingFunc(__attribute__((noescape)) BlockTy block) { 173 g0 = block; // Not OK. 174 g1 = Block_copy(block); // Not OK either. 175 } 176 177 }]; 178} 179 180def CarriesDependencyDocs : Documentation { 181 let Category = DocCatFunction; 182 let Content = [{ 183The ``carries_dependency`` attribute specifies dependency propagation into and 184out of functions. 185 186When specified on a function or Objective-C method, the ``carries_dependency`` 187attribute means that the return value carries a dependency out of the function, 188so that the implementation need not constrain ordering upon return from that 189function. Implementations of the function and its caller may choose to preserve 190dependencies instead of emitting memory ordering instructions such as fences. 191 192Note, this attribute does not change the meaning of the program, but may result 193in generation of more efficient code. 194 }]; 195} 196 197def CPUSpecificCPUDispatchDocs : Documentation { 198 let Category = DocCatFunction; 199 let Content = [{ 200The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and 201resolve multiversioned functions. This form of multiversioning provides a 202mechanism for declaring versions across translation units and manually 203specifying the resolved function list. A specified CPU defines a set of minimum 204features that are required for the function to be called. The result of this is 205that future processors execute the most restrictive version of the function the 206new processor can execute. 207 208Function versions are defined with ``cpu_specific``, which takes one or more CPU 209names as a parameter. For example: 210 211.. code-block:: c 212 213 // Declares and defines the ivybridge version of single_cpu. 214 __attribute__((cpu_specific(ivybridge))) 215 void single_cpu(void){} 216 217 // Declares and defines the atom version of single_cpu. 218 __attribute__((cpu_specific(atom))) 219 void single_cpu(void){} 220 221 // Declares and defines both the ivybridge and atom version of multi_cpu. 222 __attribute__((cpu_specific(ivybridge, atom))) 223 void multi_cpu(void){} 224 225A dispatching (or resolving) function can be declared anywhere in a project's 226source code with ``cpu_dispatch``. This attribute takes one or more CPU names 227as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch`` 228are not expected to be defined, only declared. If such a marked function has a 229definition, any side effects of the function are ignored; trivial function 230bodies are permissible for ICC compatibility. 231 232.. code-block:: c 233 234 // Creates a resolver for single_cpu above. 235 __attribute__((cpu_dispatch(ivybridge, atom))) 236 void single_cpu(void){} 237 238 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another 239 // translation unit. 240 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge))) 241 void multi_cpu(void){} 242 243Note that it is possible to have a resolving function that dispatches based on 244more or fewer options than are present in the program. Specifying fewer will 245result in the omitted options not being considered during resolution. Specifying 246a version for resolution that isn't defined in the program will result in a 247linking failure. 248 249It is also possible to specify a CPU name of ``generic`` which will be resolved 250if the executing processor doesn't satisfy the features required in the CPU 251name. The behavior of a program executing on a processor that doesn't satisfy 252any option of a multiversioned function is undefined. 253 }]; 254} 255 256def C11NoReturnDocs : Documentation { 257 let Category = DocCatFunction; 258 let Content = [{ 259A function declared as ``_Noreturn`` shall not return to its caller. The 260compiler will generate a diagnostic for a function declared as ``_Noreturn`` 261that appears to be capable of returning to its caller. 262 }]; 263} 264 265def CXX11NoReturnDocs : Documentation { 266 let Category = DocCatFunction; 267 let Content = [{ 268A function declared as ``[[noreturn]]`` shall not return to its caller. The 269compiler will generate a diagnostic for a function declared as ``[[noreturn]]`` 270that appears to be capable of returning to its caller. 271 }]; 272} 273 274def AssertCapabilityDocs : Documentation { 275 let Category = DocCatFunction; 276 let Heading = "assert_capability, assert_shared_capability"; 277 let Content = [{ 278Marks a function that dynamically tests whether a capability is held, and halts 279the program if it is not held. 280 }]; 281} 282 283def AcquireCapabilityDocs : Documentation { 284 let Category = DocCatFunction; 285 let Heading = "acquire_capability, acquire_shared_capability"; 286 let Content = [{ 287Marks a function as acquiring a capability. 288 }]; 289} 290 291def TryAcquireCapabilityDocs : Documentation { 292 let Category = DocCatFunction; 293 let Heading = "try_acquire_capability, try_acquire_shared_capability"; 294 let Content = [{ 295Marks a function that attempts to acquire a capability. This function may fail to 296actually acquire the capability; they accept a Boolean value determining 297whether acquiring the capability means success (true), or failing to acquire 298the capability means success (false). 299 }]; 300} 301 302def ReleaseCapabilityDocs : Documentation { 303 let Category = DocCatFunction; 304 let Heading = "release_capability, release_shared_capability"; 305 let Content = [{ 306Marks a function as releasing a capability. 307 }]; 308} 309 310def AssumeAlignedDocs : Documentation { 311 let Category = DocCatFunction; 312 let Content = [{ 313Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function 314declaration to specify that the return value of the function (which must be a 315pointer type) has the specified offset, in bytes, from an address with the 316specified alignment. The offset is taken to be zero if omitted. 317 318.. code-block:: c++ 319 320 // The returned pointer value has 32-byte alignment. 321 void *a() __attribute__((assume_aligned (32))); 322 323 // The returned pointer value is 4 bytes greater than an address having 324 // 32-byte alignment. 325 void *b() __attribute__((assume_aligned (32, 4))); 326 327Note that this attribute provides information to the compiler regarding a 328condition that the code already ensures is true. It does not cause the compiler 329to enforce the provided alignment assumption. 330 }]; 331} 332 333def AllocSizeDocs : Documentation { 334 let Category = DocCatFunction; 335 let Content = [{ 336The ``alloc_size`` attribute can be placed on functions that return pointers in 337order to hint to the compiler how many bytes of memory will be available at the 338returned pointer. ``alloc_size`` takes one or two arguments. 339 340- ``alloc_size(N)`` implies that argument number N equals the number of 341 available bytes at the returned pointer. 342- ``alloc_size(N, M)`` implies that the product of argument number N and 343 argument number M equals the number of available bytes at the returned 344 pointer. 345 346Argument numbers are 1-based. 347 348An example of how to use ``alloc_size`` 349 350.. code-block:: c 351 352 void *my_malloc(int a) __attribute__((alloc_size(1))); 353 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); 354 355 int main() { 356 void *const p = my_malloc(100); 357 assert(__builtin_object_size(p, 0) == 100); 358 void *const a = my_calloc(20, 5); 359 assert(__builtin_object_size(a, 0) == 100); 360 } 361 362.. Note:: This attribute works differently in clang than it does in GCC. 363 Specifically, clang will only trace ``const`` pointers (as above); we give up 364 on pointers that are not marked as ``const``. In the vast majority of cases, 365 this is unimportant, because LLVM has support for the ``alloc_size`` 366 attribute. However, this may cause mildly unintuitive behavior when used with 367 other attributes, such as ``enable_if``. 368 }]; 369} 370 371def CodeSegDocs : Documentation { 372 let Category = DocCatFunction; 373 let Content = [{ 374The ``__declspec(code_seg)`` attribute enables the placement of code into separate 375named segments that can be paged or locked in memory individually. This attribute 376is used to control the placement of instantiated templates and compiler-generated 377code. See the documentation for `__declspec(code_seg)`_ on MSDN. 378 379.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx 380 }]; 381} 382 383def AllocAlignDocs : Documentation { 384 let Category = DocCatFunction; 385 let Content = [{ 386Use ``__attribute__((alloc_align(<alignment>))`` on a function 387declaration to specify that the return value of the function (which must be a 388pointer type) is at least as aligned as the value of the indicated parameter. The 389parameter is given by its index in the list of formal parameters; the first 390parameter has index 1 unless the function is a C++ non-static member function, 391in which case the first parameter has index 2 to account for the implicit ``this`` 392parameter. 393 394.. code-block:: c++ 395 396 // The returned pointer has the alignment specified by the first parameter. 397 void *a(size_t align) __attribute__((alloc_align(1))); 398 399 // The returned pointer has the alignment specified by the second parameter. 400 void *b(void *v, size_t align) __attribute__((alloc_align(2))); 401 402 // The returned pointer has the alignment specified by the second visible 403 // parameter, however it must be adjusted for the implicit 'this' parameter. 404 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3))); 405 406Note that this attribute merely informs the compiler that a function always 407returns a sufficiently aligned pointer. It does not cause the compiler to 408emit code to enforce that alignment. The behavior is undefined if the returned 409poitner is not sufficiently aligned. 410 }]; 411} 412 413def EnableIfDocs : Documentation { 414 let Category = DocCatFunction; 415 let Content = [{ 416.. Note:: Some features of this attribute are experimental. The meaning of 417 multiple enable_if attributes on a single declaration is subject to change in 418 a future version of clang. Also, the ABI is not standardized and the name 419 mangling may change in future versions. To avoid that, use asm labels. 420 421The ``enable_if`` attribute can be placed on function declarations to control 422which overload is selected based on the values of the function's arguments. 423When combined with the ``overloadable`` attribute, this feature is also 424available in C. 425 426.. code-block:: c++ 427 428 int isdigit(int c); 429 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"))); 430 431 void foo(char c) { 432 isdigit(c); 433 isdigit(10); 434 isdigit(-10); // results in a compile-time error. 435 } 436 437The enable_if attribute takes two arguments, the first is an expression written 438in terms of the function parameters, the second is a string explaining why this 439overload candidate could not be selected to be displayed in diagnostics. The 440expression is part of the function signature for the purposes of determining 441whether it is a redeclaration (following the rules used when determining 442whether a C++ template specialization is ODR-equivalent), but is not part of 443the type. 444 445The enable_if expression is evaluated as if it were the body of a 446bool-returning constexpr function declared with the arguments of the function 447it is being applied to, then called with the parameters at the call site. If the 448result is false or could not be determined through constant expression 449evaluation, then this overload will not be chosen and the provided string may 450be used in a diagnostic if the compile fails as a result. 451 452Because the enable_if expression is an unevaluated context, there are no global 453state changes, nor the ability to pass information from the enable_if 454expression to the function body. For example, suppose we want calls to 455strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of 456strbuf) only if the size of strbuf can be determined: 457 458.. code-block:: c++ 459 460 __attribute__((always_inline)) 461 static inline size_t strnlen(const char *s, size_t maxlen) 462 __attribute__((overloadable)) 463 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))), 464 "chosen when the buffer size is known but 'maxlen' is not"))) 465 { 466 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); 467 } 468 469Multiple enable_if attributes may be applied to a single declaration. In this 470case, the enable_if expressions are evaluated from left to right in the 471following manner. First, the candidates whose enable_if expressions evaluate to 472false or cannot be evaluated are discarded. If the remaining candidates do not 473share ODR-equivalent enable_if expressions, the overload resolution is 474ambiguous. Otherwise, enable_if overload resolution continues with the next 475enable_if attribute on the candidates that have not been discarded and have 476remaining enable_if attributes. In this way, we pick the most specific 477overload out of a number of viable overloads using enable_if. 478 479.. code-block:: c++ 480 481 void f() __attribute__((enable_if(true, ""))); // #1 482 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 483 484 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 485 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 486 487In this example, a call to f() is always resolved to #2, as the first enable_if 488expression is ODR-equivalent for both declarations, but #1 does not have another 489enable_if expression to continue evaluating, so the next round of evaluation has 490only a single candidate. In a call to g(1, 1), the call is ambiguous even though 491#2 has more enable_if attributes, because the first enable_if expressions are 492not ODR-equivalent. 493 494Query for this feature with ``__has_attribute(enable_if)``. 495 496Note that functions with one or more ``enable_if`` attributes may not have 497their address taken, unless all of the conditions specified by said 498``enable_if`` are constants that evaluate to ``true``. For example: 499 500.. code-block:: c 501 502 const int TrueConstant = 1; 503 const int FalseConstant = 0; 504 int f(int a) __attribute__((enable_if(a > 0, ""))); 505 int g(int a) __attribute__((enable_if(a == 0 || a != 0, ""))); 506 int h(int a) __attribute__((enable_if(1, ""))); 507 int i(int a) __attribute__((enable_if(TrueConstant, ""))); 508 int j(int a) __attribute__((enable_if(FalseConstant, ""))); 509 510 void fn() { 511 int (*ptr)(int); 512 ptr = &f; // error: 'a > 0' is not always true 513 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant 514 ptr = &h; // OK: 1 is a truthy constant 515 ptr = &i; // OK: 'TrueConstant' is a truthy constant 516 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy 517 } 518 519Because ``enable_if`` evaluation happens during overload resolution, 520``enable_if`` may give unintuitive results when used with templates, depending 521on when overloads are resolved. In the example below, clang will emit a 522diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``: 523 524.. code-block:: c++ 525 526 double foo(int i) __attribute__((enable_if(i > 0, ""))); 527 void *foo(int i) __attribute__((enable_if(i <= 0, ""))); 528 template <int I> 529 auto bar() { return foo(I); } 530 531 template <typename T> 532 auto baz() { return foo(T::number); } 533 534 struct WithNumber { constexpr static int number = 1; }; 535 void callThem() { 536 bar<sizeof(WithNumber)>(); 537 baz<WithNumber>(); 538 } 539 540This is because, in ``bar``, ``foo`` is resolved prior to template 541instantiation, so the value for ``I`` isn't known (thus, both ``enable_if`` 542conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during 543template instantiation, so the value for ``T::number`` is known. 544 }]; 545} 546 547def DiagnoseIfDocs : Documentation { 548 let Category = DocCatFunction; 549 let Content = [{ 550The ``diagnose_if`` attribute can be placed on function declarations to emit 551warnings or errors at compile-time if calls to the attributed function meet 552certain user-defined criteria. For example: 553 554.. code-block:: c 555 556 int abs(int a) 557 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning"))); 558 int must_abs(int a) 559 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error"))); 560 561 int val = abs(1); // warning: Redundant abs call 562 int val2 = must_abs(1); // error: Redundant abs call 563 int val3 = abs(val); 564 int val4 = must_abs(val); // Because run-time checks are not emitted for 565 // diagnose_if attributes, this executes without 566 // issue. 567 568 569``diagnose_if`` is closely related to ``enable_if``, with a few key differences: 570 571* Overload resolution is not aware of ``diagnose_if`` attributes: they're 572 considered only after we select the best candidate from a given candidate set. 573* Function declarations that differ only in their ``diagnose_if`` attributes are 574 considered to be redeclarations of the same function (not overloads). 575* If the condition provided to ``diagnose_if`` cannot be evaluated, no 576 diagnostic will be emitted. 577 578Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``. 579 580As a result of bullet number two, ``diagnose_if`` attributes will stack on the 581same function. For example: 582 583.. code-block:: c 584 585 int foo() __attribute__((diagnose_if(1, "diag1", "warning"))); 586 int foo() __attribute__((diagnose_if(1, "diag2", "warning"))); 587 588 int bar = foo(); // warning: diag1 589 // warning: diag2 590 int (*fooptr)(void) = foo; // warning: diag1 591 // warning: diag2 592 593 constexpr int supportsAPILevel(int N) { return N < 5; } 594 int baz(int a) 595 __attribute__((diagnose_if(!supportsAPILevel(10), 596 "Upgrade to API level 10 to use baz", "error"))); 597 int baz(int a) 598 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning"))); 599 600 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz 601 int v = baz(0); // error: Upgrade to API level 10 to use baz 602 603Query for this feature with ``__has_attribute(diagnose_if)``. 604 }]; 605} 606 607def PassObjectSizeDocs : Documentation { 608 let Category = DocCatVariable; // Technically it's a parameter doc, but eh. 609 let Heading = "pass_object_size, pass_dynamic_object_size"; 610 let Content = [{ 611.. Note:: The mangling of functions with parameters that are annotated with 612 ``pass_object_size`` is subject to change. You can get around this by 613 using ``__asm__("foo")`` to explicitly name your functions, thus preserving 614 your ABI; also, non-overloadable C functions with ``pass_object_size`` are 615 not mangled. 616 617The ``pass_object_size(Type)`` attribute can be placed on function parameters to 618instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite 619of said function, and implicitly pass the result of this call in as an invisible 620argument of type ``size_t`` directly after the parameter annotated with 621``pass_object_size``. Clang will also replace any calls to 622``__builtin_object_size(param, Type)`` in the function by said implicit 623parameter. 624 625Example usage: 626 627.. code-block:: c 628 629 int bzero1(char *const p __attribute__((pass_object_size(0)))) 630 __attribute__((noinline)) { 631 int i = 0; 632 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) { 633 p[i] = 0; 634 } 635 return i; 636 } 637 638 int main() { 639 char chars[100]; 640 int n = bzero1(&chars[0]); 641 assert(n == sizeof(chars)); 642 return 0; 643 } 644 645If successfully evaluating ``__builtin_object_size(param, Type)`` at the 646callsite is not possible, then the "failed" value is passed in. So, using the 647definition of ``bzero1`` from above, the following code would exit cleanly: 648 649.. code-block:: c 650 651 int main2(int argc, char *argv[]) { 652 int n = bzero1(argv); 653 assert(n == -1); 654 return 0; 655 } 656 657``pass_object_size`` plays a part in overload resolution. If two overload 658candidates are otherwise equally good, then the overload with one or more 659parameters with ``pass_object_size`` is preferred. This implies that the choice 660between two identical overloads both with ``pass_object_size`` on one or more 661parameters will always be ambiguous; for this reason, having two such overloads 662is illegal. For example: 663 664.. code-block:: c++ 665 666 #define PS(N) __attribute__((pass_object_size(N))) 667 // OK 668 void Foo(char *a, char *b); // Overload A 669 // OK -- overload A has no parameters with pass_object_size. 670 void Foo(char *a PS(0), char *b PS(0)); // Overload B 671 // Error -- Same signature (sans pass_object_size) as overload B, and both 672 // overloads have one or more parameters with the pass_object_size attribute. 673 void Foo(void *a PS(0), void *b); 674 675 // OK 676 void Bar(void *a PS(0)); // Overload C 677 // OK 678 void Bar(char *c PS(1)); // Overload D 679 680 void main() { 681 char known[10], *unknown; 682 Foo(unknown, unknown); // Calls overload B 683 Foo(known, unknown); // Calls overload B 684 Foo(unknown, known); // Calls overload B 685 Foo(known, known); // Calls overload B 686 687 Bar(known); // Calls overload D 688 Bar(unknown); // Calls overload D 689 } 690 691Currently, ``pass_object_size`` is a bit restricted in terms of its usage: 692 693* Only one use of ``pass_object_size`` is allowed per parameter. 694 695* It is an error to take the address of a function with ``pass_object_size`` on 696 any of its parameters. If you wish to do this, you can create an overload 697 without ``pass_object_size`` on any parameters. 698 699* It is an error to apply the ``pass_object_size`` attribute to parameters that 700 are not pointers. Additionally, any parameter that ``pass_object_size`` is 701 applied to must be marked ``const`` at its function's definition. 702 703Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves 704identically to ``pass_object_size``, but evaluates a call to 705``__builtin_dynamic_object_size`` at the callee instead of 706``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra 707runtime checks when the object size can't be determined at compile-time. You can 708read more about ``__builtin_dynamic_object_size`` `here 709<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_. 710 711 }]; 712} 713 714def OverloadableDocs : Documentation { 715 let Category = DocCatFunction; 716 let Content = [{ 717Clang provides support for C++ function overloading in C. Function overloading 718in C is introduced using the ``overloadable`` attribute. For example, one 719might provide several overloaded versions of a ``tgsin`` function that invokes 720the appropriate standard function computing the sine of a value with ``float``, 721``double``, or ``long double`` precision: 722 723.. code-block:: c 724 725 #include <math.h> 726 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } 727 double __attribute__((overloadable)) tgsin(double x) { return sin(x); } 728 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } 729 730Given these declarations, one can call ``tgsin`` with a ``float`` value to 731receive a ``float`` result, with a ``double`` to receive a ``double`` result, 732etc. Function overloading in C follows the rules of C++ function overloading 733to pick the best overload given the call arguments, with a few C-specific 734semantics: 735 736* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a 737 floating-point promotion (per C99) rather than as a floating-point conversion 738 (as in C++). 739 740* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is 741 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are 742 compatible types. 743 744* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` 745 and ``U`` are compatible types. This conversion is given "conversion" rank. 746 747* If no viable candidates are otherwise available, we allow a conversion from a 748 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are 749 incompatible. This conversion is ranked below all other types of conversions. 750 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient 751 for ``T`` and ``U`` to be incompatible. 752 753The declaration of ``overloadable`` functions is restricted to function 754declarations and definitions. If a function is marked with the ``overloadable`` 755attribute, then all declarations and definitions of functions with that name, 756except for at most one (see the note below about unmarked overloads), must have 757the ``overloadable`` attribute. In addition, redeclarations of a function with 758the ``overloadable`` attribute must have the ``overloadable`` attribute, and 759redeclarations of a function without the ``overloadable`` attribute must *not* 760have the ``overloadable`` attribute. e.g., 761 762.. code-block:: c 763 764 int f(int) __attribute__((overloadable)); 765 float f(float); // error: declaration of "f" must have the "overloadable" attribute 766 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute 767 768 int g(int) __attribute__((overloadable)); 769 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute 770 771 int h(int); 772 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not 773 // have the "overloadable" attribute 774 775Functions marked ``overloadable`` must have prototypes. Therefore, the 776following code is ill-formed: 777 778.. code-block:: c 779 780 int h() __attribute__((overloadable)); // error: h does not have a prototype 781 782However, ``overloadable`` functions are allowed to use a ellipsis even if there 783are no named parameters (as is permitted in C++). This feature is particularly 784useful when combined with the ``unavailable`` attribute: 785 786.. code-block:: c++ 787 788 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error 789 790Functions declared with the ``overloadable`` attribute have their names mangled 791according to the same rules as C++ function names. For example, the three 792``tgsin`` functions in our motivating example get the mangled names 793``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two 794caveats to this use of name mangling: 795 796* Future versions of Clang may change the name mangling of functions overloaded 797 in C, so you should not depend on an specific mangling. To be completely 798 safe, we strongly urge the use of ``static inline`` with ``overloadable`` 799 functions. 800 801* The ``overloadable`` attribute has almost no meaning when used in C++, 802 because names will already be mangled and functions are already overloadable. 803 However, when an ``overloadable`` function occurs within an ``extern "C"`` 804 linkage specification, it's name *will* be mangled in the same way as it 805 would in C. 806 807For the purpose of backwards compatibility, at most one function with the same 808name as other ``overloadable`` functions may omit the ``overloadable`` 809attribute. In this case, the function without the ``overloadable`` attribute 810will not have its name mangled. 811 812For example: 813 814.. code-block:: c 815 816 // Notes with mangled names assume Itanium mangling. 817 int f(int); 818 int f(double) __attribute__((overloadable)); 819 void foo() { 820 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that 821 // was marked with overloadable). 822 f(1.0); // Emits a call to _Z1fd. 823 } 824 825Support for unmarked overloads is not present in some versions of clang. You may 826query for it using ``__has_extension(overloadable_unmarked)``. 827 828Query for this attribute with ``__has_attribute(overloadable)``. 829 }]; 830} 831 832def ObjCMethodFamilyDocs : Documentation { 833 let Category = DocCatFunction; 834 let Content = [{ 835Many methods in Objective-C have conventional meanings determined by their 836selectors. It is sometimes useful to be able to mark a method as having a 837particular conventional meaning despite not having the right selector, or as 838not having the conventional meaning that its selector would suggest. For these 839use cases, we provide an attribute to specifically describe the "method family" 840that a method belongs to. 841 842**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of 843``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This 844attribute can only be placed at the end of a method declaration: 845 846.. code-block:: objc 847 848 - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); 849 850Users who do not wish to change the conventional meaning of a method, and who 851merely want to document its non-standard retain and release semantics, should 852use the retaining behavior attributes (``ns_returns_retained``, 853``ns_returns_not_retained``, etc). 854 855Query for this feature with ``__has_attribute(objc_method_family)``. 856 }]; 857} 858 859def RetainBehaviorDocs : Documentation { 860 let Category = DocCatFunction; 861 let Content = [{ 862The behavior of a function with respect to reference counting for Foundation 863(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming 864convention (e.g. functions starting with "get" are assumed to return at 865``+0``). 866 867It can be overriden using a family of the following attributes. In 868Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to 869a function communicates that the object is returned at ``+1``, and the caller 870is responsible for freeing it. 871Similiarly, the annotation ``__attribute__((ns_returns_not_retained))`` 872specifies that the object is returned at ``+0`` and the ownership remains with 873the callee. 874The annotation ``__attribute__((ns_consumes_self))`` specifies that 875the Objective-C method call consumes the reference to ``self``, e.g. by 876attaching it to a supplied parameter. 877Additionally, parameters can have an annotation 878``__attribute__((ns_consumed))``, which specifies that passing an owned object 879as that parameter effectively transfers the ownership, and the caller is no 880longer responsible for it. 881These attributes affect code generation when interacting with ARC code, and 882they are used by the Clang Static Analyzer. 883 884In C programs using CoreFoundation, a similar set of attributes: 885``__attribute__((cf_returns_not_retained))``, 886``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))`` 887have the same respective semantics when applied to CoreFoundation objects. 888These attributes affect code generation when interacting with ARC code, and 889they are used by the Clang Static Analyzer. 890 891Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), 892the same attribute family is present: 893``__attribute__((os_returns_not_retained))``, 894``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``, 895with the same respective semantics. 896Similar to ``__attribute__((ns_consumes_self))``, 897``__attribute__((os_consumes_this))`` specifies that the method call consumes 898the reference to "this" (e.g., when attaching it to a different object supplied 899as a parameter). 900Out parameters (parameters the function is meant to write into, 901either via pointers-to-pointers or references-to-pointers) 902may be annotated with ``__attribute__((os_returns_retained))`` 903or ``__attribute__((os_returns_not_retained))`` which specifies that the object 904written into the out parameter should (or respectively should not) be released 905after use. 906Since often out parameters may or may not be written depending on the exit 907code of the function, 908annotations ``__attribute__((os_returns_retained_on_zero))`` 909and ``__attribute__((os_returns_retained_on_non_zero))`` specify that 910an out parameter at ``+1`` is written if and only if the function returns a zero 911(respectively non-zero) error code. 912Observe that return-code-dependent out parameter annotations are only 913available for retained out parameters, as non-retained object do not have to be 914released by the callee. 915These attributes are only used by the Clang Static Analyzer. 916 917The family of attributes ``X_returns_X_retained`` can be added to functions, 918C++ methods, and Objective-C methods and properties. 919Attributes ``X_consumed`` can be added to parameters of methods, functions, 920and Objective-C methods. 921 }]; 922} 923 924def NoDebugDocs : Documentation { 925 let Category = DocCatVariable; 926 let Content = [{ 927The ``nodebug`` attribute allows you to suppress debugging information for a 928function or method, or for a variable that is not a parameter or a non-static 929data member. 930 }]; 931} 932 933def NoDuplicateDocs : Documentation { 934 let Category = DocCatFunction; 935 let Content = [{ 936The ``noduplicate`` attribute can be placed on function declarations to control 937whether function calls to this function can be duplicated or not as a result of 938optimizations. This is required for the implementation of functions with 939certain special requirements, like the OpenCL "barrier" function, that might 940need to be run concurrently by all the threads that are executing in lockstep 941on the hardware. For example this attribute applied on the function 942"nodupfunc" in the code below avoids that: 943 944.. code-block:: c 945 946 void nodupfunc() __attribute__((noduplicate)); 947 // Setting it as a C++11 attribute is also valid 948 // void nodupfunc() [[clang::noduplicate]]; 949 void foo(); 950 void bar(); 951 952 nodupfunc(); 953 if (a > n) { 954 foo(); 955 } else { 956 bar(); 957 } 958 959gets possibly modified by some optimizations into code similar to this: 960 961.. code-block:: c 962 963 if (a > n) { 964 nodupfunc(); 965 foo(); 966 } else { 967 nodupfunc(); 968 bar(); 969 } 970 971where the call to "nodupfunc" is duplicated and sunk into the two branches 972of the condition. 973 }]; 974} 975 976def ConvergentDocs : Documentation { 977 let Category = DocCatFunction; 978 let Content = [{ 979The ``convergent`` attribute can be placed on a function declaration. It is 980translated into the LLVM ``convergent`` attribute, which indicates that the call 981instructions of a function with this attribute cannot be made control-dependent 982on any additional values. 983 984In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA, 985the call instructions of a function with this attribute must be executed by 986all work items or threads in a work group or sub group. 987 988This attribute is different from ``noduplicate`` because it allows duplicating 989function calls if it can be proved that the duplicated function calls are 990not made control-dependent on any additional values, e.g., unrolling a loop 991executed by all work items. 992 993Sample usage: 994.. code-block:: c 995 996 void convfunc(void) __attribute__((convergent)); 997 // Setting it as a C++11 attribute is also valid in a C++ program. 998 // void convfunc(void) [[clang::convergent]]; 999 1000 }]; 1001} 1002 1003def NoSplitStackDocs : Documentation { 1004 let Category = DocCatFunction; 1005 let Content = [{ 1006The ``no_split_stack`` attribute disables the emission of the split stack 1007preamble for a particular function. It has no effect if ``-fsplit-stack`` 1008is not specified. 1009 }]; 1010} 1011 1012def NoUniqueAddressDocs : Documentation { 1013 let Category = DocCatField; 1014 let Content = [{ 1015The ``no_unique_address`` attribute allows tail padding in a non-static data 1016member to overlap other members of the enclosing class (and in the special 1017case when the type is empty, permits it to fully overlap other members). 1018The field is laid out as if a base class were encountered at the corresponding 1019point within the class (except that it does not share a vptr with the enclosing 1020object). 1021 1022Example usage: 1023 1024.. code-block:: c++ 1025 1026 template<typename T, typename Alloc> struct my_vector { 1027 T *p; 1028 [[no_unique_address]] Alloc alloc; 1029 // ... 1030 }; 1031 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*)); 1032 1033``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use 1034in C++11 onwards. 1035 }]; 1036} 1037 1038def ObjCRequiresSuperDocs : Documentation { 1039 let Category = DocCatFunction; 1040 let Content = [{ 1041Some Objective-C classes allow a subclass to override a particular method in a 1042parent class but expect that the overriding method also calls the overridden 1043method in the parent class. For these cases, we provide an attribute to 1044designate that a method requires a "call to ``super``" in the overriding 1045method in the subclass. 1046 1047**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only 1048be placed at the end of a method declaration: 1049 1050.. code-block:: objc 1051 1052 - (void)foo __attribute__((objc_requires_super)); 1053 1054This attribute can only be applied the method declarations within a class, and 1055not a protocol. Currently this attribute does not enforce any placement of 1056where the call occurs in the overriding method (such as in the case of 1057``-dealloc`` where the call must appear at the end). It checks only that it 1058exists. 1059 1060Note that on both OS X and iOS that the Foundation framework provides a 1061convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this 1062attribute: 1063 1064.. code-block:: objc 1065 1066 - (void)foo NS_REQUIRES_SUPER; 1067 1068This macro is conditionally defined depending on the compiler's support for 1069this attribute. If the compiler does not support the attribute the macro 1070expands to nothing. 1071 1072Operationally, when a method has this annotation the compiler will warn if the 1073implementation of an override in a subclass does not call super. For example: 1074 1075.. code-block:: objc 1076 1077 warning: method possibly missing a [super AnnotMeth] call 1078 - (void) AnnotMeth{}; 1079 ^ 1080 }]; 1081} 1082 1083def ObjCRuntimeNameDocs : Documentation { 1084 let Category = DocCatDecl; 1085 let Content = [{ 1086By default, the Objective-C interface or protocol identifier is used 1087in the metadata name for that object. The `objc_runtime_name` 1088attribute allows annotated interfaces or protocols to use the 1089specified string argument in the object's metadata name instead of the 1090default name. 1091 1092**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute 1093can only be placed before an @protocol or @interface declaration: 1094 1095.. code-block:: objc 1096 1097 __attribute__((objc_runtime_name("MyLocalName"))) 1098 @interface Message 1099 @end 1100 1101 }]; 1102} 1103 1104def ObjCRuntimeVisibleDocs : Documentation { 1105 let Category = DocCatDecl; 1106 let Content = [{ 1107This attribute specifies that the Objective-C class to which it applies is 1108visible to the Objective-C runtime but not to the linker. Classes annotated 1109with this attribute cannot be subclassed and cannot have categories defined for 1110them. 1111 }]; 1112} 1113 1114def ObjCClassStubDocs : Documentation { 1115 let Category = DocCatType; 1116 let Content = [{ 1117This attribute specifies that the Objective-C class to which it applies is 1118instantiated at runtime. 1119 1120Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute 1121still has a "class stub" that is visible to the linker. This allows categories 1122to be defined. Static message sends with the class as a receiver use a special 1123access pattern to ensure the class is lazily instantiated from the class stub. 1124 1125Classes annotated with this attribute cannot be subclassed and cannot have 1126implementations defined for them. This attribute is intended for use in 1127Swift-generated headers for classes defined in Swift. 1128 1129Adding or removing this attribute to a class is an ABI-breaking change. 1130 }]; 1131} 1132 1133def ObjCBoxableDocs : Documentation { 1134 let Category = DocCatDecl; 1135 let Content = [{ 1136Structs and unions marked with the ``objc_boxable`` attribute can be used 1137with the Objective-C boxed expression syntax, ``@(...)``. 1138 1139**Usage**: ``__attribute__((objc_boxable))``. This attribute 1140can only be placed on a declaration of a trivially-copyable struct or union: 1141 1142.. code-block:: objc 1143 1144 struct __attribute__((objc_boxable)) some_struct { 1145 int i; 1146 }; 1147 union __attribute__((objc_boxable)) some_union { 1148 int i; 1149 float f; 1150 }; 1151 typedef struct __attribute__((objc_boxable)) _some_struct some_struct; 1152 1153 // ... 1154 1155 some_struct ss; 1156 NSValue *boxed = @(ss); 1157 1158 }]; 1159} 1160 1161def AvailabilityDocs : Documentation { 1162 let Category = DocCatFunction; 1163 let Content = [{ 1164The ``availability`` attribute can be placed on declarations to describe the 1165lifecycle of that declaration relative to operating system versions. Consider 1166the function declaration for a hypothetical function ``f``: 1167 1168.. code-block:: c++ 1169 1170 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7))); 1171 1172The availability attribute states that ``f`` was introduced in macOS 10.4, 1173deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information 1174is used by Clang to determine when it is safe to use ``f``: for example, if 1175Clang is instructed to compile code for macOS 10.5, a call to ``f()`` 1176succeeds. If Clang is instructed to compile code for macOS 10.6, the call 1177succeeds but Clang emits a warning specifying that the function is deprecated. 1178Finally, if Clang is instructed to compile code for macOS 10.7, the call 1179fails because ``f()`` is no longer available. 1180 1181The availability attribute is a comma-separated list starting with the 1182platform name and then including clauses specifying important milestones in the 1183declaration's lifetime (in any order) along with additional information. Those 1184clauses can be: 1185 1186introduced=\ *version* 1187 The first version in which this declaration was introduced. 1188 1189deprecated=\ *version* 1190 The first version in which this declaration was deprecated, meaning that 1191 users should migrate away from this API. 1192 1193obsoleted=\ *version* 1194 The first version in which this declaration was obsoleted, meaning that it 1195 was removed completely and can no longer be used. 1196 1197unavailable 1198 This declaration is never available on this platform. 1199 1200message=\ *string-literal* 1201 Additional message text that Clang will provide when emitting a warning or 1202 error about use of a deprecated or obsoleted declaration. Useful to direct 1203 users to replacement APIs. 1204 1205replacement=\ *string-literal* 1206 Additional message text that Clang will use to provide Fix-It when emitting 1207 a warning about use of a deprecated declaration. The Fix-It will replace 1208 the deprecated declaration with the new declaration specified. 1209 1210Multiple availability attributes can be placed on a declaration, which may 1211correspond to different platforms. For most platforms, the availability 1212attribute with the platform corresponding to the target platform will be used; 1213any others will be ignored. However, the availability for ``watchOS`` and 1214``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute. 1215Any explicit availability attributes for those platforms are still prefered over 1216the implicitly inferred availability attributes. If no availability attribute 1217specifies availability for the current target platform, the availability 1218attributes are ignored. Supported platforms are: 1219 1220``ios`` 1221 Apple's iOS operating system. The minimum deployment target is specified by 1222 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` 1223 command-line arguments. 1224 1225``macos`` 1226 Apple's macOS operating system. The minimum deployment target is 1227 specified by the ``-mmacosx-version-min=*version*`` command-line argument. 1228 ``macosx`` is supported for backward-compatibility reasons, but it is 1229 deprecated. 1230 1231``tvos`` 1232 Apple's tvOS operating system. The minimum deployment target is specified by 1233 the ``-mtvos-version-min=*version*`` command-line argument. 1234 1235``watchos`` 1236 Apple's watchOS operating system. The minimum deployment target is specified by 1237 the ``-mwatchos-version-min=*version*`` command-line argument. 1238 1239A declaration can typically be used even when deploying back to a platform 1240version prior to when the declaration was introduced. When this happens, the 1241declaration is `weakly linked 1242<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, 1243as if the ``weak_import`` attribute were added to the declaration. A 1244weakly-linked declaration may or may not be present a run-time, and a program 1245can determine whether the declaration is present by checking whether the 1246address of that declaration is non-NULL. 1247 1248The flag ``strict`` disallows using API when deploying back to a 1249platform version prior to when the declaration was introduced. An 1250attempt to use such API before its introduction causes a hard error. 1251Weakly-linking is almost always a better API choice, since it allows 1252users to query availability at runtime. 1253 1254If there are multiple declarations of the same entity, the availability 1255attributes must either match on a per-platform basis or later 1256declarations must not have availability attributes for that 1257platform. For example: 1258 1259.. code-block:: c 1260 1261 void g(void) __attribute__((availability(macos,introduced=10.4))); 1262 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches 1263 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform 1264 void g(void); // okay, inherits both macos and ios availability from above. 1265 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch 1266 1267When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: 1268 1269.. code-block:: objc 1270 1271 @interface A 1272 - (id)method __attribute__((availability(macos,introduced=10.4))); 1273 - (id)method2 __attribute__((availability(macos,introduced=10.4))); 1274 @end 1275 1276 @interface B : A 1277 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later 1278 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4 1279 @end 1280 1281Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from 1282``<os/availability.h>`` can simplify the spelling: 1283 1284.. code-block:: objc 1285 1286 @interface A 1287 - (id)method API_AVAILABLE(macos(10.11))); 1288 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0)); 1289 @end 1290 1291Availability attributes can also be applied using a ``#pragma clang attribute``. 1292Any explicit availability attribute whose platform corresponds to the target 1293platform is applied to a declaration regardless of the availability attributes 1294specified in the pragma. For example, in the code below, 1295``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability 1296attribute that is specified with the declaration, whereas 1297``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability 1298attribute that is applied by the pragma. 1299 1300.. code-block:: c 1301 1302 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function) 1303 void getsThePragmaAvailabilityAttribute(void); 1304 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4))); 1305 #pragma clang attribute pop 1306 1307For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can 1308be implicitly inferred from an ``iOS`` availability attribute, the logic is 1309slightly more complex. The explicit and the pragma-applied availability 1310attributes whose platform corresponds to the target platform are applied as 1311described in the previous paragraph. However, the implicitly inferred attributes 1312are applied to a declaration only when there is no explicit or pragma-applied 1313availability attribute whose platform corresponds to the target platform. For 1314example, the function below will receive the ``tvOS`` availability from the 1315pragma rather than using the inferred ``iOS`` availability from the declaration: 1316 1317.. code-block:: c 1318 1319 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function) 1320 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0))); 1321 #pragma clang attribute pop 1322 1323The compiler is also able to apply implicly inferred attributes from a pragma 1324as well. For example, when targeting ``tvOS``, the function below will receive 1325a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS`` 1326availability attribute applied by the pragma: 1327 1328.. code-block:: c 1329 1330 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function) 1331 void infersTVOSAvailabilityFromPragma(void); 1332 #pragma clang attribute pop 1333 1334The implicit attributes that are inferred from explicitly specified attributes 1335whose platform corresponds to the target platform are applied to the declaration 1336even if there is an availability attribute that can be inferred from a pragma. 1337For example, the function below will receive the ``tvOS, introduced=11.0`` 1338availability that is inferred from the attribute on the declaration rather than 1339inferring availability from the pragma: 1340 1341.. code-block:: c 1342 1343 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function) 1344 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void) 1345 __attribute__((availability(iOS,introduced=11.0))); 1346 #pragma clang attribute pop 1347 1348Also see the documentation for `@available 1349<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_ 1350 }]; 1351} 1352 1353def ExternalSourceSymbolDocs : Documentation { 1354 let Category = DocCatDecl; 1355 let Content = [{ 1356The ``external_source_symbol`` attribute specifies that a declaration originates 1357from an external source and describes the nature of that source. 1358 1359The fact that Clang is capable of recognizing declarations that were defined 1360externally can be used to provide better tooling support for mixed-language 1361projects or projects that rely on auto-generated code. For instance, an IDE that 1362uses Clang and that supports mixed-language projects can use this attribute to 1363provide a correct 'jump-to-definition' feature. For a concrete example, 1364consider a protocol that's defined in a Swift file: 1365 1366.. code-block:: swift 1367 1368 @objc public protocol SwiftProtocol { 1369 func method() 1370 } 1371 1372This protocol can be used from Objective-C code by including a header file that 1373was generated by the Swift compiler. The declarations in that header can use 1374the ``external_source_symbol`` attribute to make Clang aware of the fact 1375that ``SwiftProtocol`` actually originates from a Swift module: 1376 1377.. code-block:: objc 1378 1379 __attribute__((external_source_symbol(language="Swift",defined_in="module"))) 1380 @protocol SwiftProtocol 1381 @required 1382 - (void) method; 1383 @end 1384 1385Consequently, when 'jump-to-definition' is performed at a location that 1386references ``SwiftProtocol``, the IDE can jump to the original definition in 1387the Swift source file rather than jumping to the Objective-C declaration in the 1388auto-generated header file. 1389 1390The ``external_source_symbol`` attribute is a comma-separated list that includes 1391clauses that describe the origin and the nature of the particular declaration. 1392Those clauses can be: 1393 1394language=\ *string-literal* 1395 The name of the source language in which this declaration was defined. 1396 1397defined_in=\ *string-literal* 1398 The name of the source container in which the declaration was defined. The 1399 exact definition of source container is language-specific, e.g. Swift's 1400 source containers are modules, so ``defined_in`` should specify the Swift 1401 module name. 1402 1403generated_declaration 1404 This declaration was automatically generated by some tool. 1405 1406The clauses can be specified in any order. The clauses that are listed above are 1407all optional, but the attribute has to have at least one clause. 1408 }]; 1409} 1410 1411def RequireConstantInitDocs : Documentation { 1412 let Category = DocCatVariable; 1413 let Content = [{ 1414This attribute specifies that the variable to which it is attached is intended 1415to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_ 1416according to the rules of [basic.start.static]. The variable is required to 1417have static or thread storage duration. If the initialization of the variable 1418is not a constant initializer an error will be produced. This attribute may 1419only be used in C++. 1420 1421Note that in C++03 strict constant expression checking is not done. Instead 1422the attribute reports if Clang can emit the variable as a constant, even if it's 1423not technically a 'constant initializer'. This behavior is non-portable. 1424 1425Static storage duration variables with constant initializers avoid hard-to-find 1426bugs caused by the indeterminate order of dynamic initialization. They can also 1427be safely used during dynamic initialization across translation units. 1428 1429This attribute acts as a compile time assertion that the requirements 1430for constant initialization have been met. Since these requirements change 1431between dialects and have subtle pitfalls it's important to fail fast instead 1432of silently falling back on dynamic initialization. 1433 1434.. code-block:: c++ 1435 1436 // -std=c++14 1437 #define SAFE_STATIC [[clang::require_constant_initialization]] 1438 struct T { 1439 constexpr T(int) {} 1440 ~T(); // non-trivial 1441 }; 1442 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor. 1443 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer 1444 // copy initialization is not a constant expression on a non-literal type. 1445 }]; 1446} 1447 1448def WarnMaybeUnusedDocs : Documentation { 1449 let Category = DocCatVariable; 1450 let Heading = "maybe_unused, unused"; 1451 let Content = [{ 1452When passing the ``-Wunused`` flag to Clang, entities that are unused by the 1453program may be diagnosed. The ``[[maybe_unused]]`` (or 1454``__attribute__((unused))``) attribute can be used to silence such diagnostics 1455when the entity cannot be removed. For instance, a local variable may exist 1456solely for use in an ``assert()`` statement, which makes the local variable 1457unused when ``NDEBUG`` is defined. 1458 1459The attribute may be applied to the declaration of a class, a typedef, a 1460variable, a function or method, a function parameter, an enumeration, an 1461enumerator, a non-static data member, or a label. 1462 1463.. code-block: c++ 1464 #include <cassert> 1465 1466 [[maybe_unused]] void f([[maybe_unused]] bool thing1, 1467 [[maybe_unused]] bool thing2) { 1468 [[maybe_unused]] bool b = thing1 && thing2; 1469 assert(b); 1470 } 1471 }]; 1472} 1473 1474def WarnUnusedResultsDocs : Documentation { 1475 let Category = DocCatFunction; 1476 let Heading = "nodiscard, warn_unused_result"; 1477 let Content = [{ 1478Clang supports the ability to diagnose when the results of a function call 1479expression are discarded under suspicious circumstances. A diagnostic is 1480generated when a function or its return type is marked with ``[[nodiscard]]`` 1481(or ``__attribute__((warn_unused_result))``) and the function call appears as a 1482potentially-evaluated discarded-value expression that is not explicitly cast to 1483`void`. 1484 1485.. code-block: c++ 1486 struct [[nodiscard]] error_info { /*...*/ }; 1487 error_info enable_missile_safety_mode(); 1488 1489 void launch_missiles(); 1490 void test_missiles() { 1491 enable_missile_safety_mode(); // diagnoses 1492 launch_missiles(); 1493 } 1494 error_info &foo(); 1495 void f() { foo(); } // Does not diagnose, error_info is a reference. 1496 }]; 1497} 1498 1499def FallthroughDocs : Documentation { 1500 let Category = DocCatStmt; 1501 let Heading = "fallthrough"; 1502 let Content = [{ 1503The ``fallthrough`` (or ``clang::fallthrough``) attribute is used 1504to annotate intentional fall-through 1505between switch labels. It can only be applied to a null statement placed at a 1506point of execution between any statement and the next switch label. It is 1507common to mark these places with a specific comment, but this attribute is 1508meant to replace comments with a more strict annotation, which can be checked 1509by the compiler. This attribute doesn't change semantics of the code and can 1510be used wherever an intended fall-through occurs. It is designed to mimic 1511control-flow statements like ``break;``, so it can be placed in most places 1512where ``break;`` can, but only if there are no statements on the execution path 1513between it and the next switch label. 1514 1515By default, Clang does not warn on unannotated fallthrough from one ``switch`` 1516case to another. Diagnostics on fallthrough without a corresponding annotation 1517can be enabled with the ``-Wimplicit-fallthrough`` argument. 1518 1519Here is an example: 1520 1521.. code-block:: c++ 1522 1523 // compile with -Wimplicit-fallthrough 1524 switch (n) { 1525 case 22: 1526 case 33: // no warning: no statements between case labels 1527 f(); 1528 case 44: // warning: unannotated fall-through 1529 g(); 1530 [[clang::fallthrough]]; 1531 case 55: // no warning 1532 if (x) { 1533 h(); 1534 break; 1535 } 1536 else { 1537 i(); 1538 [[clang::fallthrough]]; 1539 } 1540 case 66: // no warning 1541 p(); 1542 [[clang::fallthrough]]; // warning: fallthrough annotation does not 1543 // directly precede case label 1544 q(); 1545 case 77: // warning: unannotated fall-through 1546 r(); 1547 } 1548 }]; 1549} 1550 1551def ARMInterruptDocs : Documentation { 1552 let Category = DocCatFunction; 1553 let Heading = "interrupt (ARM)"; 1554 let Content = [{ 1555Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on 1556ARM targets. This attribute may be attached to a function definition and 1557instructs the backend to generate appropriate function entry/exit code so that 1558it can be used directly as an interrupt service routine. 1559 1560The parameter passed to the interrupt attribute is optional, but if 1561provided it must be a string literal with one of the following values: "IRQ", 1562"FIQ", "SWI", "ABORT", "UNDEF". 1563 1564The semantics are as follows: 1565 1566- If the function is AAPCS, Clang instructs the backend to realign the stack to 1567 8 bytes on entry. This is a general requirement of the AAPCS at public 1568 interfaces, but may not hold when an exception is taken. Doing this allows 1569 other AAPCS functions to be called. 1570- If the CPU is M-class this is all that needs to be done since the architecture 1571 itself is designed in such a way that functions obeying the normal AAPCS ABI 1572 constraints are valid exception handlers. 1573- If the CPU is not M-class, the prologue and epilogue are modified to save all 1574 non-banked registers that are used, so that upon return the user-mode state 1575 will not be corrupted. Note that to avoid unnecessary overhead, only 1576 general-purpose (integer) registers are saved in this way. If VFP operations 1577 are needed, that state must be saved manually. 1578 1579 Specifically, interrupt kinds other than "FIQ" will save all core registers 1580 except "lr" and "sp". "FIQ" interrupts will save r0-r7. 1581- If the CPU is not M-class, the return instruction is changed to one of the 1582 canonical sequences permitted by the architecture for exception return. Where 1583 possible the function itself will make the necessary "lr" adjustments so that 1584 the "preferred return address" is selected. 1585 1586 Unfortunately the compiler is unable to make this guarantee for an "UNDEF" 1587 handler, where the offset from "lr" to the preferred return address depends on 1588 the execution state of the code which generated the exception. In this case 1589 a sequence equivalent to "movs pc, lr" will be used. 1590 }]; 1591} 1592 1593def MipsInterruptDocs : Documentation { 1594 let Category = DocCatFunction; 1595 let Heading = "interrupt (MIPS)"; 1596 let Content = [{ 1597Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on 1598MIPS targets. This attribute may be attached to a function definition and instructs 1599the backend to generate appropriate function entry/exit code so that it can be used 1600directly as an interrupt service routine. 1601 1602By default, the compiler will produce a function prologue and epilogue suitable for 1603an interrupt service routine that handles an External Interrupt Controller (eic) 1604generated interrupt. This behaviour can be explicitly requested with the "eic" 1605argument. 1606 1607Otherwise, for use with vectored interrupt mode, the argument passed should be 1608of the form "vector=LEVEL" where LEVEL is one of the following values: 1609"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will 1610then set the interrupt mask to the corresponding level which will mask all 1611interrupts up to and including the argument. 1612 1613The semantics are as follows: 1614 1615- The prologue is modified so that the Exception Program Counter (EPC) and 1616 Status coprocessor registers are saved to the stack. The interrupt mask is 1617 set so that the function can only be interrupted by a higher priority 1618 interrupt. The epilogue will restore the previous values of EPC and Status. 1619 1620- The prologue and epilogue are modified to save and restore all non-kernel 1621 registers as necessary. 1622 1623- The FPU is disabled in the prologue, as the floating pointer registers are not 1624 spilled to the stack. 1625 1626- The function return sequence is changed to use an exception return instruction. 1627 1628- The parameter sets the interrupt mask for the function corresponding to the 1629 interrupt level specified. If no mask is specified the interrupt mask 1630 defaults to "eic". 1631 }]; 1632} 1633 1634def MicroMipsDocs : Documentation { 1635 let Category = DocCatFunction; 1636 let Content = [{ 1637Clang supports the GNU style ``__attribute__((micromips))`` and 1638``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes 1639may be attached to a function definition and instructs the backend to generate 1640or not to generate microMIPS code for that function. 1641 1642These attributes override the `-mmicromips` and `-mno-micromips` options 1643on the command line. 1644 }]; 1645} 1646 1647def MipsLongCallStyleDocs : Documentation { 1648 let Category = DocCatFunction; 1649 let Heading = "long_call, far"; 1650 let Content = [{ 1651Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, 1652and ``__attribute__((near))`` attributes on MIPS targets. These attributes may 1653only be added to function declarations and change the code generated 1654by the compiler when directly calling the function. The ``near`` attribute 1655allows calls to the function to be made using the ``jal`` instruction, which 1656requires the function to be located in the same naturally aligned 256MB 1657segment as the caller. The ``long_call`` and ``far`` attributes are synonyms 1658and require the use of a different call sequence that works regardless 1659of the distance between the functions. 1660 1661These attributes have no effect for position-independent code. 1662 1663These attributes take priority over command line switches such 1664as ``-mlong-calls`` and ``-mno-long-calls``. 1665 }]; 1666} 1667 1668def MipsShortCallStyleDocs : Documentation { 1669 let Category = DocCatFunction; 1670 let Heading = "short_call, near"; 1671 let Content = [{ 1672Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, 1673``__attribute__((short__call))``, and ``__attribute__((near))`` attributes 1674on MIPS targets. These attributes may only be added to function declarations 1675and change the code generated by the compiler when directly calling 1676the function. The ``short_call`` and ``near`` attributes are synonyms and 1677allow calls to the function to be made using the ``jal`` instruction, which 1678requires the function to be located in the same naturally aligned 256MB segment 1679as the caller. The ``long_call`` and ``far`` attributes are synonyms and 1680require the use of a different call sequence that works regardless 1681of the distance between the functions. 1682 1683These attributes have no effect for position-independent code. 1684 1685These attributes take priority over command line switches such 1686as ``-mlong-calls`` and ``-mno-long-calls``. 1687 }]; 1688} 1689 1690def RISCVInterruptDocs : Documentation { 1691 let Category = DocCatFunction; 1692 let Heading = "interrupt (RISCV)"; 1693 let Content = [{ 1694Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV 1695targets. This attribute may be attached to a function definition and instructs 1696the backend to generate appropriate function entry/exit code so that it can be 1697used directly as an interrupt service routine. 1698 1699Permissible values for this parameter are ``user``, ``supervisor``, 1700and ``machine``. If there is no parameter, then it defaults to machine. 1701 1702Repeated interrupt attribute on the same declaration will cause a warning 1703to be emitted. In case of repeated declarations, the last one prevails. 1704 1705Refer to: 1706https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html 1707https://riscv.org/specifications/privileged-isa/ 1708The RISC-V Instruction Set Manual Volume II: Privileged Architecture 1709Version 1.10. 1710 }]; 1711} 1712 1713def AVRInterruptDocs : Documentation { 1714 let Category = DocCatFunction; 1715 let Heading = "interrupt (AVR)"; 1716 let Content = [{ 1717Clang supports the GNU style ``__attribute__((interrupt))`` attribute on 1718AVR targets. This attribute may be attached to a function definition and instructs 1719the backend to generate appropriate function entry/exit code so that it can be used 1720directly as an interrupt service routine. 1721 1722On the AVR, the hardware globally disables interrupts when an interrupt is executed. 1723The first instruction of an interrupt handler declared with this attribute is a SEI 1724instruction to re-enable interrupts. See also the signal attribute that 1725does not insert a SEI instruction. 1726 }]; 1727} 1728 1729def AVRSignalDocs : Documentation { 1730 let Category = DocCatFunction; 1731 let Content = [{ 1732Clang supports the GNU style ``__attribute__((signal))`` attribute on 1733AVR targets. This attribute may be attached to a function definition and instructs 1734the backend to generate appropriate function entry/exit code so that it can be used 1735directly as an interrupt service routine. 1736 1737Interrupt handler functions defined with the signal attribute do not re-enable interrupts. 1738}]; 1739} 1740 1741def TargetDocs : Documentation { 1742 let Category = DocCatFunction; 1743 let Content = [{ 1744Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute. 1745This attribute may be attached to a function definition and instructs 1746the backend to use different code generation options than were passed on the 1747command line. 1748 1749The current set of options correspond to the existing "subtarget features" for 1750the target with or without a "-mno-" in front corresponding to the absence 1751of the feature, as well as ``arch="CPU"`` which will change the default "CPU" 1752for the function. 1753 1754Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", 1755"avx", "xop" and largely correspond to the machine specific options handled by 1756the front end. 1757 1758Additionally, this attribute supports function multiversioning for ELF based 1759x86/x86-64 targets, which can be used to create multiple implementations of the 1760same function that will be resolved at runtime based on the priority of their 1761``target`` attribute strings. A function is considered a multiversioned function 1762if either two declarations of the function have different ``target`` attribute 1763strings, or if it has a ``target`` attribute string of ``default``. For 1764example: 1765 1766 .. code-block:: c++ 1767 1768 __attribute__((target("arch=atom"))) 1769 void foo() {} // will be called on 'atom' processors. 1770 __attribute__((target("default"))) 1771 void foo() {} // will be called on any other processors. 1772 1773All multiversioned functions must contain a ``default`` (fallback) 1774implementation, otherwise usages of the function are considered invalid. 1775Additionally, a function may not become multiversioned after its first use. 1776}]; 1777} 1778 1779def MinVectorWidthDocs : Documentation { 1780 let Category = DocCatFunction; 1781 let Content = [{ 1782Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This 1783attribute may be attached to a function and informs the backend that this 1784function desires vectors of at least this width to be generated. Target-specific 1785maximum vector widths still apply. This means even if you ask for something 1786larger than the target supports, you will only get what the target supports. 1787This attribute is meant to be a hint to control target heuristics that may 1788generate narrower vectors than what the target hardware supports. 1789 1790This is currently used by the X86 target to allow some CPUs that support 512-bit 1791vectors to be limited to using 256-bit vectors to avoid frequency penalties. 1792This is currently enabled with the ``-prefer-vector-width=256`` command line 1793option. The ``min_vector_width`` attribute can be used to prevent the backend 1794from trying to split vector operations to match the ``prefer-vector-width``. All 1795X86 vector intrinsics from x86intrin.h already set this attribute. Additionally, 1796use of any of the X86-specific vector builtins will implicitly set this 1797attribute on the calling function. The intent is that explicitly writing vector 1798code using the X86 intrinsics will prevent ``prefer-vector-width`` from 1799affecting the code. 1800}]; 1801} 1802 1803def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">; 1804 1805def AMDGPUFlatWorkGroupSizeDocs : Documentation { 1806 let Category = DocCatAMDGPUAttributes; 1807 let Content = [{ 1808The flat work-group size is the number of work-items in the work-group size 1809specified when the kernel is dispatched. It is the product of the sizes of the 1810x, y, and z dimension of the work-group. 1811 1812Clang supports the 1813``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the 1814AMDGPU target. This attribute may be attached to a kernel function definition 1815and is an optimization hint. 1816 1817``<min>`` parameter specifies the minimum flat work-group size, and ``<max>`` 1818parameter specifies the maximum flat work-group size (must be greater than 1819``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0`` 1820as ``<min>, <max>`` implies the default behavior (``128, 256``). 1821 1822If specified, the AMDGPU target backend might be able to produce better machine 1823code for barriers and perform scratch promotion by estimating available group 1824segment size. 1825 1826An error will be given if: 1827 - Specified values violate subtarget specifications; 1828 - Specified values are not compatible with values provided through other 1829 attributes. 1830 }]; 1831} 1832 1833def AMDGPUWavesPerEUDocs : Documentation { 1834 let Category = DocCatAMDGPUAttributes; 1835 let Content = [{ 1836A compute unit (CU) is responsible for executing the wavefronts of a work-group. 1837It is composed of one or more execution units (EU), which are responsible for 1838executing the wavefronts. An EU can have enough resources to maintain the state 1839of more than one executing wavefront. This allows an EU to hide latency by 1840switching between wavefronts in a similar way to symmetric multithreading on a 1841CPU. In order to allow the state for multiple wavefronts to fit on an EU, the 1842resources used by a single wavefront have to be limited. For example, the number 1843of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding, 1844but can result in having to spill some register state to memory. 1845 1846Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`` 1847attribute for the AMDGPU target. This attribute may be attached to a kernel 1848function definition and is an optimization hint. 1849 1850``<min>`` parameter specifies the requested minimum number of waves per EU, and 1851*optional* ``<max>`` parameter specifies the requested maximum number of waves 1852per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted, 1853then there is no restriction on the maximum number of waves per EU other than 1854the one dictated by the hardware for which the kernel is compiled. Passing 1855``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits). 1856 1857If specified, this attribute allows an advanced developer to tune the number of 1858wavefronts that are capable of fitting within the resources of an EU. The AMDGPU 1859target backend can use this information to limit resources, such as number of 1860SGPRs, number of VGPRs, size of available group and private memory segments, in 1861such a way that guarantees that at least ``<min>`` wavefronts and at most 1862``<max>`` wavefronts are able to fit within the resources of an EU. Requesting 1863more wavefronts can hide memory latency but limits available registers which 1864can result in spilling. Requesting fewer wavefronts can help reduce cache 1865thrashing, but can reduce memory latency hiding. 1866 1867This attribute controls the machine code generated by the AMDGPU target backend 1868to ensure it is capable of meeting the requested values. However, when the 1869kernel is executed, there may be other reasons that prevent meeting the request, 1870for example, there may be wavefronts from other kernels executing on the EU. 1871 1872An error will be given if: 1873 - Specified values violate subtarget specifications; 1874 - Specified values are not compatible with values provided through other 1875 attributes; 1876 - The AMDGPU target backend is unable to create machine code that can meet the 1877 request. 1878 }]; 1879} 1880 1881def AMDGPUNumSGPRNumVGPRDocs : Documentation { 1882 let Category = DocCatAMDGPUAttributes; 1883 let Content = [{ 1884Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and 1885``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU 1886target. These attributes may be attached to a kernel function definition and are 1887an optimization hint. 1888 1889If these attributes are specified, then the AMDGPU target backend will attempt 1890to limit the number of SGPRs and/or VGPRs used to the specified value(s). The 1891number of used SGPRs and/or VGPRs may further be rounded up to satisfy the 1892allocation requirements or constraints of the subtarget. Passing ``0`` as 1893``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits). 1894 1895These attributes can be used to test the AMDGPU target backend. It is 1896recommended that the ``amdgpu_waves_per_eu`` attribute be used to control 1897resources such as SGPRs and VGPRs since it is aware of the limits for different 1898subtargets. 1899 1900An error will be given if: 1901 - Specified values violate subtarget specifications; 1902 - Specified values are not compatible with values provided through other 1903 attributes; 1904 - The AMDGPU target backend is unable to create machine code that can meet the 1905 request. 1906 }]; 1907} 1908 1909def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> { 1910 let Content = [{ 1911Clang supports several different calling conventions, depending on the target 1912platform and architecture. The calling convention used for a function determines 1913how parameters are passed, how results are returned to the caller, and other 1914low-level details of calling a function. 1915 }]; 1916} 1917 1918def PcsDocs : Documentation { 1919 let Category = DocCatCallingConvs; 1920 let Content = [{ 1921On ARM targets, this attribute can be used to select calling conventions 1922similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and 1923"aapcs-vfp". 1924 }]; 1925} 1926 1927def AArch64VectorPcsDocs : Documentation { 1928 let Category = DocCatCallingConvs; 1929 let Content = [{ 1930On AArch64 targets, this attribute changes the calling convention of a 1931function to preserve additional floating-point and Advanced SIMD registers 1932relative to the default calling convention used for AArch64. 1933 1934This means it is more efficient to call such functions from code that performs 1935extensive floating-point and vector calculations, because fewer live SIMD and FP 1936registers need to be saved. This property makes it well-suited for e.g. 1937floating-point or vector math library functions, which are typically leaf 1938functions that require a small number of registers. 1939 1940However, using this attribute also means that it is more expensive to call 1941a function that adheres to the default calling convention from within such 1942a function. Therefore, it is recommended that this attribute is only used 1943for leaf functions. 1944 1945For more information, see the documentation for `aarch64_vector_pcs`_ on 1946the Arm Developer website. 1947 1948.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi 1949 }]; 1950} 1951 1952def RegparmDocs : Documentation { 1953 let Category = DocCatCallingConvs; 1954 let Content = [{ 1955On 32-bit x86 targets, the regparm attribute causes the compiler to pass 1956the first three integer parameters in EAX, EDX, and ECX instead of on the 1957stack. This attribute has no effect on variadic functions, and all parameters 1958are passed via the stack as normal. 1959 }]; 1960} 1961 1962def SysVABIDocs : Documentation { 1963 let Category = DocCatCallingConvs; 1964 let Content = [{ 1965On Windows x86_64 targets, this attribute changes the calling convention of a 1966function to match the default convention used on Sys V targets such as Linux, 1967Mac, and BSD. This attribute has no effect on other targets. 1968 }]; 1969} 1970 1971def MSABIDocs : Documentation { 1972 let Category = DocCatCallingConvs; 1973 let Content = [{ 1974On non-Windows x86_64 targets, this attribute changes the calling convention of 1975a function to match the default convention used on Windows x86_64. This 1976attribute has no effect on Windows targets or non-x86_64 targets. 1977 }]; 1978} 1979 1980def StdCallDocs : Documentation { 1981 let Category = DocCatCallingConvs; 1982 let Content = [{ 1983On 32-bit x86 targets, this attribute changes the calling convention of a 1984function to clear parameters off of the stack on return. This convention does 1985not support variadic calls or unprototyped functions in C, and has no effect on 1986x86_64 targets. This calling convention is used widely by the Windows API and 1987COM applications. See the documentation for `__stdcall`_ on MSDN. 1988 1989.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx 1990 }]; 1991} 1992 1993def FastCallDocs : Documentation { 1994 let Category = DocCatCallingConvs; 1995 let Content = [{ 1996On 32-bit x86 targets, this attribute changes the calling convention of a 1997function to use ECX and EDX as register parameters and clear parameters off of 1998the stack on return. This convention does not support variadic calls or 1999unprototyped functions in C, and has no effect on x86_64 targets. This calling 2000convention is supported primarily for compatibility with existing code. Users 2001seeking register parameters should use the ``regparm`` attribute, which does 2002not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN. 2003 2004.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx 2005 }]; 2006} 2007 2008def RegCallDocs : Documentation { 2009 let Category = DocCatCallingConvs; 2010 let Content = [{ 2011On x86 targets, this attribute changes the calling convention to 2012`__regcall`_ convention. This convention aims to pass as many arguments 2013as possible in registers. It also tries to utilize registers for the 2014return value whenever it is possible. 2015 2016.. _`__regcall`: https://software.intel.com/en-us/node/693069 2017 }]; 2018} 2019 2020def ThisCallDocs : Documentation { 2021 let Category = DocCatCallingConvs; 2022 let Content = [{ 2023On 32-bit x86 targets, this attribute changes the calling convention of a 2024function to use ECX for the first parameter (typically the implicit ``this`` 2025parameter of C++ methods) and clear parameters off of the stack on return. This 2026convention does not support variadic calls or unprototyped functions in C, and 2027has no effect on x86_64 targets. See the documentation for `__thiscall`_ on 2028MSDN. 2029 2030.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx 2031 }]; 2032} 2033 2034def VectorCallDocs : Documentation { 2035 let Category = DocCatCallingConvs; 2036 let Content = [{ 2037On 32-bit x86 *and* x86_64 targets, this attribute changes the calling 2038convention of a function to pass vector parameters in SSE registers. 2039 2040On 32-bit x86 targets, this calling convention is similar to ``__fastcall``. 2041The first two integer parameters are passed in ECX and EDX. Subsequent integer 2042parameters are passed in memory, and callee clears the stack. On x86_64 2043targets, the callee does *not* clear the stack, and integer parameters are 2044passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling 2045convention. 2046 2047On both 32-bit x86 and x86_64 targets, vector and floating point arguments are 2048passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are 2049passed in sequential SSE registers if enough are available. If AVX is enabled, 2050256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that 2051cannot be passed in registers for any reason is passed by reference, which 2052allows the caller to align the parameter memory. 2053 2054See the documentation for `__vectorcall`_ on MSDN for more details. 2055 2056.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx 2057 }]; 2058} 2059 2060def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> { 2061 let Content = [{ 2062Clang supports additional attributes for checking basic resource management 2063properties, specifically for unique objects that have a single owning reference. 2064The following attributes are currently supported, although **the implementation 2065for these annotations is currently in development and are subject to change.** 2066 }]; 2067} 2068 2069def SetTypestateDocs : Documentation { 2070 let Category = DocCatConsumed; 2071 let Content = [{ 2072Annotate methods that transition an object into a new state with 2073``__attribute__((set_typestate(new_state)))``. The new state must be 2074unconsumed, consumed, or unknown. 2075 }]; 2076} 2077 2078def CallableWhenDocs : Documentation { 2079 let Category = DocCatConsumed; 2080 let Content = [{ 2081Use ``__attribute__((callable_when(...)))`` to indicate what states a method 2082may be called in. Valid states are unconsumed, consumed, or unknown. Each 2083argument to this attribute must be a quoted string. E.g.: 2084 2085``__attribute__((callable_when("unconsumed", "unknown")))`` 2086 }]; 2087} 2088 2089def TestTypestateDocs : Documentation { 2090 let Category = DocCatConsumed; 2091 let Content = [{ 2092Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method 2093returns true if the object is in the specified state.. 2094 }]; 2095} 2096 2097def ParamTypestateDocs : Documentation { 2098 let Category = DocCatConsumed; 2099 let Content = [{ 2100This attribute specifies expectations about function parameters. Calls to an 2101function with annotated parameters will issue a warning if the corresponding 2102argument isn't in the expected state. The attribute is also used to set the 2103initial state of the parameter when analyzing the function's body. 2104 }]; 2105} 2106 2107def ReturnTypestateDocs : Documentation { 2108 let Category = DocCatConsumed; 2109 let Content = [{ 2110The ``return_typestate`` attribute can be applied to functions or parameters. 2111When applied to a function the attribute specifies the state of the returned 2112value. The function's body is checked to ensure that it always returns a value 2113in the specified state. On the caller side, values returned by the annotated 2114function are initialized to the given state. 2115 2116When applied to a function parameter it modifies the state of an argument after 2117a call to the function returns. The function's body is checked to ensure that 2118the parameter is in the expected state before returning. 2119 }]; 2120} 2121 2122def ConsumableDocs : Documentation { 2123 let Category = DocCatConsumed; 2124 let Content = [{ 2125Each ``class`` that uses any of the typestate annotations must first be marked 2126using the ``consumable`` attribute. Failure to do so will result in a warning. 2127 2128This attribute accepts a single parameter that must be one of the following: 2129``unknown``, ``consumed``, or ``unconsumed``. 2130 }]; 2131} 2132 2133def NoSanitizeDocs : Documentation { 2134 let Category = DocCatFunction; 2135 let Content = [{ 2136Use the ``no_sanitize`` attribute on a function or a global variable 2137declaration to specify that a particular instrumentation or set of 2138instrumentations should not be applied. The attribute takes a list of 2139string literals, which have the same meaning as values accepted by the 2140``-fno-sanitize=`` flag. For example, 2141``__attribute__((no_sanitize("address", "thread")))`` specifies that 2142AddressSanitizer and ThreadSanitizer should not be applied to the 2143function or variable. 2144 2145See :ref:`Controlling Code Generation <controlling-code-generation>` for a 2146full list of supported sanitizer flags. 2147 }]; 2148} 2149 2150def NoSanitizeAddressDocs : Documentation { 2151 let Category = DocCatFunction; 2152 // This function has multiple distinct spellings, and so it requires a custom 2153 // heading to be specified. The most common spelling is sufficient. 2154 let Heading = "no_sanitize_address, no_address_safety_analysis"; 2155 let Content = [{ 2156.. _langext-address_sanitizer: 2157 2158Use ``__attribute__((no_sanitize_address))`` on a function or a global 2159variable declaration to specify that address safety instrumentation 2160(e.g. AddressSanitizer) should not be applied. 2161 }]; 2162} 2163 2164def NoSanitizeThreadDocs : Documentation { 2165 let Category = DocCatFunction; 2166 let Heading = "no_sanitize_thread"; 2167 let Content = [{ 2168.. _langext-thread_sanitizer: 2169 2170Use ``__attribute__((no_sanitize_thread))`` on a function declaration to 2171specify that checks for data races on plain (non-atomic) memory accesses should 2172not be inserted by ThreadSanitizer. The function is still instrumented by the 2173tool to avoid false positives and provide meaningful stack traces. 2174 }]; 2175} 2176 2177def NoSanitizeMemoryDocs : Documentation { 2178 let Category = DocCatFunction; 2179 let Heading = "no_sanitize_memory"; 2180 let Content = [{ 2181.. _langext-memory_sanitizer: 2182 2183Use ``__attribute__((no_sanitize_memory))`` on a function declaration to 2184specify that checks for uninitialized memory should not be inserted 2185(e.g. by MemorySanitizer). The function may still be instrumented by the tool 2186to avoid false positives in other places. 2187 }]; 2188} 2189 2190def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> { 2191 let Content = [{ 2192Clang supports additional attributes to enable checking type safety properties 2193that can't be enforced by the C type system. To see warnings produced by these 2194checks, ensure that -Wtype-safety is enabled. Use cases include: 2195 2196* MPI library implementations, where these attributes enable checking that 2197 the buffer type matches the passed ``MPI_Datatype``; 2198* for HDF5 library there is a similar use case to MPI; 2199* checking types of variadic functions' arguments for functions like 2200 ``fcntl()`` and ``ioctl()``. 2201 2202You can detect support for these attributes with ``__has_attribute()``. For 2203example: 2204 2205.. code-block:: c++ 2206 2207 #if defined(__has_attribute) 2208 # if __has_attribute(argument_with_type_tag) && \ 2209 __has_attribute(pointer_with_type_tag) && \ 2210 __has_attribute(type_tag_for_datatype) 2211 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) 2212 /* ... other macros ... */ 2213 # endif 2214 #endif 2215 2216 #if !defined(ATTR_MPI_PWT) 2217 # define ATTR_MPI_PWT(buffer_idx, type_idx) 2218 #endif 2219 2220 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 2221 ATTR_MPI_PWT(1,3); 2222 }]; 2223} 2224 2225def ArgumentWithTypeTagDocs : Documentation { 2226 let Category = DocCatTypeSafety; 2227 let Heading = "argument_with_type_tag"; 2228 let Content = [{ 2229Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, 2230type_tag_idx)))`` on a function declaration to specify that the function 2231accepts a type tag that determines the type of some other argument. 2232 2233This attribute is primarily useful for checking arguments of variadic functions 2234(``pointer_with_type_tag`` can be used in most non-variadic cases). 2235 2236In the attribute prototype above: 2237 * ``arg_kind`` is an identifier that should be used when annotating all 2238 applicable type tags. 2239 * ``arg_idx`` provides the position of a function argument. The expected type of 2240 this function argument will be determined by the function argument specified 2241 by ``type_tag_idx``. In the code example below, "3" means that the type of the 2242 function's third argument will be determined by ``type_tag_idx``. 2243 * ``type_tag_idx`` provides the position of a function argument. This function 2244 argument will be a type tag. The type tag will determine the expected type of 2245 the argument specified by ``arg_idx``. In the code example below, "2" means 2246 that the type tag associated with the function's second argument should agree 2247 with the type of the argument specified by ``arg_idx``. 2248 2249For example: 2250 2251.. code-block:: c++ 2252 2253 int fcntl(int fd, int cmd, ...) 2254 __attribute__(( argument_with_type_tag(fcntl,3,2) )); 2255 // The function's second argument will be a type tag; this type tag will 2256 // determine the expected type of the function's third argument. 2257 }]; 2258} 2259 2260def PointerWithTypeTagDocs : Documentation { 2261 let Category = DocCatTypeSafety; 2262 let Heading = "pointer_with_type_tag"; 2263 let Content = [{ 2264Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` 2265on a function declaration to specify that the function accepts a type tag that 2266determines the pointee type of some other pointer argument. 2267 2268In the attribute prototype above: 2269 * ``ptr_kind`` is an identifier that should be used when annotating all 2270 applicable type tags. 2271 * ``ptr_idx`` provides the position of a function argument; this function 2272 argument will have a pointer type. The expected pointee type of this pointer 2273 type will be determined by the function argument specified by 2274 ``type_tag_idx``. In the code example below, "1" means that the pointee type 2275 of the function's first argument will be determined by ``type_tag_idx``. 2276 * ``type_tag_idx`` provides the position of a function argument; this function 2277 argument will be a type tag. The type tag will determine the expected pointee 2278 type of the pointer argument specified by ``ptr_idx``. In the code example 2279 below, "3" means that the type tag associated with the function's third 2280 argument should agree with the pointee type of the pointer argument specified 2281 by ``ptr_idx``. 2282 2283For example: 2284 2285.. code-block:: c++ 2286 2287 typedef int MPI_Datatype; 2288 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 2289 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 2290 // The function's 3rd argument will be a type tag; this type tag will 2291 // determine the expected pointee type of the function's 1st argument. 2292 }]; 2293} 2294 2295def TypeTagForDatatypeDocs : Documentation { 2296 let Category = DocCatTypeSafety; 2297 let Content = [{ 2298When declaring a variable, use 2299``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that 2300is tied to the ``type`` argument given to the attribute. 2301 2302In the attribute prototype above: 2303 * ``kind`` is an identifier that should be used when annotating all applicable 2304 type tags. 2305 * ``type`` indicates the name of the type. 2306 2307Clang supports annotating type tags of two forms. 2308 2309 * **Type tag that is a reference to a declared identifier.** 2310 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that 2311 identifier: 2312 2313 .. code-block:: c++ 2314 2315 typedef int MPI_Datatype; 2316 extern struct mpi_datatype mpi_datatype_int 2317 __attribute__(( type_tag_for_datatype(mpi,int) )); 2318 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) 2319 // &mpi_datatype_int is a type tag. It is tied to type "int". 2320 2321 * **Type tag that is an integral literal.** 2322 Declare a ``static const`` variable with an initializer value and attach 2323 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration: 2324 2325 .. code-block:: c++ 2326 2327 typedef int MPI_Datatype; 2328 static const MPI_Datatype mpi_datatype_int 2329 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42; 2330 #define MPI_INT ((MPI_Datatype) 42) 2331 // The number 42 is a type tag. It is tied to type "int". 2332 2333 2334The ``type_tag_for_datatype`` attribute also accepts an optional third argument 2335that determines how the type of the function argument specified by either 2336``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type 2337tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the 2338function argument specified by ``arg_idx`` is compared against the type 2339associated with the type tag. Also recall that for the ``pointer_with_type_tag`` 2340attribute, the pointee type of the function argument specified by ``ptr_idx`` is 2341compared against the type associated with the type tag.) There are two supported 2342values for this optional third argument: 2343 2344 * ``layout_compatible`` will cause types to be compared according to 2345 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the 2346 layout-compatibility rules for two standard-layout struct types and for two 2347 standard-layout union types). This is useful when creating a type tag 2348 associated with a struct or union type. For example: 2349 2350 .. code-block:: c++ 2351 2352 /* In mpi.h */ 2353 typedef int MPI_Datatype; 2354 struct internal_mpi_double_int { double d; int i; }; 2355 extern struct mpi_datatype mpi_datatype_double_int 2356 __attribute__(( type_tag_for_datatype(mpi, 2357 struct internal_mpi_double_int, layout_compatible) )); 2358 2359 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) 2360 2361 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) 2362 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 2363 2364 /* In user code */ 2365 struct my_pair { double a; int b; }; 2366 struct my_pair *buffer; 2367 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the 2368 // layout of my_pair is 2369 // compatible with that of 2370 // internal_mpi_double_int 2371 2372 struct my_int_pair { int a; int b; } 2373 struct my_int_pair *buffer2; 2374 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the 2375 // layout of my_int_pair 2376 // does not match that of 2377 // internal_mpi_double_int 2378 2379 * ``must_be_null`` specifies that the function argument specified by either 2380 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for 2381 the ``pointer_with_type_tag`` attribute) should be a null pointer constant. 2382 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For 2383 example: 2384 2385 .. code-block:: c++ 2386 2387 /* In mpi.h */ 2388 typedef int MPI_Datatype; 2389 extern struct mpi_datatype mpi_datatype_null 2390 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); 2391 2392 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) 2393 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) 2394 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 2395 2396 /* In user code */ 2397 struct my_pair { double a; int b; }; 2398 struct my_pair *buffer; 2399 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL 2400 // was specified but buffer 2401 // is not a null pointer 2402 }]; 2403} 2404 2405def FlattenDocs : Documentation { 2406 let Category = DocCatFunction; 2407 let Content = [{ 2408The ``flatten`` attribute causes calls within the attributed function to 2409be inlined unless it is impossible to do so, for example if the body of the 2410callee is unavailable or if the callee has the ``noinline`` attribute. 2411 }]; 2412} 2413 2414def FormatDocs : Documentation { 2415 let Category = DocCatFunction; 2416 let Content = [{ 2417 2418Clang supports the ``format`` attribute, which indicates that the function 2419accepts a ``printf`` or ``scanf``-like format string and corresponding 2420arguments or a ``va_list`` that contains these arguments. 2421 2422Please see `GCC documentation about format attribute 2423<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details 2424about attribute syntax. 2425 2426Clang implements two kinds of checks with this attribute. 2427 2428#. Clang checks that the function with the ``format`` attribute is called with 2429 a format string that uses format specifiers that are allowed, and that 2430 arguments match the format string. This is the ``-Wformat`` warning, it is 2431 on by default. 2432 2433#. Clang checks that the format string argument is a literal string. This is 2434 the ``-Wformat-nonliteral`` warning, it is off by default. 2435 2436 Clang implements this mostly the same way as GCC, but there is a difference 2437 for functions that accept a ``va_list`` argument (for example, ``vprintf``). 2438 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such 2439 functions. Clang does not warn if the format string comes from a function 2440 parameter, where the function is annotated with a compatible attribute, 2441 otherwise it warns. For example: 2442 2443 .. code-block:: c 2444 2445 __attribute__((__format__ (__scanf__, 1, 3))) 2446 void foo(const char* s, char *buf, ...) { 2447 va_list ap; 2448 va_start(ap, buf); 2449 2450 vprintf(s, ap); // warning: format string is not a string literal 2451 } 2452 2453 In this case we warn because ``s`` contains a format string for a 2454 ``scanf``-like function, but it is passed to a ``printf``-like function. 2455 2456 If the attribute is removed, clang still warns, because the format string is 2457 not a string literal. 2458 2459 Another example: 2460 2461 .. code-block:: c 2462 2463 __attribute__((__format__ (__printf__, 1, 3))) 2464 void foo(const char* s, char *buf, ...) { 2465 va_list ap; 2466 va_start(ap, buf); 2467 2468 vprintf(s, ap); // warning 2469 } 2470 2471 In this case Clang does not warn because the format string ``s`` and 2472 the corresponding arguments are annotated. If the arguments are 2473 incorrect, the caller of ``foo`` will receive a warning. 2474 }]; 2475} 2476 2477def AlignValueDocs : Documentation { 2478 let Category = DocCatType; 2479 let Content = [{ 2480The align_value attribute can be added to the typedef of a pointer type or the 2481declaration of a variable of pointer or reference type. It specifies that the 2482pointer will point to, or the reference will bind to, only objects with at 2483least the provided alignment. This alignment value must be some positive power 2484of 2. 2485 2486 .. code-block:: c 2487 2488 typedef double * aligned_double_ptr __attribute__((align_value(64))); 2489 void foo(double & x __attribute__((align_value(128)), 2490 aligned_double_ptr y) { ... } 2491 2492If the pointer value does not have the specified alignment at runtime, the 2493behavior of the program is undefined. 2494 }]; 2495} 2496 2497def FlagEnumDocs : Documentation { 2498 let Category = DocCatDecl; 2499 let Content = [{ 2500This attribute can be added to an enumerator to signal to the compiler that it 2501is intended to be used as a flag type. This will cause the compiler to assume 2502that the range of the type includes all of the values that you can get by 2503manipulating bits of the enumerator when issuing warnings. 2504 }]; 2505} 2506 2507def EnumExtensibilityDocs : Documentation { 2508 let Category = DocCatDecl; 2509 let Content = [{ 2510Attribute ``enum_extensibility`` is used to distinguish between enum definitions 2511that are extensible and those that are not. The attribute can take either 2512``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the 2513enum type takes a value that corresponds to one of the enumerators listed in the 2514enum definition or, when the enum is annotated with ``flag_enum``, a value that 2515can be constructed using values corresponding to the enumerators. ``open`` 2516indicates a variable of the enum type can take any values allowed by the 2517standard and instructs clang to be more lenient when issuing warnings. 2518 2519.. code-block:: c 2520 2521 enum __attribute__((enum_extensibility(closed))) ClosedEnum { 2522 A0, A1 2523 }; 2524 2525 enum __attribute__((enum_extensibility(open))) OpenEnum { 2526 B0, B1 2527 }; 2528 2529 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum { 2530 C0 = 1 << 0, C1 = 1 << 1 2531 }; 2532 2533 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum { 2534 D0 = 1 << 0, D1 = 1 << 1 2535 }; 2536 2537 void foo1() { 2538 enum ClosedEnum ce; 2539 enum OpenEnum oe; 2540 enum ClosedFlagEnum cfe; 2541 enum OpenFlagEnum ofe; 2542 2543 ce = A1; // no warnings 2544 ce = 100; // warning issued 2545 oe = B1; // no warnings 2546 oe = 100; // no warnings 2547 cfe = C0 | C1; // no warnings 2548 cfe = C0 | C1 | 4; // warning issued 2549 ofe = D0 | D1; // no warnings 2550 ofe = D0 | D1 | 4; // no warnings 2551 } 2552 2553 }]; 2554} 2555 2556def EmptyBasesDocs : Documentation { 2557 let Category = DocCatDecl; 2558 let Content = [{ 2559The empty_bases attribute permits the compiler to utilize the 2560empty-base-optimization more frequently. 2561This attribute only applies to struct, class, and union types. 2562It is only supported when using the Microsoft C++ ABI. 2563 }]; 2564} 2565 2566def LayoutVersionDocs : Documentation { 2567 let Category = DocCatDecl; 2568 let Content = [{ 2569The layout_version attribute requests that the compiler utilize the class 2570layout rules of a particular compiler version. 2571This attribute only applies to struct, class, and union types. 2572It is only supported when using the Microsoft C++ ABI. 2573 }]; 2574} 2575 2576def LifetimeBoundDocs : Documentation { 2577 let Category = DocCatFunction; 2578 let Content = [{ 2579The ``lifetimebound`` attribute indicates that a resource owned by 2580a function parameter or implicit object parameter 2581is retained by the return value of the annotated function 2582(or, for a parameter of a constructor, in the value of the constructed object). 2583It is only supported in C++. 2584 2585This attribute provides an experimental implementation of the facility 2586described in the C++ committee paper [http://wg21.link/p0936r0](P0936R0), 2587and is subject to change as the design of the corresponding functionality 2588changes. 2589 }]; 2590} 2591 2592def TrivialABIDocs : Documentation { 2593 let Category = DocCatDecl; 2594 let Content = [{ 2595The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union. 2596It instructs the compiler to pass and return the type using the C ABI for the 2597underlying type when the type would otherwise be considered non-trivial for the 2598purpose of calls. 2599A class annotated with `trivial_abi` can have non-trivial destructors or copy/move constructors without automatically becoming non-trivial for the purposes of calls. For example: 2600 2601 .. code-block:: c++ 2602 2603 // A is trivial for the purposes of calls because `trivial_abi` makes the 2604 // user-provided special functions trivial. 2605 struct __attribute__((trivial_abi)) A { 2606 ~A(); 2607 A(const A &); 2608 A(A &&); 2609 int x; 2610 }; 2611 2612 // B's destructor and copy/move constructor are considered trivial for the 2613 // purpose of calls because A is trivial. 2614 struct B { 2615 A a; 2616 }; 2617 2618If a type is trivial for the purposes of calls, has a non-trivial destructor, 2619and is passed as an argument by value, the convention is that the callee will 2620destroy the object before returning. 2621 2622Attribute ``trivial_abi`` has no effect in the following cases: 2623 2624- The class directly declares a virtual base or virtual methods. 2625- The class has a base class that is non-trivial for the purposes of calls. 2626- The class has a non-static data member whose type is non-trivial for the purposes of calls, which includes: 2627 2628 - classes that are non-trivial for the purposes of calls 2629 - __weak-qualified types in Objective-C++ 2630 - arrays of any of the above 2631 }]; 2632} 2633 2634def MSInheritanceDocs : Documentation { 2635 let Category = DocCatDecl; 2636 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance"; 2637 let Content = [{ 2638This collection of keywords is enabled under ``-fms-extensions`` and controls 2639the pointer-to-member representation used on ``*-*-win32`` targets. 2640 2641The ``*-*-win32`` targets utilize a pointer-to-member representation which 2642varies in size and alignment depending on the definition of the underlying 2643class. 2644 2645However, this is problematic when a forward declaration is only available and 2646no definition has been made yet. In such cases, Clang is forced to utilize the 2647most general representation that is available to it. 2648 2649These keywords make it possible to use a pointer-to-member representation other 2650than the most general one regardless of whether or not the definition will ever 2651be present in the current translation unit. 2652 2653This family of keywords belong between the ``class-key`` and ``class-name``: 2654 2655.. code-block:: c++ 2656 2657 struct __single_inheritance S; 2658 int S::*i; 2659 struct S {}; 2660 2661This keyword can be applied to class templates but only has an effect when used 2662on full specializations: 2663 2664.. code-block:: c++ 2665 2666 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template 2667 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization 2668 template <> struct __single_inheritance A<int, float>; 2669 2670Note that choosing an inheritance model less general than strictly necessary is 2671an error: 2672 2673.. code-block:: c++ 2674 2675 struct __multiple_inheritance S; // error: inheritance model does not match definition 2676 int S::*i; 2677 struct S {}; 2678}]; 2679} 2680 2681def MSNoVTableDocs : Documentation { 2682 let Category = DocCatDecl; 2683 let Content = [{ 2684This attribute can be added to a class declaration or definition to signal to 2685the compiler that constructors and destructors will not reference the virtual 2686function table. It is only supported when using the Microsoft C++ ABI. 2687 }]; 2688} 2689 2690def OptnoneDocs : Documentation { 2691 let Category = DocCatFunction; 2692 let Content = [{ 2693The ``optnone`` attribute suppresses essentially all optimizations 2694on a function or method, regardless of the optimization level applied to 2695the compilation unit as a whole. This is particularly useful when you 2696need to debug a particular function, but it is infeasible to build the 2697entire application without optimization. Avoiding optimization on the 2698specified function can improve the quality of the debugging information 2699for that function. 2700 2701This attribute is incompatible with the ``always_inline`` and ``minsize`` 2702attributes. 2703 }]; 2704} 2705 2706def LoopHintDocs : Documentation { 2707 let Category = DocCatStmt; 2708 let Heading = "#pragma clang loop"; 2709 let Content = [{ 2710The ``#pragma clang loop`` directive allows loop optimization hints to be 2711specified for the subsequent loop. The directive allows pipelining to be 2712disabled, or vectorization, interleaving, and unrolling to be enabled or disabled. 2713Vector width, interleave count, unrolling count, and the initiation interval 2714for pipelining can be explicitly specified. See `language extensions 2715<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 2716for details. 2717 }]; 2718} 2719 2720def UnrollHintDocs : Documentation { 2721 let Category = DocCatStmt; 2722 let Heading = "#pragma unroll, #pragma nounroll"; 2723 let Content = [{ 2724Loop unrolling optimization hints can be specified with ``#pragma unroll`` and 2725``#pragma nounroll``. The pragma is placed immediately before a for, while, 2726do-while, or c++11 range-based for loop. 2727 2728Specifying ``#pragma unroll`` without a parameter directs the loop unroller to 2729attempt to fully unroll the loop if the trip count is known at compile time and 2730attempt to partially unroll the loop if the trip count is not known at compile 2731time: 2732 2733.. code-block:: c++ 2734 2735 #pragma unroll 2736 for (...) { 2737 ... 2738 } 2739 2740Specifying the optional parameter, ``#pragma unroll _value_``, directs the 2741unroller to unroll the loop ``_value_`` times. The parameter may optionally be 2742enclosed in parentheses: 2743 2744.. code-block:: c++ 2745 2746 #pragma unroll 16 2747 for (...) { 2748 ... 2749 } 2750 2751 #pragma unroll(16) 2752 for (...) { 2753 ... 2754 } 2755 2756Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled: 2757 2758.. code-block:: c++ 2759 2760 #pragma nounroll 2761 for (...) { 2762 ... 2763 } 2764 2765``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to 2766``#pragma clang loop unroll(full)`` and 2767``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll`` 2768is equivalent to ``#pragma clang loop unroll(disable)``. See 2769`language extensions 2770<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 2771for further details including limitations of the unroll hints. 2772 }]; 2773} 2774 2775def PipelineHintDocs : Documentation { 2776 let Category = DocCatStmt; 2777 let Heading = "#pragma clang loop pipeline, #pragma clang loop pipeline_initiation_interval"; 2778 let Content = [{ 2779 Software Pipelining optimization is a technique used to optimize loops by 2780 utilizing instruction-level parallelism. It reorders loop instructions to 2781 overlap iterations. As a result, the next iteration starts before the previous 2782 iteration has finished. The module scheduling technique creates a schedule for 2783 one iteration such that when repeating at regular intervals, no inter-iteration 2784 dependencies are violated. This constant interval(in cycles) between the start 2785 of iterations is called the initiation interval. i.e. The initiation interval 2786 is the number of cycles between two iterations of an unoptimized loop in the 2787 newly created schedule. A new, optimized loop is created such that a single iteration 2788 of the loop executes in the same number of cycles as the initiation interval. 2789 For further details see <https://llvm.org/pubs/2005-06-17-LattnerMSThesis-book.pdf>. 2790 2791 ``#pragma clang loop pipeline and #pragma loop pipeline_initiation_interval`` 2792 could be used as hints for the software pipelining optimization. The pragma is 2793 placed immediately before a for, while, do-while, or a C++11 range-based for 2794 loop. 2795 2796 Using ``#pragma clang loop pipeline(disable)`` avoids the software pipelining 2797 optimization. The disable state can only be specified: 2798 2799 .. code-block:: c++ 2800 2801 #pragma clang loop pipeline(disable) 2802 for (...) { 2803 ... 2804 } 2805 2806 Using ``#pragma loop pipeline_initiation_interval`` instructs 2807 the software pipeliner to try the specified initiation interval. 2808 If a schedule was found then the resulting loop iteration would have 2809 the specified cycle count. If a schedule was not found then loop 2810 remains unchanged. The initiation interval must be a positive number 2811 greater than zero: 2812 2813 .. code-block:: c++ 2814 2815 #pragma loop pipeline_initiation_interval(10) 2816 for (...) { 2817 ... 2818 } 2819 2820 }]; 2821} 2822 2823def OpenCLUnrollHintDocs : Documentation { 2824 let Category = DocCatStmt; 2825 let Content = [{ 2826The opencl_unroll_hint attribute qualifier can be used to specify that a loop 2827(for, while and do loops) can be unrolled. This attribute qualifier can be 2828used to specify full unrolling or partial unrolling by a specified amount. 2829This is a compiler hint and the compiler may ignore this directive. See 2830`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_ 2831s6.11.5 for details. 2832 }]; 2833} 2834 2835def OpenCLIntelReqdSubGroupSizeDocs : Documentation { 2836 let Category = DocCatStmt; 2837 let Content = [{ 2838The optional attribute intel_reqd_sub_group_size can be used to indicate that 2839the kernel must be compiled and executed with the specified subgroup size. When 2840this attribute is present, get_max_sub_group_size() is guaranteed to return the 2841specified integer value. This is important for the correctness of many subgroup 2842algorithms, and in some cases may be used by the compiler to generate more optimal 2843code. See `cl_intel_required_subgroup_size 2844<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>` 2845for details. 2846 }]; 2847} 2848 2849def OpenCLAccessDocs : Documentation { 2850 let Category = DocCatStmt; 2851 let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)"; 2852 let Content = [{ 2853The access qualifiers must be used with image object arguments or pipe arguments 2854to declare if they are being read or written by a kernel or function. 2855 2856The read_only/__read_only, write_only/__write_only and read_write/__read_write 2857names are reserved for use as access qualifiers and shall not be used otherwise. 2858 2859.. code-block:: c 2860 2861 kernel void 2862 foo (read_only image2d_t imageA, 2863 write_only image2d_t imageB) { 2864 ... 2865 } 2866 2867In the above example imageA is a read-only 2D image object, and imageB is a 2868write-only 2D image object. 2869 2870The read_write (or __read_write) qualifier can not be used with pipe. 2871 2872More details can be found in the OpenCL C language Spec v2.0, Section 6.6. 2873 }]; 2874} 2875 2876def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> { 2877 let Content = [{ 2878The address space qualifier may be used to specify the region of memory that is 2879used to allocate the object. OpenCL supports the following address spaces: 2880__generic(generic), __global(global), __local(local), __private(private), 2881__constant(constant). 2882 2883 .. code-block:: c 2884 2885 __constant int c = ...; 2886 2887 __generic int* foo(global int* g) { 2888 __local int* l; 2889 private int p; 2890 ... 2891 return l; 2892 } 2893 2894More details can be found in the OpenCL C language Spec v2.0, Section 6.5. 2895 }]; 2896} 2897 2898def OpenCLAddressSpaceGenericDocs : Documentation { 2899 let Category = DocOpenCLAddressSpaces; 2900 let Content = [{ 2901The generic address space attribute is only available with OpenCL v2.0 and later. 2902It can be used with pointer types. Variables in global and local scope and 2903function parameters in non-kernel functions can have the generic address space 2904type attribute. It is intended to be a placeholder for any other address space 2905except for '__constant' in OpenCL code which can be used with multiple address 2906spaces. 2907 }]; 2908} 2909 2910def OpenCLAddressSpaceConstantDocs : Documentation { 2911 let Category = DocOpenCLAddressSpaces; 2912 let Content = [{ 2913The constant address space attribute signals that an object is located in 2914a constant (non-modifiable) memory region. It is available to all work items. 2915Any type can be annotated with the constant address space attribute. Objects 2916with the constant address space qualifier can be declared in any scope and must 2917have an initializer. 2918 }]; 2919} 2920 2921def OpenCLAddressSpaceGlobalDocs : Documentation { 2922 let Category = DocOpenCLAddressSpaces; 2923 let Content = [{ 2924The global address space attribute specifies that an object is allocated in 2925global memory, which is accessible by all work items. The content stored in this 2926memory area persists between kernel executions. Pointer types to the global 2927address space are allowed as function parameters or local variables. Starting 2928with OpenCL v2.0, the global address space can be used with global (program 2929scope) variables and static local variable as well. 2930 }]; 2931} 2932 2933def OpenCLAddressSpaceLocalDocs : Documentation { 2934 let Category = DocOpenCLAddressSpaces; 2935 let Content = [{ 2936The local address space specifies that an object is allocated in the local (work 2937group) memory area, which is accessible to all work items in the same work 2938group. The content stored in this memory region is not accessible after 2939the kernel execution ends. In a kernel function scope, any variable can be in 2940the local address space. In other scopes, only pointer types to the local address 2941space are allowed. Local address space variables cannot have an initializer. 2942 }]; 2943} 2944 2945def OpenCLAddressSpacePrivateDocs : Documentation { 2946 let Category = DocOpenCLAddressSpaces; 2947 let Content = [{ 2948The private address space specifies that an object is allocated in the private 2949(work item) memory. Other work items cannot access the same memory area and its 2950content is destroyed after work item execution ends. Local variables can be 2951declared in the private address space. Function arguments are always in the 2952private address space. Kernel function arguments of a pointer or an array type 2953cannot point to the private address space. 2954 }]; 2955} 2956 2957def OpenCLNoSVMDocs : Documentation { 2958 let Category = DocCatVariable; 2959 let Content = [{ 2960OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for 2961pointer variable. It informs the compiler that the pointer does not refer 2962to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details. 2963 2964Since it is not widely used and has been removed from OpenCL 2.1, it is ignored 2965by Clang. 2966 }]; 2967} 2968def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> { 2969 let Content = [{ 2970Whether a particular pointer may be "null" is an important concern when working with pointers in the C family of languages. The various nullability attributes indicate whether a particular pointer can be null or not, which makes APIs more expressive and can help static analysis tools identify bugs involving null pointers. Clang supports several kinds of nullability attributes: the ``nonnull`` and ``returns_nonnull`` attributes indicate which function or method parameters and result types can never be null, while nullability type qualifiers indicate which pointer types can be null (``_Nullable``) or cannot be null (``_Nonnull``). 2971 2972The nullability (type) qualifiers express whether a value of a given pointer type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning for null (the ``_Nonnull`` qualifier), or for which the purpose of null is unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers are expressed within the type system, they are more general than the ``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for example) a nullable pointer to an array of nonnull pointers. Nullability qualifiers are written to the right of the pointer to which they apply. For example: 2973 2974 .. code-block:: c 2975 2976 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior). 2977 int fetch(int * _Nonnull ptr) { return *ptr; } 2978 2979 // 'ptr' may be null. 2980 int fetch_or_zero(int * _Nullable ptr) { 2981 return ptr ? *ptr : 0; 2982 } 2983 2984 // A nullable pointer to non-null pointers to const characters. 2985 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n); 2986 2987In Objective-C, there is an alternate spelling for the nullability qualifiers that can be used in Objective-C methods and properties using context-sensitive, non-underscored keywords. For example: 2988 2989 .. code-block:: objective-c 2990 2991 @interface NSView : NSResponder 2992 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView; 2993 @property (assign, nullable) NSView *superview; 2994 @property (readonly, nonnull) NSArray *subviews; 2995 @end 2996 }]; 2997} 2998 2999def TypeNonNullDocs : Documentation { 3000 let Category = NullabilityDocs; 3001 let Content = [{ 3002The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful value for a value of the ``_Nonnull`` pointer type. For example, given a declaration such as: 3003 3004 .. code-block:: c 3005 3006 int fetch(int * _Nonnull ptr); 3007 3008a caller of ``fetch`` should not provide a null value, and the compiler will produce a warning if it sees a literal null value passed to ``fetch``. Note that, unlike the declaration attribute ``nonnull``, the presence of ``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch`` is free to consider null undefined behavior or (perhaps for backward-compatibility reasons) defensively handle null. 3009 }]; 3010} 3011 3012def TypeNullableDocs : Documentation { 3013 let Category = NullabilityDocs; 3014 let Content = [{ 3015The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given: 3016 3017 .. code-block:: c 3018 3019 int fetch_or_zero(int * _Nullable ptr); 3020 3021a caller of ``fetch_or_zero`` can provide null. 3022 }]; 3023} 3024 3025def TypeNullUnspecifiedDocs : Documentation { 3026 let Category = NullabilityDocs; 3027 let Content = [{ 3028The ``_Null_unspecified`` nullability qualifier indicates that neither the ``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer type. It is used primarily to indicate that the role of null with specific pointers in a nullability-annotated header is unclear, e.g., due to overly-complex implementations or historical factors with a long-lived API. 3029 }]; 3030} 3031 3032def NonNullDocs : Documentation { 3033 let Category = NullabilityDocs; 3034 let Content = [{ 3035The ``nonnull`` attribute indicates that some function parameters must not be null, and can be used in several different ways. It's original usage (`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_) is as a function (or Objective-C method) attribute that specifies which parameters of the function are nonnull in a comma-separated list. For example: 3036 3037 .. code-block:: c 3038 3039 extern void * my_memcpy (void *dest, const void *src, size_t len) 3040 __attribute__((nonnull (1, 2))); 3041 3042Here, the ``nonnull`` attribute indicates that parameters 1 and 2 3043cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null: 3044 3045 .. code-block:: c 3046 3047 extern void * my_memcpy (void *dest, const void *src, size_t len) 3048 __attribute__((nonnull)); 3049 3050Clang also allows the ``nonnull`` attribute to be placed directly on a function (or Objective-C method) parameter, eliminating the need to specify the parameter index ahead of type. For example: 3051 3052 .. code-block:: c 3053 3054 extern void * my_memcpy (void *dest __attribute__((nonnull)), 3055 const void *src __attribute__((nonnull)), size_t len); 3056 3057Note that the ``nonnull`` attribute indicates that passing null to a non-null parameter is undefined behavior, which the optimizer may take advantage of to, e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable. 3058 }]; 3059} 3060 3061def ReturnsNonNullDocs : Documentation { 3062 let Category = NullabilityDocs; 3063 let Content = [{ 3064The ``returns_nonnull`` attribute indicates that a particular function (or Objective-C method) always returns a non-null pointer. For example, a particular system ``malloc`` might be defined to terminate a process when memory is not available rather than returning a null pointer: 3065 3066 .. code-block:: c 3067 3068 extern void * malloc (size_t size) __attribute__((returns_nonnull)); 3069 3070The ``returns_nonnull`` attribute implies that returning a null pointer is undefined behavior, which the optimizer may take advantage of. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable 3071}]; 3072} 3073 3074def NoAliasDocs : Documentation { 3075 let Category = DocCatFunction; 3076 let Content = [{ 3077The ``noalias`` attribute indicates that the only memory accesses inside 3078function are loads and stores from objects pointed to by its pointer-typed 3079arguments, with arbitrary offsets. 3080 }]; 3081} 3082 3083def OMPDeclareSimdDocs : Documentation { 3084 let Category = DocCatFunction; 3085 let Heading = "#pragma omp declare simd"; 3086 let Content = [{ 3087The `declare simd` construct can be applied to a function to enable the creation 3088of one or more versions that can process multiple arguments using SIMD 3089instructions from a single invocation in a SIMD loop. The `declare simd` 3090directive is a declarative directive. There may be multiple `declare simd` 3091directives for a function. The use of a `declare simd` construct on a function 3092enables the creation of SIMD versions of the associated function that can be 3093used to process multiple arguments from a single invocation from a SIMD loop 3094concurrently. 3095The syntax of the `declare simd` construct is as follows: 3096 3097 .. code-block:: none 3098 3099 #pragma omp declare simd [clause[[,] clause] ...] new-line 3100 [#pragma omp declare simd [clause[[,] clause] ...] new-line] 3101 [...] 3102 function definition or declaration 3103 3104where clause is one of the following: 3105 3106 .. code-block:: none 3107 3108 simdlen(length) 3109 linear(argument-list[:constant-linear-step]) 3110 aligned(argument-list[:alignment]) 3111 uniform(argument-list) 3112 inbranch 3113 notinbranch 3114 3115 }]; 3116} 3117 3118def OMPDeclareTargetDocs : Documentation { 3119 let Category = DocCatFunction; 3120 let Heading = "#pragma omp declare target"; 3121 let Content = [{ 3122The `declare target` directive specifies that variables and functions are mapped 3123to a device for OpenMP offload mechanism. 3124 3125The syntax of the declare target directive is as follows: 3126 3127 .. code-block:: c 3128 3129 #pragma omp declare target new-line 3130 declarations-definition-seq 3131 #pragma omp end declare target new-line 3132 }]; 3133} 3134 3135def NoStackProtectorDocs : Documentation { 3136 let Category = DocCatFunction; 3137 let Content = [{ 3138Clang supports the ``__attribute__((no_stack_protector))`` attribute which disables 3139the stack protector on the specified function. This attribute is useful for 3140selectively disabling the stack protector on some functions when building with 3141``-fstack-protector`` compiler option. 3142 3143For example, it disables the stack protector for the function ``foo`` but function 3144``bar`` will still be built with the stack protector with the ``-fstack-protector`` 3145option. 3146 3147.. code-block:: c 3148 3149 int __attribute__((no_stack_protector)) 3150 foo (int x); // stack protection will be disabled for foo. 3151 3152 int bar(int y); // bar can be built with the stack protector. 3153 3154 }]; 3155} 3156 3157def NotTailCalledDocs : Documentation { 3158 let Category = DocCatFunction; 3159 let Content = [{ 3160The ``not_tail_called`` attribute prevents tail-call optimization on statically bound calls. It has no effect on indirect calls. Virtual functions, objective-c methods, and functions marked as ``always_inline`` cannot be marked as ``not_tail_called``. 3161 3162For example, it prevents tail-call optimization in the following case: 3163 3164 .. code-block:: c 3165 3166 int __attribute__((not_tail_called)) foo1(int); 3167 3168 int foo2(int a) { 3169 return foo1(a); // No tail-call optimization on direct calls. 3170 } 3171 3172However, it doesn't prevent tail-call optimization in this case: 3173 3174 .. code-block:: c 3175 3176 int __attribute__((not_tail_called)) foo1(int); 3177 3178 int foo2(int a) { 3179 int (*fn)(int) = &foo1; 3180 3181 // not_tail_called has no effect on an indirect call even if the call can be 3182 // resolved at compile time. 3183 return (*fn)(a); 3184 } 3185 3186Marking virtual functions as ``not_tail_called`` is an error: 3187 3188 .. code-block:: c++ 3189 3190 class Base { 3191 public: 3192 // not_tail_called on a virtual function is an error. 3193 [[clang::not_tail_called]] virtual int foo1(); 3194 3195 virtual int foo2(); 3196 3197 // Non-virtual functions can be marked ``not_tail_called``. 3198 [[clang::not_tail_called]] int foo3(); 3199 }; 3200 3201 class Derived1 : public Base { 3202 public: 3203 int foo1() override; 3204 3205 // not_tail_called on a virtual function is an error. 3206 [[clang::not_tail_called]] int foo2() override; 3207 }; 3208 }]; 3209} 3210 3211def NoThrowDocs : Documentation { 3212 let Category = DocCatFunction; 3213 let Content = [{ 3214Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style 3215``__declspec(nothrow)`` attribute as an equivalent of `noexcept` on function 3216declarations. This attribute informs the compiler that the annotated function 3217does not throw an exception. This prevents exception-unwinding. This attribute 3218is particularly useful on functions in the C Standard Library that are 3219guaranteed to not throw an exception. 3220 }]; 3221} 3222 3223def InternalLinkageDocs : Documentation { 3224 let Category = DocCatFunction; 3225 let Content = [{ 3226The ``internal_linkage`` attribute changes the linkage type of the declaration to internal. 3227This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition, 3228this attribute affects all methods and static data members of that class. 3229This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables. 3230 }]; 3231} 3232 3233def ExcludeFromExplicitInstantiationDocs : Documentation { 3234 let Category = DocCatFunction; 3235 let Content = [{ 3236The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a 3237class template from being part of explicit template instantiations of that 3238class template. This means that an explicit instantiation will not instantiate 3239members of the class template marked with the attribute, but also that code 3240where an extern template declaration of the enclosing class template is visible 3241will not take for granted that an external instantiation of the class template 3242would provide those members (which would otherwise be a link error, since the 3243explicit instantiation won't provide those members). For example, let's say we 3244don't want the ``data()`` method to be part of libc++'s ABI. To make sure it 3245is not exported from the dylib, we give it hidden visibility: 3246 3247 .. code-block:: c++ 3248 3249 // in <string> 3250 template <class CharT> 3251 class basic_string { 3252 public: 3253 __attribute__((__visibility__("hidden"))) 3254 const value_type* data() const noexcept { ... } 3255 }; 3256 3257 template class basic_string<char>; 3258 3259Since an explicit template instantiation declaration for ``basic_string<char>`` 3260is provided, the compiler is free to assume that ``basic_string<char>::data()`` 3261will be provided by another translation unit, and it is free to produce an 3262external call to this function. However, since ``data()`` has hidden visibility 3263and the explicit template instantiation is provided in a shared library (as 3264opposed to simply another translation unit), ``basic_string<char>::data()`` 3265won't be found and a link error will ensue. This happens because the compiler 3266assumes that ``basic_string<char>::data()`` is part of the explicit template 3267instantiation declaration, when it really isn't. To tell the compiler that 3268``data()`` is not part of the explicit template instantiation declaration, the 3269``exclude_from_explicit_instantiation`` attribute can be used: 3270 3271 .. code-block:: c++ 3272 3273 // in <string> 3274 template <class CharT> 3275 class basic_string { 3276 public: 3277 __attribute__((__visibility__("hidden"))) 3278 __attribute__((exclude_from_explicit_instantiation)) 3279 const value_type* data() const noexcept { ... } 3280 }; 3281 3282 template class basic_string<char>; 3283 3284Now, the compiler won't assume that ``basic_string<char>::data()`` is provided 3285externally despite there being an explicit template instantiation declaration: 3286the compiler will implicitly instantiate ``basic_string<char>::data()`` in the 3287TUs where it is used. 3288 3289This attribute can be used on static and non-static member functions of class 3290templates, static data members of class templates and member classes of class 3291templates. 3292 }]; 3293} 3294 3295def DisableTailCallsDocs : Documentation { 3296 let Category = DocCatFunction; 3297 let Content = [{ 3298The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function. 3299 3300For example: 3301 3302 .. code-block:: c 3303 3304 int callee(int); 3305 3306 int foo(int a) __attribute__((disable_tail_calls)) { 3307 return callee(a); // This call is not tail-call optimized. 3308 } 3309 3310Marking virtual functions as ``disable_tail_calls`` is legal. 3311 3312 .. code-block:: c++ 3313 3314 int callee(int); 3315 3316 class Base { 3317 public: 3318 [[clang::disable_tail_calls]] virtual int foo1() { 3319 return callee(); // This call is not tail-call optimized. 3320 } 3321 }; 3322 3323 class Derived1 : public Base { 3324 public: 3325 int foo1() override { 3326 return callee(); // This call is tail-call optimized. 3327 } 3328 }; 3329 3330 }]; 3331} 3332 3333def AnyX86NoCallerSavedRegistersDocs : Documentation { 3334 let Category = DocCatFunction; 3335 let Content = [{ 3336Use this attribute to indicate that the specified function has no 3337caller-saved registers. That is, all registers are callee-saved except for 3338registers used for passing parameters to the function or returning parameters 3339from the function. 3340The compiler saves and restores any modified registers that were not used for 3341passing or returning arguments to the function. 3342 3343The user can call functions specified with the 'no_caller_saved_registers' 3344attribute from an interrupt handler without saving and restoring all 3345call-clobbered registers. 3346 3347Note that 'no_caller_saved_registers' attribute is not a calling convention. 3348In fact, it only overrides the decision of which registers should be saved by 3349the caller, but not how the parameters are passed from the caller to the callee. 3350 3351For example: 3352 3353 .. code-block:: c 3354 3355 __attribute__ ((no_caller_saved_registers, fastcall)) 3356 void f (int arg1, int arg2) { 3357 ... 3358 } 3359 3360 In this case parameters 'arg1' and 'arg2' will be passed in registers. 3361 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as 3362 register parameters. However, it will not assume any scratch registers and 3363 should save and restore any modified registers except for ECX and EDX. 3364 }]; 3365} 3366 3367def X86ForceAlignArgPointerDocs : Documentation { 3368 let Category = DocCatFunction; 3369 let Content = [{ 3370Use this attribute to force stack alignment. 3371 3372Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions 3373(like 'movaps') that work with the stack require operands to be 16-byte aligned. 3374This attribute realigns the stack in the function prologue to make sure the 3375stack can be used with SSE instructions. 3376 3377Note that the x86_64 ABI forces 16-byte stack alignment at the call site. 3378Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in 3379rare cases where the caller does not align the stack properly (e.g. flow 3380jumps from i386 arch code). 3381 3382 .. code-block:: c 3383 3384 __attribute__ ((force_align_arg_pointer)) 3385 void f () { 3386 ... 3387 } 3388 3389 }]; 3390} 3391 3392def AnyX86NoCfCheckDocs : Documentation { 3393 let Category = DocCatFunction; 3394 let Content = [{ 3395Jump Oriented Programming attacks rely on tampering with addresses used by 3396indirect call / jmp, e.g. redirect control-flow to non-programmer 3397intended bytes in the binary. 3398X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow 3399Enforcement Technology (CET). IBT instruments ENDBR instructions used to 3400specify valid targets of indirect call / jmp. 3401The ``nocf_check`` attribute has two roles: 34021. Appertains to a function - do not add ENDBR instruction at the beginning of 3403the function. 34042. Appertains to a function pointer - do not track the target function of this 3405pointer (by adding nocf_check prefix to the indirect-call instruction). 3406}]; 3407} 3408 3409def SwiftCallDocs : Documentation { 3410 let Category = DocCatVariable; 3411 let Content = [{ 3412The ``swiftcall`` attribute indicates that a function should be called 3413using the Swift calling convention for a function or function pointer. 3414 3415The lowering for the Swift calling convention, as described by the Swift 3416ABI documentation, occurs in multiple phases. The first, "high-level" 3417phase breaks down the formal parameters and results into innately direct 3418and indirect components, adds implicit paraameters for the generic 3419signature, and assigns the context and error ABI treatments to parameters 3420where applicable. The second phase breaks down the direct parameters 3421and results from the first phase and assigns them to registers or the 3422stack. The ``swiftcall`` convention only handles this second phase of 3423lowering; the C function type must accurately reflect the results 3424of the first phase, as follows: 3425 3426- Results classified as indirect by high-level lowering should be 3427 represented as parameters with the ``swift_indirect_result`` attribute. 3428 3429- Results classified as direct by high-level lowering should be represented 3430 as follows: 3431 3432 - First, remove any empty direct results. 3433 3434 - If there are no direct results, the C result type should be ``void``. 3435 3436 - If there is one direct result, the C result type should be a type with 3437 the exact layout of that result type. 3438 3439 - If there are a multiple direct results, the C result type should be 3440 a struct type with the exact layout of a tuple of those results. 3441 3442- Parameters classified as indirect by high-level lowering should be 3443 represented as parameters of pointer type. 3444 3445- Parameters classified as direct by high-level lowering should be 3446 omitted if they are empty types; otherwise, they should be represented 3447 as a parameter type with a layout exactly matching the layout of the 3448 Swift parameter type. 3449 3450- The context parameter, if present, should be represented as a trailing 3451 parameter with the ``swift_context`` attribute. 3452 3453- The error result parameter, if present, should be represented as a 3454 trailing parameter (always following a context parameter) with the 3455 ``swift_error_result`` attribute. 3456 3457``swiftcall`` does not support variadic arguments or unprototyped functions. 3458 3459The parameter ABI treatment attributes are aspects of the function type. 3460A function type which which applies an ABI treatment attribute to a 3461parameter is a different type from an otherwise-identical function type 3462that does not. A single parameter may not have multiple ABI treatment 3463attributes. 3464 3465Support for this feature is target-dependent, although it should be 3466supported on every target that Swift supports. Query for this support 3467with ``__has_attribute(swiftcall)``. This implies support for the 3468``swift_context``, ``swift_error_result``, and ``swift_indirect_result`` 3469attributes. 3470 }]; 3471} 3472 3473def SwiftContextDocs : Documentation { 3474 let Category = DocCatVariable; 3475 let Content = [{ 3476The ``swift_context`` attribute marks a parameter of a ``swiftcall`` 3477function as having the special context-parameter ABI treatment. 3478 3479This treatment generally passes the context value in a special register 3480which is normally callee-preserved. 3481 3482A ``swift_context`` parameter must either be the last parameter or must be 3483followed by a ``swift_error_result`` parameter (which itself must always be 3484the last parameter). 3485 3486A context parameter must have pointer or reference type. 3487 }]; 3488} 3489 3490def SwiftErrorResultDocs : Documentation { 3491 let Category = DocCatVariable; 3492 let Content = [{ 3493The ``swift_error_result`` attribute marks a parameter of a ``swiftcall`` 3494function as having the special error-result ABI treatment. 3495 3496This treatment generally passes the underlying error value in and out of 3497the function through a special register which is normally callee-preserved. 3498This is modeled in C by pretending that the register is addressable memory: 3499 3500- The caller appears to pass the address of a variable of pointer type. 3501 The current value of this variable is copied into the register before 3502 the call; if the call returns normally, the value is copied back into the 3503 variable. 3504 3505- The callee appears to receive the address of a variable. This address 3506 is actually a hidden location in its own stack, initialized with the 3507 value of the register upon entry. When the function returns normally, 3508 the value in that hidden location is written back to the register. 3509 3510A ``swift_error_result`` parameter must be the last parameter, and it must be 3511preceded by a ``swift_context`` parameter. 3512 3513A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some 3514type T. Note that no qualifiers are permitted on the intermediate level. 3515 3516It is undefined behavior if the caller does not pass a pointer or 3517reference to a valid object. 3518 3519The standard convention is that the error value itself (that is, the 3520value stored in the apparent argument) will be null upon function entry, 3521but this is not enforced by the ABI. 3522 }]; 3523} 3524 3525def SwiftIndirectResultDocs : Documentation { 3526 let Category = DocCatVariable; 3527 let Content = [{ 3528The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall`` 3529function as having the special indirect-result ABI treatment. 3530 3531This treatment gives the parameter the target's normal indirect-result 3532ABI treatment, which may involve passing it differently from an ordinary 3533parameter. However, only the first indirect result will receive this 3534treatment. Furthermore, low-level lowering may decide that a direct result 3535must be returned indirectly; if so, this will take priority over the 3536``swift_indirect_result`` parameters. 3537 3538A ``swift_indirect_result`` parameter must either be the first parameter or 3539follow another ``swift_indirect_result`` parameter. 3540 3541A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for 3542some object type ``T``. If ``T`` is a complete type at the point of 3543definition of a function, it is undefined behavior if the argument 3544value does not point to storage of adequate size and alignment for a 3545value of type ``T``. 3546 3547Making indirect results explicit in the signature allows C functions to 3548directly construct objects into them without relying on language 3549optimizations like C++'s named return value optimization (NRVO). 3550 }]; 3551} 3552 3553def SuppressDocs : Documentation { 3554 let Category = DocCatStmt; 3555 let Content = [{ 3556The ``[[gsl::suppress]]`` attribute suppresses specific 3557clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable 3558way. The attribute can be attached to declarations, statements, and at 3559namespace scope. 3560 3561.. code-block:: c++ 3562 3563 [[gsl::suppress("Rh-public")]] 3564 void f_() { 3565 int *p; 3566 [[gsl::suppress("type")]] { 3567 p = reinterpret_cast<int*>(7); 3568 } 3569 } 3570 namespace N { 3571 [[clang::suppress("type", "bounds")]]; 3572 ... 3573 } 3574 3575.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement 3576 }]; 3577} 3578 3579def AbiTagsDocs : Documentation { 3580 let Category = DocCatFunction; 3581 let Content = [{ 3582The ``abi_tag`` attribute can be applied to a function, variable, class or 3583inline namespace declaration to modify the mangled name of the entity. It gives 3584the ability to distinguish between different versions of the same entity but 3585with different ABI versions supported. For example, a newer version of a class 3586could have a different set of data members and thus have a different size. Using 3587the ``abi_tag`` attribute, it is possible to have different mangled names for 3588a global variable of the class type. Therefore, the old code could keep using 3589the old manged name and the new code will use the new mangled name with tags. 3590 }]; 3591} 3592 3593def PreserveMostDocs : Documentation { 3594 let Category = DocCatCallingConvs; 3595 let Content = [{ 3596On X86-64 and AArch64 targets, this attribute changes the calling convention of 3597a function. The ``preserve_most`` calling convention attempts to make the code 3598in the caller as unintrusive as possible. This convention behaves identically 3599to the ``C`` calling convention on how arguments and return values are passed, 3600but it uses a different set of caller/callee-saved registers. This alleviates 3601the burden of saving and recovering a large register set before and after the 3602call in the caller. If the arguments are passed in callee-saved registers, 3603then they will be preserved by the callee across the call. This doesn't 3604apply for values returned in callee-saved registers. 3605 3606- On X86-64 the callee preserves all general purpose registers, except for 3607 R11. R11 can be used as a scratch register. Floating-point registers 3608 (XMMs/YMMs) are not preserved and need to be saved by the caller. 3609 3610The idea behind this convention is to support calls to runtime functions 3611that have a hot path and a cold path. The hot path is usually a small piece 3612of code that doesn't use many registers. The cold path might need to call out to 3613another function and therefore only needs to preserve the caller-saved 3614registers, which haven't already been saved by the caller. The 3615`preserve_most` calling convention is very similar to the ``cold`` calling 3616convention in terms of caller/callee-saved registers, but they are used for 3617different types of function calls. ``coldcc`` is for function calls that are 3618rarely executed, whereas `preserve_most` function calls are intended to be 3619on the hot path and definitely executed a lot. Furthermore ``preserve_most`` 3620doesn't prevent the inliner from inlining the function call. 3621 3622This calling convention will be used by a future version of the Objective-C 3623runtime and should therefore still be considered experimental at this time. 3624Although this convention was created to optimize certain runtime calls to 3625the Objective-C runtime, it is not limited to this runtime and might be used 3626by other runtimes in the future too. The current implementation only 3627supports X86-64 and AArch64, but the intention is to support more architectures 3628in the future. 3629 }]; 3630} 3631 3632def PreserveAllDocs : Documentation { 3633 let Category = DocCatCallingConvs; 3634 let Content = [{ 3635On X86-64 and AArch64 targets, this attribute changes the calling convention of 3636a function. The ``preserve_all`` calling convention attempts to make the code 3637in the caller even less intrusive than the ``preserve_most`` calling convention. 3638This calling convention also behaves identical to the ``C`` calling convention 3639on how arguments and return values are passed, but it uses a different set of 3640caller/callee-saved registers. This removes the burden of saving and 3641recovering a large register set before and after the call in the caller. If 3642the arguments are passed in callee-saved registers, then they will be 3643preserved by the callee across the call. This doesn't apply for values 3644returned in callee-saved registers. 3645 3646- On X86-64 the callee preserves all general purpose registers, except for 3647 R11. R11 can be used as a scratch register. Furthermore it also preserves 3648 all floating-point registers (XMMs/YMMs). 3649 3650The idea behind this convention is to support calls to runtime functions 3651that don't need to call out to any other functions. 3652 3653This calling convention, like the ``preserve_most`` calling convention, will be 3654used by a future version of the Objective-C runtime and should be considered 3655experimental at this time. 3656 }]; 3657} 3658 3659def DeprecatedDocs : Documentation { 3660 let Category = DocCatDecl; 3661 let Content = [{ 3662The ``deprecated`` attribute can be applied to a function, a variable, or a 3663type. This is useful when identifying functions, variables, or types that are 3664expected to be removed in a future version of a program. 3665 3666Consider the function declaration for a hypothetical function ``f``: 3667 3668.. code-block:: c++ 3669 3670 void f(void) __attribute__((deprecated("message", "replacement"))); 3671 3672When spelled as `__attribute__((deprecated))`, the deprecated attribute can have 3673two optional string arguments. The first one is the message to display when 3674emitting the warning; the second one enables the compiler to provide a Fix-It 3675to replace the deprecated name with a new name. Otherwise, when spelled as 3676`[[gnu::deprecated]] or [[deprecated]]`, the attribute can have one optional 3677string argument which is the message to display when emitting the warning. 3678 }]; 3679} 3680 3681def IFuncDocs : Documentation { 3682 let Category = DocCatFunction; 3683 let Content = [{ 3684``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function. 3685 3686The symbol name of the resolver function is given in quotes. A function with this name (after mangling) must be defined in the current translation unit; it may be ``static``. The resolver function should return a pointer. 3687 3688The ``ifunc`` attribute may only be used on a function declaration. A function declaration with an ``ifunc`` attribute is considered to be a definition of the declared entity. The entity must not have weak linkage; for example, in C++, it cannot be applied to a declaration if a definition at that location would be considered inline. 3689 3690Not all targets support this attribute. ELF target support depends on both the linker and runtime linker, and is available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later. Non-ELF targets currently do not support this attribute. 3691 }]; 3692} 3693 3694def LTOVisibilityDocs : Documentation { 3695 let Category = DocCatDecl; 3696 let Content = [{ 3697See :doc:`LTOVisibility`. 3698 }]; 3699} 3700 3701def RenderScriptKernelAttributeDocs : Documentation { 3702 let Category = DocCatFunction; 3703 let Content = [{ 3704``__attribute__((kernel))`` is used to mark a ``kernel`` function in 3705RenderScript. 3706 3707In RenderScript, ``kernel`` functions are used to express data-parallel 3708computations. The RenderScript runtime efficiently parallelizes ``kernel`` 3709functions to run on computational resources such as multi-core CPUs and GPUs. 3710See the RenderScript_ documentation for more information. 3711 3712.. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html 3713 }]; 3714} 3715 3716def XRayDocs : Documentation { 3717 let Category = DocCatFunction; 3718 let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args"; 3719 let Content = [{ 3720``__attribute__((xray_always_instrument))`` or ``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), methods (in Objective C), and free functions (in C, C++, and Objective C) to be instrumented with XRay. This will cause the function to always have space at the beginning and exit points to allow for runtime patching. 3721 3722Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points. 3723 3724If a function has neither of these attributes, they become subject to the XRay heuristics used to determine whether a function should be instrumented or otherwise. 3725 3726``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is used to preserve N function arguments for the logging function. Currently, only N==1 is supported. 3727 }]; 3728} 3729 3730def TransparentUnionDocs : Documentation { 3731 let Category = DocCatDecl; 3732 let Content = [{ 3733This attribute can be applied to a union to change the behaviour of calls to 3734functions that have an argument with a transparent union type. The compiler 3735behaviour is changed in the following manner: 3736 3737- A value whose type is any member of the transparent union can be passed as an 3738 argument without the need to cast that value. 3739 3740- The argument is passed to the function using the calling convention of the 3741 first member of the transparent union. Consequently, all the members of the 3742 transparent union should have the same calling convention as its first member. 3743 3744Transparent unions are not supported in C++. 3745 }]; 3746} 3747 3748def ObjCSubclassingRestrictedDocs : Documentation { 3749 let Category = DocCatDecl; 3750 let Content = [{ 3751This attribute can be added to an Objective-C ``@interface`` declaration to 3752ensure that this class cannot be subclassed. 3753 }]; 3754} 3755 3756def ObjCNonLazyClassDocs : Documentation { 3757 let Category = DocCatDecl; 3758 let Content = [{ 3759This attribute can be added to an Objective-C ``@interface`` or 3760``@implementation`` declaration to add the class to the list of non-lazily 3761initialized classes. A non-lazy class will be initialized eagerly when the 3762Objective-C runtime is loaded. This is required for certain system classes which 3763have instances allocated in non-standard ways, such as the classes for blocks 3764and constant strings. Adding this attribute is essentially equivalent to 3765providing a trivial `+load` method but avoids the (fairly small) load-time 3766overheads associated with defining and calling such a method. 3767 }]; 3768} 3769 3770def SelectAnyDocs : Documentation { 3771 let Category = DocCatDecl; 3772 let Content = [{ 3773This attribute appertains to a global symbol, causing it to have a weak 3774definition ( 3775`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_ 3776), allowing the linker to select any definition. 3777 3778For more information see 3779`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_ 3780or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_. 3781}]; } 3782 3783def WebAssemblyImportModuleDocs : Documentation { 3784 let Category = DocCatFunction; 3785 let Content = [{ 3786Clang supports the ``__attribute__((import_module(<module_name>)))`` 3787attribute for the WebAssembly target. This attribute may be attached to a 3788function declaration, where it modifies how the symbol is to be imported 3789within the WebAssembly linking environment. 3790 3791WebAssembly imports use a two-level namespace scheme, consisting of a module 3792name, which typically identifies a module from which to import, and a field 3793name, which typically identifies a field from that module to import. By 3794default, module names for C/C++ symbols are assigned automatically by the 3795linker. This attribute can be used to override the default behavior, and 3796reuqest a specific module name be used instead. 3797 }]; 3798} 3799 3800def WebAssemblyImportNameDocs : Documentation { 3801 let Category = DocCatFunction; 3802 let Content = [{ 3803Clang supports the ``__attribute__((import_name(<name>)))`` 3804attribute for the WebAssembly target. This attribute may be attached to a 3805function declaration, where it modifies how the symbol is to be imported 3806within the WebAssembly linking environment. 3807 3808WebAssembly imports use a two-level namespace scheme, consisting of a module 3809name, which typically identifies a module from which to import, and a field 3810name, which typically identifies a field from that module to import. By 3811default, field names for C/C++ symbols are the same as their C/C++ symbol 3812names. This attribute can be used to override the default behavior, and 3813reuqest a specific field name be used instead. 3814 }]; 3815} 3816 3817def ArtificialDocs : Documentation { 3818 let Category = DocCatFunction; 3819 let Content = [{ 3820The ``artificial`` attribute can be applied to an inline function. If such a 3821function is inlined, the attribute indicates that debuggers should associate 3822the resulting instructions with the call site, rather than with the 3823corresponding line within the inlined callee. 3824 }]; 3825} 3826 3827def NoDerefDocs : Documentation { 3828 let Category = DocCatType; 3829 let Content = [{ 3830The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types. 3831This is ideally used with pointers that point to special memory which cannot be read 3832from or written to, but allowing for the pointer to be used in pointer arithmetic. 3833The following are examples of valid expressions where dereferences are diagnosed: 3834 3835.. code-block:: c 3836 3837 int __attribute__((noderef)) *p; 3838 int x = *p; // warning 3839 3840 int __attribute__((noderef)) **p2; 3841 x = **p2; // warning 3842 3843 int * __attribute__((noderef)) *p3; 3844 p = *p3; // warning 3845 3846 struct S { 3847 int a; 3848 }; 3849 struct S __attribute__((noderef)) *s; 3850 x = s->a; // warning 3851 x = (*s).a; // warning 3852 3853Not all dereferences may diagnose a warning if the value directed by the pointer may not be 3854accessed. The following are examples of valid expressions where may not be diagnosed: 3855 3856.. code-block:: c 3857 3858 int *q; 3859 int __attribute__((noderef)) *p; 3860 q = &*p; 3861 q = *&p; 3862 3863 struct S { 3864 int a; 3865 }; 3866 struct S __attribute__((noderef)) *s; 3867 p = &s->a; 3868 p = &(*s).a; 3869 3870``noderef`` is currently only supported for pointers and arrays and not usable for 3871references or Objective-C object pointers. 3872 3873.. code-block: c++ 3874 3875 int x = 2; 3876 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type 3877 3878.. code-block: objc 3879 3880 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type 3881}]; 3882} 3883 3884def ReinitializesDocs : Documentation { 3885 let Category = DocCatFunction; 3886 let Content = [{ 3887The ``reinitializes`` attribute can be applied to a non-static, non-const C++ 3888member function to indicate that this member function reinitializes the entire 3889object to a known state, independent of the previous state of the object. 3890 3891This attribute can be interpreted by static analyzers that warn about uses of an 3892object that has been left in an indeterminate state by a move operation. If a 3893member function marked with the ``reinitializes`` attribute is called on a 3894moved-from object, the analyzer can conclude that the object is no longer in an 3895indeterminate state. 3896 3897A typical example where this attribute would be used is on functions that clear 3898a container class: 3899 3900.. code-block:: c++ 3901 3902 template <class T> 3903 class Container { 3904 public: 3905 ... 3906 [[clang::reinitializes]] void Clear(); 3907 ... 3908 }; 3909 }]; 3910} 3911 3912def AlwaysDestroyDocs : Documentation { 3913 let Category = DocCatVariable; 3914 let Content = [{ 3915The ``always_destroy`` attribute specifies that a variable with static or thread 3916storage duration should have its exit-time destructor run. This attribute is the 3917default unless clang was invoked with -fno-c++-static-destructors. 3918 }]; 3919} 3920 3921def NoDestroyDocs : Documentation { 3922 let Category = DocCatVariable; 3923 let Content = [{ 3924The ``no_destroy`` attribute specifies that a variable with static or thread 3925storage duration shouldn't have its exit-time destructor run. Annotating every 3926static and thread duration variable with this attribute is equivalent to 3927invoking clang with -fno-c++-static-destructors. 3928 3929If a variable is declared with this attribute, clang doesn't access check or 3930generate the type's destructor. If you have a type that you only want to be 3931annotated with ``no_destroy``, you can therefore declare the destructor private: 3932 3933.. code-block:: c++ 3934 3935 struct only_no_destroy { 3936 only_no_destroy(); 3937 private: 3938 ~only_no_destroy(); 3939 }; 3940 3941 [[clang::no_destroy]] only_no_destroy global; // fine! 3942 3943Note that destructors are still required for subobjects of aggregates annotated 3944with this attribute. This is because previously constructed subobjects need to 3945be destroyed if an exception gets thrown before the initialization of the 3946complete object is complete. For instance: 3947 3948.. code-block::c++ 3949 3950 void f() { 3951 try { 3952 [[clang::no_destroy]] 3953 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor. 3954 } catch (...) { 3955 // Handle the error 3956 } 3957 } 3958 3959Here, if the construction of `array[9]` fails with an exception, `array[0..8]` 3960will be destroyed, so the element's destructor needs to be accessible. 3961 }]; 3962} 3963 3964def UninitializedDocs : Documentation { 3965 let Category = DocCatVariable; 3966 let Content = [{ 3967The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to 3968initialize trivial automatic stack variables. By default, trivial automatic 3969stack variables are uninitialized. This attribute is used to override the 3970command-line parameter, forcing variables to remain uninitialized. It has no 3971semantic meaning in that using uninitialized values is undefined behavior, 3972it rather documents the programmer's intent. 3973 }]; 3974} 3975 3976def CallbackDocs : Documentation { 3977 let Category = DocCatFunction; 3978 let Content = [{ 3979The ``callback`` attribute specifies that the annotated function may invoke the 3980specified callback zero or more times. The callback, as well as the passed 3981arguments, are identified by their parameter name or position (starting with 39821!) in the annotated function. The first position in the attribute identifies 3983the callback callee, the following positions declare describe its arguments. 3984The callback callee is required to be callable with the number, and order, of 3985the specified arguments. The index `0`, or the identifier `this`, is used to 3986represent an implicit "this" pointer in class methods. If there is no implicit 3987"this" pointer it shall not be referenced. The index '-1', or the name "__", 3988represents an unknown callback callee argument. This can be a value which is 3989not present in the declared parameter list, or one that is, but is potentially 3990inspected, captured, or modified. Parameter names and indices can be mixed in 3991the callback attribute. 3992 3993The ``callback`` attribute, which is directly translated to ``callback`` 3994metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the 3995connection between the call to the annotated function and the callback callee. 3996This can enable interprocedural optimizations which were otherwise impossible. 3997If a function parameter is mentioned in the ``callback`` attribute, through its 3998position, it is undefined if that parameter is used for anything other than the 3999actual callback. Inspected, captured, or modified parameters shall not be 4000listed in the ``callback`` metadata. 4001 4002Example encodings for the callback performed by `pthread_create` are shown 4003below. The explicit attribute annotation indicates that the third parameter 4004(`start_routine`) is called zero or more times by the `pthread_create` function, 4005and that the fourth parameter (`arg`) is passed along. Note that the callback 4006behavior of `pthread_create` is automatically recognized by Clang. In addition, 4007the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for 4008`#pragma omp target teams` and `#pragma omp parallel`, respectively, are also 4009automatically recognized as broker functions. Further functions might be added 4010in the future. 4011 4012 .. code-block:: c 4013 4014 __attribute__((callback (start_routine, arg))) 4015 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 4016 void *(*start_routine) (void *), void *arg); 4017 4018 __attribute__((callback (3, 4))) 4019 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 4020 void *(*start_routine) (void *), void *arg); 4021 4022 }]; 4023} 4024 4025def GnuInlineDocs : Documentation { 4026 let Category = DocCatFunction; 4027 let Content = [{ 4028The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline 4029semantics, meaning: 4030 4031* If any declaration that is declared ``inline`` is not declared ``extern``, 4032 then the ``inline`` keyword is just a hint. In particular, an out-of-line 4033 definition is still emitted for a function with external linkage, even if all 4034 call sites are inlined, unlike in C99 and C++ inline semantics. 4035 4036* If all declarations that are declared ``inline`` are also declared 4037 ``extern``, then the function body is present only for inlining and no 4038 out-of-line version is emitted. 4039 4040Some important consequences: ``static inline`` emits an out-of-line 4041version if needed, a plain ``inline`` definition emits an out-of-line version 4042always, and an ``extern inline`` definition (in a header) followed by a 4043(non-``extern``) ``inline`` declaration in a source file emits an out-of-line 4044version of the function in that source file but provides the function body for 4045inlining to all includers of the header. 4046 4047Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or 4048``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually 4049exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline`` 4050function attribute can be used to get GNU inline semantics on a per function 4051basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is 4052already being compiled with GNU inline semantics as the implied default. It is 4053unspecified which macro is defined in a C++ compilation. 4054 4055GNU inline semantics are the default behavior with ``-std=gnu89``, 4056``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``. 4057 }]; 4058} 4059 4060def SpeculativeLoadHardeningDocs : Documentation { 4061 let Category = DocCatFunction; 4062 let Content = [{ 4063 This attribute can be applied to a function declaration in order to indicate 4064 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_ 4065 should be enabled for the function body. This can also be applied to a method 4066 in Objective C. This attribute will take precedence over the command line flag in 4067 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified. 4068 4069 Speculative Load Hardening is a best-effort mitigation against 4070 information leak attacks that make use of control flow 4071 miss-speculation - specifically miss-speculation of whether a branch 4072 is taken or not. Typically vulnerabilities enabling such attacks are 4073 classified as "Spectre variant #1". Notably, this does not attempt to 4074 mitigate against miss-speculation of branch target, classified as 4075 "Spectre variant #2" vulnerabilities. 4076 4077 When inlining, the attribute is sticky. Inlining a function that 4078 carries this attribute will cause the caller to gain the 4079 attribute. This is intended to provide a maximally conservative model 4080 where the code in a function annotated with this attribute will always 4081 (even after inlining) end up hardened. 4082 }]; 4083} 4084 4085def NoSpeculativeLoadHardeningDocs : Documentation { 4086 let Category = DocCatFunction; 4087 let Content = [{ 4088 This attribute can be applied to a function declaration in order to indicate 4089 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_ 4090 is *not* needed for the function body. This can also be applied to a method 4091 in Objective C. This attribute will take precedence over the command line flag in 4092 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified. 4093 4094 Warning: This attribute may not prevent Speculative Load Hardening from being 4095 enabled for a function which inlines a function that has the 4096 'speculative_load_hardening' attribute. This is intended to provide a 4097 maximally conservative model where the code that is marked with the 4098 'speculative_load_hardening' attribute will always (even when inlined) 4099 be hardened. A user of this attribute may want to mark functions called by 4100 a function they do not want to be hardened with the 'noinline' attribute. 4101 4102 For example: 4103 4104 .. code-block:: c 4105 4106 __attribute__((speculative_load_hardening)) 4107 int foo(int i) { 4108 return i; 4109 } 4110 4111 // Note: bar() may still have speculative load hardening enabled if 4112 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline)) 4113 // to avoid this situation. 4114 __attribute__((no_speculative_load_hardening)) 4115 int bar(int i) { 4116 return foo(i); 4117 } 4118 }]; 4119} 4120 4121def ObjCExternallyRetainedDocs : Documentation { 4122 let Category = DocCatVariable; 4123 let Content = [{ 4124The ``objc_externally_retained`` attribute can be applied to strong local 4125variables, functions, methods, or blocks to opt into 4126`externally-retained semantics 4127<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_. 4128 4129When applied to the definition of a function, method, or block, every parameter 4130of the function with implicit strong retainable object pointer type is 4131considered externally-retained, and becomes ``const``. By explicitly annotating 4132a parameter with ``__strong``, you can opt back into the default 4133non-externally-retained behaviour for that parameter. For instance, 4134``first_param`` is externally-retained below, but not ``second_param``: 4135 4136.. code-block:: objc 4137 4138 __attribute__((objc_externally_retained)) 4139 void f(NSArray *first_param, __strong NSArray *second_param) { 4140 // ... 4141 } 4142 4143Likewise, when applied to a strong local variable, that variable becomes 4144``const`` and is considered externally-retained. 4145 4146When compiled without ``-fobjc-arc``, this attribute is ignored. 4147}]; } 4148 4149def MIGConventionDocs : Documentation { 4150 let Category = DocCatFunction; 4151 let Content = [{ 4152 The Mach Interface Generator release-on-success convention dictates 4153functions that follow it to only release arguments passed to them when they 4154return "success" (a ``kern_return_t`` error code that indicates that 4155no errors have occured). Otherwise the release is performed by the MIG client 4156that called the function. The annotation ``__attribute__((mig_server_routine))`` 4157is applied in order to specify which functions are expected to follow the 4158convention. This allows the Static Analyzer to find bugs caused by violations of 4159that convention. The attribute would normally appear on the forward declaration 4160of the actual server routine in the MIG server header, but it may also be 4161added to arbitrary functions that need to follow the same convention - for 4162example, a user can add them to auxiliary functions called by the server routine 4163that have their return value of type ``kern_return_t`` unconditionally returned 4164from the routine. The attribute can be applied to C++ methods, and in this case 4165it will be automatically applied to overrides if the method is virtual. The 4166attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``. 4167}]; 4168} 4169 4170def MSAllocatorDocs : Documentation { 4171 let Category = DocCatFunction; 4172 let Content = [{ 4173The ``__declspec(allocator)`` attribute is applied to functions that allocate 4174memory, such as operator new in C++. When CodeView debug information is emitted 4175(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to 4176record the code offset of heap allocation call sites in the debug info. It will 4177also record the type being allocated using some local heuristics. The Visual 4178Studio debugger uses this information to `profile memory usage`_. 4179 4180.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage 4181 4182This attribute does not affect optimizations in any way, unlike GCC's 4183``__attribute__((malloc))``. 4184}]; 4185} 4186 4187def HIPPinnedShadowDocs : Documentation { 4188 let Category = DocCatType; 4189 let Content = [{ 4190The GNU style attribute __attribute__((hip_pinned_shadow)) or MSVC style attribute 4191__declspec(hip_pinned_shadow) can be added to the definition of a global variable 4192to indicate it is a HIP pinned shadow variable. A HIP pinned shadow variable can 4193be accessed on both device side and host side. It has external linkage and is 4194not initialized on device side. It has internal linkage and is initialized by 4195the initializer on host side. 4196 }]; 4197}