1//==--- AttrDocs.td - Attribute documentation ----------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===---------------------------------------------------------------------===// 9 10def GlobalDocumentation { 11 code Intro =[{.. 12 ------------------------------------------------------------------- 13 NOTE: This file is automatically generated by running clang-tblgen 14 -gen-attr-docs. Do not edit this file by hand!! 15 ------------------------------------------------------------------- 16 17=================== 18Attributes in Clang 19=================== 20.. contents:: 21 :local: 22 23Introduction 24============ 25 26This page lists the attributes currently supported by Clang. 27}]; 28} 29 30def SectionDocs : Documentation { 31 let Category = DocCatVariable; 32 let Content = [{ 33The ``section`` attribute allows you to specify a specific section a 34global variable or function should be in after translation. 35 }]; 36 let Heading = "section (gnu::section, __declspec(allocate))"; 37} 38 39def InitSegDocs : Documentation { 40 let Category = DocCatVariable; 41 let Content = [{ 42The attribute applied by ``pragma init_seg()`` controls the section into 43which global initialization function pointers are emitted. It is only 44available with ``-fms-extensions``. Typically, this function pointer is 45emitted into ``.CRT$XCU`` on Windows. The user can change the order of 46initialization by using a different section name with the same 47``.CRT$XC`` prefix and a suffix that sorts lexicographically before or 48after the standard ``.CRT$XCU`` sections. See the init_seg_ 49documentation on MSDN for more information. 50 51.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx 52 }]; 53} 54 55def TLSModelDocs : Documentation { 56 let Category = DocCatVariable; 57 let Content = [{ 58The ``tls_model`` attribute allows you to specify which thread-local storage 59model to use. It accepts the following strings: 60 61* global-dynamic 62* local-dynamic 63* initial-exec 64* local-exec 65 66TLS models are mutually exclusive. 67 }]; 68} 69 70def ThreadDocs : Documentation { 71 let Category = DocCatVariable; 72 let Content = [{ 73The ``__declspec(thread)`` attribute declares a variable with thread local 74storage. It is available under the ``-fms-extensions`` flag for MSVC 75compatibility. See the documentation for `__declspec(thread)`_ on MSDN. 76 77.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx 78 79In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the 80GNU ``__thread`` keyword. The variable must not have a destructor and must have 81a constant initializer, if any. The attribute only applies to variables 82declared with static storage duration, such as globals, class static data 83members, and static locals. 84 }]; 85} 86 87def CarriesDependencyDocs : Documentation { 88 let Category = DocCatFunction; 89 let Content = [{ 90The ``carries_dependency`` attribute specifies dependency propagation into and 91out of functions. 92 93When specified on a function or Objective-C method, the ``carries_dependency`` 94attribute means that the return value carries a dependency out of the function, 95so that the implementation need not constrain ordering upon return from that 96function. Implementations of the function and its caller may choose to preserve 97dependencies instead of emitting memory ordering instructions such as fences. 98 99Note, this attribute does not change the meaning of the program, but may result 100in generation of more efficient code. 101 }]; 102} 103 104def C11NoReturnDocs : Documentation { 105 let Category = DocCatFunction; 106 let Content = [{ 107A function declared as ``_Noreturn`` shall not return to its caller. The 108compiler will generate a diagnostic for a function declared as ``_Noreturn`` 109that appears to be capable of returning to its caller. 110 }]; 111} 112 113def CXX11NoReturnDocs : Documentation { 114 let Category = DocCatFunction; 115 let Content = [{ 116A function declared as ``[[noreturn]]`` shall not return to its caller. The 117compiler will generate a diagnostic for a function declared as ``[[noreturn]]`` 118that appears to be capable of returning to its caller. 119 }]; 120} 121 122def AssertCapabilityDocs : Documentation { 123 let Category = DocCatFunction; 124 let Heading = "assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)"; 125 let Content = [{ 126Marks a function that dynamically tests whether a capability is held, and halts 127the program if it is not held. 128 }]; 129} 130 131def AcquireCapabilityDocs : Documentation { 132 let Category = DocCatFunction; 133 let Heading = "acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)"; 134 let Content = [{ 135Marks a function as acquiring a capability. 136 }]; 137} 138 139def TryAcquireCapabilityDocs : Documentation { 140 let Category = DocCatFunction; 141 let Heading = "try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)"; 142 let Content = [{ 143Marks a function that attempts to acquire a capability. This function may fail to 144actually acquire the capability; they accept a Boolean value determining 145whether acquiring the capability means success (true), or failing to acquire 146the capability means success (false). 147 }]; 148} 149 150def ReleaseCapabilityDocs : Documentation { 151 let Category = DocCatFunction; 152 let Heading = "release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)"; 153 let Content = [{ 154Marks a function as releasing a capability. 155 }]; 156} 157 158def AssumeAlignedDocs : Documentation { 159 let Category = DocCatFunction; 160 let Content = [{ 161Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function 162declaration to specify that the return value of the function (which must be a 163pointer type) has the specified offset, in bytes, from an address with the 164specified alignment. The offset is taken to be zero if omitted. 165 166.. code-block:: c++ 167 168 // The returned pointer value has 32-byte alignment. 169 void *a() __attribute__((assume_aligned (32))); 170 171 // The returned pointer value is 4 bytes greater than an address having 172 // 32-byte alignment. 173 void *b() __attribute__((assume_aligned (32, 4))); 174 175Note that this attribute provides information to the compiler regarding a 176condition that the code already ensures is true. It does not cause the compiler 177to enforce the provided alignment assumption. 178 }]; 179} 180 181def EnableIfDocs : Documentation { 182 let Category = DocCatFunction; 183 let Content = [{ 184.. Note:: Some features of this attribute are experimental. The meaning of 185 multiple enable_if attributes on a single declaration is subject to change in 186 a future version of clang. Also, the ABI is not standardized and the name 187 mangling may change in future versions. To avoid that, use asm labels. 188 189The ``enable_if`` attribute can be placed on function declarations to control 190which overload is selected based on the values of the function's arguments. 191When combined with the ``overloadable`` attribute, this feature is also 192available in C. 193 194.. code-block:: c++ 195 196 int isdigit(int c); 197 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"))); 198 199 void foo(char c) { 200 isdigit(c); 201 isdigit(10); 202 isdigit(-10); // results in a compile-time error. 203 } 204 205The enable_if attribute takes two arguments, the first is an expression written 206in terms of the function parameters, the second is a string explaining why this 207overload candidate could not be selected to be displayed in diagnostics. The 208expression is part of the function signature for the purposes of determining 209whether it is a redeclaration (following the rules used when determining 210whether a C++ template specialization is ODR-equivalent), but is not part of 211the type. 212 213The enable_if expression is evaluated as if it were the body of a 214bool-returning constexpr function declared with the arguments of the function 215it is being applied to, then called with the parameters at the call site. If the 216result is false or could not be determined through constant expression 217evaluation, then this overload will not be chosen and the provided string may 218be used in a diagnostic if the compile fails as a result. 219 220Because the enable_if expression is an unevaluated context, there are no global 221state changes, nor the ability to pass information from the enable_if 222expression to the function body. For example, suppose we want calls to 223strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of 224strbuf) only if the size of strbuf can be determined: 225 226.. code-block:: c++ 227 228 __attribute__((always_inline)) 229 static inline size_t strnlen(const char *s, size_t maxlen) 230 __attribute__((overloadable)) 231 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))), 232 "chosen when the buffer size is known but 'maxlen' is not"))) 233 { 234 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); 235 } 236 237Multiple enable_if attributes may be applied to a single declaration. In this 238case, the enable_if expressions are evaluated from left to right in the 239following manner. First, the candidates whose enable_if expressions evaluate to 240false or cannot be evaluated are discarded. If the remaining candidates do not 241share ODR-equivalent enable_if expressions, the overload resolution is 242ambiguous. Otherwise, enable_if overload resolution continues with the next 243enable_if attribute on the candidates that have not been discarded and have 244remaining enable_if attributes. In this way, we pick the most specific 245overload out of a number of viable overloads using enable_if. 246 247.. code-block:: c++ 248 249 void f() __attribute__((enable_if(true, ""))); // #1 250 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 251 252 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 253 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 254 255In this example, a call to f() is always resolved to #2, as the first enable_if 256expression is ODR-equivalent for both declarations, but #1 does not have another 257enable_if expression to continue evaluating, so the next round of evaluation has 258only a single candidate. In a call to g(1, 1), the call is ambiguous even though 259#2 has more enable_if attributes, because the first enable_if expressions are 260not ODR-equivalent. 261 262Query for this feature with ``__has_attribute(enable_if)``. 263 }]; 264} 265 266def PassObjectSizeDocs : Documentation { 267 let Category = DocCatVariable; // Technically it's a parameter doc, but eh. 268 let Content = [{ 269.. Note:: The mangling of functions with parameters that are annotated with 270 ``pass_object_size`` is subject to change. You can get around this by 271 using ``__asm__("foo")`` to explicitly name your functions, thus preserving 272 your ABI; also, non-overloadable C functions with ``pass_object_size`` are 273 not mangled. 274 275The ``pass_object_size(Type)`` attribute can be placed on function parameters to 276instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite 277of said function, and implicitly pass the result of this call in as an invisible 278argument of type ``size_t`` directly after the parameter annotated with 279``pass_object_size``. Clang will also replace any calls to 280``__builtin_object_size(param, Type)`` in the function by said implicit 281parameter. 282 283Example usage: 284 285.. code-block:: c 286 287 int bzero1(char *const p __attribute__((pass_object_size(0)))) 288 __attribute__((noinline)) { 289 int i = 0; 290 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) { 291 p[i] = 0; 292 } 293 return i; 294 } 295 296 int main() { 297 char chars[100]; 298 int n = bzero1(&chars[0]); 299 assert(n == sizeof(chars)); 300 return 0; 301 } 302 303If successfully evaluating ``__builtin_object_size(param, Type)`` at the 304callsite is not possible, then the "failed" value is passed in. So, using the 305definition of ``bzero1`` from above, the following code would exit cleanly: 306 307.. code-block:: c 308 309 int main2(int argc, char *argv[]) { 310 int n = bzero1(argv); 311 assert(n == -1); 312 return 0; 313 } 314 315``pass_object_size`` plays a part in overload resolution. If two overload 316candidates are otherwise equally good, then the overload with one or more 317parameters with ``pass_object_size`` is preferred. This implies that the choice 318between two identical overloads both with ``pass_object_size`` on one or more 319parameters will always be ambiguous; for this reason, having two such overloads 320is illegal. For example: 321 322.. code-block:: c++ 323 324 #define PS(N) __attribute__((pass_object_size(N))) 325 // OK 326 void Foo(char *a, char *b); // Overload A 327 // OK -- overload A has no parameters with pass_object_size. 328 void Foo(char *a PS(0), char *b PS(0)); // Overload B 329 // Error -- Same signature (sans pass_object_size) as overload B, and both 330 // overloads have one or more parameters with the pass_object_size attribute. 331 void Foo(void *a PS(0), void *b); 332 333 // OK 334 void Bar(void *a PS(0)); // Overload C 335 // OK 336 void Bar(char *c PS(1)); // Overload D 337 338 void main() { 339 char known[10], *unknown; 340 Foo(unknown, unknown); // Calls overload B 341 Foo(known, unknown); // Calls overload B 342 Foo(unknown, known); // Calls overload B 343 Foo(known, known); // Calls overload B 344 345 Bar(known); // Calls overload D 346 Bar(unknown); // Calls overload D 347 } 348 349Currently, ``pass_object_size`` is a bit restricted in terms of its usage: 350 351* Only one use of ``pass_object_size`` is allowed per parameter. 352 353* It is an error to take the address of a function with ``pass_object_size`` on 354 any of its parameters. If you wish to do this, you can create an overload 355 without ``pass_object_size`` on any parameters. 356 357* It is an error to apply the ``pass_object_size`` attribute to parameters that 358 are not pointers. Additionally, any parameter that ``pass_object_size`` is 359 applied to must be marked ``const`` at its function's definition. 360 }]; 361} 362 363def OverloadableDocs : Documentation { 364 let Category = DocCatFunction; 365 let Content = [{ 366Clang provides support for C++ function overloading in C. Function overloading 367in C is introduced using the ``overloadable`` attribute. For example, one 368might provide several overloaded versions of a ``tgsin`` function that invokes 369the appropriate standard function computing the sine of a value with ``float``, 370``double``, or ``long double`` precision: 371 372.. code-block:: c 373 374 #include <math.h> 375 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } 376 double __attribute__((overloadable)) tgsin(double x) { return sin(x); } 377 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } 378 379Given these declarations, one can call ``tgsin`` with a ``float`` value to 380receive a ``float`` result, with a ``double`` to receive a ``double`` result, 381etc. Function overloading in C follows the rules of C++ function overloading 382to pick the best overload given the call arguments, with a few C-specific 383semantics: 384 385* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a 386 floating-point promotion (per C99) rather than as a floating-point conversion 387 (as in C++). 388 389* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is 390 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are 391 compatible types. 392 393* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` 394 and ``U`` are compatible types. This conversion is given "conversion" rank. 395 396The declaration of ``overloadable`` functions is restricted to function 397declarations and definitions. Most importantly, if any function with a given 398name is given the ``overloadable`` attribute, then all function declarations 399and definitions with that name (and in that scope) must have the 400``overloadable`` attribute. This rule even applies to redeclarations of 401functions whose original declaration had the ``overloadable`` attribute, e.g., 402 403.. code-block:: c 404 405 int f(int) __attribute__((overloadable)); 406 float f(float); // error: declaration of "f" must have the "overloadable" attribute 407 408 int g(int) __attribute__((overloadable)); 409 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute 410 411Functions marked ``overloadable`` must have prototypes. Therefore, the 412following code is ill-formed: 413 414.. code-block:: c 415 416 int h() __attribute__((overloadable)); // error: h does not have a prototype 417 418However, ``overloadable`` functions are allowed to use a ellipsis even if there 419are no named parameters (as is permitted in C++). This feature is particularly 420useful when combined with the ``unavailable`` attribute: 421 422.. code-block:: c++ 423 424 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error 425 426Functions declared with the ``overloadable`` attribute have their names mangled 427according to the same rules as C++ function names. For example, the three 428``tgsin`` functions in our motivating example get the mangled names 429``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two 430caveats to this use of name mangling: 431 432* Future versions of Clang may change the name mangling of functions overloaded 433 in C, so you should not depend on an specific mangling. To be completely 434 safe, we strongly urge the use of ``static inline`` with ``overloadable`` 435 functions. 436 437* The ``overloadable`` attribute has almost no meaning when used in C++, 438 because names will already be mangled and functions are already overloadable. 439 However, when an ``overloadable`` function occurs within an ``extern "C"`` 440 linkage specification, it's name *will* be mangled in the same way as it 441 would in C. 442 443Query for this feature with ``__has_extension(attribute_overloadable)``. 444 }]; 445} 446 447def ObjCMethodFamilyDocs : Documentation { 448 let Category = DocCatFunction; 449 let Content = [{ 450Many methods in Objective-C have conventional meanings determined by their 451selectors. It is sometimes useful to be able to mark a method as having a 452particular conventional meaning despite not having the right selector, or as 453not having the conventional meaning that its selector would suggest. For these 454use cases, we provide an attribute to specifically describe the "method family" 455that a method belongs to. 456 457**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of 458``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This 459attribute can only be placed at the end of a method declaration: 460 461.. code-block:: objc 462 463 - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); 464 465Users who do not wish to change the conventional meaning of a method, and who 466merely want to document its non-standard retain and release semantics, should 467use the retaining behavior attributes (``ns_returns_retained``, 468``ns_returns_not_retained``, etc). 469 470Query for this feature with ``__has_attribute(objc_method_family)``. 471 }]; 472} 473 474def NoDuplicateDocs : Documentation { 475 let Category = DocCatFunction; 476 let Content = [{ 477The ``noduplicate`` attribute can be placed on function declarations to control 478whether function calls to this function can be duplicated or not as a result of 479optimizations. This is required for the implementation of functions with 480certain special requirements, like the OpenCL "barrier" function, that might 481need to be run concurrently by all the threads that are executing in lockstep 482on the hardware. For example this attribute applied on the function 483"nodupfunc" in the code below avoids that: 484 485.. code-block:: c 486 487 void nodupfunc() __attribute__((noduplicate)); 488 // Setting it as a C++11 attribute is also valid 489 // void nodupfunc() [[clang::noduplicate]]; 490 void foo(); 491 void bar(); 492 493 nodupfunc(); 494 if (a > n) { 495 foo(); 496 } else { 497 bar(); 498 } 499 500gets possibly modified by some optimizations into code similar to this: 501 502.. code-block:: c 503 504 if (a > n) { 505 nodupfunc(); 506 foo(); 507 } else { 508 nodupfunc(); 509 bar(); 510 } 511 512where the call to "nodupfunc" is duplicated and sunk into the two branches 513of the condition. 514 }]; 515} 516 517def NoSplitStackDocs : Documentation { 518 let Category = DocCatFunction; 519 let Content = [{ 520The ``no_split_stack`` attribute disables the emission of the split stack 521preamble for a particular function. It has no effect if ``-fsplit-stack`` 522is not specified. 523 }]; 524} 525 526def ObjCRequiresSuperDocs : Documentation { 527 let Category = DocCatFunction; 528 let Content = [{ 529Some Objective-C classes allow a subclass to override a particular method in a 530parent class but expect that the overriding method also calls the overridden 531method in the parent class. For these cases, we provide an attribute to 532designate that a method requires a "call to ``super``" in the overriding 533method in the subclass. 534 535**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only 536be placed at the end of a method declaration: 537 538.. code-block:: objc 539 540 - (void)foo __attribute__((objc_requires_super)); 541 542This attribute can only be applied the method declarations within a class, and 543not a protocol. Currently this attribute does not enforce any placement of 544where the call occurs in the overriding method (such as in the case of 545``-dealloc`` where the call must appear at the end). It checks only that it 546exists. 547 548Note that on both OS X and iOS that the Foundation framework provides a 549convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this 550attribute: 551 552.. code-block:: objc 553 554 - (void)foo NS_REQUIRES_SUPER; 555 556This macro is conditionally defined depending on the compiler's support for 557this attribute. If the compiler does not support the attribute the macro 558expands to nothing. 559 560Operationally, when a method has this annotation the compiler will warn if the 561implementation of an override in a subclass does not call super. For example: 562 563.. code-block:: objc 564 565 warning: method possibly missing a [super AnnotMeth] call 566 - (void) AnnotMeth{}; 567 ^ 568 }]; 569} 570 571def ObjCRuntimeNameDocs : Documentation { 572 let Category = DocCatFunction; 573 let Content = [{ 574By default, the Objective-C interface or protocol identifier is used 575in the metadata name for that object. The `objc_runtime_name` 576attribute allows annotated interfaces or protocols to use the 577specified string argument in the object's metadata name instead of the 578default name. 579 580**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute 581can only be placed before an @protocol or @interface declaration: 582 583.. code-block:: objc 584 585 __attribute__((objc_runtime_name("MyLocalName"))) 586 @interface Message 587 @end 588 589 }]; 590} 591 592def ObjCBoxableDocs : Documentation { 593 let Category = DocCatFunction; 594 let Content = [{ 595Structs and unions marked with the ``objc_boxable`` attribute can be used 596with the Objective-C boxed expression syntax, ``@(...)``. 597 598**Usage**: ``__attribute__((objc_boxable))``. This attribute 599can only be placed on a declaration of a trivially-copyable struct or union: 600 601.. code-block:: objc 602 603 struct __attribute__((objc_boxable)) some_struct { 604 int i; 605 }; 606 union __attribute__((objc_boxable)) some_union { 607 int i; 608 float f; 609 }; 610 typedef struct __attribute__((objc_boxable)) _some_struct some_struct; 611 612 // ... 613 614 some_struct ss; 615 NSValue *boxed = @(ss); 616 617 }]; 618} 619 620def AvailabilityDocs : Documentation { 621 let Category = DocCatFunction; 622 let Content = [{ 623The ``availability`` attribute can be placed on declarations to describe the 624lifecycle of that declaration relative to operating system versions. Consider 625the function declaration for a hypothetical function ``f``: 626 627.. code-block:: c++ 628 629 void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7))); 630 631The availability attribute states that ``f`` was introduced in Mac OS X 10.4, 632deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information 633is used by Clang to determine when it is safe to use ``f``: for example, if 634Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()`` 635succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call 636succeeds but Clang emits a warning specifying that the function is deprecated. 637Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call 638fails because ``f()`` is no longer available. 639 640The availability attribute is a comma-separated list starting with the 641platform name and then including clauses specifying important milestones in the 642declaration's lifetime (in any order) along with additional information. Those 643clauses can be: 644 645introduced=\ *version* 646 The first version in which this declaration was introduced. 647 648deprecated=\ *version* 649 The first version in which this declaration was deprecated, meaning that 650 users should migrate away from this API. 651 652obsoleted=\ *version* 653 The first version in which this declaration was obsoleted, meaning that it 654 was removed completely and can no longer be used. 655 656unavailable 657 This declaration is never available on this platform. 658 659message=\ *string-literal* 660 Additional message text that Clang will provide when emitting a warning or 661 error about use of a deprecated or obsoleted declaration. Useful to direct 662 users to replacement APIs. 663 664Multiple availability attributes can be placed on a declaration, which may 665correspond to different platforms. Only the availability attribute with the 666platform corresponding to the target platform will be used; any others will be 667ignored. If no availability attribute specifies availability for the current 668target platform, the availability attributes are ignored. Supported platforms 669are: 670 671``ios`` 672 Apple's iOS operating system. The minimum deployment target is specified by 673 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` 674 command-line arguments. 675 676``macosx`` 677 Apple's Mac OS X operating system. The minimum deployment target is 678 specified by the ``-mmacosx-version-min=*version*`` command-line argument. 679 680``tvos`` 681 Apple's tvOS operating system. The minimum deployment target is specified by 682 the ``-mtvos-version-min=*version*`` command-line argument. 683 684``watchos`` 685 Apple's watchOS operating system. The minimum deployment target is specified by 686 the ``-mwatchos-version-min=*version*`` command-line argument. 687 688A declaration can be used even when deploying back to a platform version prior 689to when the declaration was introduced. When this happens, the declaration is 690`weakly linked 691<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, 692as if the ``weak_import`` attribute were added to the declaration. A 693weakly-linked declaration may or may not be present a run-time, and a program 694can determine whether the declaration is present by checking whether the 695address of that declaration is non-NULL. 696 697If there are multiple declarations of the same entity, the availability 698attributes must either match on a per-platform basis or later 699declarations must not have availability attributes for that 700platform. For example: 701 702.. code-block:: c 703 704 void g(void) __attribute__((availability(macosx,introduced=10.4))); 705 void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches 706 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform 707 void g(void); // okay, inherits both macosx and ios availability from above. 708 void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch 709 710When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: 711 712.. code-block:: objc 713 714 @interface A 715 - (id)method __attribute__((availability(macosx,introduced=10.4))); 716 - (id)method2 __attribute__((availability(macosx,introduced=10.4))); 717 @end 718 719 @interface B : A 720 - (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later 721 - (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4 722 @end 723 }]; 724} 725 726def FallthroughDocs : Documentation { 727 let Category = DocCatStmt; 728 let Content = [{ 729The ``clang::fallthrough`` attribute is used along with the 730``-Wimplicit-fallthrough`` argument to annotate intentional fall-through 731between switch labels. It can only be applied to a null statement placed at a 732point of execution between any statement and the next switch label. It is 733common to mark these places with a specific comment, but this attribute is 734meant to replace comments with a more strict annotation, which can be checked 735by the compiler. This attribute doesn't change semantics of the code and can 736be used wherever an intended fall-through occurs. It is designed to mimic 737control-flow statements like ``break;``, so it can be placed in most places 738where ``break;`` can, but only if there are no statements on the execution path 739between it and the next switch label. 740 741Here is an example: 742 743.. code-block:: c++ 744 745 // compile with -Wimplicit-fallthrough 746 switch (n) { 747 case 22: 748 case 33: // no warning: no statements between case labels 749 f(); 750 case 44: // warning: unannotated fall-through 751 g(); 752 [[clang::fallthrough]]; 753 case 55: // no warning 754 if (x) { 755 h(); 756 break; 757 } 758 else { 759 i(); 760 [[clang::fallthrough]]; 761 } 762 case 66: // no warning 763 p(); 764 [[clang::fallthrough]]; // warning: fallthrough annotation does not 765 // directly precede case label 766 q(); 767 case 77: // warning: unannotated fall-through 768 r(); 769 } 770 }]; 771} 772 773def ARMInterruptDocs : Documentation { 774 let Category = DocCatFunction; 775 let Content = [{ 776Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on 777ARM targets. This attribute may be attached to a function definition and 778instructs the backend to generate appropriate function entry/exit code so that 779it can be used directly as an interrupt service routine. 780 781The parameter passed to the interrupt attribute is optional, but if 782provided it must be a string literal with one of the following values: "IRQ", 783"FIQ", "SWI", "ABORT", "UNDEF". 784 785The semantics are as follows: 786 787- If the function is AAPCS, Clang instructs the backend to realign the stack to 788 8 bytes on entry. This is a general requirement of the AAPCS at public 789 interfaces, but may not hold when an exception is taken. Doing this allows 790 other AAPCS functions to be called. 791- If the CPU is M-class this is all that needs to be done since the architecture 792 itself is designed in such a way that functions obeying the normal AAPCS ABI 793 constraints are valid exception handlers. 794- If the CPU is not M-class, the prologue and epilogue are modified to save all 795 non-banked registers that are used, so that upon return the user-mode state 796 will not be corrupted. Note that to avoid unnecessary overhead, only 797 general-purpose (integer) registers are saved in this way. If VFP operations 798 are needed, that state must be saved manually. 799 800 Specifically, interrupt kinds other than "FIQ" will save all core registers 801 except "lr" and "sp". "FIQ" interrupts will save r0-r7. 802- If the CPU is not M-class, the return instruction is changed to one of the 803 canonical sequences permitted by the architecture for exception return. Where 804 possible the function itself will make the necessary "lr" adjustments so that 805 the "preferred return address" is selected. 806 807 Unfortunately the compiler is unable to make this guarantee for an "UNDEF" 808 handler, where the offset from "lr" to the preferred return address depends on 809 the execution state of the code which generated the exception. In this case 810 a sequence equivalent to "movs pc, lr" will be used. 811 }]; 812} 813 814def MipsInterruptDocs : Documentation { 815 let Category = DocCatFunction; 816 let Content = [{ 817Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on 818MIPS targets. This attribute may be attached to a function definition and instructs 819the backend to generate appropriate function entry/exit code so that it can be used 820directly as an interrupt service routine. 821 822By default, the compiler will produce a function prologue and epilogue suitable for 823an interrupt service routine that handles an External Interrupt Controller (eic) 824generated interrupt. This behaviour can be explicitly requested with the "eic" 825argument. 826 827Otherwise, for use with vectored interrupt mode, the argument passed should be 828of the form "vector=LEVEL" where LEVEL is one of the following values: 829"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will 830then set the interrupt mask to the corresponding level which will mask all 831interrupts up to and including the argument. 832 833The semantics are as follows: 834 835- The prologue is modified so that the Exception Program Counter (EPC) and 836 Status coprocessor registers are saved to the stack. The interrupt mask is 837 set so that the function can only be interrupted by a higher priority 838 interrupt. The epilogue will restore the previous values of EPC and Status. 839 840- The prologue and epilogue are modified to save and restore all non-kernel 841 registers as necessary. 842 843- The FPU is disabled in the prologue, as the floating pointer registers are not 844 spilled to the stack. 845 846- The function return sequence is changed to use an exception return instruction. 847 848- The parameter sets the interrupt mask for the function corresponding to the 849 interrupt level specified. If no mask is specified the interrupt mask 850 defaults to "eic". 851 }]; 852} 853 854def TargetDocs : Documentation { 855 let Category = DocCatFunction; 856 let Content = [{ 857Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute. 858This attribute may be attached to a function definition and instructs 859the backend to use different code generation options than were passed on the 860command line. 861 862The current set of options correspond to the existing "subtarget features" for 863the target with or without a "-mno-" in front corresponding to the absence 864of the feature, as well as ``arch="CPU"`` which will change the default "CPU" 865for the function. 866 867Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", 868"avx", "xop" and largely correspond to the machine specific options handled by 869the front end. 870}]; 871} 872 873def DocCatAMDGPURegisterAttributes : 874 DocumentationCategory<"AMD GPU Register Attributes"> { 875 let Content = [{ 876Clang supports attributes for controlling register usage on AMD GPU 877targets. These attributes may be attached to a kernel function 878definition and is an optimization hint to the backend for the maximum 879number of registers to use. This is useful in cases where register 880limited occupancy is known to be an important factor for the 881performance for the kernel. 882 883The semantics are as follows: 884 885- The backend will attempt to limit the number of used registers to 886 the specified value, but the exact number used is not 887 guaranteed. The number used may be rounded up to satisfy the 888 allocation requirements or ABI constraints of the subtarget. For 889 example, on Southern Islands VGPRs may only be allocated in 890 increments of 4, so requesting a limit of 39 VGPRs will really 891 attempt to use up to 40. Requesting more registers than the 892 subtarget supports will truncate to the maximum allowed. The backend 893 may also use fewer registers than requested whenever possible. 894 895- 0 implies the default no limit on register usage. 896 897- Ignored on older VLIW subtargets which did not have separate scalar 898 and vector registers, R600 through Northern Islands. 899 900}]; 901} 902 903 904def AMDGPUNumVGPRDocs : Documentation { 905 let Category = DocCatAMDGPURegisterAttributes; 906 let Content = [{ 907Clang supports the 908``__attribute__((amdgpu_num_vgpr(<num_registers>)))`` attribute on AMD 909Southern Islands GPUs and later for controlling the number of vector 910registers. A typical value would be between 4 and 256 in increments 911of 4. 912}]; 913} 914 915def AMDGPUNumSGPRDocs : Documentation { 916 let Category = DocCatAMDGPURegisterAttributes; 917 let Content = [{ 918 919Clang supports the 920``__attribute__((amdgpu_num_sgpr(<num_registers>)))`` attribute on AMD 921Southern Islands GPUs and later for controlling the number of scalar 922registers. A typical value would be between 8 and 104 in increments of 9238. 924 925Due to common instruction constraints, an additional 2-4 SGPRs are 926typically required for internal use depending on features used. This 927value is a hint for the total number of SGPRs to use, and not the 928number of user SGPRs, so no special consideration needs to be given 929for these. 930}]; 931} 932 933def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> { 934 let Content = [{ 935Clang supports several different calling conventions, depending on the target 936platform and architecture. The calling convention used for a function determines 937how parameters are passed, how results are returned to the caller, and other 938low-level details of calling a function. 939 }]; 940} 941 942def PcsDocs : Documentation { 943 let Category = DocCatCallingConvs; 944 let Content = [{ 945On ARM targets, this attribute can be used to select calling conventions 946similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and 947"aapcs-vfp". 948 }]; 949} 950 951def RegparmDocs : Documentation { 952 let Category = DocCatCallingConvs; 953 let Content = [{ 954On 32-bit x86 targets, the regparm attribute causes the compiler to pass 955the first three integer parameters in EAX, EDX, and ECX instead of on the 956stack. This attribute has no effect on variadic functions, and all parameters 957are passed via the stack as normal. 958 }]; 959} 960 961def SysVABIDocs : Documentation { 962 let Category = DocCatCallingConvs; 963 let Content = [{ 964On Windows x86_64 targets, this attribute changes the calling convention of a 965function to match the default convention used on Sys V targets such as Linux, 966Mac, and BSD. This attribute has no effect on other targets. 967 }]; 968} 969 970def MSABIDocs : Documentation { 971 let Category = DocCatCallingConvs; 972 let Content = [{ 973On non-Windows x86_64 targets, this attribute changes the calling convention of 974a function to match the default convention used on Windows x86_64. This 975attribute has no effect on Windows targets or non-x86_64 targets. 976 }]; 977} 978 979def StdCallDocs : Documentation { 980 let Category = DocCatCallingConvs; 981 let Content = [{ 982On 32-bit x86 targets, this attribute changes the calling convention of a 983function to clear parameters off of the stack on return. This convention does 984not support variadic calls or unprototyped functions in C, and has no effect on 985x86_64 targets. This calling convention is used widely by the Windows API and 986COM applications. See the documentation for `__stdcall`_ on MSDN. 987 988.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx 989 }]; 990} 991 992def FastCallDocs : Documentation { 993 let Category = DocCatCallingConvs; 994 let Content = [{ 995On 32-bit x86 targets, this attribute changes the calling convention of a 996function to use ECX and EDX as register parameters and clear parameters off of 997the stack on return. This convention does not support variadic calls or 998unprototyped functions in C, and has no effect on x86_64 targets. This calling 999convention is supported primarily for compatibility with existing code. Users 1000seeking register parameters should use the ``regparm`` attribute, which does 1001not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN. 1002 1003.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx 1004 }]; 1005} 1006 1007def ThisCallDocs : Documentation { 1008 let Category = DocCatCallingConvs; 1009 let Content = [{ 1010On 32-bit x86 targets, this attribute changes the calling convention of a 1011function to use ECX for the first parameter (typically the implicit ``this`` 1012parameter of C++ methods) and clear parameters off of the stack on return. This 1013convention does not support variadic calls or unprototyped functions in C, and 1014has no effect on x86_64 targets. See the documentation for `__thiscall`_ on 1015MSDN. 1016 1017.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx 1018 }]; 1019} 1020 1021def VectorCallDocs : Documentation { 1022 let Category = DocCatCallingConvs; 1023 let Content = [{ 1024On 32-bit x86 *and* x86_64 targets, this attribute changes the calling 1025convention of a function to pass vector parameters in SSE registers. 1026 1027On 32-bit x86 targets, this calling convention is similar to ``__fastcall``. 1028The first two integer parameters are passed in ECX and EDX. Subsequent integer 1029parameters are passed in memory, and callee clears the stack. On x86_64 1030targets, the callee does *not* clear the stack, and integer parameters are 1031passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling 1032convention. 1033 1034On both 32-bit x86 and x86_64 targets, vector and floating point arguments are 1035passed in XMM0-XMM5. Homogenous vector aggregates of up to four elements are 1036passed in sequential SSE registers if enough are available. If AVX is enabled, 1037256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that 1038cannot be passed in registers for any reason is passed by reference, which 1039allows the caller to align the parameter memory. 1040 1041See the documentation for `__vectorcall`_ on MSDN for more details. 1042 1043.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx 1044 }]; 1045} 1046 1047def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> { 1048 let Content = [{ 1049Clang supports additional attributes for checking basic resource management 1050properties, specifically for unique objects that have a single owning reference. 1051The following attributes are currently supported, although **the implementation 1052for these annotations is currently in development and are subject to change.** 1053 }]; 1054} 1055 1056def SetTypestateDocs : Documentation { 1057 let Category = DocCatConsumed; 1058 let Content = [{ 1059Annotate methods that transition an object into a new state with 1060``__attribute__((set_typestate(new_state)))``. The new state must be 1061unconsumed, consumed, or unknown. 1062 }]; 1063} 1064 1065def CallableWhenDocs : Documentation { 1066 let Category = DocCatConsumed; 1067 let Content = [{ 1068Use ``__attribute__((callable_when(...)))`` to indicate what states a method 1069may be called in. Valid states are unconsumed, consumed, or unknown. Each 1070argument to this attribute must be a quoted string. E.g.: 1071 1072``__attribute__((callable_when("unconsumed", "unknown")))`` 1073 }]; 1074} 1075 1076def TestTypestateDocs : Documentation { 1077 let Category = DocCatConsumed; 1078 let Content = [{ 1079Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method 1080returns true if the object is in the specified state.. 1081 }]; 1082} 1083 1084def ParamTypestateDocs : Documentation { 1085 let Category = DocCatConsumed; 1086 let Content = [{ 1087This attribute specifies expectations about function parameters. Calls to an 1088function with annotated parameters will issue a warning if the corresponding 1089argument isn't in the expected state. The attribute is also used to set the 1090initial state of the parameter when analyzing the function's body. 1091 }]; 1092} 1093 1094def ReturnTypestateDocs : Documentation { 1095 let Category = DocCatConsumed; 1096 let Content = [{ 1097The ``return_typestate`` attribute can be applied to functions or parameters. 1098When applied to a function the attribute specifies the state of the returned 1099value. The function's body is checked to ensure that it always returns a value 1100in the specified state. On the caller side, values returned by the annotated 1101function are initialized to the given state. 1102 1103When applied to a function parameter it modifies the state of an argument after 1104a call to the function returns. The function's body is checked to ensure that 1105the parameter is in the expected state before returning. 1106 }]; 1107} 1108 1109def ConsumableDocs : Documentation { 1110 let Category = DocCatConsumed; 1111 let Content = [{ 1112Each ``class`` that uses any of the typestate annotations must first be marked 1113using the ``consumable`` attribute. Failure to do so will result in a warning. 1114 1115This attribute accepts a single parameter that must be one of the following: 1116``unknown``, ``consumed``, or ``unconsumed``. 1117 }]; 1118} 1119 1120def NoSanitizeDocs : Documentation { 1121 let Category = DocCatFunction; 1122 let Content = [{ 1123Use the ``no_sanitize`` attribute on a function declaration to specify 1124that a particular instrumentation or set of instrumentations should not be 1125applied to that function. The attribute takes a list of string literals, 1126which have the same meaning as values accepted by the ``-fno-sanitize=`` 1127flag. For example, ``__attribute__((no_sanitize("address", "thread")))`` 1128specifies that AddressSanitizer and ThreadSanitizer should not be applied 1129to the function. 1130 1131See :ref:`Controlling Code Generation <controlling-code-generation>` for a 1132full list of supported sanitizer flags. 1133 }]; 1134} 1135 1136def NoSanitizeAddressDocs : Documentation { 1137 let Category = DocCatFunction; 1138 // This function has multiple distinct spellings, and so it requires a custom 1139 // heading to be specified. The most common spelling is sufficient. 1140 let Heading = "no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)"; 1141 let Content = [{ 1142.. _langext-address_sanitizer: 1143 1144Use ``__attribute__((no_sanitize_address))`` on a function declaration to 1145specify that address safety instrumentation (e.g. AddressSanitizer) should 1146not be applied to that function. 1147 }]; 1148} 1149 1150def NoSanitizeThreadDocs : Documentation { 1151 let Category = DocCatFunction; 1152 let Heading = "no_sanitize_thread"; 1153 let Content = [{ 1154.. _langext-thread_sanitizer: 1155 1156Use ``__attribute__((no_sanitize_thread))`` on a function declaration to 1157specify that checks for data races on plain (non-atomic) memory accesses should 1158not be inserted by ThreadSanitizer. The function is still instrumented by the 1159tool to avoid false positives and provide meaningful stack traces. 1160 }]; 1161} 1162 1163def NoSanitizeMemoryDocs : Documentation { 1164 let Category = DocCatFunction; 1165 let Heading = "no_sanitize_memory"; 1166 let Content = [{ 1167.. _langext-memory_sanitizer: 1168 1169Use ``__attribute__((no_sanitize_memory))`` on a function declaration to 1170specify that checks for uninitialized memory should not be inserted 1171(e.g. by MemorySanitizer). The function may still be instrumented by the tool 1172to avoid false positives in other places. 1173 }]; 1174} 1175 1176def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> { 1177 let Content = [{ 1178Clang supports additional attributes to enable checking type safety properties 1179that can't be enforced by the C type system. Use cases include: 1180 1181* MPI library implementations, where these attributes enable checking that 1182 the buffer type matches the passed ``MPI_Datatype``; 1183* for HDF5 library there is a similar use case to MPI; 1184* checking types of variadic functions' arguments for functions like 1185 ``fcntl()`` and ``ioctl()``. 1186 1187You can detect support for these attributes with ``__has_attribute()``. For 1188example: 1189 1190.. code-block:: c++ 1191 1192 #if defined(__has_attribute) 1193 # if __has_attribute(argument_with_type_tag) && \ 1194 __has_attribute(pointer_with_type_tag) && \ 1195 __has_attribute(type_tag_for_datatype) 1196 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) 1197 /* ... other macros ... */ 1198 # endif 1199 #endif 1200 1201 #if !defined(ATTR_MPI_PWT) 1202 # define ATTR_MPI_PWT(buffer_idx, type_idx) 1203 #endif 1204 1205 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 1206 ATTR_MPI_PWT(1,3); 1207 }]; 1208} 1209 1210def ArgumentWithTypeTagDocs : Documentation { 1211 let Category = DocCatTypeSafety; 1212 let Heading = "argument_with_type_tag"; 1213 let Content = [{ 1214Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, 1215type_tag_idx)))`` on a function declaration to specify that the function 1216accepts a type tag that determines the type of some other argument. 1217``arg_kind`` is an identifier that should be used when annotating all 1218applicable type tags. 1219 1220This attribute is primarily useful for checking arguments of variadic functions 1221(``pointer_with_type_tag`` can be used in most non-variadic cases). 1222 1223For example: 1224 1225.. code-block:: c++ 1226 1227 int fcntl(int fd, int cmd, ...) 1228 __attribute__(( argument_with_type_tag(fcntl,3,2) )); 1229 }]; 1230} 1231 1232def PointerWithTypeTagDocs : Documentation { 1233 let Category = DocCatTypeSafety; 1234 let Heading = "pointer_with_type_tag"; 1235 let Content = [{ 1236Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` 1237on a function declaration to specify that the function accepts a type tag that 1238determines the pointee type of some other pointer argument. 1239 1240For example: 1241 1242.. code-block:: c++ 1243 1244 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) 1245 __attribute__(( pointer_with_type_tag(mpi,1,3) )); 1246 }]; 1247} 1248 1249def TypeTagForDatatypeDocs : Documentation { 1250 let Category = DocCatTypeSafety; 1251 let Content = [{ 1252Clang supports annotating type tags of two forms. 1253 1254* **Type tag that is an expression containing a reference to some declared 1255 identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a 1256 declaration with that identifier: 1257 1258 .. code-block:: c++ 1259 1260 extern struct mpi_datatype mpi_datatype_int 1261 __attribute__(( type_tag_for_datatype(mpi,int) )); 1262 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) 1263 1264* **Type tag that is an integral literal.** Introduce a ``static const`` 1265 variable with a corresponding initializer value and attach 1266 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration, 1267 for example: 1268 1269 .. code-block:: c++ 1270 1271 #define MPI_INT ((MPI_Datatype) 42) 1272 static const MPI_Datatype mpi_datatype_int 1273 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42 1274 1275The attribute also accepts an optional third argument that determines how the 1276expression is compared to the type tag. There are two supported flags: 1277 1278* ``layout_compatible`` will cause types to be compared according to 1279 layout-compatibility rules (C++11 [class.mem] p 17, 18). This is 1280 implemented to support annotating types like ``MPI_DOUBLE_INT``. 1281 1282 For example: 1283 1284 .. code-block:: c++ 1285 1286 /* In mpi.h */ 1287 struct internal_mpi_double_int { double d; int i; }; 1288 extern struct mpi_datatype mpi_datatype_double_int 1289 __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) )); 1290 1291 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) 1292 1293 /* In user code */ 1294 struct my_pair { double a; int b; }; 1295 struct my_pair *buffer; 1296 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning 1297 1298 struct my_int_pair { int a; int b; } 1299 struct my_int_pair *buffer2; 1300 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element 1301 // type 'struct my_int_pair' 1302 // doesn't match specified MPI_Datatype 1303 1304* ``must_be_null`` specifies that the expression should be a null pointer 1305 constant, for example: 1306 1307 .. code-block:: c++ 1308 1309 /* In mpi.h */ 1310 extern struct mpi_datatype mpi_datatype_null 1311 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); 1312 1313 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) 1314 1315 /* In user code */ 1316 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL 1317 // was specified but buffer 1318 // is not a null pointer 1319 }]; 1320} 1321 1322def FlattenDocs : Documentation { 1323 let Category = DocCatFunction; 1324 let Content = [{ 1325The ``flatten`` attribute causes calls within the attributed function to 1326be inlined unless it is impossible to do so, for example if the body of the 1327callee is unavailable or if the callee has the ``noinline`` attribute. 1328 }]; 1329} 1330 1331def FormatDocs : Documentation { 1332 let Category = DocCatFunction; 1333 let Content = [{ 1334 1335Clang supports the ``format`` attribute, which indicates that the function 1336accepts a ``printf`` or ``scanf``-like format string and corresponding 1337arguments or a ``va_list`` that contains these arguments. 1338 1339Please see `GCC documentation about format attribute 1340<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details 1341about attribute syntax. 1342 1343Clang implements two kinds of checks with this attribute. 1344 1345#. Clang checks that the function with the ``format`` attribute is called with 1346 a format string that uses format specifiers that are allowed, and that 1347 arguments match the format string. This is the ``-Wformat`` warning, it is 1348 on by default. 1349 1350#. Clang checks that the format string argument is a literal string. This is 1351 the ``-Wformat-nonliteral`` warning, it is off by default. 1352 1353 Clang implements this mostly the same way as GCC, but there is a difference 1354 for functions that accept a ``va_list`` argument (for example, ``vprintf``). 1355 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such 1356 functions. Clang does not warn if the format string comes from a function 1357 parameter, where the function is annotated with a compatible attribute, 1358 otherwise it warns. For example: 1359 1360 .. code-block:: c 1361 1362 __attribute__((__format__ (__scanf__, 1, 3))) 1363 void foo(const char* s, char *buf, ...) { 1364 va_list ap; 1365 va_start(ap, buf); 1366 1367 vprintf(s, ap); // warning: format string is not a string literal 1368 } 1369 1370 In this case we warn because ``s`` contains a format string for a 1371 ``scanf``-like function, but it is passed to a ``printf``-like function. 1372 1373 If the attribute is removed, clang still warns, because the format string is 1374 not a string literal. 1375 1376 Another example: 1377 1378 .. code-block:: c 1379 1380 __attribute__((__format__ (__printf__, 1, 3))) 1381 void foo(const char* s, char *buf, ...) { 1382 va_list ap; 1383 va_start(ap, buf); 1384 1385 vprintf(s, ap); // warning 1386 } 1387 1388 In this case Clang does not warn because the format string ``s`` and 1389 the corresponding arguments are annotated. If the arguments are 1390 incorrect, the caller of ``foo`` will receive a warning. 1391 }]; 1392} 1393 1394def AlignValueDocs : Documentation { 1395 let Category = DocCatType; 1396 let Content = [{ 1397The align_value attribute can be added to the typedef of a pointer type or the 1398declaration of a variable of pointer or reference type. It specifies that the 1399pointer will point to, or the reference will bind to, only objects with at 1400least the provided alignment. This alignment value must be some positive power 1401of 2. 1402 1403 .. code-block:: c 1404 1405 typedef double * aligned_double_ptr __attribute__((align_value(64))); 1406 void foo(double & x __attribute__((align_value(128)), 1407 aligned_double_ptr y) { ... } 1408 1409If the pointer value does not have the specified alignment at runtime, the 1410behavior of the program is undefined. 1411 }]; 1412} 1413 1414def FlagEnumDocs : Documentation { 1415 let Category = DocCatType; 1416 let Content = [{ 1417This attribute can be added to an enumerator to signal to the compiler that it 1418is intended to be used as a flag type. This will cause the compiler to assume 1419that the range of the type includes all of the values that you can get by 1420manipulating bits of the enumerator when issuing warnings. 1421 }]; 1422} 1423 1424def MSInheritanceDocs : Documentation { 1425 let Category = DocCatType; 1426 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance"; 1427 let Content = [{ 1428This collection of keywords is enabled under ``-fms-extensions`` and controls 1429the pointer-to-member representation used on ``*-*-win32`` targets. 1430 1431The ``*-*-win32`` targets utilize a pointer-to-member representation which 1432varies in size and alignment depending on the definition of the underlying 1433class. 1434 1435However, this is problematic when a forward declaration is only available and 1436no definition has been made yet. In such cases, Clang is forced to utilize the 1437most general representation that is available to it. 1438 1439These keywords make it possible to use a pointer-to-member representation other 1440than the most general one regardless of whether or not the definition will ever 1441be present in the current translation unit. 1442 1443This family of keywords belong between the ``class-key`` and ``class-name``: 1444 1445.. code-block:: c++ 1446 1447 struct __single_inheritance S; 1448 int S::*i; 1449 struct S {}; 1450 1451This keyword can be applied to class templates but only has an effect when used 1452on full specializations: 1453 1454.. code-block:: c++ 1455 1456 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template 1457 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization 1458 template <> struct __single_inheritance A<int, float>; 1459 1460Note that choosing an inheritance model less general than strictly necessary is 1461an error: 1462 1463.. code-block:: c++ 1464 1465 struct __multiple_inheritance S; // error: inheritance model does not match definition 1466 int S::*i; 1467 struct S {}; 1468}]; 1469} 1470 1471def MSNoVTableDocs : Documentation { 1472 let Category = DocCatType; 1473 let Content = [{ 1474This attribute can be added to a class declaration or definition to signal to 1475the compiler that constructors and destructors will not reference the virtual 1476function table. It is only supported when using the Microsoft C++ ABI. 1477 }]; 1478} 1479 1480def OptnoneDocs : Documentation { 1481 let Category = DocCatFunction; 1482 let Content = [{ 1483The ``optnone`` attribute suppresses essentially all optimizations 1484on a function or method, regardless of the optimization level applied to 1485the compilation unit as a whole. This is particularly useful when you 1486need to debug a particular function, but it is infeasible to build the 1487entire application without optimization. Avoiding optimization on the 1488specified function can improve the quality of the debugging information 1489for that function. 1490 1491This attribute is incompatible with the ``always_inline`` and ``minsize`` 1492attributes. 1493 }]; 1494} 1495 1496def LoopHintDocs : Documentation { 1497 let Category = DocCatStmt; 1498 let Heading = "#pragma clang loop"; 1499 let Content = [{ 1500The ``#pragma clang loop`` directive allows loop optimization hints to be 1501specified for the subsequent loop. The directive allows vectorization, 1502interleaving, and unrolling to be enabled or disabled. Vector width as well 1503as interleave and unrolling count can be manually specified. See 1504`language extensions 1505<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 1506for details. 1507 }]; 1508} 1509 1510def UnrollHintDocs : Documentation { 1511 let Category = DocCatStmt; 1512 let Heading = "#pragma unroll, #pragma nounroll"; 1513 let Content = [{ 1514Loop unrolling optimization hints can be specified with ``#pragma unroll`` and 1515``#pragma nounroll``. The pragma is placed immediately before a for, while, 1516do-while, or c++11 range-based for loop. 1517 1518Specifying ``#pragma unroll`` without a parameter directs the loop unroller to 1519attempt to fully unroll the loop if the trip count is known at compile time and 1520attempt to partially unroll the loop if the trip count is not known at compile 1521time: 1522 1523.. code-block:: c++ 1524 1525 #pragma unroll 1526 for (...) { 1527 ... 1528 } 1529 1530Specifying the optional parameter, ``#pragma unroll _value_``, directs the 1531unroller to unroll the loop ``_value_`` times. The parameter may optionally be 1532enclosed in parentheses: 1533 1534.. code-block:: c++ 1535 1536 #pragma unroll 16 1537 for (...) { 1538 ... 1539 } 1540 1541 #pragma unroll(16) 1542 for (...) { 1543 ... 1544 } 1545 1546Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled: 1547 1548.. code-block:: c++ 1549 1550 #pragma nounroll 1551 for (...) { 1552 ... 1553 } 1554 1555``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to 1556``#pragma clang loop unroll(full)`` and 1557``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll`` 1558is equivalent to ``#pragma clang loop unroll(disable)``. See 1559`language extensions 1560<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_ 1561for further details including limitations of the unroll hints. 1562 }]; 1563} 1564 1565def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> { 1566 let Content = [{ 1567The address space qualifier may be used to specify the region of memory that is 1568used to allocate the object. OpenCL supports the following address spaces: 1569__generic(generic), __global(global), __local(local), __private(private), 1570__constant(constant). 1571 1572 .. code-block:: c 1573 1574 __constant int c = ...; 1575 1576 __generic int* foo(global int* g) { 1577 __local int* l; 1578 private int p; 1579 ... 1580 return l; 1581 } 1582 1583More details can be found in the OpenCL C language Spec v2.0, Section 6.5. 1584 }]; 1585} 1586 1587def OpenCLAddressSpaceGenericDocs : Documentation { 1588 let Category = DocOpenCLAddressSpaces; 1589 let Content = [{ 1590The generic address space attribute is only available with OpenCL v2.0 and later. 1591It can be used with pointer types. Variables in global and local scope and 1592function parameters in non-kernel functions can have the generic address space 1593type attribute. It is intended to be a placeholder for any other address space 1594except for '__constant' in OpenCL code which can be used with multiple address 1595spaces. 1596 }]; 1597} 1598 1599def OpenCLAddressSpaceConstantDocs : Documentation { 1600 let Category = DocOpenCLAddressSpaces; 1601 let Content = [{ 1602The constant address space attribute signals that an object is located in 1603a constant (non-modifiable) memory region. It is available to all work items. 1604Any type can be annotated with the constant address space attribute. Objects 1605with the constant address space qualifier can be declared in any scope and must 1606have an initializer. 1607 }]; 1608} 1609 1610def OpenCLAddressSpaceGlobalDocs : Documentation { 1611 let Category = DocOpenCLAddressSpaces; 1612 let Content = [{ 1613The global address space attribute specifies that an object is allocated in 1614global memory, which is accessible by all work items. The content stored in this 1615memory area persists between kernel executions. Pointer types to the global 1616address space are allowed as function parameters or local variables. Starting 1617with OpenCL v2.0, the global address space can be used with global (program 1618scope) variables and static local variable as well. 1619 }]; 1620} 1621 1622def OpenCLAddressSpaceLocalDocs : Documentation { 1623 let Category = DocOpenCLAddressSpaces; 1624 let Content = [{ 1625The local address space specifies that an object is allocated in the local (work 1626group) memory area, which is accessible to all work items in the same work 1627group. The content stored in this memory region is not accessible after 1628the kernel execution ends. In a kernel function scope, any variable can be in 1629the local address space. In other scopes, only pointer types to the local address 1630space are allowed. Local address space variables cannot have an initializer. 1631 }]; 1632} 1633 1634def OpenCLAddressSpacePrivateDocs : Documentation { 1635 let Category = DocOpenCLAddressSpaces; 1636 let Content = [{ 1637The private address space specifies that an object is allocated in the private 1638(work item) memory. Other work items cannot access the same memory area and its 1639content is destroyed after work item execution ends. Local variables can be 1640declared in the private address space. Function arguments are always in the 1641private address space. Kernel function arguments of a pointer or an array type 1642cannot point to the private address space. 1643 }]; 1644} 1645 1646def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> { 1647 let Content = [{ 1648Whether 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``). 1649 1650The 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: 1651 1652 .. code-block:: c 1653 1654 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior). 1655 int fetch(int * _Nonnull ptr) { return *ptr; } 1656 1657 // 'ptr' may be null. 1658 int fetch_or_zero(int * _Nullable ptr) { 1659 return ptr ? *ptr : 0; 1660 } 1661 1662 // A nullable pointer to non-null pointers to const characters. 1663 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n); 1664 1665In 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: 1666 1667 .. code-block:: objective-c 1668 1669 @interface NSView : NSResponder 1670 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView; 1671 @property (assign, nullable) NSView *superview; 1672 @property (readonly, nonnull) NSArray *subviews; 1673 @end 1674 }]; 1675} 1676 1677def TypeNonNullDocs : Documentation { 1678 let Category = NullabilityDocs; 1679 let Content = [{ 1680The ``_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: 1681 1682 .. code-block:: c 1683 1684 int fetch(int * _Nonnull ptr); 1685 1686a 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. 1687 }]; 1688} 1689 1690def TypeNullableDocs : Documentation { 1691 let Category = NullabilityDocs; 1692 let Content = [{ 1693The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given: 1694 1695 .. code-block:: c 1696 1697 int fetch_or_zero(int * _Nullable ptr); 1698 1699a caller of ``fetch_or_zero`` can provide null. 1700 }]; 1701} 1702 1703def TypeNullUnspecifiedDocs : Documentation { 1704 let Category = NullabilityDocs; 1705 let Content = [{ 1706The ``_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. 1707 }]; 1708} 1709 1710def NonNullDocs : Documentation { 1711 let Category = NullabilityDocs; 1712 let Content = [{ 1713The ``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: 1714 1715 .. code-block:: c 1716 1717 extern void * my_memcpy (void *dest, const void *src, size_t len) 1718 __attribute__((nonnull (1, 2))); 1719 1720Here, the ``nonnull`` attribute indicates that parameters 1 and 2 1721cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null: 1722 1723 .. code-block:: c 1724 1725 extern void * my_memcpy (void *dest, const void *src, size_t len) 1726 __attribute__((nonnull)); 1727 1728Clang 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: 1729 1730 .. code-block:: c 1731 1732 extern void * my_memcpy (void *dest __attribute__((nonnull)), 1733 const void *src __attribute__((nonnull)), size_t len); 1734 1735Note 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. 1736 }]; 1737} 1738 1739def ReturnsNonNullDocs : Documentation { 1740 let Category = NullabilityDocs; 1741 let Content = [{ 1742The ``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: 1743 1744 .. code-block:: c 1745 1746 extern void * malloc (size_t size) __attribute__((returns_nonnull)); 1747 1748The ``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 1749}]; 1750} 1751 1752def NoAliasDocs : Documentation { 1753 let Category = DocCatFunction; 1754 let Content = [{ 1755The ``noalias`` attribute indicates that the only memory accesses inside 1756function are loads and stores from objects pointed to by its pointer-typed 1757arguments, with arbitrary offsets. 1758 }]; 1759} 1760 1761def NotTailCalledDocs : Documentation { 1762 let Category = DocCatFunction; 1763 let Content = [{ 1764The ``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``. 1765 1766For example, it prevents tail-call optimization in the following case: 1767 1768 .. code-block: c 1769 1770 int __attribute__((not_tail_called)) foo1(int); 1771 1772 int foo2(int a) { 1773 return foo1(a); // No tail-call optimization on direct calls. 1774 } 1775 1776However, it doesn't prevent tail-call optimization in this case: 1777 1778 .. code-block: c 1779 1780 int __attribute__((not_tail_called)) foo1(int); 1781 1782 int foo2(int a) { 1783 int (*fn)(int) = &foo1; 1784 1785 // not_tail_called has no effect on an indirect call even if the call can be 1786 // resolved at compile time. 1787 return (*fn)(a); 1788 } 1789 1790Marking virtual functions as ``not_tail_called`` is an error: 1791 1792 .. code-block: c++ 1793 1794 class Base { 1795 public: 1796 // not_tail_called on a virtual function is an error. 1797 [[clang::not_tail_called]] virtual int foo1(); 1798 1799 virtual int foo2(); 1800 1801 // Non-virtual functions can be marked ``not_tail_called``. 1802 [[clang::not_tail_called]] int foo3(); 1803 }; 1804 1805 class Derived1 : public Base { 1806 public: 1807 int foo1() override; 1808 1809 // not_tail_called on a virtual function is an error. 1810 [[clang::not_tail_called]] int foo2() override; 1811 }; 1812 }]; 1813} 1814 1815def InternalLinkageDocs : Documentation { 1816 let Category = DocCatFunction; 1817 let Content = [{ 1818The ``internal_linkage`` attribute changes the linkage type of the declaration to internal. 1819This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition, 1820this attribute affects all methods and static data members of that class. 1821This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables. 1822 }]; 1823} 1824 1825def DisableTailCallsDocs : Documentation { 1826 let Category = DocCatFunction; 1827 let Content = [{ 1828The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function. 1829 1830For example: 1831 1832 .. code-block:: c 1833 1834 int callee(int); 1835 1836 int foo(int a) __attribute__((disable_tail_calls)) { 1837 return callee(a); // This call is not tail-call optimized. 1838 } 1839 1840Marking virtual functions as ``disable_tail_calls`` is legal. 1841 1842 .. code-block: c++ 1843 1844 int callee(int); 1845 1846 class Base { 1847 public: 1848 [[clang::disable_tail_calls]] virtual int foo1() { 1849 return callee(); // This call is not tail-call optimized. 1850 } 1851 }; 1852 1853 class Derived1 : public Base { 1854 public: 1855 int foo1() override { 1856 return callee(); // This call is tail-call optimized. 1857 } 1858 }; 1859 1860 }]; 1861} 1862