Home | History | Annotate | Download | only in docs
      1 ..
      2   -------------------------------------------------------------------
      3   NOTE: This file is automatically generated by running clang-tblgen
      4   -gen-attr-docs. Do not edit this file by hand!!
      5   -------------------------------------------------------------------
      6 
      7 ===================
      8 Attributes in Clang
      9 ===================
     10 .. contents::
     11    :local:
     12 
     13 Introduction
     14 ============
     15 
     16 This page lists the attributes currently supported by Clang.
     17 
     18 Function Attributes
     19 ===================
     20 
     21 
     22 interrupt
     23 ---------
     24 .. csv-table:: Supported Syntaxes
     25    :header: "GNU", "C++11", "__declspec", "Keyword"
     26 
     27    "X","","",""
     28 
     29 Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
     30 ARM targets. This attribute may be attached to a function definition and
     31 instructs the backend to generate appropriate function entry/exit code so that
     32 it can be used directly as an interrupt service routine.
     33 
     34 The parameter passed to the interrupt attribute is optional, but if
     35 provided it must be a string literal with one of the following values: "IRQ",
     36 "FIQ", "SWI", "ABORT", "UNDEF".
     37 
     38 The semantics are as follows:
     39 
     40 - If the function is AAPCS, Clang instructs the backend to realign the stack to
     41   8 bytes on entry. This is a general requirement of the AAPCS at public
     42   interfaces, but may not hold when an exception is taken. Doing this allows
     43   other AAPCS functions to be called.
     44 - If the CPU is M-class this is all that needs to be done since the architecture
     45   itself is designed in such a way that functions obeying the normal AAPCS ABI
     46   constraints are valid exception handlers.
     47 - If the CPU is not M-class, the prologue and epilogue are modified to save all
     48   non-banked registers that are used, so that upon return the user-mode state
     49   will not be corrupted. Note that to avoid unnecessary overhead, only
     50   general-purpose (integer) registers are saved in this way. If VFP operations
     51   are needed, that state must be saved manually.
     52 
     53   Specifically, interrupt kinds other than "FIQ" will save all core registers
     54   except "lr" and "sp". "FIQ" interrupts will save r0-r7.
     55 - If the CPU is not M-class, the return instruction is changed to one of the
     56   canonical sequences permitted by the architecture for exception return. Where
     57   possible the function itself will make the necessary "lr" adjustments so that
     58   the "preferred return address" is selected.
     59 
     60   Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
     61   handler, where the offset from "lr" to the preferred return address depends on
     62   the execution state of the code which generated the exception. In this case
     63   a sequence equivalent to "movs pc, lr" will be used.
     64 
     65 
     66 acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)
     67 -----------------------------------------------------------------------------------------------------------
     68 .. csv-table:: Supported Syntaxes
     69    :header: "GNU", "C++11", "__declspec", "Keyword"
     70 
     71    "X","X","",""
     72 
     73 Marks a function as acquiring a capability.
     74 
     75 
     76 assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)
     77 -------------------------------------------------------------------------------------------------------
     78 .. csv-table:: Supported Syntaxes
     79    :header: "GNU", "C++11", "__declspec", "Keyword"
     80 
     81    "X","X","",""
     82 
     83 Marks a function that dynamically tests whether a capability is held, and halts
     84 the program if it is not held.
     85 
     86 
     87 availability
     88 ------------
     89 .. csv-table:: Supported Syntaxes
     90    :header: "GNU", "C++11", "__declspec", "Keyword"
     91 
     92    "X","","",""
     93 
     94 The ``availability`` attribute can be placed on declarations to describe the
     95 lifecycle of that declaration relative to operating system versions.  Consider
     96 the function declaration for a hypothetical function ``f``:
     97 
     98 .. code-block:: c++
     99 
    100   void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
    101 
    102 The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
    103 deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7.  This information
    104 is used by Clang to determine when it is safe to use ``f``: for example, if
    105 Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
    106 succeeds.  If Clang is instructed to compile code for Mac OS X 10.6, the call
    107 succeeds but Clang emits a warning specifying that the function is deprecated.
    108 Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
    109 fails because ``f()`` is no longer available.
    110 
    111 The availability attribute is a comma-separated list starting with the
    112 platform name and then including clauses specifying important milestones in the
    113 declaration's lifetime (in any order) along with additional information.  Those
    114 clauses can be:
    115 
    116 introduced=\ *version*
    117   The first version in which this declaration was introduced.
    118 
    119 deprecated=\ *version*
    120   The first version in which this declaration was deprecated, meaning that
    121   users should migrate away from this API.
    122 
    123 obsoleted=\ *version*
    124   The first version in which this declaration was obsoleted, meaning that it
    125   was removed completely and can no longer be used.
    126 
    127 unavailable
    128   This declaration is never available on this platform.
    129 
    130 message=\ *string-literal*
    131   Additional message text that Clang will provide when emitting a warning or
    132   error about use of a deprecated or obsoleted declaration.  Useful to direct
    133   users to replacement APIs.
    134 
    135 Multiple availability attributes can be placed on a declaration, which may
    136 correspond to different platforms.  Only the availability attribute with the
    137 platform corresponding to the target platform will be used; any others will be
    138 ignored.  If no availability attribute specifies availability for the current
    139 target platform, the availability attributes are ignored.  Supported platforms
    140 are:
    141 
    142 ``ios``
    143   Apple's iOS operating system.  The minimum deployment target is specified by
    144   the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
    145   command-line arguments.
    146 
    147 ``macosx``
    148   Apple's Mac OS X operating system.  The minimum deployment target is
    149   specified by the ``-mmacosx-version-min=*version*`` command-line argument.
    150 
    151 A declaration can be used even when deploying back to a platform version prior
    152 to when the declaration was introduced.  When this happens, the declaration is
    153 `weakly linked
    154 <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
    155 as if the ``weak_import`` attribute were added to the declaration.  A
    156 weakly-linked declaration may or may not be present a run-time, and a program
    157 can determine whether the declaration is present by checking whether the
    158 address of that declaration is non-NULL.
    159 
    160 If there are multiple declarations of the same entity, the availability
    161 attributes must either match on a per-platform basis or later
    162 declarations must not have availability attributes for that
    163 platform. For example:
    164 
    165 .. code-block:: c
    166 
    167   void g(void) __attribute__((availability(macosx,introduced=10.4)));
    168   void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches
    169   void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
    170   void g(void); // okay, inherits both macosx and ios availability from above.
    171   void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch
    172 
    173 When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
    174 
    175 .. code-block:: objc
    176 
    177   @interface A
    178   - (id)method __attribute__((availability(macosx,introduced=10.4)));
    179   - (id)method2 __attribute__((availability(macosx,introduced=10.4)));
    180   @end
    181 
    182   @interface B : A
    183   - (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later
    184   - (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4
    185   @end
    186 
    187 
    188 _Noreturn
    189 ---------
    190 .. csv-table:: Supported Syntaxes
    191    :header: "GNU", "C++11", "__declspec", "Keyword"
    192 
    193    "","","","X"
    194 
    195 A function declared as ``_Noreturn`` shall not return to its caller. The
    196 compiler will generate a diagnostic for a function declared as ``_Noreturn``
    197 that appears to be capable of returning to its caller.
    198 
    199 
    200 noreturn
    201 --------
    202 .. csv-table:: Supported Syntaxes
    203    :header: "GNU", "C++11", "__declspec", "Keyword"
    204 
    205    "","X","",""
    206 
    207 A function declared as ``[[noreturn]]`` shall not return to its caller. The
    208 compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
    209 that appears to be capable of returning to its caller.
    210 
    211 
    212 carries_dependency
    213 ------------------
    214 .. csv-table:: Supported Syntaxes
    215    :header: "GNU", "C++11", "__declspec", "Keyword"
    216 
    217    "X","X","",""
    218 
    219 The ``carries_dependency`` attribute specifies dependency propagation into and
    220 out of functions.
    221 
    222 When specified on a function or Objective-C method, the ``carries_dependency``
    223 attribute means that the return value carries a dependency out of the function, 
    224 so that the implementation need not constrain ordering upon return from that
    225 function. Implementations of the function and its caller may choose to preserve
    226 dependencies instead of emitting memory ordering instructions such as fences.
    227 
    228 Note, this attribute does not change the meaning of the program, but may result
    229 in generation of more efficient code.
    230 
    231 
    232 enable_if
    233 ---------
    234 .. csv-table:: Supported Syntaxes
    235    :header: "GNU", "C++11", "__declspec", "Keyword"
    236 
    237    "X","","",""
    238 
    239 The ``enable_if`` attribute can be placed on function declarations to control
    240 which overload is selected based on the values of the function's arguments.
    241 When combined with the ``overloadable`` attribute, this feature is also
    242 available in C.
    243 
    244 .. code-block:: c++
    245 
    246   int isdigit(int c);
    247   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")));
    248   
    249   void foo(char c) {
    250     isdigit(c);
    251     isdigit(10);
    252     isdigit(-10);  // results in a compile-time error.
    253   }
    254 
    255 The enable_if attribute takes two arguments, the first is an expression written
    256 in terms of the function parameters, the second is a string explaining why this
    257 overload candidate could not be selected to be displayed in diagnostics. The
    258 expression is part of the function signature for the purposes of determining
    259 whether it is a redeclaration (following the rules used when determining
    260 whether a C++ template specialization is ODR-equivalent), but is not part of
    261 the type.
    262 
    263 The enable_if expression is evaluated as if it were the body of a
    264 bool-returning constexpr function declared with the arguments of the function
    265 it is being applied to, then called with the parameters at the callsite. If the
    266 result is false or could not be determined through constant expression
    267 evaluation, then this overload will not be chosen and the provided string may
    268 be used in a diagnostic if the compile fails as a result.
    269 
    270 Because the enable_if expression is an unevaluated context, there are no global
    271 state changes, nor the ability to pass information from the enable_if
    272 expression to the function body. For example, suppose we want calls to
    273 strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
    274 strbuf) only if the size of strbuf can be determined:
    275 
    276 .. code-block:: c++
    277 
    278   __attribute__((always_inline))
    279   static inline size_t strnlen(const char *s, size_t maxlen)
    280     __attribute__((overloadable))
    281     __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
    282                              "chosen when the buffer size is known but 'maxlen' is not")))
    283   {
    284     return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
    285   }
    286 
    287 Multiple enable_if attributes may be applied to a single declaration. In this
    288 case, the enable_if expressions are evaluated from left to right in the
    289 following manner. First, the candidates whose enable_if expressions evaluate to
    290 false or cannot be evaluated are discarded. If the remaining candidates do not
    291 share ODR-equivalent enable_if expressions, the overload resolution is
    292 ambiguous. Otherwise, enable_if overload resolution continues with the next
    293 enable_if attribute on the candidates that have not been discarded and have
    294 remaining enable_if attributes. In this way, we pick the most specific
    295 overload out of a number of viable overloads using enable_if.
    296 
    297 .. code-block:: c++
    298 
    299   void f() __attribute__((enable_if(true, "")));  // #1
    300   void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, "")));  // #2
    301   
    302   void g(int i, int j) __attribute__((enable_if(i, "")));  // #1
    303   void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true)));  // #2
    304 
    305 In this example, a call to f() is always resolved to #2, as the first enable_if
    306 expression is ODR-equivalent for both declarations, but #1 does not have another
    307 enable_if expression to continue evaluating, so the next round of evaluation has
    308 only a single candidate. In a call to g(1, 1), the call is ambiguous even though
    309 #2 has more enable_if attributes, because the first enable_if expressions are
    310 not ODR-equivalent.
    311 
    312 Query for this feature with ``__has_attribute(enable_if)``.
    313 
    314 
    315 flatten (gnu::flatten)
    316 ----------------------
    317 .. csv-table:: Supported Syntaxes
    318    :header: "GNU", "C++11", "__declspec", "Keyword"
    319 
    320    "X","X","",""
    321 
    322 The ``flatten`` attribute causes calls within the attributed function to
    323 be inlined unless it is impossible to do so, for example if the body of the
    324 callee is unavailable or if the callee has the ``noinline`` attribute.
    325 
    326 
    327 format (gnu::format)
    328 --------------------
    329 .. csv-table:: Supported Syntaxes
    330    :header: "GNU", "C++11", "__declspec", "Keyword"
    331 
    332    "X","X","",""
    333 
    334 Clang supports the ``format`` attribute, which indicates that the function
    335 accepts a ``printf`` or ``scanf``-like format string and corresponding
    336 arguments or a ``va_list`` that contains these arguments.
    337 
    338 Please see `GCC documentation about format attribute
    339 <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
    340 about attribute syntax.
    341 
    342 Clang implements two kinds of checks with this attribute.
    343 
    344 #. Clang checks that the function with the ``format`` attribute is called with
    345    a format string that uses format specifiers that are allowed, and that
    346    arguments match the format string.  This is the ``-Wformat`` warning, it is
    347    on by default.
    348 
    349 #. Clang checks that the format string argument is a literal string.  This is
    350    the ``-Wformat-nonliteral`` warning, it is off by default.
    351 
    352    Clang implements this mostly the same way as GCC, but there is a difference
    353    for functions that accept a ``va_list`` argument (for example, ``vprintf``).
    354    GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
    355    fuctions.  Clang does not warn if the format string comes from a function
    356    parameter, where the function is annotated with a compatible attribute,
    357    otherwise it warns.  For example:
    358 
    359    .. code-block:: c
    360 
    361      __attribute__((__format__ (__scanf__, 1, 3)))
    362      void foo(const char* s, char *buf, ...) {
    363        va_list ap;
    364        va_start(ap, buf);
    365 
    366        vprintf(s, ap); // warning: format string is not a string literal
    367      }
    368 
    369    In this case we warn because ``s`` contains a format string for a
    370    ``scanf``-like function, but it is passed to a ``printf``-like function.
    371 
    372    If the attribute is removed, clang still warns, because the format string is
    373    not a string literal.
    374 
    375    Another example:
    376 
    377    .. code-block:: c
    378 
    379      __attribute__((__format__ (__printf__, 1, 3)))
    380      void foo(const char* s, char *buf, ...) {
    381        va_list ap;
    382        va_start(ap, buf);
    383 
    384        vprintf(s, ap); // warning
    385      }
    386 
    387    In this case Clang does not warn because the format string ``s`` and
    388    the corresponding arguments are annotated.  If the arguments are
    389    incorrect, the caller of ``foo`` will receive a warning.
    390 
    391 
    392 noduplicate (clang::noduplicate)
    393 --------------------------------
    394 .. csv-table:: Supported Syntaxes
    395    :header: "GNU", "C++11", "__declspec", "Keyword"
    396 
    397    "X","X","",""
    398 
    399 The ``noduplicate`` attribute can be placed on function declarations to control
    400 whether function calls to this function can be duplicated or not as a result of
    401 optimizations. This is required for the implementation of functions with
    402 certain special requirements, like the OpenCL "barrier" function, that might
    403 need to be run concurrently by all the threads that are executing in lockstep
    404 on the hardware. For example this attribute applied on the function
    405 "nodupfunc" in the code below avoids that:
    406 
    407 .. code-block:: c
    408 
    409   void nodupfunc() __attribute__((noduplicate));
    410   // Setting it as a C++11 attribute is also valid
    411   // void nodupfunc() [[clang::noduplicate]];
    412   void foo();
    413   void bar();
    414 
    415   nodupfunc();
    416   if (a > n) {
    417     foo();
    418   } else {
    419     bar();
    420   }
    421 
    422 gets possibly modified by some optimizations into code similar to this:
    423 
    424 .. code-block:: c
    425 
    426   if (a > n) {
    427     nodupfunc();
    428     foo();
    429   } else {
    430     nodupfunc();
    431     bar();
    432   }
    433 
    434 where the call to "nodupfunc" is duplicated and sunk into the two branches
    435 of the condition.
    436 
    437 
    438 no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)
    439 -----------------------------------------------------------------------------------------------------------
    440 .. csv-table:: Supported Syntaxes
    441    :header: "GNU", "C++11", "__declspec", "Keyword"
    442 
    443    "X","X","",""
    444 
    445 .. _langext-address_sanitizer:
    446 
    447 Use ``__attribute__((no_sanitize_address))`` on a function declaration to
    448 specify that address safety instrumentation (e.g. AddressSanitizer) should
    449 not be applied to that function.
    450 
    451 
    452 no_sanitize_memory
    453 ------------------
    454 .. csv-table:: Supported Syntaxes
    455    :header: "GNU", "C++11", "__declspec", "Keyword"
    456 
    457    "X","","",""
    458 
    459 .. _langext-memory_sanitizer:
    460 
    461 Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
    462 specify that checks for uninitialized memory should not be inserted 
    463 (e.g. by MemorySanitizer). The function may still be instrumented by the tool
    464 to avoid false positives in other places.
    465 
    466 
    467 no_sanitize_thread
    468 ------------------
    469 .. csv-table:: Supported Syntaxes
    470    :header: "GNU", "C++11", "__declspec", "Keyword"
    471 
    472    "X","","",""
    473 
    474 .. _langext-thread_sanitizer:
    475 
    476 Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
    477 specify that checks for data races on plain (non-atomic) memory accesses should
    478 not be inserted by ThreadSanitizer. The function is still instrumented by the
    479 tool to avoid false positives and provide meaningful stack traces.
    480 
    481 
    482 no_split_stack (gnu::no_split_stack)
    483 ------------------------------------
    484 .. csv-table:: Supported Syntaxes
    485    :header: "GNU", "C++11", "__declspec", "Keyword"
    486 
    487    "X","X","",""
    488 
    489 The ``no_split_stack`` attribute disables the emission of the split stack
    490 preamble for a particular function. It has no effect if ``-fsplit-stack``
    491 is not specified.
    492 
    493 
    494 objc_method_family
    495 ------------------
    496 .. csv-table:: Supported Syntaxes
    497    :header: "GNU", "C++11", "__declspec", "Keyword"
    498 
    499    "X","","",""
    500 
    501 Many methods in Objective-C have conventional meanings determined by their
    502 selectors. It is sometimes useful to be able to mark a method as having a
    503 particular conventional meaning despite not having the right selector, or as
    504 not having the conventional meaning that its selector would suggest. For these
    505 use cases, we provide an attribute to specifically describe the "method family"
    506 that a method belongs to.
    507 
    508 **Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
    509 ``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``.  This
    510 attribute can only be placed at the end of a method declaration:
    511 
    512 .. code-block:: objc
    513 
    514   - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
    515 
    516 Users who do not wish to change the conventional meaning of a method, and who
    517 merely want to document its non-standard retain and release semantics, should
    518 use the retaining behavior attributes (``ns_returns_retained``,
    519 ``ns_returns_not_retained``, etc).
    520 
    521 Query for this feature with ``__has_attribute(objc_method_family)``.
    522 
    523 
    524 objc_requires_super
    525 -------------------
    526 .. csv-table:: Supported Syntaxes
    527    :header: "GNU", "C++11", "__declspec", "Keyword"
    528 
    529    "X","","",""
    530 
    531 Some Objective-C classes allow a subclass to override a particular method in a
    532 parent class but expect that the overriding method also calls the overridden
    533 method in the parent class. For these cases, we provide an attribute to
    534 designate that a method requires a "call to ``super``" in the overriding
    535 method in the subclass.
    536 
    537 **Usage**: ``__attribute__((objc_requires_super))``.  This attribute can only
    538 be placed at the end of a method declaration:
    539 
    540 .. code-block:: objc
    541 
    542   - (void)foo __attribute__((objc_requires_super));
    543 
    544 This attribute can only be applied the method declarations within a class, and
    545 not a protocol.  Currently this attribute does not enforce any placement of
    546 where the call occurs in the overriding method (such as in the case of
    547 ``-dealloc`` where the call must appear at the end).  It checks only that it
    548 exists.
    549 
    550 Note that on both OS X and iOS that the Foundation framework provides a
    551 convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
    552 attribute:
    553 
    554 .. code-block:: objc
    555 
    556   - (void)foo NS_REQUIRES_SUPER;
    557 
    558 This macro is conditionally defined depending on the compiler's support for
    559 this attribute.  If the compiler does not support the attribute the macro
    560 expands to nothing.
    561 
    562 Operationally, when a method has this annotation the compiler will warn if the
    563 implementation of an override in a subclass does not call super.  For example:
    564 
    565 .. code-block:: objc
    566 
    567    warning: method possibly missing a [super AnnotMeth] call
    568    - (void) AnnotMeth{};
    569                       ^
    570 
    571 
    572 optnone (clang::optnone)
    573 ------------------------
    574 .. csv-table:: Supported Syntaxes
    575    :header: "GNU", "C++11", "__declspec", "Keyword"
    576 
    577    "X","X","",""
    578 
    579 The ``optnone`` attribute suppresses essentially all optimizations
    580 on a function or method, regardless of the optimization level applied to
    581 the compilation unit as a whole.  This is particularly useful when you
    582 need to debug a particular function, but it is infeasible to build the
    583 entire application without optimization.  Avoiding optimization on the
    584 specified function can improve the quality of the debugging information
    585 for that function.
    586 
    587 This attribute is incompatible with the ``always_inline`` attribute.
    588 
    589 
    590 overloadable
    591 ------------
    592 .. csv-table:: Supported Syntaxes
    593    :header: "GNU", "C++11", "__declspec", "Keyword"
    594 
    595    "X","","",""
    596 
    597 Clang provides support for C++ function overloading in C.  Function overloading
    598 in C is introduced using the ``overloadable`` attribute.  For example, one
    599 might provide several overloaded versions of a ``tgsin`` function that invokes
    600 the appropriate standard function computing the sine of a value with ``float``,
    601 ``double``, or ``long double`` precision:
    602 
    603 .. code-block:: c
    604 
    605   #include <math.h>
    606   float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
    607   double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
    608   long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
    609 
    610 Given these declarations, one can call ``tgsin`` with a ``float`` value to
    611 receive a ``float`` result, with a ``double`` to receive a ``double`` result,
    612 etc.  Function overloading in C follows the rules of C++ function overloading
    613 to pick the best overload given the call arguments, with a few C-specific
    614 semantics:
    615 
    616 * Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
    617   floating-point promotion (per C99) rather than as a floating-point conversion
    618   (as in C++).
    619 
    620 * A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
    621   considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
    622   compatible types.
    623 
    624 * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
    625   and ``U`` are compatible types.  This conversion is given "conversion" rank.
    626 
    627 The declaration of ``overloadable`` functions is restricted to function
    628 declarations and definitions.  Most importantly, if any function with a given
    629 name is given the ``overloadable`` attribute, then all function declarations
    630 and definitions with that name (and in that scope) must have the
    631 ``overloadable`` attribute.  This rule even applies to redeclarations of
    632 functions whose original declaration had the ``overloadable`` attribute, e.g.,
    633 
    634 .. code-block:: c
    635 
    636   int f(int) __attribute__((overloadable));
    637   float f(float); // error: declaration of "f" must have the "overloadable" attribute
    638 
    639   int g(int) __attribute__((overloadable));
    640   int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
    641 
    642 Functions marked ``overloadable`` must have prototypes.  Therefore, the
    643 following code is ill-formed:
    644 
    645 .. code-block:: c
    646 
    647   int h() __attribute__((overloadable)); // error: h does not have a prototype
    648 
    649 However, ``overloadable`` functions are allowed to use a ellipsis even if there
    650 are no named parameters (as is permitted in C++).  This feature is particularly
    651 useful when combined with the ``unavailable`` attribute:
    652 
    653 .. code-block:: c++
    654 
    655   void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
    656 
    657 Functions declared with the ``overloadable`` attribute have their names mangled
    658 according to the same rules as C++ function names.  For example, the three
    659 ``tgsin`` functions in our motivating example get the mangled names
    660 ``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively.  There are two
    661 caveats to this use of name mangling:
    662 
    663 * Future versions of Clang may change the name mangling of functions overloaded
    664   in C, so you should not depend on an specific mangling.  To be completely
    665   safe, we strongly urge the use of ``static inline`` with ``overloadable``
    666   functions.
    667 
    668 * The ``overloadable`` attribute has almost no meaning when used in C++,
    669   because names will already be mangled and functions are already overloadable.
    670   However, when an ``overloadable`` function occurs within an ``extern "C"``
    671   linkage specification, it's name *will* be mangled in the same way as it
    672   would in C.
    673 
    674 Query for this feature with ``__has_extension(attribute_overloadable)``.
    675 
    676 
    677 pcs (gnu::pcs)
    678 --------------
    679 .. csv-table:: Supported Syntaxes
    680    :header: "GNU", "C++11", "__declspec", "Keyword"
    681 
    682    "X","X","",""
    683 
    684 On ARM targets, this can attribute can be used to select calling conventions,
    685 similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
    686 "aapcs-vfp".
    687 
    688 
    689 release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)
    690 -----------------------------------------------------------------------------------------------------------
    691 .. csv-table:: Supported Syntaxes
    692    :header: "GNU", "C++11", "__declspec", "Keyword"
    693 
    694    "X","X","",""
    695 
    696 Marks a function as releasing a capability.
    697 
    698 
    699 try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)
    700 ---------------------------------------------------------------------------------------------------------------------------
    701 .. csv-table:: Supported Syntaxes
    702    :header: "GNU", "C++11", "__declspec", "Keyword"
    703 
    704    "X","X","",""
    705 
    706 Marks a function that attempts to acquire a capability. This function may fail to
    707 actually acquire the capability; they accept a Boolean value determining
    708 whether acquiring the capability means success (true), or failing to acquire
    709 the capability means success (false).
    710 
    711 
    712 Variable Attributes
    713 ===================
    714 
    715 
    716 section (gnu::section, __declspec(allocate))
    717 --------------------------------------------
    718 .. csv-table:: Supported Syntaxes
    719    :header: "GNU", "C++11", "__declspec", "Keyword"
    720 
    721    "X","X","X",""
    722 
    723 The ``section`` attribute allows you to specify a specific section a
    724 global variable or function should be in after translation.
    725 
    726 
    727 tls_model (gnu::tls_model)
    728 --------------------------
    729 .. csv-table:: Supported Syntaxes
    730    :header: "GNU", "C++11", "__declspec", "Keyword"
    731 
    732    "X","X","",""
    733 
    734 The ``tls_model`` attribute allows you to specify which thread-local storage
    735 model to use. It accepts the following strings:
    736 
    737 * global-dynamic
    738 * local-dynamic
    739 * initial-exec
    740 * local-exec
    741 
    742 TLS models are mutually exclusive.
    743 
    744 
    745 thread
    746 ------
    747 .. csv-table:: Supported Syntaxes
    748    :header: "GNU", "C++11", "__declspec", "Keyword"
    749 
    750    "","","X",""
    751 
    752 The ``__declspec(thread)`` attribute declares a variable with thread local
    753 storage.  It is available under the ``-fms-extensions`` flag for MSVC
    754 compatibility.  Documentation for the Visual C++ attribute is available on MSDN_.
    755 
    756 .. _MSDN: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
    757 
    758 In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
    759 GNU ``__thread`` keyword.  The variable must not have a destructor and must have
    760 a constant initializer, if any.  The attribute only applies to variables
    761 declared with static storage duration, such as globals, class static data
    762 members, and static locals.
    763 
    764 
    765 Type Attributes
    766 ===============
    767 
    768 
    769 __single_inhertiance, __multiple_inheritance, __virtual_inheritance
    770 -------------------------------------------------------------------
    771 .. csv-table:: Supported Syntaxes
    772    :header: "GNU", "C++11", "__declspec", "Keyword"
    773 
    774    "","","","X"
    775 
    776 This collection of keywords is enabled under ``-fms-extensions`` and controls
    777 the pointer-to-member representation used on ``*-*-win32`` targets.
    778 
    779 The ``*-*-win32`` targets utilize a pointer-to-member representation which
    780 varies in size and alignment depending on the definition of the underlying
    781 class.
    782 
    783 However, this is problematic when a forward declaration is only available and
    784 no definition has been made yet.  In such cases, Clang is forced to utilize the
    785 most general representation that is available to it.
    786 
    787 These keywords make it possible to use a pointer-to-member representation other
    788 than the most general one regardless of whether or not the definition will ever
    789 be present in the current translation unit.
    790 
    791 This family of keywords belong between the ``class-key`` and ``class-name``:
    792 
    793 .. code-block:: c++
    794 
    795   struct __single_inheritance S;
    796   int S::*i;
    797   struct S {};
    798 
    799 This keyword can be applied to class templates but only has an effect when used
    800 on full specializations:
    801 
    802 .. code-block:: c++
    803 
    804   template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
    805   template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
    806   template <> struct __single_inheritance A<int, float>;
    807 
    808 Note that choosing an inheritance model less general than strictly necessary is
    809 an error:
    810 
    811 .. code-block:: c++
    812 
    813   struct __multiple_inheritance S; // error: inheritance model does not match definition
    814   int S::*i;
    815   struct S {};
    816 
    817 
    818 Statement Attributes
    819 ====================
    820 
    821 
    822 fallthrough (clang::fallthrough)
    823 --------------------------------
    824 .. csv-table:: Supported Syntaxes
    825    :header: "GNU", "C++11", "__declspec", "Keyword"
    826 
    827    "","X","",""
    828 
    829 The ``clang::fallthrough`` attribute is used along with the
    830 ``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
    831 between switch labels.  It can only be applied to a null statement placed at a
    832 point of execution between any statement and the next switch label.  It is
    833 common to mark these places with a specific comment, but this attribute is
    834 meant to replace comments with a more strict annotation, which can be checked
    835 by the compiler.  This attribute doesn't change semantics of the code and can
    836 be used wherever an intended fall-through occurs.  It is designed to mimic
    837 control-flow statements like ``break;``, so it can be placed in most places
    838 where ``break;`` can, but only if there are no statements on the execution path
    839 between it and the next switch label.
    840 
    841 Here is an example:
    842 
    843 .. code-block:: c++
    844 
    845   // compile with -Wimplicit-fallthrough
    846   switch (n) {
    847   case 22:
    848   case 33:  // no warning: no statements between case labels
    849     f();
    850   case 44:  // warning: unannotated fall-through
    851     g();
    852     [[clang::fallthrough]];
    853   case 55:  // no warning
    854     if (x) {
    855       h();
    856       break;
    857     }
    858     else {
    859       i();
    860       [[clang::fallthrough]];
    861     }
    862   case 66:  // no warning
    863     p();
    864     [[clang::fallthrough]]; // warning: fallthrough annotation does not
    865                             //          directly precede case label
    866     q();
    867   case 77:  // warning: unannotated fall-through
    868     r();
    869   }
    870 
    871 
    872 Consumed Annotation Checking
    873 ============================
    874 Clang supports additional attributes for checking basic resource management
    875 properties, specifically for unique objects that have a single owning reference.
    876 The following attributes are currently supported, although **the implementation
    877 for these annotations is currently in development and are subject to change.**
    878 
    879 callable_when
    880 -------------
    881 .. csv-table:: Supported Syntaxes
    882    :header: "GNU", "C++11", "__declspec", "Keyword"
    883 
    884    "X","","",""
    885 
    886 Use ``__attribute__((callable_when(...)))`` to indicate what states a method
    887 may be called in.  Valid states are unconsumed, consumed, or unknown.  Each
    888 argument to this attribute must be a quoted string.  E.g.:
    889 
    890 ``__attribute__((callable_when("unconsumed", "unknown")))``
    891 
    892 
    893 consumable
    894 ----------
    895 .. csv-table:: Supported Syntaxes
    896    :header: "GNU", "C++11", "__declspec", "Keyword"
    897 
    898    "X","","",""
    899 
    900 Each ``class`` that uses any of the typestate annotations must first be marked
    901 using the ``consumable`` attribute.  Failure to do so will result in a warning.
    902 
    903 This attribute accepts a single parameter that must be one of the following:
    904 ``unknown``, ``consumed``, or ``unconsumed``.
    905 
    906 
    907 param_typestate
    908 ---------------
    909 .. csv-table:: Supported Syntaxes
    910    :header: "GNU", "C++11", "__declspec", "Keyword"
    911 
    912    "X","","",""
    913 
    914 This attribute specifies expectations about function parameters.  Calls to an
    915 function with annotated parameters will issue a warning if the corresponding
    916 argument isn't in the expected state.  The attribute is also used to set the
    917 initial state of the parameter when analyzing the function's body.
    918 
    919 
    920 return_typestate
    921 ----------------
    922 .. csv-table:: Supported Syntaxes
    923    :header: "GNU", "C++11", "__declspec", "Keyword"
    924 
    925    "X","","",""
    926 
    927 The ``return_typestate`` attribute can be applied to functions or parameters.
    928 When applied to a function the attribute specifies the state of the returned
    929 value.  The function's body is checked to ensure that it always returns a value
    930 in the specified state.  On the caller side, values returned by the annotated
    931 function are initialized to the given state.
    932 
    933 When applied to a function parameter it modifies the state of an argument after
    934 a call to the function returns.  The function's body is checked to ensure that
    935 the parameter is in the expected state before returning.
    936 
    937 
    938 set_typestate
    939 -------------
    940 .. csv-table:: Supported Syntaxes
    941    :header: "GNU", "C++11", "__declspec", "Keyword"
    942 
    943    "X","","",""
    944 
    945 Annotate methods that transition an object into a new state with
    946 ``__attribute__((set_typestate(new_state)))``.  The new new state must be
    947 unconsumed, consumed, or unknown.
    948 
    949 
    950 test_typestate
    951 --------------
    952 .. csv-table:: Supported Syntaxes
    953    :header: "GNU", "C++11", "__declspec", "Keyword"
    954 
    955    "X","","",""
    956 
    957 Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
    958 returns true if the object is in the specified state..
    959 
    960 
    961 Type Safety Checking
    962 ====================
    963 Clang supports additional attributes to enable checking type safety properties
    964 that can't be enforced by the C type system.  Use cases include:
    965 
    966 * MPI library implementations, where these attributes enable checking that
    967   the buffer type matches the passed ``MPI_Datatype``;
    968 * for HDF5 library there is a similar use case to MPI;
    969 * checking types of variadic functions' arguments for functions like
    970   ``fcntl()`` and ``ioctl()``.
    971 
    972 You can detect support for these attributes with ``__has_attribute()``.  For
    973 example:
    974 
    975 .. code-block:: c++
    976 
    977   #if defined(__has_attribute)
    978   #  if __has_attribute(argument_with_type_tag) && \
    979         __has_attribute(pointer_with_type_tag) && \
    980         __has_attribute(type_tag_for_datatype)
    981   #    define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
    982   /* ... other macros ...  */
    983   #  endif
    984   #endif
    985 
    986   #if !defined(ATTR_MPI_PWT)
    987   # define ATTR_MPI_PWT(buffer_idx, type_idx)
    988   #endif
    989 
    990   int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
    991       ATTR_MPI_PWT(1,3);
    992 
    993 argument_with_type_tag
    994 ----------------------
    995 .. csv-table:: Supported Syntaxes
    996    :header: "GNU", "C++11", "__declspec", "Keyword"
    997 
    998    "X","","",""
    999 
   1000 Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
   1001 type_tag_idx)))`` on a function declaration to specify that the function
   1002 accepts a type tag that determines the type of some other argument.
   1003 ``arg_kind`` is an identifier that should be used when annotating all
   1004 applicable type tags.
   1005 
   1006 This attribute is primarily useful for checking arguments of variadic functions
   1007 (``pointer_with_type_tag`` can be used in most non-variadic cases).
   1008 
   1009 For example:
   1010 
   1011 .. code-block:: c++
   1012 
   1013   int fcntl(int fd, int cmd, ...)
   1014       __attribute__(( argument_with_type_tag(fcntl,3,2) ));
   1015 
   1016 
   1017 pointer_with_type_tag
   1018 ---------------------
   1019 .. csv-table:: Supported Syntaxes
   1020    :header: "GNU", "C++11", "__declspec", "Keyword"
   1021 
   1022    "X","","",""
   1023 
   1024 Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
   1025 on a function declaration to specify that the function accepts a type tag that
   1026 determines the pointee type of some other pointer argument.
   1027 
   1028 For example:
   1029 
   1030 .. code-block:: c++
   1031 
   1032   int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
   1033       __attribute__(( pointer_with_type_tag(mpi,1,3) ));
   1034 
   1035 
   1036 type_tag_for_datatype
   1037 ---------------------
   1038 .. csv-table:: Supported Syntaxes
   1039    :header: "GNU", "C++11", "__declspec", "Keyword"
   1040 
   1041    "X","","",""
   1042 
   1043 Clang supports annotating type tags of two forms.
   1044 
   1045 * **Type tag that is an expression containing a reference to some declared
   1046   identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
   1047   declaration with that identifier:
   1048 
   1049   .. code-block:: c++
   1050 
   1051     extern struct mpi_datatype mpi_datatype_int
   1052         __attribute__(( type_tag_for_datatype(mpi,int) ));
   1053     #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
   1054 
   1055 * **Type tag that is an integral literal.** Introduce a ``static const``
   1056   variable with a corresponding initializer value and attach
   1057   ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
   1058   for example:
   1059 
   1060   .. code-block:: c++
   1061 
   1062     #define MPI_INT ((MPI_Datatype) 42)
   1063     static const MPI_Datatype mpi_datatype_int
   1064         __attribute__(( type_tag_for_datatype(mpi,int) )) = 42
   1065 
   1066 The attribute also accepts an optional third argument that determines how the
   1067 expression is compared to the type tag.  There are two supported flags:
   1068 
   1069 * ``layout_compatible`` will cause types to be compared according to
   1070   layout-compatibility rules (C++11 [class.mem] p 17, 18).  This is
   1071   implemented to support annotating types like ``MPI_DOUBLE_INT``.
   1072 
   1073   For example:
   1074 
   1075   .. code-block:: c++
   1076 
   1077     /* In mpi.h */
   1078     struct internal_mpi_double_int { double d; int i; };
   1079     extern struct mpi_datatype mpi_datatype_double_int
   1080         __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
   1081 
   1082     #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
   1083 
   1084     /* In user code */
   1085     struct my_pair { double a; int b; };
   1086     struct my_pair *buffer;
   1087     MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ...  */); // no warning
   1088 
   1089     struct my_int_pair { int a; int b; }
   1090     struct my_int_pair *buffer2;
   1091     MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ...  */); // warning: actual buffer element
   1092                                                       // type 'struct my_int_pair'
   1093                                                       // doesn't match specified MPI_Datatype
   1094 
   1095 * ``must_be_null`` specifies that the expression should be a null pointer
   1096   constant, for example:
   1097 
   1098   .. code-block:: c++
   1099 
   1100     /* In mpi.h */
   1101     extern struct mpi_datatype mpi_datatype_null
   1102         __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
   1103 
   1104     #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
   1105 
   1106     /* In user code */
   1107     MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ...  */); // warning: MPI_DATATYPE_NULL
   1108                                                         // was specified but buffer
   1109                                                         // is not a null pointer
   1110 
   1111 
   1112