1 //==--- AttrDocs.td - Attribute documentation ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===---------------------------------------------------------------------===//
10 // To test that the documentation builds cleanly, you must run clang-tblgen to
11 // convert the .td file into a .rst file, and then run sphinx to convert the
12 // .rst file into an HTML file. After completing testing, you should revert the
13 // generated .rst file so that the modified version does not get checked in to
16 // To run clang-tblgen to generate the .rst file:
17 // clang-tblgen -gen-attr-docs -I <root>/llvm/tools/clang/include
18 // <root>/llvm/tools/clang/include/clang/Basic/Attr.td -o
19 // <root>/llvm/tools/clang/docs/AttributeReference.rst
21 // To run sphinx to generate the .html files (note that sphinx-build must be
22 // available on the PATH):
23 // Windows (from within the clang\docs directory):
25 // Non-Windows (from within the clang\docs directory):
26 // make -f Makefile.sphinx html
28 def GlobalDocumentation {
30 -------------------------------------------------------------------
31 NOTE: This file is automatically generated by running clang-tblgen
32 -gen-attr-docs. Do not edit this file by hand!!
33 -------------------------------------------------------------------
44 This page lists the attributes currently supported by Clang.
48 def SectionDocs : Documentation {
49 let Category = DocCatVariable;
51 The ``section`` attribute allows you to specify a specific section a
52 global variable or function should be in after translation.
54 let Heading = "section (gnu::section, __declspec(allocate))";
57 def InitSegDocs : Documentation {
58 let Category = DocCatVariable;
60 The attribute applied by ``pragma init_seg()`` controls the section into
61 which global initialization function pointers are emitted. It is only
62 available with ``-fms-extensions``. Typically, this function pointer is
63 emitted into ``.CRT$XCU`` on Windows. The user can change the order of
64 initialization by using a different section name with the same
65 ``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
66 after the standard ``.CRT$XCU`` sections. See the init_seg_
67 documentation on MSDN for more information.
69 .. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
73 def TLSModelDocs : Documentation {
74 let Category = DocCatVariable;
76 The ``tls_model`` attribute allows you to specify which thread-local storage
77 model to use. It accepts the following strings:
84 TLS models are mutually exclusive.
88 def DLLExportDocs : Documentation {
89 let Category = DocCatVariable;
91 The ``__declspec(dllexport)`` attribute declares a variable, function, or
92 Objective-C interface to be exported from the module. It is available under the
93 ``-fdeclspec`` flag for compatibility with various compilers. The primary use
94 is for COFF object files which explicitly specify what interfaces are available
95 for external use. See the dllexport_ documentation on MSDN for more
98 .. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
102 def DLLImportDocs : Documentation {
103 let Category = DocCatVariable;
105 The ``__declspec(dllimport)`` attribute declares a variable, function, or
106 Objective-C interface to be imported from an external module. It is available
107 under the ``-fdeclspec`` flag for compatibility with various compilers. The
108 primary use is for COFF object files which explicitly specify what interfaces
109 are imported from external modules. See the dllimport_ documentation on MSDN
110 for more information.
112 .. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
116 def ThreadDocs : Documentation {
117 let Category = DocCatVariable;
119 The ``__declspec(thread)`` attribute declares a variable with thread local
120 storage. It is available under the ``-fms-extensions`` flag for MSVC
121 compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
123 .. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
125 In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
126 GNU ``__thread`` keyword. The variable must not have a destructor and must have
127 a constant initializer, if any. The attribute only applies to variables
128 declared with static storage duration, such as globals, class static data
129 members, and static locals.
133 def NoEscapeDocs : Documentation {
134 let Category = DocCatVariable;
136 ``noescape`` placed on a function parameter of a pointer type is used to inform
137 the compiler that the pointer cannot escape: that is, no reference to the object
138 the pointer points to that is derived from the parameter value will survive
139 after the function returns. Users are responsible for making sure parameters
140 annotated with ``noescape`` do not actuallly escape.
148 void nonescapingFunc(__attribute__((noescape)) int *p) {
152 void escapingFunc(__attribute__((noescape)) int *p) {
156 Additionally, when the parameter is a `block pointer
157 <https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
158 applies to copies of the block. For example:
162 typedef void (^BlockTy)();
165 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
169 void escapingFunc(__attribute__((noescape)) BlockTy block) {
170 g0 = block; // Not OK.
171 g1 = Block_copy(block); // Not OK either.
177 def CarriesDependencyDocs : Documentation {
178 let Category = DocCatFunction;
180 The ``carries_dependency`` attribute specifies dependency propagation into and
183 When specified on a function or Objective-C method, the ``carries_dependency``
184 attribute means that the return value carries a dependency out of the function,
185 so that the implementation need not constrain ordering upon return from that
186 function. Implementations of the function and its caller may choose to preserve
187 dependencies instead of emitting memory ordering instructions such as fences.
189 Note, this attribute does not change the meaning of the program, but may result
190 in generation of more efficient code.
194 def C11NoReturnDocs : Documentation {
195 let Category = DocCatFunction;
197 A function declared as ``_Noreturn`` shall not return to its caller. The
198 compiler will generate a diagnostic for a function declared as ``_Noreturn``
199 that appears to be capable of returning to its caller.
203 def CXX11NoReturnDocs : Documentation {
204 let Category = DocCatFunction;
206 A function declared as ``[[noreturn]]`` shall not return to its caller. The
207 compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
208 that appears to be capable of returning to its caller.
212 def AssertCapabilityDocs : Documentation {
213 let Category = DocCatFunction;
214 let Heading = "assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)";
216 Marks a function that dynamically tests whether a capability is held, and halts
217 the program if it is not held.
221 def AcquireCapabilityDocs : Documentation {
222 let Category = DocCatFunction;
223 let Heading = "acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)";
225 Marks a function as acquiring a capability.
229 def TryAcquireCapabilityDocs : Documentation {
230 let Category = DocCatFunction;
231 let Heading = "try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)";
233 Marks a function that attempts to acquire a capability. This function may fail to
234 actually acquire the capability; they accept a Boolean value determining
235 whether acquiring the capability means success (true), or failing to acquire
236 the capability means success (false).
240 def ReleaseCapabilityDocs : Documentation {
241 let Category = DocCatFunction;
242 let Heading = "release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)";
244 Marks a function as releasing a capability.
248 def AssumeAlignedDocs : Documentation {
249 let Category = DocCatFunction;
251 Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
252 declaration to specify that the return value of the function (which must be a
253 pointer type) has the specified offset, in bytes, from an address with the
254 specified alignment. The offset is taken to be zero if omitted.
258 // The returned pointer value has 32-byte alignment.
259 void *a() __attribute__((assume_aligned (32)));
261 // The returned pointer value is 4 bytes greater than an address having
262 // 32-byte alignment.
263 void *b() __attribute__((assume_aligned (32, 4)));
265 Note that this attribute provides information to the compiler regarding a
266 condition that the code already ensures is true. It does not cause the compiler
267 to enforce the provided alignment assumption.
271 def AllocSizeDocs : Documentation {
272 let Category = DocCatFunction;
274 The ``alloc_size`` attribute can be placed on functions that return pointers in
275 order to hint to the compiler how many bytes of memory will be available at the
276 returned poiner. ``alloc_size`` takes one or two arguments.
278 - ``alloc_size(N)`` implies that argument number N equals the number of
279 available bytes at the returned pointer.
280 - ``alloc_size(N, M)`` implies that the product of argument number N and
281 argument number M equals the number of available bytes at the returned
284 Argument numbers are 1-based.
286 An example of how to use ``alloc_size``
290 void *my_malloc(int a) __attribute__((alloc_size(1)));
291 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
294 void *const p = my_malloc(100);
295 assert(__builtin_object_size(p, 0) == 100);
296 void *const a = my_calloc(20, 5);
297 assert(__builtin_object_size(a, 0) == 100);
300 .. Note:: This attribute works differently in clang than it does in GCC.
301 Specifically, clang will only trace ``const`` pointers (as above); we give up
302 on pointers that are not marked as ``const``. In the vast majority of cases,
303 this is unimportant, because LLVM has support for the ``alloc_size``
304 attribute. However, this may cause mildly unintuitive behavior when used with
305 other attributes, such as ``enable_if``.
309 def AllocAlignDocs : Documentation {
310 let Category = DocCatFunction;
312 Use ``__attribute__((alloc_align(<alignment>))`` on a function
313 declaration to specify that the return value of the function (which must be a
314 pointer type) is at least as aligned as the value of the indicated parameter. The
315 parameter is given by its index in the list of formal parameters; the first
316 parameter has index 1 unless the function is a C++ non-static member function,
317 in which case the first parameter has index 2 to account for the implicit ``this``
322 // The returned pointer has the alignment specified by the first parameter.
323 void *a(size_t align) __attribute__((alloc_align(1)));
325 // The returned pointer has the alignment specified by the second parameter.
326 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
328 // The returned pointer has the alignment specified by the second visible
329 // parameter, however it must be adjusted for the implicit 'this' parameter.
330 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
332 Note that this attribute merely informs the compiler that a function always
333 returns a sufficiently aligned pointer. It does not cause the compiler to
334 emit code to enforce that alignment. The behavior is undefined if the returned
335 poitner is not sufficiently aligned.
339 def EnableIfDocs : Documentation {
340 let Category = DocCatFunction;
342 .. Note:: Some features of this attribute are experimental. The meaning of
343 multiple enable_if attributes on a single declaration is subject to change in
344 a future version of clang. Also, the ABI is not standardized and the name
345 mangling may change in future versions. To avoid that, use asm labels.
347 The ``enable_if`` attribute can be placed on function declarations to control
348 which overload is selected based on the values of the function's arguments.
349 When combined with the ``overloadable`` attribute, this feature is also
355 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")));
360 isdigit(-10); // results in a compile-time error.
363 The enable_if attribute takes two arguments, the first is an expression written
364 in terms of the function parameters, the second is a string explaining why this
365 overload candidate could not be selected to be displayed in diagnostics. The
366 expression is part of the function signature for the purposes of determining
367 whether it is a redeclaration (following the rules used when determining
368 whether a C++ template specialization is ODR-equivalent), but is not part of
371 The enable_if expression is evaluated as if it were the body of a
372 bool-returning constexpr function declared with the arguments of the function
373 it is being applied to, then called with the parameters at the call site. If the
374 result is false or could not be determined through constant expression
375 evaluation, then this overload will not be chosen and the provided string may
376 be used in a diagnostic if the compile fails as a result.
378 Because the enable_if expression is an unevaluated context, there are no global
379 state changes, nor the ability to pass information from the enable_if
380 expression to the function body. For example, suppose we want calls to
381 strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
382 strbuf) only if the size of strbuf can be determined:
386 __attribute__((always_inline))
387 static inline size_t strnlen(const char *s, size_t maxlen)
388 __attribute__((overloadable))
389 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
390 "chosen when the buffer size is known but 'maxlen' is not")))
392 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
395 Multiple enable_if attributes may be applied to a single declaration. In this
396 case, the enable_if expressions are evaluated from left to right in the
397 following manner. First, the candidates whose enable_if expressions evaluate to
398 false or cannot be evaluated are discarded. If the remaining candidates do not
399 share ODR-equivalent enable_if expressions, the overload resolution is
400 ambiguous. Otherwise, enable_if overload resolution continues with the next
401 enable_if attribute on the candidates that have not been discarded and have
402 remaining enable_if attributes. In this way, we pick the most specific
403 overload out of a number of viable overloads using enable_if.
407 void f() __attribute__((enable_if(true, ""))); // #1
408 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
410 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
411 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
413 In this example, a call to f() is always resolved to #2, as the first enable_if
414 expression is ODR-equivalent for both declarations, but #1 does not have another
415 enable_if expression to continue evaluating, so the next round of evaluation has
416 only a single candidate. In a call to g(1, 1), the call is ambiguous even though
417 #2 has more enable_if attributes, because the first enable_if expressions are
420 Query for this feature with ``__has_attribute(enable_if)``.
422 Note that functions with one or more ``enable_if`` attributes may not have
423 their address taken, unless all of the conditions specified by said
424 ``enable_if`` are constants that evaluate to ``true``. For example:
428 const int TrueConstant = 1;
429 const int FalseConstant = 0;
430 int f(int a) __attribute__((enable_if(a > 0, "")));
431 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
432 int h(int a) __attribute__((enable_if(1, "")));
433 int i(int a) __attribute__((enable_if(TrueConstant, "")));
434 int j(int a) __attribute__((enable_if(FalseConstant, "")));
438 ptr = &f; // error: 'a > 0' is not always true
439 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
440 ptr = &h; // OK: 1 is a truthy constant
441 ptr = &i; // OK: 'TrueConstant' is a truthy constant
442 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
445 Because ``enable_if`` evaluation happens during overload resolution,
446 ``enable_if`` may give unintuitive results when used with templates, depending
447 on when overloads are resolved. In the example below, clang will emit a
448 diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
452 double foo(int i) __attribute__((enable_if(i > 0, "")));
453 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
455 auto bar() { return foo(I); }
457 template <typename T>
458 auto baz() { return foo(T::number); }
460 struct WithNumber { constexpr static int number = 1; };
462 bar<sizeof(WithNumber)>();
466 This is because, in ``bar``, ``foo`` is resolved prior to template
467 instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
468 conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
469 template instantiation, so the value for ``T::number`` is known.
473 def DiagnoseIfDocs : Documentation {
474 let Category = DocCatFunction;
476 The ``diagnose_if`` attribute can be placed on function declarations to emit
477 warnings or errors at compile-time if calls to the attributed function meet
478 certain user-defined criteria. For example:
483 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
485 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
487 int val = abs(1); // warning: Redundant abs call
488 int val2 = must_abs(1); // error: Redundant abs call
490 int val4 = must_abs(val); // Because run-time checks are not emitted for
491 // diagnose_if attributes, this executes without
495 ``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
497 * Overload resolution is not aware of ``diagnose_if`` attributes: they're
498 considered only after we select the best candidate from a given candidate set.
499 * Function declarations that differ only in their ``diagnose_if`` attributes are
500 considered to be redeclarations of the same function (not overloads).
501 * If the condition provided to ``diagnose_if`` cannot be evaluated, no
502 diagnostic will be emitted.
504 Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
506 As a result of bullet number two, ``diagnose_if`` attributes will stack on the
507 same function. For example:
511 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
512 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
514 int bar = foo(); // warning: diag1
516 int (*fooptr)(void) = foo; // warning: diag1
519 constexpr int supportsAPILevel(int N) { return N < 5; }
521 __attribute__((diagnose_if(!supportsAPILevel(10),
522 "Upgrade to API level 10 to use baz", "error")));
524 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
526 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
527 int v = baz(0); // error: Upgrade to API level 10 to use baz
529 Query for this feature with ``__has_attribute(diagnose_if)``.
533 def PassObjectSizeDocs : Documentation {
534 let Category = DocCatVariable; // Technically it's a parameter doc, but eh.
536 .. Note:: The mangling of functions with parameters that are annotated with
537 ``pass_object_size`` is subject to change. You can get around this by
538 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
539 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
542 The ``pass_object_size(Type)`` attribute can be placed on function parameters to
543 instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
544 of said function, and implicitly pass the result of this call in as an invisible
545 argument of type ``size_t`` directly after the parameter annotated with
546 ``pass_object_size``. Clang will also replace any calls to
547 ``__builtin_object_size(param, Type)`` in the function by said implicit
554 int bzero1(char *const p __attribute__((pass_object_size(0))))
555 __attribute__((noinline)) {
557 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
565 int n = bzero1(&chars[0]);
566 assert(n == sizeof(chars));
570 If successfully evaluating ``__builtin_object_size(param, Type)`` at the
571 callsite is not possible, then the "failed" value is passed in. So, using the
572 definition of ``bzero1`` from above, the following code would exit cleanly:
576 int main2(int argc, char *argv[]) {
577 int n = bzero1(argv);
582 ``pass_object_size`` plays a part in overload resolution. If two overload
583 candidates are otherwise equally good, then the overload with one or more
584 parameters with ``pass_object_size`` is preferred. This implies that the choice
585 between two identical overloads both with ``pass_object_size`` on one or more
586 parameters will always be ambiguous; for this reason, having two such overloads
587 is illegal. For example:
591 #define PS(N) __attribute__((pass_object_size(N)))
593 void Foo(char *a, char *b); // Overload A
594 // OK -- overload A has no parameters with pass_object_size.
595 void Foo(char *a PS(0), char *b PS(0)); // Overload B
596 // Error -- Same signature (sans pass_object_size) as overload B, and both
597 // overloads have one or more parameters with the pass_object_size attribute.
598 void Foo(void *a PS(0), void *b);
601 void Bar(void *a PS(0)); // Overload C
603 void Bar(char *c PS(1)); // Overload D
606 char known[10], *unknown;
607 Foo(unknown, unknown); // Calls overload B
608 Foo(known, unknown); // Calls overload B
609 Foo(unknown, known); // Calls overload B
610 Foo(known, known); // Calls overload B
612 Bar(known); // Calls overload D
613 Bar(unknown); // Calls overload D
616 Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
618 * Only one use of ``pass_object_size`` is allowed per parameter.
620 * It is an error to take the address of a function with ``pass_object_size`` on
621 any of its parameters. If you wish to do this, you can create an overload
622 without ``pass_object_size`` on any parameters.
624 * It is an error to apply the ``pass_object_size`` attribute to parameters that
625 are not pointers. Additionally, any parameter that ``pass_object_size`` is
626 applied to must be marked ``const`` at its function's definition.
630 def OverloadableDocs : Documentation {
631 let Category = DocCatFunction;
633 Clang provides support for C++ function overloading in C. Function overloading
634 in C is introduced using the ``overloadable`` attribute. For example, one
635 might provide several overloaded versions of a ``tgsin`` function that invokes
636 the appropriate standard function computing the sine of a value with ``float``,
637 ``double``, or ``long double`` precision:
642 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
643 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
644 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
646 Given these declarations, one can call ``tgsin`` with a ``float`` value to
647 receive a ``float`` result, with a ``double`` to receive a ``double`` result,
648 etc. Function overloading in C follows the rules of C++ function overloading
649 to pick the best overload given the call arguments, with a few C-specific
652 * Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
653 floating-point promotion (per C99) rather than as a floating-point conversion
656 * A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
657 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
660 * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
661 and ``U`` are compatible types. This conversion is given "conversion" rank.
663 * If no viable candidates are otherwise available, we allow a conversion from a
664 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
665 incompatible. This conversion is ranked below all other types of conversions.
666 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
667 for ``T`` and ``U`` to be incompatible.
669 The declaration of ``overloadable`` functions is restricted to function
670 declarations and definitions. If a function is marked with the ``overloadable``
671 attribute, then all declarations and definitions of functions with that name,
672 except for at most one (see the note below about unmarked overloads), must have
673 the ``overloadable`` attribute. In addition, redeclarations of a function with
674 the ``overloadable`` attribute must have the ``overloadable`` attribute, and
675 redeclarations of a function without the ``overloadable`` attribute must *not*
676 have the ``overloadable`` attribute. e.g.,
680 int f(int) __attribute__((overloadable));
681 float f(float); // error: declaration of "f" must have the "overloadable" attribute
682 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
684 int g(int) __attribute__((overloadable));
685 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
688 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
689 // have the "overloadable" attribute
691 Functions marked ``overloadable`` must have prototypes. Therefore, the
692 following code is ill-formed:
696 int h() __attribute__((overloadable)); // error: h does not have a prototype
698 However, ``overloadable`` functions are allowed to use a ellipsis even if there
699 are no named parameters (as is permitted in C++). This feature is particularly
700 useful when combined with the ``unavailable`` attribute:
704 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
706 Functions declared with the ``overloadable`` attribute have their names mangled
707 according to the same rules as C++ function names. For example, the three
708 ``tgsin`` functions in our motivating example get the mangled names
709 ``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
710 caveats to this use of name mangling:
712 * Future versions of Clang may change the name mangling of functions overloaded
713 in C, so you should not depend on an specific mangling. To be completely
714 safe, we strongly urge the use of ``static inline`` with ``overloadable``
717 * The ``overloadable`` attribute has almost no meaning when used in C++,
718 because names will already be mangled and functions are already overloadable.
719 However, when an ``overloadable`` function occurs within an ``extern "C"``
720 linkage specification, it's name *will* be mangled in the same way as it
723 For the purpose of backwards compatibility, at most one function with the same
724 name as other ``overloadable`` functions may omit the ``overloadable``
725 attribute. In this case, the function without the ``overloadable`` attribute
726 will not have its name mangled.
732 // Notes with mangled names assume Itanium mangling.
734 int f(double) __attribute__((overloadable));
736 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
737 // was marked with overloadable).
738 f(1.0); // Emits a call to _Z1fd.
741 Support for unmarked overloads is not present in some versions of clang. You may
742 query for it using ``__has_extension(overloadable_unmarked)``.
744 Query for this attribute with ``__has_attribute(overloadable)``.
748 def ObjCMethodFamilyDocs : Documentation {
749 let Category = DocCatFunction;
751 Many methods in Objective-C have conventional meanings determined by their
752 selectors. It is sometimes useful to be able to mark a method as having a
753 particular conventional meaning despite not having the right selector, or as
754 not having the conventional meaning that its selector would suggest. For these
755 use cases, we provide an attribute to specifically describe the "method family"
756 that a method belongs to.
758 **Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
759 ``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
760 attribute can only be placed at the end of a method declaration:
764 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
766 Users who do not wish to change the conventional meaning of a method, and who
767 merely want to document its non-standard retain and release semantics, should
768 use the retaining behavior attributes (``ns_returns_retained``,
769 ``ns_returns_not_retained``, etc).
771 Query for this feature with ``__has_attribute(objc_method_family)``.
775 def NoDebugDocs : Documentation {
776 let Category = DocCatVariable;
778 The ``nodebug`` attribute allows you to suppress debugging information for a
779 function or method, or for a variable that is not a parameter or a non-static
784 def NoDuplicateDocs : Documentation {
785 let Category = DocCatFunction;
787 The ``noduplicate`` attribute can be placed on function declarations to control
788 whether function calls to this function can be duplicated or not as a result of
789 optimizations. This is required for the implementation of functions with
790 certain special requirements, like the OpenCL "barrier" function, that might
791 need to be run concurrently by all the threads that are executing in lockstep
792 on the hardware. For example this attribute applied on the function
793 "nodupfunc" in the code below avoids that:
797 void nodupfunc() __attribute__((noduplicate));
798 // Setting it as a C++11 attribute is also valid
799 // void nodupfunc() [[clang::noduplicate]];
810 gets possibly modified by some optimizations into code similar to this:
822 where the call to "nodupfunc" is duplicated and sunk into the two branches
827 def ConvergentDocs : Documentation {
828 let Category = DocCatFunction;
830 The ``convergent`` attribute can be placed on a function declaration. It is
831 translated into the LLVM ``convergent`` attribute, which indicates that the call
832 instructions of a function with this attribute cannot be made control-dependent
833 on any additional values.
835 In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA,
836 the call instructions of a function with this attribute must be executed by
837 all work items or threads in a work group or sub group.
839 This attribute is different from ``noduplicate`` because it allows duplicating
840 function calls if it can be proved that the duplicated function calls are
841 not made control-dependent on any additional values, e.g., unrolling a loop
842 executed by all work items.
847 void convfunc(void) __attribute__((convergent));
848 // Setting it as a C++11 attribute is also valid in a C++ program.
849 // void convfunc(void) [[clang::convergent]];
854 def NoSplitStackDocs : Documentation {
855 let Category = DocCatFunction;
857 The ``no_split_stack`` attribute disables the emission of the split stack
858 preamble for a particular function. It has no effect if ``-fsplit-stack``
863 def ObjCRequiresSuperDocs : Documentation {
864 let Category = DocCatFunction;
866 Some Objective-C classes allow a subclass to override a particular method in a
867 parent class but expect that the overriding method also calls the overridden
868 method in the parent class. For these cases, we provide an attribute to
869 designate that a method requires a "call to ``super``" in the overriding
870 method in the subclass.
872 **Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
873 be placed at the end of a method declaration:
877 - (void)foo __attribute__((objc_requires_super));
879 This attribute can only be applied the method declarations within a class, and
880 not a protocol. Currently this attribute does not enforce any placement of
881 where the call occurs in the overriding method (such as in the case of
882 ``-dealloc`` where the call must appear at the end). It checks only that it
885 Note that on both OS X and iOS that the Foundation framework provides a
886 convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
891 - (void)foo NS_REQUIRES_SUPER;
893 This macro is conditionally defined depending on the compiler's support for
894 this attribute. If the compiler does not support the attribute the macro
897 Operationally, when a method has this annotation the compiler will warn if the
898 implementation of an override in a subclass does not call super. For example:
902 warning: method possibly missing a [super AnnotMeth] call
903 - (void) AnnotMeth{};
908 def ObjCRuntimeNameDocs : Documentation {
909 let Category = DocCatFunction;
911 By default, the Objective-C interface or protocol identifier is used
912 in the metadata name for that object. The `objc_runtime_name`
913 attribute allows annotated interfaces or protocols to use the
914 specified string argument in the object's metadata name instead of the
917 **Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
918 can only be placed before an @protocol or @interface declaration:
922 __attribute__((objc_runtime_name("MyLocalName")))
929 def ObjCRuntimeVisibleDocs : Documentation {
930 let Category = DocCatFunction;
932 This attribute specifies that the Objective-C class to which it applies is visible to the Objective-C runtime but not to the linker. Classes annotated with this attribute cannot be subclassed and cannot have categories defined for them.
936 def ObjCBoxableDocs : Documentation {
937 let Category = DocCatFunction;
939 Structs and unions marked with the ``objc_boxable`` attribute can be used
940 with the Objective-C boxed expression syntax, ``@(...)``.
942 **Usage**: ``__attribute__((objc_boxable))``. This attribute
943 can only be placed on a declaration of a trivially-copyable struct or union:
947 struct __attribute__((objc_boxable)) some_struct {
950 union __attribute__((objc_boxable)) some_union {
954 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
959 NSValue *boxed = @(ss);
964 def AvailabilityDocs : Documentation {
965 let Category = DocCatFunction;
967 The ``availability`` attribute can be placed on declarations to describe the
968 lifecycle of that declaration relative to operating system versions. Consider
969 the function declaration for a hypothetical function ``f``:
973 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
975 The availability attribute states that ``f`` was introduced in macOS 10.4,
976 deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
977 is used by Clang to determine when it is safe to use ``f``: for example, if
978 Clang is instructed to compile code for macOS 10.5, a call to ``f()``
979 succeeds. If Clang is instructed to compile code for macOS 10.6, the call
980 succeeds but Clang emits a warning specifying that the function is deprecated.
981 Finally, if Clang is instructed to compile code for macOS 10.7, the call
982 fails because ``f()`` is no longer available.
984 The availability attribute is a comma-separated list starting with the
985 platform name and then including clauses specifying important milestones in the
986 declaration's lifetime (in any order) along with additional information. Those
989 introduced=\ *version*
990 The first version in which this declaration was introduced.
992 deprecated=\ *version*
993 The first version in which this declaration was deprecated, meaning that
994 users should migrate away from this API.
996 obsoleted=\ *version*
997 The first version in which this declaration was obsoleted, meaning that it
998 was removed completely and can no longer be used.
1001 This declaration is never available on this platform.
1003 message=\ *string-literal*
1004 Additional message text that Clang will provide when emitting a warning or
1005 error about use of a deprecated or obsoleted declaration. Useful to direct
1006 users to replacement APIs.
1008 replacement=\ *string-literal*
1009 Additional message text that Clang will use to provide Fix-It when emitting
1010 a warning about use of a deprecated declaration. The Fix-It will replace
1011 the deprecated declaration with the new declaration specified.
1013 Multiple availability attributes can be placed on a declaration, which may
1014 correspond to different platforms. Only the availability attribute with the
1015 platform corresponding to the target platform will be used; any others will be
1016 ignored. If no availability attribute specifies availability for the current
1017 target platform, the availability attributes are ignored. Supported platforms
1021 Apple's iOS operating system. The minimum deployment target is specified by
1022 the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
1023 command-line arguments.
1026 Apple's macOS operating system. The minimum deployment target is
1027 specified by the ``-mmacosx-version-min=*version*`` command-line argument.
1028 ``macosx`` is supported for backward-compatibility reasons, but it is
1032 Apple's tvOS operating system. The minimum deployment target is specified by
1033 the ``-mtvos-version-min=*version*`` command-line argument.
1036 Apple's watchOS operating system. The minimum deployment target is specified by
1037 the ``-mwatchos-version-min=*version*`` command-line argument.
1039 A declaration can typically be used even when deploying back to a platform
1040 version prior to when the declaration was introduced. When this happens, the
1041 declaration is `weakly linked
1042 <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1043 as if the ``weak_import`` attribute were added to the declaration. A
1044 weakly-linked declaration may or may not be present a run-time, and a program
1045 can determine whether the declaration is present by checking whether the
1046 address of that declaration is non-NULL.
1048 The flag ``strict`` disallows using API when deploying back to a
1049 platform version prior to when the declaration was introduced. An
1050 attempt to use such API before its introduction causes a hard error.
1051 Weakly-linking is almost always a better API choice, since it allows
1052 users to query availability at runtime.
1054 If there are multiple declarations of the same entity, the availability
1055 attributes must either match on a per-platform basis or later
1056 declarations must not have availability attributes for that
1057 platform. For example:
1061 void g(void) __attribute__((availability(macos,introduced=10.4)));
1062 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1063 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1064 void g(void); // okay, inherits both macos and ios availability from above.
1065 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1067 When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1069 .. code-block:: objc
1072 - (id)method __attribute__((availability(macos,introduced=10.4)));
1073 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1077 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1078 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1081 Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1082 ``<os/availability.h>`` can simplify the spelling:
1084 .. code-block:: objc
1087 - (id)method API_AVAILABLE(macos(10.11)));
1088 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1091 Also see the documentation for `@available
1092 <http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_
1096 def ExternalSourceSymbolDocs : Documentation {
1097 let Category = DocCatFunction;
1099 The ``external_source_symbol`` attribute specifies that a declaration originates
1100 from an external source and describes the nature of that source.
1102 The fact that Clang is capable of recognizing declarations that were defined
1103 externally can be used to provide better tooling support for mixed-language
1104 projects or projects that rely on auto-generated code. For instance, an IDE that
1105 uses Clang and that supports mixed-language projects can use this attribute to
1106 provide a correct 'jump-to-definition' feature. For a concrete example,
1107 consider a protocol that's defined in a Swift file:
1109 .. code-block:: swift
1111 @objc public protocol SwiftProtocol {
1115 This protocol can be used from Objective-C code by including a header file that
1116 was generated by the Swift compiler. The declarations in that header can use
1117 the ``external_source_symbol`` attribute to make Clang aware of the fact
1118 that ``SwiftProtocol`` actually originates from a Swift module:
1120 .. code-block:: objc
1122 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
1123 @protocol SwiftProtocol
1128 Consequently, when 'jump-to-definition' is performed at a location that
1129 references ``SwiftProtocol``, the IDE can jump to the original definition in
1130 the Swift source file rather than jumping to the Objective-C declaration in the
1131 auto-generated header file.
1133 The ``external_source_symbol`` attribute is a comma-separated list that includes
1134 clauses that describe the origin and the nature of the particular declaration.
1135 Those clauses can be:
1137 language=\ *string-literal*
1138 The name of the source language in which this declaration was defined.
1140 defined_in=\ *string-literal*
1141 The name of the source container in which the declaration was defined. The
1142 exact definition of source container is language-specific, e.g. Swift's
1143 source containers are modules, so ``defined_in`` should specify the Swift
1146 generated_declaration
1147 This declaration was automatically generated by some tool.
1149 The clauses can be specified in any order. The clauses that are listed above are
1150 all optional, but the attribute has to have at least one clause.
1154 def RequireConstantInitDocs : Documentation {
1155 let Category = DocCatVariable;
1157 This attribute specifies that the variable to which it is attached is intended
1158 to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1159 according to the rules of [basic.start.static]. The variable is required to
1160 have static or thread storage duration. If the initialization of the variable
1161 is not a constant initializer an error will be produced. This attribute may
1162 only be used in C++.
1164 Note that in C++03 strict constant expression checking is not done. Instead
1165 the attribute reports if Clang can emit the variable as a constant, even if it's
1166 not technically a 'constant initializer'. This behavior is non-portable.
1168 Static storage duration variables with constant initializers avoid hard-to-find
1169 bugs caused by the indeterminate order of dynamic initialization. They can also
1170 be safely used during dynamic initialization across translation units.
1172 This attribute acts as a compile time assertion that the requirements
1173 for constant initialization have been met. Since these requirements change
1174 between dialects and have subtle pitfalls it's important to fail fast instead
1175 of silently falling back on dynamic initialization.
1180 #define SAFE_STATIC [[clang::require_constant_initialization]]
1183 ~T(); // non-trivial
1185 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
1186 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
1187 // copy initialization is not a constant expression on a non-literal type.
1191 def WarnMaybeUnusedDocs : Documentation {
1192 let Category = DocCatVariable;
1193 let Heading = "maybe_unused, unused, gnu::unused";
1195 When passing the ``-Wunused`` flag to Clang, entities that are unused by the
1196 program may be diagnosed. The ``[[maybe_unused]]`` (or
1197 ``__attribute__((unused))``) attribute can be used to silence such diagnostics
1198 when the entity cannot be removed. For instance, a local variable may exist
1199 solely for use in an ``assert()`` statement, which makes the local variable
1200 unused when ``NDEBUG`` is defined.
1202 The attribute may be applied to the declaration of a class, a typedef, a
1203 variable, a function or method, a function parameter, an enumeration, an
1204 enumerator, a non-static data member, or a label.
1209 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
1210 [[maybe_unused]] bool thing2) {
1211 [[maybe_unused]] bool b = thing1 && thing2;
1217 def WarnUnusedResultsDocs : Documentation {
1218 let Category = DocCatFunction;
1219 let Heading = "nodiscard, warn_unused_result, clang::warn_unused_result, gnu::warn_unused_result";
1221 Clang supports the ability to diagnose when the results of a function call
1222 expression are discarded under suspicious circumstances. A diagnostic is
1223 generated when a function or its return type is marked with ``[[nodiscard]]``
1224 (or ``__attribute__((warn_unused_result))``) and the function call appears as a
1225 potentially-evaluated discarded-value expression that is not explicitly cast to
1229 struct [[nodiscard]] error_info { /*...*/ };
1230 error_info enable_missile_safety_mode();
1232 void launch_missiles();
1233 void test_missiles() {
1234 enable_missile_safety_mode(); // diagnoses
1238 void f() { foo(); } // Does not diagnose, error_info is a reference.
1242 def FallthroughDocs : Documentation {
1243 let Category = DocCatStmt;
1244 let Heading = "fallthrough, clang::fallthrough";
1246 The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
1247 to annotate intentional fall-through
1248 between switch labels. It can only be applied to a null statement placed at a
1249 point of execution between any statement and the next switch label. It is
1250 common to mark these places with a specific comment, but this attribute is
1251 meant to replace comments with a more strict annotation, which can be checked
1252 by the compiler. This attribute doesn't change semantics of the code and can
1253 be used wherever an intended fall-through occurs. It is designed to mimic
1254 control-flow statements like ``break;``, so it can be placed in most places
1255 where ``break;`` can, but only if there are no statements on the execution path
1256 between it and the next switch label.
1258 By default, Clang does not warn on unannotated fallthrough from one ``switch``
1259 case to another. Diagnostics on fallthrough without a corresponding annotation
1260 can be enabled with the ``-Wimplicit-fallthrough`` argument.
1266 // compile with -Wimplicit-fallthrough
1269 case 33: // no warning: no statements between case labels
1271 case 44: // warning: unannotated fall-through
1273 [[clang::fallthrough]];
1274 case 55: // no warning
1281 [[clang::fallthrough]];
1283 case 66: // no warning
1285 [[clang::fallthrough]]; // warning: fallthrough annotation does not
1286 // directly precede case label
1288 case 77: // warning: unannotated fall-through
1294 def ARMInterruptDocs : Documentation {
1295 let Category = DocCatFunction;
1296 let Heading = "interrupt (ARM)";
1298 Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
1299 ARM targets. This attribute may be attached to a function definition and
1300 instructs the backend to generate appropriate function entry/exit code so that
1301 it can be used directly as an interrupt service routine.
1303 The parameter passed to the interrupt attribute is optional, but if
1304 provided it must be a string literal with one of the following values: "IRQ",
1305 "FIQ", "SWI", "ABORT", "UNDEF".
1307 The semantics are as follows:
1309 - If the function is AAPCS, Clang instructs the backend to realign the stack to
1310 8 bytes on entry. This is a general requirement of the AAPCS at public
1311 interfaces, but may not hold when an exception is taken. Doing this allows
1312 other AAPCS functions to be called.
1313 - If the CPU is M-class this is all that needs to be done since the architecture
1314 itself is designed in such a way that functions obeying the normal AAPCS ABI
1315 constraints are valid exception handlers.
1316 - If the CPU is not M-class, the prologue and epilogue are modified to save all
1317 non-banked registers that are used, so that upon return the user-mode state
1318 will not be corrupted. Note that to avoid unnecessary overhead, only
1319 general-purpose (integer) registers are saved in this way. If VFP operations
1320 are needed, that state must be saved manually.
1322 Specifically, interrupt kinds other than "FIQ" will save all core registers
1323 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
1324 - If the CPU is not M-class, the return instruction is changed to one of the
1325 canonical sequences permitted by the architecture for exception return. Where
1326 possible the function itself will make the necessary "lr" adjustments so that
1327 the "preferred return address" is selected.
1329 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
1330 handler, where the offset from "lr" to the preferred return address depends on
1331 the execution state of the code which generated the exception. In this case
1332 a sequence equivalent to "movs pc, lr" will be used.
1336 def MipsInterruptDocs : Documentation {
1337 let Category = DocCatFunction;
1338 let Heading = "interrupt (MIPS)";
1340 Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
1341 MIPS targets. This attribute may be attached to a function definition and instructs
1342 the backend to generate appropriate function entry/exit code so that it can be used
1343 directly as an interrupt service routine.
1345 By default, the compiler will produce a function prologue and epilogue suitable for
1346 an interrupt service routine that handles an External Interrupt Controller (eic)
1347 generated interrupt. This behaviour can be explicitly requested with the "eic"
1350 Otherwise, for use with vectored interrupt mode, the argument passed should be
1351 of the form "vector=LEVEL" where LEVEL is one of the following values:
1352 "sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
1353 then set the interrupt mask to the corresponding level which will mask all
1354 interrupts up to and including the argument.
1356 The semantics are as follows:
1358 - The prologue is modified so that the Exception Program Counter (EPC) and
1359 Status coprocessor registers are saved to the stack. The interrupt mask is
1360 set so that the function can only be interrupted by a higher priority
1361 interrupt. The epilogue will restore the previous values of EPC and Status.
1363 - The prologue and epilogue are modified to save and restore all non-kernel
1364 registers as necessary.
1366 - The FPU is disabled in the prologue, as the floating pointer registers are not
1367 spilled to the stack.
1369 - The function return sequence is changed to use an exception return instruction.
1371 - The parameter sets the interrupt mask for the function corresponding to the
1372 interrupt level specified. If no mask is specified the interrupt mask
1377 def MicroMipsDocs : Documentation {
1378 let Category = DocCatFunction;
1380 Clang supports the GNU style ``__attribute__((micromips))`` and
1381 ``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
1382 may be attached to a function definition and instructs the backend to generate
1383 or not to generate microMIPS code for that function.
1385 These attributes override the `-mmicromips` and `-mno-micromips` options
1386 on the command line.
1390 def MipsLongCallStyleDocs : Documentation {
1391 let Category = DocCatFunction;
1392 let Heading = "long_call (gnu::long_call, gnu::far)";
1394 Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1395 and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
1396 only be added to function declarations and change the code generated
1397 by the compiler when directly calling the function. The ``near`` attribute
1398 allows calls to the function to be made using the ``jal`` instruction, which
1399 requires the function to be located in the same naturally aligned 256MB
1400 segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
1401 and require the use of a different call sequence that works regardless
1402 of the distance between the functions.
1404 These attributes have no effect for position-independent code.
1406 These attributes take priority over command line switches such
1407 as ``-mlong-calls`` and ``-mno-long-calls``.
1411 def MipsShortCallStyleDocs : Documentation {
1412 let Category = DocCatFunction;
1413 let Heading = "short_call (gnu::short_call, gnu::near)";
1415 Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1416 ``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
1417 on MIPS targets. These attributes may only be added to function declarations
1418 and change the code generated by the compiler when directly calling
1419 the function. The ``short_call`` and ``near`` attributes are synonyms and
1420 allow calls to the function to be made using the ``jal`` instruction, which
1421 requires the function to be located in the same naturally aligned 256MB segment
1422 as the caller. The ``long_call`` and ``far`` attributes are synonyms and
1423 require the use of a different call sequence that works regardless
1424 of the distance between the functions.
1426 These attributes have no effect for position-independent code.
1428 These attributes take priority over command line switches such
1429 as ``-mlong-calls`` and ``-mno-long-calls``.
1433 def AVRInterruptDocs : Documentation {
1434 let Category = DocCatFunction;
1435 let Heading = "interrupt (AVR)";
1437 Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
1438 AVR targets. This attribute may be attached to a function definition and instructs
1439 the backend to generate appropriate function entry/exit code so that it can be used
1440 directly as an interrupt service routine.
1442 On the AVR, the hardware globally disables interrupts when an interrupt is executed.
1443 The first instruction of an interrupt handler declared with this attribute is a SEI
1444 instruction to re-enable interrupts. See also the signal attribute that
1445 does not insert a SEI instruction.
1449 def AVRSignalDocs : Documentation {
1450 let Category = DocCatFunction;
1452 Clang supports the GNU style ``__attribute__((signal))`` attribute on
1453 AVR targets. This attribute may be attached to a function definition and instructs
1454 the backend to generate appropriate function entry/exit code so that it can be used
1455 directly as an interrupt service routine.
1457 Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
1461 def TargetDocs : Documentation {
1462 let Category = DocCatFunction;
1464 Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
1465 This attribute may be attached to a function definition and instructs
1466 the backend to use different code generation options than were passed on the
1469 The current set of options correspond to the existing "subtarget features" for
1470 the target with or without a "-mno-" in front corresponding to the absence
1471 of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
1474 Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
1475 "avx", "xop" and largely correspond to the machine specific options handled by
1480 def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">;
1482 def AMDGPUFlatWorkGroupSizeDocs : Documentation {
1483 let Category = DocCatAMDGPUAttributes;
1485 The flat work-group size is the number of work-items in the work-group size
1486 specified when the kernel is dispatched. It is the product of the sizes of the
1487 x, y, and z dimension of the work-group.
1490 ``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
1491 AMDGPU target. This attribute may be attached to a kernel function definition
1492 and is an optimization hint.
1494 ``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
1495 parameter specifies the maximum flat work-group size (must be greater than
1496 ``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
1497 as ``<min>, <max>`` implies the default behavior (``128, 256``).
1499 If specified, the AMDGPU target backend might be able to produce better machine
1500 code for barriers and perform scratch promotion by estimating available group
1503 An error will be given if:
1504 - Specified values violate subtarget specifications;
1505 - Specified values are not compatible with values provided through other
1510 def AMDGPUWavesPerEUDocs : Documentation {
1511 let Category = DocCatAMDGPUAttributes;
1513 A compute unit (CU) is responsible for executing the wavefronts of a work-group.
1514 It is composed of one or more execution units (EU), which are responsible for
1515 executing the wavefronts. An EU can have enough resources to maintain the state
1516 of more than one executing wavefront. This allows an EU to hide latency by
1517 switching between wavefronts in a similar way to symmetric multithreading on a
1518 CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
1519 resources used by a single wavefront have to be limited. For example, the number
1520 of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
1521 but can result in having to spill some register state to memory.
1523 Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
1524 attribute for the AMDGPU target. This attribute may be attached to a kernel
1525 function definition and is an optimization hint.
1527 ``<min>`` parameter specifies the requested minimum number of waves per EU, and
1528 *optional* ``<max>`` parameter specifies the requested maximum number of waves
1529 per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
1530 then there is no restriction on the maximum number of waves per EU other than
1531 the one dictated by the hardware for which the kernel is compiled. Passing
1532 ``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
1534 If specified, this attribute allows an advanced developer to tune the number of
1535 wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
1536 target backend can use this information to limit resources, such as number of
1537 SGPRs, number of VGPRs, size of available group and private memory segments, in
1538 such a way that guarantees that at least ``<min>`` wavefronts and at most
1539 ``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
1540 more wavefronts can hide memory latency but limits available registers which
1541 can result in spilling. Requesting fewer wavefronts can help reduce cache
1542 thrashing, but can reduce memory latency hiding.
1544 This attribute controls the machine code generated by the AMDGPU target backend
1545 to ensure it is capable of meeting the requested values. However, when the
1546 kernel is executed, there may be other reasons that prevent meeting the request,
1547 for example, there may be wavefronts from other kernels executing on the EU.
1549 An error will be given if:
1550 - Specified values violate subtarget specifications;
1551 - Specified values are not compatible with values provided through other
1553 - The AMDGPU target backend is unable to create machine code that can meet the
1558 def AMDGPUNumSGPRNumVGPRDocs : Documentation {
1559 let Category = DocCatAMDGPUAttributes;
1561 Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
1562 ``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
1563 target. These attributes may be attached to a kernel function definition and are
1564 an optimization hint.
1566 If these attributes are specified, then the AMDGPU target backend will attempt
1567 to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
1568 number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
1569 allocation requirements or constraints of the subtarget. Passing ``0`` as
1570 ``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
1572 These attributes can be used to test the AMDGPU target backend. It is
1573 recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
1574 resources such as SGPRs and VGPRs since it is aware of the limits for different
1577 An error will be given if:
1578 - Specified values violate subtarget specifications;
1579 - Specified values are not compatible with values provided through other
1581 - The AMDGPU target backend is unable to create machine code that can meet the
1586 def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> {
1588 Clang supports several different calling conventions, depending on the target
1589 platform and architecture. The calling convention used for a function determines
1590 how parameters are passed, how results are returned to the caller, and other
1591 low-level details of calling a function.
1595 def PcsDocs : Documentation {
1596 let Category = DocCatCallingConvs;
1598 On ARM targets, this attribute can be used to select calling conventions
1599 similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
1604 def RegparmDocs : Documentation {
1605 let Category = DocCatCallingConvs;
1607 On 32-bit x86 targets, the regparm attribute causes the compiler to pass
1608 the first three integer parameters in EAX, EDX, and ECX instead of on the
1609 stack. This attribute has no effect on variadic functions, and all parameters
1610 are passed via the stack as normal.
1614 def SysVABIDocs : Documentation {
1615 let Category = DocCatCallingConvs;
1617 On Windows x86_64 targets, this attribute changes the calling convention of a
1618 function to match the default convention used on Sys V targets such as Linux,
1619 Mac, and BSD. This attribute has no effect on other targets.
1623 def MSABIDocs : Documentation {
1624 let Category = DocCatCallingConvs;
1626 On non-Windows x86_64 targets, this attribute changes the calling convention of
1627 a function to match the default convention used on Windows x86_64. This
1628 attribute has no effect on Windows targets or non-x86_64 targets.
1632 def StdCallDocs : Documentation {
1633 let Category = DocCatCallingConvs;
1635 On 32-bit x86 targets, this attribute changes the calling convention of a
1636 function to clear parameters off of the stack on return. This convention does
1637 not support variadic calls or unprototyped functions in C, and has no effect on
1638 x86_64 targets. This calling convention is used widely by the Windows API and
1639 COM applications. See the documentation for `__stdcall`_ on MSDN.
1641 .. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
1645 def FastCallDocs : Documentation {
1646 let Category = DocCatCallingConvs;
1648 On 32-bit x86 targets, this attribute changes the calling convention of a
1649 function to use ECX and EDX as register parameters and clear parameters off of
1650 the stack on return. This convention does not support variadic calls or
1651 unprototyped functions in C, and has no effect on x86_64 targets. This calling
1652 convention is supported primarily for compatibility with existing code. Users
1653 seeking register parameters should use the ``regparm`` attribute, which does
1654 not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
1656 .. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
1660 def RegCallDocs : Documentation {
1661 let Category = DocCatCallingConvs;
1663 On x86 targets, this attribute changes the calling convention to
1664 `__regcall`_ convention. This convention aims to pass as many arguments
1665 as possible in registers. It also tries to utilize registers for the
1666 return value whenever it is possible.
1668 .. _`__regcall`: https://software.intel.com/en-us/node/693069
1672 def ThisCallDocs : Documentation {
1673 let Category = DocCatCallingConvs;
1675 On 32-bit x86 targets, this attribute changes the calling convention of a
1676 function to use ECX for the first parameter (typically the implicit ``this``
1677 parameter of C++ methods) and clear parameters off of the stack on return. This
1678 convention does not support variadic calls or unprototyped functions in C, and
1679 has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
1682 .. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx
1686 def VectorCallDocs : Documentation {
1687 let Category = DocCatCallingConvs;
1689 On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
1690 convention of a function to pass vector parameters in SSE registers.
1692 On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
1693 The first two integer parameters are passed in ECX and EDX. Subsequent integer
1694 parameters are passed in memory, and callee clears the stack. On x86_64
1695 targets, the callee does *not* clear the stack, and integer parameters are
1696 passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
1699 On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
1700 passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
1701 passed in sequential SSE registers if enough are available. If AVX is enabled,
1702 256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
1703 cannot be passed in registers for any reason is passed by reference, which
1704 allows the caller to align the parameter memory.
1706 See the documentation for `__vectorcall`_ on MSDN for more details.
1708 .. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx
1712 def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> {
1714 Clang supports additional attributes for checking basic resource management
1715 properties, specifically for unique objects that have a single owning reference.
1716 The following attributes are currently supported, although **the implementation
1717 for these annotations is currently in development and are subject to change.**
1721 def SetTypestateDocs : Documentation {
1722 let Category = DocCatConsumed;
1724 Annotate methods that transition an object into a new state with
1725 ``__attribute__((set_typestate(new_state)))``. The new state must be
1726 unconsumed, consumed, or unknown.
1730 def CallableWhenDocs : Documentation {
1731 let Category = DocCatConsumed;
1733 Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1734 may be called in. Valid states are unconsumed, consumed, or unknown. Each
1735 argument to this attribute must be a quoted string. E.g.:
1737 ``__attribute__((callable_when("unconsumed", "unknown")))``
1741 def TestTypestateDocs : Documentation {
1742 let Category = DocCatConsumed;
1744 Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
1745 returns true if the object is in the specified state..
1749 def ParamTypestateDocs : Documentation {
1750 let Category = DocCatConsumed;
1752 This attribute specifies expectations about function parameters. Calls to an
1753 function with annotated parameters will issue a warning if the corresponding
1754 argument isn't in the expected state. The attribute is also used to set the
1755 initial state of the parameter when analyzing the function's body.
1759 def ReturnTypestateDocs : Documentation {
1760 let Category = DocCatConsumed;
1762 The ``return_typestate`` attribute can be applied to functions or parameters.
1763 When applied to a function the attribute specifies the state of the returned
1764 value. The function's body is checked to ensure that it always returns a value
1765 in the specified state. On the caller side, values returned by the annotated
1766 function are initialized to the given state.
1768 When applied to a function parameter it modifies the state of an argument after
1769 a call to the function returns. The function's body is checked to ensure that
1770 the parameter is in the expected state before returning.
1774 def ConsumableDocs : Documentation {
1775 let Category = DocCatConsumed;
1777 Each ``class`` that uses any of the typestate annotations must first be marked
1778 using the ``consumable`` attribute. Failure to do so will result in a warning.
1780 This attribute accepts a single parameter that must be one of the following:
1781 ``unknown``, ``consumed``, or ``unconsumed``.
1785 def NoSanitizeDocs : Documentation {
1786 let Category = DocCatFunction;
1788 Use the ``no_sanitize`` attribute on a function declaration to specify
1789 that a particular instrumentation or set of instrumentations should not be
1790 applied to that function. The attribute takes a list of string literals,
1791 which have the same meaning as values accepted by the ``-fno-sanitize=``
1792 flag. For example, ``__attribute__((no_sanitize("address", "thread")))``
1793 specifies that AddressSanitizer and ThreadSanitizer should not be applied
1796 See :ref:`Controlling Code Generation <controlling-code-generation>` for a
1797 full list of supported sanitizer flags.
1801 def NoSanitizeAddressDocs : Documentation {
1802 let Category = DocCatFunction;
1803 // This function has multiple distinct spellings, and so it requires a custom
1804 // heading to be specified. The most common spelling is sufficient.
1805 let Heading = "no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)";
1807 .. _langext-address_sanitizer:
1809 Use ``__attribute__((no_sanitize_address))`` on a function declaration to
1810 specify that address safety instrumentation (e.g. AddressSanitizer) should
1811 not be applied to that function.
1815 def NoSanitizeThreadDocs : Documentation {
1816 let Category = DocCatFunction;
1817 let Heading = "no_sanitize_thread";
1819 .. _langext-thread_sanitizer:
1821 Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
1822 specify that checks for data races on plain (non-atomic) memory accesses should
1823 not be inserted by ThreadSanitizer. The function is still instrumented by the
1824 tool to avoid false positives and provide meaningful stack traces.
1828 def NoSanitizeMemoryDocs : Documentation {
1829 let Category = DocCatFunction;
1830 let Heading = "no_sanitize_memory";
1832 .. _langext-memory_sanitizer:
1834 Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
1835 specify that checks for uninitialized memory should not be inserted
1836 (e.g. by MemorySanitizer). The function may still be instrumented by the tool
1837 to avoid false positives in other places.
1841 def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> {
1843 Clang supports additional attributes to enable checking type safety properties
1844 that can't be enforced by the C type system. To see warnings produced by these
1845 checks, ensure that -Wtype-safety is enabled. Use cases include:
1847 * MPI library implementations, where these attributes enable checking that
1848 the buffer type matches the passed ``MPI_Datatype``;
1849 * for HDF5 library there is a similar use case to MPI;
1850 * checking types of variadic functions' arguments for functions like
1851 ``fcntl()`` and ``ioctl()``.
1853 You can detect support for these attributes with ``__has_attribute()``. For
1858 #if defined(__has_attribute)
1859 # if __has_attribute(argument_with_type_tag) && \
1860 __has_attribute(pointer_with_type_tag) && \
1861 __has_attribute(type_tag_for_datatype)
1862 # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
1863 /* ... other macros ... */
1867 #if !defined(ATTR_MPI_PWT)
1868 # define ATTR_MPI_PWT(buffer_idx, type_idx)
1871 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1876 def ArgumentWithTypeTagDocs : Documentation {
1877 let Category = DocCatTypeSafety;
1878 let Heading = "argument_with_type_tag";
1880 Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
1881 type_tag_idx)))`` on a function declaration to specify that the function
1882 accepts a type tag that determines the type of some other argument.
1884 This attribute is primarily useful for checking arguments of variadic functions
1885 (``pointer_with_type_tag`` can be used in most non-variadic cases).
1887 In the attribute prototype above:
1888 * ``arg_kind`` is an identifier that should be used when annotating all
1889 applicable type tags.
1890 * ``arg_idx`` provides the position of a function argument. The expected type of
1891 this function argument will be determined by the function argument specified
1892 by ``type_tag_idx``. In the code example below, "3" means that the type of the
1893 function's third argument will be determined by ``type_tag_idx``.
1894 * ``type_tag_idx`` provides the position of a function argument. This function
1895 argument will be a type tag. The type tag will determine the expected type of
1896 the argument specified by ``arg_idx``. In the code example below, "2" means
1897 that the type tag associated with the function's second argument should agree
1898 with the type of the argument specified by ``arg_idx``.
1904 int fcntl(int fd, int cmd, ...)
1905 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
1906 // The function's second argument will be a type tag; this type tag will
1907 // determine the expected type of the function's third argument.
1911 def PointerWithTypeTagDocs : Documentation {
1912 let Category = DocCatTypeSafety;
1913 let Heading = "pointer_with_type_tag";
1915 Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
1916 on a function declaration to specify that the function accepts a type tag that
1917 determines the pointee type of some other pointer argument.
1919 In the attribute prototype above:
1920 * ``ptr_kind`` is an identifier that should be used when annotating all
1921 applicable type tags.
1922 * ``ptr_idx`` provides the position of a function argument; this function
1923 argument will have a pointer type. The expected pointee type of this pointer
1924 type will be determined by the function argument specified by
1925 ``type_tag_idx``. In the code example below, "1" means that the pointee type
1926 of the function's first argument will be determined by ``type_tag_idx``.
1927 * ``type_tag_idx`` provides the position of a function argument; this function
1928 argument will be a type tag. The type tag will determine the expected pointee
1929 type of the pointer argument specified by ``ptr_idx``. In the code example
1930 below, "3" means that the type tag associated with the function's third
1931 argument should agree with the pointee type of the pointer argument specified
1938 typedef int MPI_Datatype;
1939 int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
1940 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
1941 // The function's 3rd argument will be a type tag; this type tag will
1942 // determine the expected pointee type of the function's 1st argument.
1946 def TypeTagForDatatypeDocs : Documentation {
1947 let Category = DocCatTypeSafety;
1949 When declaring a variable, use
1950 ``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
1951 is tied to the ``type`` argument given to the attribute.
1953 In the attribute prototype above:
1954 * ``kind`` is an identifier that should be used when annotating all applicable
1956 * ``type`` indicates the name of the type.
1958 Clang supports annotating type tags of two forms.
1960 * **Type tag that is a reference to a declared identifier.**
1961 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
1966 typedef int MPI_Datatype;
1967 extern struct mpi_datatype mpi_datatype_int
1968 __attribute__(( type_tag_for_datatype(mpi,int) ));
1969 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
1970 // &mpi_datatype_int is a type tag. It is tied to type "int".
1972 * **Type tag that is an integral literal.**
1973 Declare a ``static const`` variable with an initializer value and attach
1974 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
1978 typedef int MPI_Datatype;
1979 static const MPI_Datatype mpi_datatype_int
1980 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
1981 #define MPI_INT ((MPI_Datatype) 42)
1982 // The number 42 is a type tag. It is tied to type "int".
1985 The ``type_tag_for_datatype`` attribute also accepts an optional third argument
1986 that determines how the type of the function argument specified by either
1987 ``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
1988 tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
1989 function argument specified by ``arg_idx`` is compared against the type
1990 associated with the type tag. Also recall that for the ``pointer_with_type_tag``
1991 attribute, the pointee type of the function argument specified by ``ptr_idx`` is
1992 compared against the type associated with the type tag.) There are two supported
1993 values for this optional third argument:
1995 * ``layout_compatible`` will cause types to be compared according to
1996 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
1997 layout-compatibility rules for two standard-layout struct types and for two
1998 standard-layout union types). This is useful when creating a type tag
1999 associated with a struct or union type. For example:
2004 typedef int MPI_Datatype;
2005 struct internal_mpi_double_int { double d; int i; };
2006 extern struct mpi_datatype mpi_datatype_double_int
2007 __attribute__(( type_tag_for_datatype(mpi,
2008 struct internal_mpi_double_int, layout_compatible) ));
2010 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
2012 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
2013 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2016 struct my_pair { double a; int b; };
2017 struct my_pair *buffer;
2018 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
2019 // layout of my_pair is
2020 // compatible with that of
2021 // internal_mpi_double_int
2023 struct my_int_pair { int a; int b; }
2024 struct my_int_pair *buffer2;
2025 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
2026 // layout of my_int_pair
2027 // does not match that of
2028 // internal_mpi_double_int
2030 * ``must_be_null`` specifies that the function argument specified by either
2031 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
2032 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
2033 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
2039 typedef int MPI_Datatype;
2040 extern struct mpi_datatype mpi_datatype_null
2041 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
2043 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
2044 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
2045 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2048 struct my_pair { double a; int b; };
2049 struct my_pair *buffer;
2050 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
2051 // was specified but buffer
2052 // is not a null pointer
2056 def FlattenDocs : Documentation {
2057 let Category = DocCatFunction;
2059 The ``flatten`` attribute causes calls within the attributed function to
2060 be inlined unless it is impossible to do so, for example if the body of the
2061 callee is unavailable or if the callee has the ``noinline`` attribute.
2065 def FormatDocs : Documentation {
2066 let Category = DocCatFunction;
2069 Clang supports the ``format`` attribute, which indicates that the function
2070 accepts a ``printf`` or ``scanf``-like format string and corresponding
2071 arguments or a ``va_list`` that contains these arguments.
2073 Please see `GCC documentation about format attribute
2074 <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
2075 about attribute syntax.
2077 Clang implements two kinds of checks with this attribute.
2079 #. Clang checks that the function with the ``format`` attribute is called with
2080 a format string that uses format specifiers that are allowed, and that
2081 arguments match the format string. This is the ``-Wformat`` warning, it is
2084 #. Clang checks that the format string argument is a literal string. This is
2085 the ``-Wformat-nonliteral`` warning, it is off by default.
2087 Clang implements this mostly the same way as GCC, but there is a difference
2088 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
2089 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
2090 functions. Clang does not warn if the format string comes from a function
2091 parameter, where the function is annotated with a compatible attribute,
2092 otherwise it warns. For example:
2096 __attribute__((__format__ (__scanf__, 1, 3)))
2097 void foo(const char* s, char *buf, ...) {
2101 vprintf(s, ap); // warning: format string is not a string literal
2104 In this case we warn because ``s`` contains a format string for a
2105 ``scanf``-like function, but it is passed to a ``printf``-like function.
2107 If the attribute is removed, clang still warns, because the format string is
2108 not a string literal.
2114 __attribute__((__format__ (__printf__, 1, 3)))
2115 void foo(const char* s, char *buf, ...) {
2119 vprintf(s, ap); // warning
2122 In this case Clang does not warn because the format string ``s`` and
2123 the corresponding arguments are annotated. If the arguments are
2124 incorrect, the caller of ``foo`` will receive a warning.
2128 def AlignValueDocs : Documentation {
2129 let Category = DocCatType;
2131 The align_value attribute can be added to the typedef of a pointer type or the
2132 declaration of a variable of pointer or reference type. It specifies that the
2133 pointer will point to, or the reference will bind to, only objects with at
2134 least the provided alignment. This alignment value must be some positive power
2139 typedef double * aligned_double_ptr __attribute__((align_value(64)));
2140 void foo(double & x __attribute__((align_value(128)),
2141 aligned_double_ptr y) { ... }
2143 If the pointer value does not have the specified alignment at runtime, the
2144 behavior of the program is undefined.
2148 def FlagEnumDocs : Documentation {
2149 let Category = DocCatType;
2151 This attribute can be added to an enumerator to signal to the compiler that it
2152 is intended to be used as a flag type. This will cause the compiler to assume
2153 that the range of the type includes all of the values that you can get by
2154 manipulating bits of the enumerator when issuing warnings.
2158 def EnumExtensibilityDocs : Documentation {
2159 let Category = DocCatType;
2161 Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2162 that are extensible and those that are not. The attribute can take either
2163 ``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2164 enum type takes a value that corresponds to one of the enumerators listed in the
2165 enum definition or, when the enum is annotated with ``flag_enum``, a value that
2166 can be constructed using values corresponding to the enumerators. ``open``
2167 indicates a variable of the enum type can take any values allowed by the
2168 standard and instructs clang to be more lenient when issuing warnings.
2172 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2176 enum __attribute__((enum_extensibility(open))) OpenEnum {
2180 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2181 C0 = 1 << 0, C1 = 1 << 1
2184 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
2185 D0 = 1 << 0, D1 = 1 << 1
2191 enum ClosedFlagEnum cfe;
2192 enum OpenFlagEnum ofe;
2194 ce = A1; // no warnings
2195 ce = 100; // warning issued
2196 oe = B1; // no warnings
2197 oe = 100; // no warnings
2198 cfe = C0 | C1; // no warnings
2199 cfe = C0 | C1 | 4; // warning issued
2200 ofe = D0 | D1; // no warnings
2201 ofe = D0 | D1 | 4; // no warnings
2207 def EmptyBasesDocs : Documentation {
2208 let Category = DocCatType;
2210 The empty_bases attribute permits the compiler to utilize the
2211 empty-base-optimization more frequently.
2212 This attribute only applies to struct, class, and union types.
2213 It is only supported when using the Microsoft C++ ABI.
2217 def LayoutVersionDocs : Documentation {
2218 let Category = DocCatType;
2220 The layout_version attribute requests that the compiler utilize the class
2221 layout rules of a particular compiler version.
2222 This attribute only applies to struct, class, and union types.
2223 It is only supported when using the Microsoft C++ ABI.
2227 def MSInheritanceDocs : Documentation {
2228 let Category = DocCatType;
2229 let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
2231 This collection of keywords is enabled under ``-fms-extensions`` and controls
2232 the pointer-to-member representation used on ``*-*-win32`` targets.
2234 The ``*-*-win32`` targets utilize a pointer-to-member representation which
2235 varies in size and alignment depending on the definition of the underlying
2238 However, this is problematic when a forward declaration is only available and
2239 no definition has been made yet. In such cases, Clang is forced to utilize the
2240 most general representation that is available to it.
2242 These keywords make it possible to use a pointer-to-member representation other
2243 than the most general one regardless of whether or not the definition will ever
2244 be present in the current translation unit.
2246 This family of keywords belong between the ``class-key`` and ``class-name``:
2250 struct __single_inheritance S;
2254 This keyword can be applied to class templates but only has an effect when used
2255 on full specializations:
2259 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
2260 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
2261 template <> struct __single_inheritance A<int, float>;
2263 Note that choosing an inheritance model less general than strictly necessary is
2268 struct __multiple_inheritance S; // error: inheritance model does not match definition
2274 def MSNoVTableDocs : Documentation {
2275 let Category = DocCatType;
2277 This attribute can be added to a class declaration or definition to signal to
2278 the compiler that constructors and destructors will not reference the virtual
2279 function table. It is only supported when using the Microsoft C++ ABI.
2283 def OptnoneDocs : Documentation {
2284 let Category = DocCatFunction;
2286 The ``optnone`` attribute suppresses essentially all optimizations
2287 on a function or method, regardless of the optimization level applied to
2288 the compilation unit as a whole. This is particularly useful when you
2289 need to debug a particular function, but it is infeasible to build the
2290 entire application without optimization. Avoiding optimization on the
2291 specified function can improve the quality of the debugging information
2294 This attribute is incompatible with the ``always_inline`` and ``minsize``
2299 def LoopHintDocs : Documentation {
2300 let Category = DocCatStmt;
2301 let Heading = "#pragma clang loop";
2303 The ``#pragma clang loop`` directive allows loop optimization hints to be
2304 specified for the subsequent loop. The directive allows vectorization,
2305 interleaving, and unrolling to be enabled or disabled. Vector width as well
2306 as interleave and unrolling count can be manually specified. See
2307 `language extensions
2308 <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2313 def UnrollHintDocs : Documentation {
2314 let Category = DocCatStmt;
2315 let Heading = "#pragma unroll, #pragma nounroll";
2317 Loop unrolling optimization hints can be specified with ``#pragma unroll`` and
2318 ``#pragma nounroll``. The pragma is placed immediately before a for, while,
2319 do-while, or c++11 range-based for loop.
2321 Specifying ``#pragma unroll`` without a parameter directs the loop unroller to
2322 attempt to fully unroll the loop if the trip count is known at compile time and
2323 attempt to partially unroll the loop if the trip count is not known at compile
2333 Specifying the optional parameter, ``#pragma unroll _value_``, directs the
2334 unroller to unroll the loop ``_value_`` times. The parameter may optionally be
2335 enclosed in parentheses:
2349 Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
2358 ``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
2359 ``#pragma clang loop unroll(full)`` and
2360 ``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
2361 is equivalent to ``#pragma clang loop unroll(disable)``. See
2362 `language extensions
2363 <http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2364 for further details including limitations of the unroll hints.
2368 def OpenCLUnrollHintDocs : Documentation {
2369 let Category = DocCatStmt;
2370 let Heading = "__attribute__((opencl_unroll_hint))";
2372 The opencl_unroll_hint attribute qualifier can be used to specify that a loop
2373 (for, while and do loops) can be unrolled. This attribute qualifier can be
2374 used to specify full unrolling or partial unrolling by a specified amount.
2375 This is a compiler hint and the compiler may ignore this directive. See
2376 `OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
2377 s6.11.5 for details.
2381 def OpenCLIntelReqdSubGroupSizeDocs : Documentation {
2382 let Category = DocCatStmt;
2383 let Heading = "__attribute__((intel_reqd_sub_group_size))";
2385 The optional attribute intel_reqd_sub_group_size can be used to indicate that
2386 the kernel must be compiled and executed with the specified subgroup size. When
2387 this attribute is present, get_max_sub_group_size() is guaranteed to return the
2388 specified integer value. This is important for the correctness of many subgroup
2389 algorithms, and in some cases may be used by the compiler to generate more optimal
2390 code. See `cl_intel_required_subgroup_size
2391 <https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
2396 def OpenCLAccessDocs : Documentation {
2397 let Category = DocCatStmt;
2398 let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)";
2400 The access qualifiers must be used with image object arguments or pipe arguments
2401 to declare if they are being read or written by a kernel or function.
2403 The read_only/__read_only, write_only/__write_only and read_write/__read_write
2404 names are reserved for use as access qualifiers and shall not be used otherwise.
2409 foo (read_only image2d_t imageA,
2410 write_only image2d_t imageB) {
2414 In the above example imageA is a read-only 2D image object, and imageB is a
2415 write-only 2D image object.
2417 The read_write (or __read_write) qualifier can not be used with pipe.
2419 More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
2423 def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> {
2425 The address space qualifier may be used to specify the region of memory that is
2426 used to allocate the object. OpenCL supports the following address spaces:
2427 __generic(generic), __global(global), __local(local), __private(private),
2428 __constant(constant).
2432 __constant int c = ...;
2434 __generic int* foo(global int* g) {
2441 More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
2445 def OpenCLAddressSpaceGenericDocs : Documentation {
2446 let Category = DocOpenCLAddressSpaces;
2448 The generic address space attribute is only available with OpenCL v2.0 and later.
2449 It can be used with pointer types. Variables in global and local scope and
2450 function parameters in non-kernel functions can have the generic address space
2451 type attribute. It is intended to be a placeholder for any other address space
2452 except for '__constant' in OpenCL code which can be used with multiple address
2457 def OpenCLAddressSpaceConstantDocs : Documentation {
2458 let Category = DocOpenCLAddressSpaces;
2460 The constant address space attribute signals that an object is located in
2461 a constant (non-modifiable) memory region. It is available to all work items.
2462 Any type can be annotated with the constant address space attribute. Objects
2463 with the constant address space qualifier can be declared in any scope and must
2464 have an initializer.
2468 def OpenCLAddressSpaceGlobalDocs : Documentation {
2469 let Category = DocOpenCLAddressSpaces;
2471 The global address space attribute specifies that an object is allocated in
2472 global memory, which is accessible by all work items. The content stored in this
2473 memory area persists between kernel executions. Pointer types to the global
2474 address space are allowed as function parameters or local variables. Starting
2475 with OpenCL v2.0, the global address space can be used with global (program
2476 scope) variables and static local variable as well.
2480 def OpenCLAddressSpaceLocalDocs : Documentation {
2481 let Category = DocOpenCLAddressSpaces;
2483 The local address space specifies that an object is allocated in the local (work
2484 group) memory area, which is accessible to all work items in the same work
2485 group. The content stored in this memory region is not accessible after
2486 the kernel execution ends. In a kernel function scope, any variable can be in
2487 the local address space. In other scopes, only pointer types to the local address
2488 space are allowed. Local address space variables cannot have an initializer.
2492 def OpenCLAddressSpacePrivateDocs : Documentation {
2493 let Category = DocOpenCLAddressSpaces;
2495 The private address space specifies that an object is allocated in the private
2496 (work item) memory. Other work items cannot access the same memory area and its
2497 content is destroyed after work item execution ends. Local variables can be
2498 declared in the private address space. Function arguments are always in the
2499 private address space. Kernel function arguments of a pointer or an array type
2500 cannot point to the private address space.
2504 def OpenCLNoSVMDocs : Documentation {
2505 let Category = DocCatVariable;
2507 OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for
2508 pointer variable. It informs the compiler that the pointer does not refer
2509 to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
2511 Since it is not widely used and has been removed from OpenCL 2.1, it is ignored
2515 def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> {
2517 Whether 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``).
2519 The 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:
2523 // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).
2524 int fetch(int * _Nonnull ptr) { return *ptr; }
2526 // 'ptr' may be null.
2527 int fetch_or_zero(int * _Nullable ptr) {
2528 return ptr ? *ptr : 0;
2531 // A nullable pointer to non-null pointers to const characters.
2532 const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
2534 In 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:
2536 .. code-block:: objective-c
2538 @interface NSView : NSResponder
2539 - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView;
2540 @property (assign, nullable) NSView *superview;
2541 @property (readonly, nonnull) NSArray *subviews;
2546 def TypeNonNullDocs : Documentation {
2547 let Category = NullabilityDocs;
2549 The ``_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:
2553 int fetch(int * _Nonnull ptr);
2555 a 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.
2559 def TypeNullableDocs : Documentation {
2560 let Category = NullabilityDocs;
2562 The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given:
2566 int fetch_or_zero(int * _Nullable ptr);
2568 a caller of ``fetch_or_zero`` can provide null.
2572 def TypeNullUnspecifiedDocs : Documentation {
2573 let Category = NullabilityDocs;
2575 The ``_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.
2579 def NonNullDocs : Documentation {
2580 let Category = NullabilityDocs;
2582 The ``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:
2586 extern void * my_memcpy (void *dest, const void *src, size_t len)
2587 __attribute__((nonnull (1, 2)));
2589 Here, the ``nonnull`` attribute indicates that parameters 1 and 2
2590 cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
2594 extern void * my_memcpy (void *dest, const void *src, size_t len)
2595 __attribute__((nonnull));
2597 Clang 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:
2601 extern void * my_memcpy (void *dest __attribute__((nonnull)),
2602 const void *src __attribute__((nonnull)), size_t len);
2604 Note 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.
2608 def ReturnsNonNullDocs : Documentation {
2609 let Category = NullabilityDocs;
2611 The ``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:
2615 extern void * malloc (size_t size) __attribute__((returns_nonnull));
2617 The ``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
2621 def NoAliasDocs : Documentation {
2622 let Category = DocCatFunction;
2624 The ``noalias`` attribute indicates that the only memory accesses inside
2625 function are loads and stores from objects pointed to by its pointer-typed
2626 arguments, with arbitrary offsets.
2630 def OMPDeclareSimdDocs : Documentation {
2631 let Category = DocCatFunction;
2632 let Heading = "#pragma omp declare simd";
2634 The `declare simd` construct can be applied to a function to enable the creation
2635 of one or more versions that can process multiple arguments using SIMD
2636 instructions from a single invocation in a SIMD loop. The `declare simd`
2637 directive is a declarative directive. There may be multiple `declare simd`
2638 directives for a function. The use of a `declare simd` construct on a function
2639 enables the creation of SIMD versions of the associated function that can be
2640 used to process multiple arguments from a single invocation from a SIMD loop
2642 The syntax of the `declare simd` construct is as follows:
2644 .. code-block:: none
2646 #pragma omp declare simd [clause[[,] clause] ...] new-line
2647 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
2649 function definition or declaration
2651 where clause is one of the following:
2653 .. code-block:: none
2656 linear(argument-list[:constant-linear-step])
2657 aligned(argument-list[:alignment])
2658 uniform(argument-list)
2665 def OMPDeclareTargetDocs : Documentation {
2666 let Category = DocCatFunction;
2667 let Heading = "#pragma omp declare target";
2669 The `declare target` directive specifies that variables and functions are mapped
2670 to a device for OpenMP offload mechanism.
2672 The syntax of the declare target directive is as follows:
2676 #pragma omp declare target new-line
2677 declarations-definition-seq
2678 #pragma omp end declare target new-line
2682 def NotTailCalledDocs : Documentation {
2683 let Category = DocCatFunction;
2685 The ``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``.
2687 For example, it prevents tail-call optimization in the following case:
2691 int __attribute__((not_tail_called)) foo1(int);
2694 return foo1(a); // No tail-call optimization on direct calls.
2697 However, it doesn't prevent tail-call optimization in this case:
2701 int __attribute__((not_tail_called)) foo1(int);
2704 int (*fn)(int) = &foo1;
2706 // not_tail_called has no effect on an indirect call even if the call can be
2707 // resolved at compile time.
2711 Marking virtual functions as ``not_tail_called`` is an error:
2717 // not_tail_called on a virtual function is an error.
2718 [[clang::not_tail_called]] virtual int foo1();
2722 // Non-virtual functions can be marked ``not_tail_called``.
2723 [[clang::not_tail_called]] int foo3();
2726 class Derived1 : public Base {
2728 int foo1() override;
2730 // not_tail_called on a virtual function is an error.
2731 [[clang::not_tail_called]] int foo2() override;
2736 def NoThrowDocs : Documentation {
2737 let Category = DocCatFunction;
2739 Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
2740 ``__declspec(nothrow)`` attribute as an equivilent of `noexcept` on function
2741 declarations. This attribute informs the compiler that the annotated function
2742 does not throw an exception. This prevents exception-unwinding. This attribute
2743 is particularly useful on functions in the C Standard Library that are
2744 guaranteed to not throw an exception.
2748 def InternalLinkageDocs : Documentation {
2749 let Category = DocCatFunction;
2751 The ``internal_linkage`` attribute changes the linkage type of the declaration to internal.
2752 This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition,
2753 this attribute affects all methods and static data members of that class.
2754 This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables.
2758 def DisableTailCallsDocs : Documentation {
2759 let Category = DocCatFunction;
2761 The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function.
2769 int foo(int a) __attribute__((disable_tail_calls)) {
2770 return callee(a); // This call is not tail-call optimized.
2773 Marking virtual functions as ``disable_tail_calls`` is legal.
2781 [[clang::disable_tail_calls]] virtual int foo1() {
2782 return callee(); // This call is not tail-call optimized.
2786 class Derived1 : public Base {
2788 int foo1() override {
2789 return callee(); // This call is tail-call optimized.
2796 def AnyX86NoCallerSavedRegistersDocs : Documentation {
2797 let Category = DocCatFunction;
2799 Use this attribute to indicate that the specified function has no
2800 caller-saved registers. That is, all registers are callee-saved except for
2801 registers used for passing parameters to the function or returning parameters
2803 The compiler saves and restores any modified registers that were not used for
2804 passing or returning arguments to the function.
2806 The user can call functions specified with the 'no_caller_saved_registers'
2807 attribute from an interrupt handler without saving and restoring all
2808 call-clobbered registers.
2810 Note that 'no_caller_saved_registers' attribute is not a calling convention.
2811 In fact, it only overrides the decision of which registers should be saved by
2812 the caller, but not how the parameters are passed from the caller to the callee.
2818 __attribute__ ((no_caller_saved_registers, fastcall))
2819 void f (int arg1, int arg2) {
2823 In this case parameters 'arg1' and 'arg2' will be passed in registers.
2824 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
2825 register parameters. However, it will not assume any scratch registers and
2826 should save and restore any modified registers except for ECX and EDX.
2830 def X86ForceAlignArgPointerDocs : Documentation {
2831 let Category = DocCatFunction;
2833 Use this attribute to force stack alignment.
2835 Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
2836 (like 'movaps') that work with the stack require operands to be 16-byte aligned.
2837 This attribute realigns the stack in the function prologue to make sure the
2838 stack can be used with SSE instructions.
2840 Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
2841 Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
2842 rare cases where the caller does not align the stack properly (e.g. flow
2843 jumps from i386 arch code).
2847 __attribute__ ((force_align_arg_pointer))
2855 def SwiftCallDocs : Documentation {
2856 let Category = DocCatVariable;
2858 The ``swiftcall`` attribute indicates that a function should be called
2859 using the Swift calling convention for a function or function pointer.
2861 The lowering for the Swift calling convention, as described by the Swift
2862 ABI documentation, occurs in multiple phases. The first, "high-level"
2863 phase breaks down the formal parameters and results into innately direct
2864 and indirect components, adds implicit paraameters for the generic
2865 signature, and assigns the context and error ABI treatments to parameters
2866 where applicable. The second phase breaks down the direct parameters
2867 and results from the first phase and assigns them to registers or the
2868 stack. The ``swiftcall`` convention only handles this second phase of
2869 lowering; the C function type must accurately reflect the results
2870 of the first phase, as follows:
2872 - Results classified as indirect by high-level lowering should be
2873 represented as parameters with the ``swift_indirect_result`` attribute.
2875 - Results classified as direct by high-level lowering should be represented
2878 - First, remove any empty direct results.
2880 - If there are no direct results, the C result type should be ``void``.
2882 - If there is one direct result, the C result type should be a type with
2883 the exact layout of that result type.
2885 - If there are a multiple direct results, the C result type should be
2886 a struct type with the exact layout of a tuple of those results.
2888 - Parameters classified as indirect by high-level lowering should be
2889 represented as parameters of pointer type.
2891 - Parameters classified as direct by high-level lowering should be
2892 omitted if they are empty types; otherwise, they should be represented
2893 as a parameter type with a layout exactly matching the layout of the
2894 Swift parameter type.
2896 - The context parameter, if present, should be represented as a trailing
2897 parameter with the ``swift_context`` attribute.
2899 - The error result parameter, if present, should be represented as a
2900 trailing parameter (always following a context parameter) with the
2901 ``swift_error_result`` attribute.
2903 ``swiftcall`` does not support variadic arguments or unprototyped functions.
2905 The parameter ABI treatment attributes are aspects of the function type.
2906 A function type which which applies an ABI treatment attribute to a
2907 parameter is a different type from an otherwise-identical function type
2908 that does not. A single parameter may not have multiple ABI treatment
2911 Support for this feature is target-dependent, although it should be
2912 supported on every target that Swift supports. Query for this support
2913 with ``__has_attribute(swiftcall)``. This implies support for the
2914 ``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
2919 def SwiftContextDocs : Documentation {
2920 let Category = DocCatVariable;
2922 The ``swift_context`` attribute marks a parameter of a ``swiftcall``
2923 function as having the special context-parameter ABI treatment.
2925 This treatment generally passes the context value in a special register
2926 which is normally callee-preserved.
2928 A ``swift_context`` parameter must either be the last parameter or must be
2929 followed by a ``swift_error_result`` parameter (which itself must always be
2930 the last parameter).
2932 A context parameter must have pointer or reference type.
2936 def SwiftErrorResultDocs : Documentation {
2937 let Category = DocCatVariable;
2939 The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
2940 function as having the special error-result ABI treatment.
2942 This treatment generally passes the underlying error value in and out of
2943 the function through a special register which is normally callee-preserved.
2944 This is modeled in C by pretending that the register is addressable memory:
2946 - The caller appears to pass the address of a variable of pointer type.
2947 The current value of this variable is copied into the register before
2948 the call; if the call returns normally, the value is copied back into the
2951 - The callee appears to receive the address of a variable. This address
2952 is actually a hidden location in its own stack, initialized with the
2953 value of the register upon entry. When the function returns normally,
2954 the value in that hidden location is written back to the register.
2956 A ``swift_error_result`` parameter must be the last parameter, and it must be
2957 preceded by a ``swift_context`` parameter.
2959 A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
2960 type T. Note that no qualifiers are permitted on the intermediate level.
2962 It is undefined behavior if the caller does not pass a pointer or
2963 reference to a valid object.
2965 The standard convention is that the error value itself (that is, the
2966 value stored in the apparent argument) will be null upon function entry,
2967 but this is not enforced by the ABI.
2971 def SwiftIndirectResultDocs : Documentation {
2972 let Category = DocCatVariable;
2974 The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
2975 function as having the special indirect-result ABI treatment.
2977 This treatment gives the parameter the target's normal indirect-result
2978 ABI treatment, which may involve passing it differently from an ordinary
2979 parameter. However, only the first indirect result will receive this
2980 treatment. Furthermore, low-level lowering may decide that a direct result
2981 must be returned indirectly; if so, this will take priority over the
2982 ``swift_indirect_result`` parameters.
2984 A ``swift_indirect_result`` parameter must either be the first parameter or
2985 follow another ``swift_indirect_result`` parameter.
2987 A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
2988 some object type ``T``. If ``T`` is a complete type at the point of
2989 definition of a function, it is undefined behavior if the argument
2990 value does not point to storage of adequate size and alignment for a
2991 value of type ``T``.
2993 Making indirect results explicit in the signature allows C functions to
2994 directly construct objects into them without relying on language
2995 optimizations like C++'s named return value optimization (NRVO).
2999 def SuppressDocs : Documentation {
3000 let Category = DocCatStmt;
3002 The ``[[gsl::suppress]]`` attribute suppresses specific
3003 clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
3004 way. The attribute can be attached to declarations, statements, and at
3009 [[gsl::suppress("Rh-public")]]
3012 [[gsl::suppress("type")]] {
3013 p = reinterpret_cast<int*>(7);
3017 [[clang::suppress("type", "bounds")]];
3021 .. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement
3025 def AbiTagsDocs : Documentation {
3026 let Category = DocCatFunction;
3028 The ``abi_tag`` attribute can be applied to a function, variable, class or
3029 inline namespace declaration to modify the mangled name of the entity. It gives
3030 the ability to distinguish between different versions of the same entity but
3031 with different ABI versions supported. For example, a newer version of a class
3032 could have a different set of data members and thus have a different size. Using
3033 the ``abi_tag`` attribute, it is possible to have different mangled names for
3034 a global variable of the class type. Therefor, the old code could keep using
3035 the old manged name and the new code will use the new mangled name with tags.
3039 def PreserveMostDocs : Documentation {
3040 let Category = DocCatCallingConvs;
3042 On X86-64 and AArch64 targets, this attribute changes the calling convention of
3043 a function. The ``preserve_most`` calling convention attempts to make the code
3044 in the caller as unintrusive as possible. This convention behaves identically
3045 to the ``C`` calling convention on how arguments and return values are passed,
3046 but it uses a different set of caller/callee-saved registers. This alleviates
3047 the burden of saving and recovering a large register set before and after the
3048 call in the caller. If the arguments are passed in callee-saved registers,
3049 then they will be preserved by the callee across the call. This doesn't
3050 apply for values returned in callee-saved registers.
3052 - On X86-64 the callee preserves all general purpose registers, except for
3053 R11. R11 can be used as a scratch register. Floating-point registers
3054 (XMMs/YMMs) are not preserved and need to be saved by the caller.
3056 The idea behind this convention is to support calls to runtime functions
3057 that have a hot path and a cold path. The hot path is usually a small piece
3058 of code that doesn't use many registers. The cold path might need to call out to
3059 another function and therefore only needs to preserve the caller-saved
3060 registers, which haven't already been saved by the caller. The
3061 `preserve_most` calling convention is very similar to the ``cold`` calling
3062 convention in terms of caller/callee-saved registers, but they are used for
3063 different types of function calls. ``coldcc`` is for function calls that are
3064 rarely executed, whereas `preserve_most` function calls are intended to be
3065 on the hot path and definitely executed a lot. Furthermore ``preserve_most``
3066 doesn't prevent the inliner from inlining the function call.
3068 This calling convention will be used by a future version of the Objective-C
3069 runtime and should therefore still be considered experimental at this time.
3070 Although this convention was created to optimize certain runtime calls to
3071 the Objective-C runtime, it is not limited to this runtime and might be used
3072 by other runtimes in the future too. The current implementation only
3073 supports X86-64 and AArch64, but the intention is to support more architectures
3078 def PreserveAllDocs : Documentation {
3079 let Category = DocCatCallingConvs;
3081 On X86-64 and AArch64 targets, this attribute changes the calling convention of
3082 a function. The ``preserve_all`` calling convention attempts to make the code
3083 in the caller even less intrusive than the ``preserve_most`` calling convention.
3084 This calling convention also behaves identical to the ``C`` calling convention
3085 on how arguments and return values are passed, but it uses a different set of
3086 caller/callee-saved registers. This removes the burden of saving and
3087 recovering a large register set before and after the call in the caller. If
3088 the arguments are passed in callee-saved registers, then they will be
3089 preserved by the callee across the call. This doesn't apply for values
3090 returned in callee-saved registers.
3092 - On X86-64 the callee preserves all general purpose registers, except for
3093 R11. R11 can be used as a scratch register. Furthermore it also preserves
3094 all floating-point registers (XMMs/YMMs).
3096 The idea behind this convention is to support calls to runtime functions
3097 that don't need to call out to any other functions.
3099 This calling convention, like the ``preserve_most`` calling convention, will be
3100 used by a future version of the Objective-C runtime and should be considered
3101 experimental at this time.
3105 def DeprecatedDocs : Documentation {
3106 let Category = DocCatFunction;
3108 The ``deprecated`` attribute can be applied to a function, a variable, or a
3109 type. This is useful when identifying functions, variables, or types that are
3110 expected to be removed in a future version of a program.
3112 Consider the function declaration for a hypothetical function ``f``:
3116 void f(void) __attribute__((deprecated("message", "replacement")));
3118 When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
3119 two optional string arguments. The first one is the message to display when
3120 emitting the warning; the second one enables the compiler to provide a Fix-It
3121 to replace the deprecated name with a new name. Otherwise, when spelled as
3122 `[[gnu::deprecated]] or [[deprecated]]`, the attribute can have one optional
3123 string argument which is the message to display when emitting the warning.
3127 def IFuncDocs : Documentation {
3128 let Category = DocCatFunction;
3130 ``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function.
3132 The 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 take no arguments and return a pointer.
3134 The ``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.
3136 Not all targets support this attribute. ELF targets support this attribute when using binutils v2.20.1 or higher and glibc v2.11.1 or higher. Non-ELF targets currently do not support this attribute.
3140 def LTOVisibilityDocs : Documentation {
3141 let Category = DocCatType;
3143 See :doc:`LTOVisibility`.
3147 def RenderScriptKernelAttributeDocs : Documentation {
3148 let Category = DocCatFunction;
3150 ``__attribute__((kernel))`` is used to mark a ``kernel`` function in
3153 In RenderScript, ``kernel`` functions are used to express data-parallel
3154 computations. The RenderScript runtime efficiently parallelizes ``kernel``
3155 functions to run on computational resources such as multi-core CPUs and GPUs.
3156 See the RenderScript_ documentation for more information.
3158 .. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html
3162 def XRayDocs : Documentation {
3163 let Category = DocCatFunction;
3164 let Heading = "xray_always_instrument (clang::xray_always_instrument), xray_never_instrument (clang::xray_never_instrument), xray_log_args (clang::xray_log_args)";
3166 ``__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.
3168 Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
3170 If 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.
3172 ``__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.
3176 def TransparentUnionDocs : Documentation {
3177 let Category = DocCatType;
3179 This attribute can be applied to a union to change the behaviour of calls to
3180 functions that have an argument with a transparent union type. The compiler
3181 behaviour is changed in the following manner:
3183 - A value whose type is any member of the transparent union can be passed as an
3184 argument without the need to cast that value.
3186 - The argument is passed to the function using the calling convention of the
3187 first member of the transparent union. Consequently, all the members of the
3188 transparent union should have the same calling convention as its first member.
3190 Transparent unions are not supported in C++.
3194 def ObjCSubclassingRestrictedDocs : Documentation {
3195 let Category = DocCatType;
3197 This attribute can be added to an Objective-C ``@interface`` declaration to
3198 ensure that this class cannot be subclassed.
3203 def SelectAnyDocs : Documentation {
3204 let Category = DocCatType;
3206 This attribute appertains to a global symbol, causing it to have a weak
3208 `linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
3209 ), allowing the linker to select any definition.
3211 For more information see
3212 `gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
3213 or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.