Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
llvm-project/clang/include/clang/Basic/AttrDocs.td
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
7055 lines (5748 sloc)
275 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//==--- AttrDocs.td - Attribute documentation ----------------------------===// | |
// | |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |
// See https://llvm.org/LICENSE.txt for license information. | |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |
// | |
//===---------------------------------------------------------------------===// | |
// To test that the documentation builds cleanly, you must run clang-tblgen to | |
// convert the .td file into a .rst file, and then run sphinx to convert the | |
// .rst file into an HTML file. After completing testing, you should revert the | |
// generated .rst file so that the modified version does not get checked in to | |
// version control. | |
// | |
// To run clang-tblgen to generate the .rst file: | |
// clang-tblgen -gen-attr-docs -I <root>/llvm/tools/clang/include | |
// <root>/llvm/tools/clang/include/clang/Basic/Attr.td -o | |
// <root>/llvm/tools/clang/docs/AttributeReference.rst | |
// | |
// To run sphinx to generate the .html files (note that sphinx-build must be | |
// available on the PATH): | |
// Windows (from within the clang\docs directory): | |
// make.bat html | |
// Non-Windows (from within the clang\docs directory): | |
// sphinx-build -b html _build/html | |
def GlobalDocumentation { | |
code Intro =[{.. | |
------------------------------------------------------------------- | |
NOTE: This file is automatically generated by running clang-tblgen | |
-gen-attr-docs. Do not edit this file by hand!! | |
------------------------------------------------------------------- | |
=================== | |
Attributes in Clang | |
=================== | |
.. contents:: | |
:local: | |
.. |br| raw:: html | |
<br/> | |
Introduction | |
============ | |
This page lists the attributes currently supported by Clang. | |
}]; | |
} | |
def SectionDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``section`` attribute allows you to specify a specific section a | |
global variable or function should be in after translation. | |
}]; | |
let Heading = "section, __declspec(allocate)"; | |
} | |
def UsedDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
This attribute, when attached to a function or variable definition, indicates | |
that there may be references to the entity which are not apparent in the source | |
code. For example, it may be referenced from inline ``asm``, or it may be | |
found through a dynamic symbol or section lookup. | |
The compiler must emit the definition even if it appears to be unused, and it | |
must not apply optimizations which depend on fully understanding how the entity | |
is used. | |
Whether this attribute has any effect on the linker depends on the target and | |
the linker. Most linkers support the feature of section garbage collection | |
(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or | |
discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O | |
targets (Windows and Apple platforms), the `used` attribute prevents symbols | |
from being removed by linker section GC. On ELF targets, it has no effect on its | |
own, and the linker may remove the definition if it is not otherwise referenced. | |
This linker GC can be avoided by also adding the ``retain`` attribute. Note | |
that ``retain`` requires special support from the linker; see that attribute's | |
documentation for further information. | |
}]; | |
} | |
def RetainDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
This attribute, when attached to a function or variable definition, prevents | |
section garbage collection in the linker. It does not prevent other discard | |
mechanisms, such as archive member selection, and COMDAT group resolution. | |
If the compiler does not emit the definition, e.g. because it was not used in | |
the translation unit or the compiler was able to eliminate all of the uses, | |
this attribute has no effect. This attribute is typically combined with the | |
``used`` attribute to force the definition to be emitted and preserved into the | |
final linked image. | |
This attribute is only necessary on ELF targets; other targets prevent section | |
garbage collection by the linker when using the ``used`` attribute alone. | |
Using the attributes together should result in consistent behavior across | |
targets. | |
This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension. | |
This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as | |
well as in ``ld.lld`` 13. | |
}]; | |
} | |
def InitPriorityDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
In C++, the order in which global variables are initialized across translation | |
units is unspecified, unlike the ordering within a single translation unit. The | |
``init_priority`` attribute allows you to specify a relative ordering for the | |
initialization of objects declared at namespace scope in C++. The priority is | |
given as an integer constant expression between 101 and 65535 (inclusive). | |
Priorities outside of that range are reserved for use by the implementation. A | |
lower value indicates a higher priority of initialization. Note that only the | |
relative ordering of values is important. For example: | |
.. code-block:: c++ | |
struct SomeType { SomeType(); }; | |
__attribute__((init_priority(200))) SomeType Obj1; | |
__attribute__((init_priority(101))) SomeType Obj2; | |
``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of | |
initialization being the opposite. | |
On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and | |
``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)`` | |
uses the default 65535 priority. | |
This attribute is only supported for C++ and Objective-C++ and is ignored in | |
other language modes. Currently, this attribute is not implemented on z/OS. | |
}]; | |
} | |
def InitSegDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The attribute applied by ``pragma init_seg()`` controls the section into | |
which global initialization function pointers are emitted. It is only | |
available with ``-fms-extensions``. Typically, this function pointer is | |
emitted into ``.CRT$XCU`` on Windows. The user can change the order of | |
initialization by using a different section name with the same | |
``.CRT$XC`` prefix and a suffix that sorts lexicographically before or | |
after the standard ``.CRT$XCU`` sections. See the init_seg_ | |
documentation on MSDN for more information. | |
.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx | |
}]; | |
} | |
def TLSModelDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``tls_model`` attribute allows you to specify which thread-local storage | |
model to use. It accepts the following strings: | |
* global-dynamic | |
* local-dynamic | |
* initial-exec | |
* local-exec | |
TLS models are mutually exclusive. | |
}]; | |
} | |
def DLLExportDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``__declspec(dllexport)`` attribute declares a variable, function, or | |
Objective-C interface to be exported from the module. It is available under the | |
``-fdeclspec`` flag for compatibility with various compilers. The primary use | |
is for COFF object files which explicitly specify what interfaces are available | |
for external use. See the dllexport_ documentation on MSDN for more | |
information. | |
.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx | |
}]; | |
} | |
def DLLImportDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``__declspec(dllimport)`` attribute declares a variable, function, or | |
Objective-C interface to be imported from an external module. It is available | |
under the ``-fdeclspec`` flag for compatibility with various compilers. The | |
primary use is for COFF object files which explicitly specify what interfaces | |
are imported from external modules. See the dllimport_ documentation on MSDN | |
for more information. | |
Note that a dllimport function may still be inlined, if its definition is | |
available and it doesn't reference any non-dllimport functions or global | |
variables. | |
.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx | |
}]; | |
} | |
def ThreadDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``__declspec(thread)`` attribute declares a variable with thread local | |
storage. It is available under the ``-fms-extensions`` flag for MSVC | |
compatibility. See the documentation for `__declspec(thread)`_ on MSDN. | |
.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx | |
In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the | |
GNU ``__thread`` keyword. The variable must not have a destructor and must have | |
a constant initializer, if any. The attribute only applies to variables | |
declared with static storage duration, such as globals, class static data | |
members, and static locals. | |
}]; | |
} | |
def NoEscapeDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
``noescape`` placed on a function parameter of a pointer type is used to inform | |
the compiler that the pointer cannot escape: that is, no reference to the object | |
the pointer points to that is derived from the parameter value will survive | |
after the function returns. Users are responsible for making sure parameters | |
annotated with ``noescape`` do not actually escape. Calling ``free()`` on such | |
a parameter does not constitute an escape. | |
For example: | |
.. code-block:: c | |
int *gp; | |
void nonescapingFunc(__attribute__((noescape)) int *p) { | |
*p += 100; // OK. | |
} | |
void escapingFunc(__attribute__((noescape)) int *p) { | |
gp = p; // Not OK. | |
} | |
Additionally, when the parameter is a `block pointer | |
<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction | |
applies to copies of the block. For example: | |
.. code-block:: c | |
typedef void (^BlockTy)(); | |
BlockTy g0, g1; | |
void nonescapingFunc(__attribute__((noescape)) BlockTy block) { | |
block(); // OK. | |
} | |
void escapingFunc(__attribute__((noescape)) BlockTy block) { | |
g0 = block; // Not OK. | |
g1 = Block_copy(block); // Not OK either. | |
} | |
}]; | |
} | |
def MaybeUndefDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``maybe_undef`` attribute can be placed on a function parameter. It indicates | |
that the parameter is allowed to use undef values. It informs the compiler | |
to insert a freeze LLVM IR instruction on the function parameter. | |
Please note that this is an attribute that is used as an internal | |
implementation detail and not intended to be used by external users. | |
In languages HIP, CUDA etc., some functions have multi-threaded semantics and | |
it is enough for only one or some threads to provide defined arguments. | |
Depending on semantics, undef arguments in some threads don't produce | |
undefined results in the function call. Since, these functions accept undefined | |
arguments, ``maybe_undef`` attribute can be placed. | |
Sample usage: | |
.. code-block:: c | |
void maybeundeffunc(int __attribute__((maybe_undef))param); | |
}]; | |
} | |
def CarriesDependencyDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``carries_dependency`` attribute specifies dependency propagation into and | |
out of functions. | |
When specified on a function or Objective-C method, the ``carries_dependency`` | |
attribute means that the return value carries a dependency out of the function, | |
so that the implementation need not constrain ordering upon return from that | |
function. Implementations of the function and its caller may choose to preserve | |
dependencies instead of emitting memory ordering instructions such as fences. | |
Note, this attribute does not change the meaning of the program, but may result | |
in generation of more efficient code. | |
}]; | |
} | |
def CPUSpecificCPUDispatchDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and | |
resolve multiversioned functions. This form of multiversioning provides a | |
mechanism for declaring versions across translation units and manually | |
specifying the resolved function list. A specified CPU defines a set of minimum | |
features that are required for the function to be called. The result of this is | |
that future processors execute the most restrictive version of the function the | |
new processor can execute. | |
In addition, unlike the ICC implementation of this feature, the selection of the | |
version does not consider the manufacturer or microarchitecture of the processor. | |
It tests solely the list of features that are both supported by the specified | |
processor and present in the compiler-rt library. This can be surprising at times, | |
as the runtime processor may be from a completely different manufacturer, as long | |
as it supports the same feature set. | |
This can additionally be surprising, as some processors are indistringuishable from | |
others based on the list of testable features. When this happens, the variant | |
is selected in an unspecified manner. | |
Function versions are defined with ``cpu_specific``, which takes one or more CPU | |
names as a parameter. For example: | |
.. code-block:: c | |
// Declares and defines the ivybridge version of single_cpu. | |
__attribute__((cpu_specific(ivybridge))) | |
void single_cpu(void){} | |
// Declares and defines the atom version of single_cpu. | |
__attribute__((cpu_specific(atom))) | |
void single_cpu(void){} | |
// Declares and defines both the ivybridge and atom version of multi_cpu. | |
__attribute__((cpu_specific(ivybridge, atom))) | |
void multi_cpu(void){} | |
A dispatching (or resolving) function can be declared anywhere in a project's | |
source code with ``cpu_dispatch``. This attribute takes one or more CPU names | |
as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch`` | |
are not expected to be defined, only declared. If such a marked function has a | |
definition, any side effects of the function are ignored; trivial function | |
bodies are permissible for ICC compatibility. | |
.. code-block:: c | |
// Creates a resolver for single_cpu above. | |
__attribute__((cpu_dispatch(ivybridge, atom))) | |
void single_cpu(void){} | |
// Creates a resolver for multi_cpu, but adds a 3rd version defined in another | |
// translation unit. | |
__attribute__((cpu_dispatch(ivybridge, atom, sandybridge))) | |
void multi_cpu(void){} | |
Note that it is possible to have a resolving function that dispatches based on | |
more or fewer options than are present in the program. Specifying fewer will | |
result in the omitted options not being considered during resolution. Specifying | |
a version for resolution that isn't defined in the program will result in a | |
linking failure. | |
It is also possible to specify a CPU name of ``generic`` which will be resolved | |
if the executing processor doesn't satisfy the features required in the CPU | |
name. The behavior of a program executing on a processor that doesn't satisfy | |
any option of a multiversioned function is undefined. | |
}]; | |
} | |
def SYCLKernelDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``sycl_kernel`` attribute specifies that a function template will be used | |
to outline device code and to generate an OpenCL kernel. | |
Here is a code example of the SYCL program, which demonstrates the compiler's | |
outlining job: | |
.. code-block:: c++ | |
int foo(int x) { return ++x; } | |
using namespace cl::sycl; | |
queue Q; | |
buffer<int, 1> a(range<1>{1024}); | |
Q.submit([&](handler& cgh) { | |
auto A = a.get_access<access::mode::write>(cgh); | |
cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) { | |
A[index] = index[0] + foo(42); | |
}); | |
} | |
A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel". | |
A SYCL kernel defines the entry point to the "device part" of the code. The | |
compiler will emit all symbols accessible from a "kernel". In this code | |
example, the compiler will emit "foo" function. More details about the | |
compilation of functions for the device part can be found in the SYCL 1.2.1 | |
specification Section 6.4. | |
To show to the compiler entry point to the "device part" of the code, the SYCL | |
runtime can use the ``sycl_kernel`` attribute in the following way: | |
.. code-block:: c++ | |
namespace cl { | |
namespace sycl { | |
class handler { | |
template <typename KernelName, typename KernelType/*, ...*/> | |
__attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) { | |
// ... | |
KernelFuncObj(); | |
} | |
template <typename KernelName, typename KernelType, int Dims> | |
void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) { | |
#ifdef __SYCL_DEVICE_ONLY__ | |
sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc); | |
#else | |
// Host implementation | |
#endif | |
} | |
}; | |
} // namespace sycl | |
} // namespace cl | |
The compiler will also generate an OpenCL kernel using the function marked with | |
the ``sycl_kernel`` attribute. | |
Here is the list of SYCL device compiler expectations with regard to the | |
function marked with the ``sycl_kernel`` attribute: | |
- The function must be a template with at least two type template parameters. | |
The compiler generates an OpenCL kernel and uses the first template parameter | |
as a unique name for the generated OpenCL kernel. The host application uses | |
this unique name to invoke the OpenCL kernel generated for the SYCL kernel | |
specialized by this name and second template parameter ``KernelType`` (which | |
might be an unnamed function object type). | |
- The function must have at least one parameter. The first parameter is | |
required to be a function object type (named or unnamed i.e. lambda). The | |
compiler uses function object type fields to generate OpenCL kernel | |
parameters. | |
- The function must return void. The compiler reuses the body of marked functions to | |
generate the OpenCL kernel body, and the OpenCL kernel must return ``void``. | |
The SYCL kernel in the previous code sample meets these expectations. | |
}]; | |
} | |
def SYCLSpecialClassDocs : Documentation { | |
let Category = DocCatStmt; | |
let Content = [{ | |
SYCL defines some special classes (accessor, sampler, and stream) which require | |
specific handling during the generation of the SPIR entry point. | |
The ``__attribute__((sycl_special_class))`` attribute is used in SYCL | |
headers to indicate that a class or a struct needs a specific handling when | |
it is passed from host to device. | |
Special classes will have a mandatory ``__init`` method and an optional | |
``__finalize`` method (the ``__finalize`` method is used only with the | |
``stream`` type). Kernel parameters types are extract from the ``__init`` method | |
parameters. The kernel function arguments list is derived from the | |
arguments of the ``__init`` method. The arguments of the ``__init`` method are | |
copied into the kernel function argument list and the ``__init`` and | |
``__finalize`` methods are called at the beginning and the end of the kernel, | |
respectively. | |
The ``__init`` and ``__finalize`` methods must be defined inside the | |
special class. | |
Please note that this is an attribute that is used as an internal | |
implementation detail and not intended to be used by external users. | |
The syntax of the attribute is as follows: | |
.. code-block:: text | |
class __attribute__((sycl_special_class)) accessor {}; | |
class [[clang::sycl_special_class]] accessor {}; | |
This is a code example that illustrates the use of the attribute: | |
.. code-block:: c++ | |
class __attribute__((sycl_special_class)) SpecialType { | |
int F1; | |
int F2; | |
void __init(int f1) { | |
F1 = f1; | |
F2 = f1; | |
} | |
void __finalize() {} | |
public: | |
SpecialType() = default; | |
int getF2() const { return F2; } | |
}; | |
int main () { | |
SpecialType T; | |
cgh.single_task([=] { | |
T.getF2(); | |
}); | |
} | |
This would trigger the following kernel entry point in the AST: | |
.. code-block:: c++ | |
void __sycl_kernel(int f1) { | |
SpecialType T; | |
T.__init(f1); | |
... | |
T.__finalize() | |
} | |
}]; | |
} | |
def C11NoReturnDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
A function declared as ``_Noreturn`` shall not return to its caller. The | |
compiler will generate a diagnostic for a function declared as ``_Noreturn`` | |
that appears to be capable of returning to its caller. Despite being a type | |
specifier, the ``_Noreturn`` attribute cannot be specified on a function | |
pointer type. | |
}]; | |
} | |
def CXX11NoReturnDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "noreturn, _Noreturn"; | |
let Content = [{ | |
A function declared as ``[[noreturn]]`` shall not return to its caller. The | |
compiler will generate a diagnostic for a function declared as ``[[noreturn]]`` | |
that appears to be capable of returning to its caller. | |
The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code | |
migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``. | |
}]; | |
} | |
def NoMergeDocs : Documentation { | |
let Category = DocCatStmt; | |
let Content = [{ | |
If a statement is marked ``nomerge`` and contains call expressions, those call | |
expressions inside the statement will not be merged during optimization. This | |
attribute can be used to prevent the optimizer from obscuring the source | |
location of certain calls. For example, it will prevent tail merging otherwise | |
identical code sequences that raise an exception or terminate the program. Tail | |
merging normally reduces the precision of source location information, making | |
stack traces less useful for debugging. This attribute gives the user control | |
over the tradeoff between code size and debug information precision. | |
``nomerge`` attribute can also be used as function attribute to prevent all | |
calls to the specified function from merging. It has no effect on indirect | |
calls. | |
}]; | |
} | |
def NoInlineDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
This function attribute suppresses the inlining of a function at the call sites | |
of the function. | |
``[[clang::noinline]]`` spelling can be used as a statement attribute; other | |
spellings of the attribute are not supported on statements. If a statement is | |
marked ``[[clang::noinline]]`` and contains calls, those calls inside the | |
statement will not be inlined by the compiler. | |
``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to | |
avoid diagnostics due to usage of ``__attribute__((__noinline__))`` | |
with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``. | |
.. code-block:: c | |
int example(void) { | |
int r; | |
[[clang::noinline]] foo(); | |
[[clang::noinline]] r = bar(); | |
return r; | |
} | |
}]; | |
} | |
def MustTailDocs : Documentation { | |
let Category = DocCatStmt; | |
let Content = [{ | |
If a ``return`` statement is marked ``musttail``, this indicates that the | |
compiler must generate a tail call for the program to be correct, even when | |
optimizations are disabled. This guarantees that the call will not cause | |
unbounded stack growth if it is part of a recursive cycle in the call graph. | |
If the callee is a virtual function that is implemented by a thunk, there is | |
no guarantee in general that the thunk tail-calls the implementation of the | |
virtual function, so such a call in a recursive cycle can still result in | |
unbounded stack growth. | |
``clang::musttail`` can only be applied to a ``return`` statement whose value | |
is the result of a function call (even functions returning void must use | |
``return``, although no value is returned). The target function must have the | |
same number of arguments as the caller. The types of the return value and all | |
arguments must be similar according to C++ rules (differing only in cv | |
qualifiers or array size), including the implicit "this" argument, if any. | |
Any variables in scope, including all arguments to the function and the | |
return value must be trivially destructible. The calling convention of the | |
caller and callee must match, and they must not be variadic functions or have | |
old style K&R C function declarations. | |
``clang::musttail`` provides assurances that the tail call can be optimized on | |
all targets, not just one. | |
}]; | |
} | |
def AssertCapabilityDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "assert_capability, assert_shared_capability"; | |
let Content = [{ | |
Marks a function that dynamically tests whether a capability is held, and halts | |
the program if it is not held. | |
}]; | |
} | |
def AcquireCapabilityDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "acquire_capability, acquire_shared_capability"; | |
let Content = [{ | |
Marks a function as acquiring a capability. | |
}]; | |
} | |
def TryAcquireCapabilityDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "try_acquire_capability, try_acquire_shared_capability"; | |
let Content = [{ | |
Marks a function that attempts to acquire a capability. This function may fail to | |
actually acquire the capability; they accept a Boolean value determining | |
whether acquiring the capability means success (true), or failing to acquire | |
the capability means success (false). | |
}]; | |
} | |
def ReleaseCapabilityDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "release_capability, release_shared_capability"; | |
let Content = [{ | |
Marks a function as releasing a capability. | |
}]; | |
} | |
def AssumeAlignedDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function | |
declaration to specify that the return value of the function (which must be a | |
pointer type) has the specified offset, in bytes, from an address with the | |
specified alignment. The offset is taken to be zero if omitted. | |
.. code-block:: c++ | |
// The returned pointer value has 32-byte alignment. | |
void *a() __attribute__((assume_aligned (32))); | |
// The returned pointer value is 4 bytes greater than an address having | |
// 32-byte alignment. | |
void *b() __attribute__((assume_aligned (32, 4))); | |
Note that this attribute provides information to the compiler regarding a | |
condition that the code already ensures is true. It does not cause the compiler | |
to enforce the provided alignment assumption. | |
}]; | |
} | |
def AllocSizeDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``alloc_size`` attribute can be placed on functions that return pointers in | |
order to hint to the compiler how many bytes of memory will be available at the | |
returned pointer. ``alloc_size`` takes one or two arguments. | |
- ``alloc_size(N)`` implies that argument number N equals the number of | |
available bytes at the returned pointer. | |
- ``alloc_size(N, M)`` implies that the product of argument number N and | |
argument number M equals the number of available bytes at the returned | |
pointer. | |
Argument numbers are 1-based. | |
An example of how to use ``alloc_size`` | |
.. code-block:: c | |
void *my_malloc(int a) __attribute__((alloc_size(1))); | |
void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); | |
int main() { | |
void *const p = my_malloc(100); | |
assert(__builtin_object_size(p, 0) == 100); | |
void *const a = my_calloc(20, 5); | |
assert(__builtin_object_size(a, 0) == 100); | |
} | |
.. Note:: This attribute works differently in clang than it does in GCC. | |
Specifically, clang will only trace ``const`` pointers (as above); we give up | |
on pointers that are not marked as ``const``. In the vast majority of cases, | |
this is unimportant, because LLVM has support for the ``alloc_size`` | |
attribute. However, this may cause mildly unintuitive behavior when used with | |
other attributes, such as ``enable_if``. | |
}]; | |
} | |
def CodeSegDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``__declspec(code_seg)`` attribute enables the placement of code into separate | |
named segments that can be paged or locked in memory individually. This attribute | |
is used to control the placement of instantiated templates and compiler-generated | |
code. See the documentation for `__declspec(code_seg)`_ on MSDN. | |
.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx | |
}]; | |
} | |
def AllocAlignDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Use ``__attribute__((alloc_align(<alignment>))`` on a function | |
declaration to specify that the return value of the function (which must be a | |
pointer type) is at least as aligned as the value of the indicated parameter. The | |
parameter is given by its index in the list of formal parameters; the first | |
parameter has index 1 unless the function is a C++ non-static member function, | |
in which case the first parameter has index 2 to account for the implicit ``this`` | |
parameter. | |
.. code-block:: c++ | |
// The returned pointer has the alignment specified by the first parameter. | |
void *a(size_t align) __attribute__((alloc_align(1))); | |
// The returned pointer has the alignment specified by the second parameter. | |
void *b(void *v, size_t align) __attribute__((alloc_align(2))); | |
// The returned pointer has the alignment specified by the second visible | |
// parameter, however it must be adjusted for the implicit 'this' parameter. | |
void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3))); | |
Note that this attribute merely informs the compiler that a function always | |
returns a sufficiently aligned pointer. It does not cause the compiler to | |
emit code to enforce that alignment. The behavior is undefined if the returned | |
pointer is not sufficiently aligned. | |
}]; | |
} | |
def EnableIfDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
.. Note:: Some features of this attribute are experimental. The meaning of | |
multiple enable_if attributes on a single declaration is subject to change in | |
a future version of clang. Also, the ABI is not standardized and the name | |
mangling may change in future versions. To avoid that, use asm labels. | |
The ``enable_if`` attribute can be placed on function declarations to control | |
which overload is selected based on the values of the function's arguments. | |
When combined with the ``overloadable`` attribute, this feature is also | |
available in C. | |
.. code-block:: c++ | |
int isdigit(int c); | |
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"))); | |
void foo(char c) { | |
isdigit(c); | |
isdigit(10); | |
isdigit(-10); // results in a compile-time error. | |
} | |
The enable_if attribute takes two arguments, the first is an expression written | |
in terms of the function parameters, the second is a string explaining why this | |
overload candidate could not be selected to be displayed in diagnostics. The | |
expression is part of the function signature for the purposes of determining | |
whether it is a redeclaration (following the rules used when determining | |
whether a C++ template specialization is ODR-equivalent), but is not part of | |
the type. | |
The enable_if expression is evaluated as if it were the body of a | |
bool-returning constexpr function declared with the arguments of the function | |
it is being applied to, then called with the parameters at the call site. If the | |
result is false or could not be determined through constant expression | |
evaluation, then this overload will not be chosen and the provided string may | |
be used in a diagnostic if the compile fails as a result. | |
Because the enable_if expression is an unevaluated context, there are no global | |
state changes, nor the ability to pass information from the enable_if | |
expression to the function body. For example, suppose we want calls to | |
strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of | |
strbuf) only if the size of strbuf can be determined: | |
.. code-block:: c++ | |
__attribute__((always_inline)) | |
static inline size_t strnlen(const char *s, size_t maxlen) | |
__attribute__((overloadable)) | |
__attribute__((enable_if(__builtin_object_size(s, 0) != -1))), | |
"chosen when the buffer size is known but 'maxlen' is not"))) | |
{ | |
return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); | |
} | |
Multiple enable_if attributes may be applied to a single declaration. In this | |
case, the enable_if expressions are evaluated from left to right in the | |
following manner. First, the candidates whose enable_if expressions evaluate to | |
false or cannot be evaluated are discarded. If the remaining candidates do not | |
share ODR-equivalent enable_if expressions, the overload resolution is | |
ambiguous. Otherwise, enable_if overload resolution continues with the next | |
enable_if attribute on the candidates that have not been discarded and have | |
remaining enable_if attributes. In this way, we pick the most specific | |
overload out of a number of viable overloads using enable_if. | |
.. code-block:: c++ | |
void f() __attribute__((enable_if(true, ""))); // #1 | |
void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 | |
void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 | |
void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 | |
In this example, a call to f() is always resolved to #2, as the first enable_if | |
expression is ODR-equivalent for both declarations, but #1 does not have another | |
enable_if expression to continue evaluating, so the next round of evaluation has | |
only a single candidate. In a call to g(1, 1), the call is ambiguous even though | |
#2 has more enable_if attributes, because the first enable_if expressions are | |
not ODR-equivalent. | |
Query for this feature with ``__has_attribute(enable_if)``. | |
Note that functions with one or more ``enable_if`` attributes may not have | |
their address taken, unless all of the conditions specified by said | |
``enable_if`` are constants that evaluate to ``true``. For example: | |
.. code-block:: c | |
const int TrueConstant = 1; | |
const int FalseConstant = 0; | |
int f(int a) __attribute__((enable_if(a > 0, ""))); | |
int g(int a) __attribute__((enable_if(a == 0 || a != 0, ""))); | |
int h(int a) __attribute__((enable_if(1, ""))); | |
int i(int a) __attribute__((enable_if(TrueConstant, ""))); | |
int j(int a) __attribute__((enable_if(FalseConstant, ""))); | |
void fn() { | |
int (*ptr)(int); | |
ptr = &f; // error: 'a > 0' is not always true | |
ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant | |
ptr = &h; // OK: 1 is a truthy constant | |
ptr = &i; // OK: 'TrueConstant' is a truthy constant | |
ptr = &j; // error: 'FalseConstant' is a constant, but not truthy | |
} | |
Because ``enable_if`` evaluation happens during overload resolution, | |
``enable_if`` may give unintuitive results when used with templates, depending | |
on when overloads are resolved. In the example below, clang will emit a | |
diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``: | |
.. code-block:: c++ | |
double foo(int i) __attribute__((enable_if(i > 0, ""))); | |
void *foo(int i) __attribute__((enable_if(i <= 0, ""))); | |
template <int I> | |
auto bar() { return foo(I); } | |
template <typename T> | |
auto baz() { return foo(T::number); } | |
struct WithNumber { constexpr static int number = 1; }; | |
void callThem() { | |
bar<sizeof(WithNumber)>(); | |
baz<WithNumber>(); | |
} | |
This is because, in ``bar``, ``foo`` is resolved prior to template | |
instantiation, so the value for ``I`` isn't known (thus, both ``enable_if`` | |
conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during | |
template instantiation, so the value for ``T::number`` is known. | |
}]; | |
} | |
def DiagnoseIfDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``diagnose_if`` attribute can be placed on function declarations to emit | |
warnings or errors at compile-time if calls to the attributed function meet | |
certain user-defined criteria. For example: | |
.. code-block:: c | |
int abs(int a) | |
__attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning"))); | |
int must_abs(int a) | |
__attribute__((diagnose_if(a >= 0, "Redundant abs call", "error"))); | |
int val = abs(1); // warning: Redundant abs call | |
int val2 = must_abs(1); // error: Redundant abs call | |
int val3 = abs(val); | |
int val4 = must_abs(val); // Because run-time checks are not emitted for | |
// diagnose_if attributes, this executes without | |
// issue. | |
``diagnose_if`` is closely related to ``enable_if``, with a few key differences: | |
* Overload resolution is not aware of ``diagnose_if`` attributes: they're | |
considered only after we select the best candidate from a given candidate set. | |
* Function declarations that differ only in their ``diagnose_if`` attributes are | |
considered to be redeclarations of the same function (not overloads). | |
* If the condition provided to ``diagnose_if`` cannot be evaluated, no | |
diagnostic will be emitted. | |
Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``. | |
As a result of bullet number two, ``diagnose_if`` attributes will stack on the | |
same function. For example: | |
.. code-block:: c | |
int foo() __attribute__((diagnose_if(1, "diag1", "warning"))); | |
int foo() __attribute__((diagnose_if(1, "diag2", "warning"))); | |
int bar = foo(); // warning: diag1 | |
// warning: diag2 | |
int (*fooptr)(void) = foo; // warning: diag1 | |
// warning: diag2 | |
constexpr int supportsAPILevel(int N) { return N < 5; } | |
int baz(int a) | |
__attribute__((diagnose_if(!supportsAPILevel(10), | |
"Upgrade to API level 10 to use baz", "error"))); | |
int baz(int a) | |
__attribute__((diagnose_if(!a, "0 is not recommended.", "warning"))); | |
int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz | |
int v = baz(0); // error: Upgrade to API level 10 to use baz | |
Query for this feature with ``__has_attribute(diagnose_if)``. | |
}]; | |
} | |
def PassObjectSizeDocs : Documentation { | |
let Category = DocCatVariable; // Technically it's a parameter doc, but eh. | |
let Heading = "pass_object_size, pass_dynamic_object_size"; | |
let Content = [{ | |
.. Note:: The mangling of functions with parameters that are annotated with | |
``pass_object_size`` is subject to change. You can get around this by | |
using ``__asm__("foo")`` to explicitly name your functions, thus preserving | |
your ABI; also, non-overloadable C functions with ``pass_object_size`` are | |
not mangled. | |
The ``pass_object_size(Type)`` attribute can be placed on function parameters to | |
instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite | |
of said function, and implicitly pass the result of this call in as an invisible | |
argument of type ``size_t`` directly after the parameter annotated with | |
``pass_object_size``. Clang will also replace any calls to | |
``__builtin_object_size(param, Type)`` in the function by said implicit | |
parameter. | |
Example usage: | |
.. code-block:: c | |
int bzero1(char *const p __attribute__((pass_object_size(0)))) | |
__attribute__((noinline)) { | |
int i = 0; | |
for (/**/; i < (int)__builtin_object_size(p, 0); ++i) { | |
p[i] = 0; | |
} | |
return i; | |
} | |
int main() { | |
char chars[100]; | |
int n = bzero1(&chars[0]); | |
assert(n == sizeof(chars)); | |
return 0; | |
} | |
If successfully evaluating ``__builtin_object_size(param, Type)`` at the | |
callsite is not possible, then the "failed" value is passed in. So, using the | |
definition of ``bzero1`` from above, the following code would exit cleanly: | |
.. code-block:: c | |
int main2(int argc, char *argv[]) { | |
int n = bzero1(argv); | |
assert(n == -1); | |
return 0; | |
} | |
``pass_object_size`` plays a part in overload resolution. If two overload | |
candidates are otherwise equally good, then the overload with one or more | |
parameters with ``pass_object_size`` is preferred. This implies that the choice | |
between two identical overloads both with ``pass_object_size`` on one or more | |
parameters will always be ambiguous; for this reason, having two such overloads | |
is illegal. For example: | |
.. code-block:: c++ | |
#define PS(N) __attribute__((pass_object_size(N))) | |
// OK | |
void Foo(char *a, char *b); // Overload A | |
// OK -- overload A has no parameters with pass_object_size. | |
void Foo(char *a PS(0), char *b PS(0)); // Overload B | |
// Error -- Same signature (sans pass_object_size) as overload B, and both | |
// overloads have one or more parameters with the pass_object_size attribute. | |
void Foo(void *a PS(0), void *b); | |
// OK | |
void Bar(void *a PS(0)); // Overload C | |
// OK | |
void Bar(char *c PS(1)); // Overload D | |
void main() { | |
char known[10], *unknown; | |
Foo(unknown, unknown); // Calls overload B | |
Foo(known, unknown); // Calls overload B | |
Foo(unknown, known); // Calls overload B | |
Foo(known, known); // Calls overload B | |
Bar(known); // Calls overload D | |
Bar(unknown); // Calls overload D | |
} | |
Currently, ``pass_object_size`` is a bit restricted in terms of its usage: | |
* Only one use of ``pass_object_size`` is allowed per parameter. | |
* It is an error to take the address of a function with ``pass_object_size`` on | |
any of its parameters. If you wish to do this, you can create an overload | |
without ``pass_object_size`` on any parameters. | |
* It is an error to apply the ``pass_object_size`` attribute to parameters that | |
are not pointers. Additionally, any parameter that ``pass_object_size`` is | |
applied to must be marked ``const`` at its function's definition. | |
Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves | |
identically to ``pass_object_size``, but evaluates a call to | |
``__builtin_dynamic_object_size`` at the callee instead of | |
``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra | |
runtime checks when the object size can't be determined at compile-time. You can | |
read more about ``__builtin_dynamic_object_size`` `here | |
<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_. | |
}]; | |
} | |
def OverloadableDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang provides support for C++ function overloading in C. Function overloading | |
in C is introduced using the ``overloadable`` attribute. For example, one | |
might provide several overloaded versions of a ``tgsin`` function that invokes | |
the appropriate standard function computing the sine of a value with ``float``, | |
``double``, or ``long double`` precision: | |
.. code-block:: c | |
#include <math.h> | |
float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } | |
double __attribute__((overloadable)) tgsin(double x) { return sin(x); } | |
long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } | |
Given these declarations, one can call ``tgsin`` with a ``float`` value to | |
receive a ``float`` result, with a ``double`` to receive a ``double`` result, | |
etc. Function overloading in C follows the rules of C++ function overloading | |
to pick the best overload given the call arguments, with a few C-specific | |
semantics: | |
* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a | |
floating-point promotion (per C99) rather than as a floating-point conversion | |
(as in C++). | |
* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is | |
considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are | |
compatible types. | |
* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` | |
and ``U`` are compatible types. This conversion is given "conversion" rank. | |
* If no viable candidates are otherwise available, we allow a conversion from a | |
pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are | |
incompatible. This conversion is ranked below all other types of conversions. | |
Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient | |
for ``T`` and ``U`` to be incompatible. | |
The declaration of ``overloadable`` functions is restricted to function | |
declarations and definitions. If a function is marked with the ``overloadable`` | |
attribute, then all declarations and definitions of functions with that name, | |
except for at most one (see the note below about unmarked overloads), must have | |
the ``overloadable`` attribute. In addition, redeclarations of a function with | |
the ``overloadable`` attribute must have the ``overloadable`` attribute, and | |
redeclarations of a function without the ``overloadable`` attribute must *not* | |
have the ``overloadable`` attribute. e.g., | |
.. code-block:: c | |
int f(int) __attribute__((overloadable)); | |
float f(float); // error: declaration of "f" must have the "overloadable" attribute | |
int f(int); // error: redeclaration of "f" must have the "overloadable" attribute | |
int g(int) __attribute__((overloadable)); | |
int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute | |
int h(int); | |
int h(int) __attribute__((overloadable)); // error: declaration of "h" must not | |
// have the "overloadable" attribute | |
Functions marked ``overloadable`` must have prototypes. Therefore, the | |
following code is ill-formed: | |
.. code-block:: c | |
int h() __attribute__((overloadable)); // error: h does not have a prototype | |
However, ``overloadable`` functions are allowed to use a ellipsis even if there | |
are no named parameters (as is permitted in C++). This feature is particularly | |
useful when combined with the ``unavailable`` attribute: | |
.. code-block:: c++ | |
void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error | |
Functions declared with the ``overloadable`` attribute have their names mangled | |
according to the same rules as C++ function names. For example, the three | |
``tgsin`` functions in our motivating example get the mangled names | |
``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two | |
caveats to this use of name mangling: | |
* Future versions of Clang may change the name mangling of functions overloaded | |
in C, so you should not depend on an specific mangling. To be completely | |
safe, we strongly urge the use of ``static inline`` with ``overloadable`` | |
functions. | |
* The ``overloadable`` attribute has almost no meaning when used in C++, | |
because names will already be mangled and functions are already overloadable. | |
However, when an ``overloadable`` function occurs within an ``extern "C"`` | |
linkage specification, it's name *will* be mangled in the same way as it | |
would in C. | |
For the purpose of backwards compatibility, at most one function with the same | |
name as other ``overloadable`` functions may omit the ``overloadable`` | |
attribute. In this case, the function without the ``overloadable`` attribute | |
will not have its name mangled. | |
For example: | |
.. code-block:: c | |
// Notes with mangled names assume Itanium mangling. | |
int f(int); | |
int f(double) __attribute__((overloadable)); | |
void foo() { | |
f(5); // Emits a call to f (not _Z1fi, as it would with an overload that | |
// was marked with overloadable). | |
f(1.0); // Emits a call to _Z1fd. | |
} | |
Support for unmarked overloads is not present in some versions of clang. You may | |
query for it using ``__has_extension(overloadable_unmarked)``. | |
Query for this attribute with ``__has_attribute(overloadable)``. | |
}]; | |
} | |
def ObjCMethodFamilyDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Many methods in Objective-C have conventional meanings determined by their | |
selectors. It is sometimes useful to be able to mark a method as having a | |
particular conventional meaning despite not having the right selector, or as | |
not having the conventional meaning that its selector would suggest. For these | |
use cases, we provide an attribute to specifically describe the "method family" | |
that a method belongs to. | |
**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of | |
``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This | |
attribute can only be placed at the end of a method declaration: | |
.. code-block:: objc | |
- (NSString *)initMyStringValue __attribute__((objc_method_family(none))); | |
Users who do not wish to change the conventional meaning of a method, and who | |
merely want to document its non-standard retain and release semantics, should | |
use the retaining behavior attributes (``ns_returns_retained``, | |
``ns_returns_not_retained``, etc). | |
Query for this feature with ``__has_attribute(objc_method_family)``. | |
}]; | |
} | |
def RetainBehaviorDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The behavior of a function with respect to reference counting for Foundation | |
(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming | |
convention (e.g. functions starting with "get" are assumed to return at | |
``+0``). | |
It can be overridden using a family of the following attributes. In | |
Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to | |
a function communicates that the object is returned at ``+1``, and the caller | |
is responsible for freeing it. | |
Similarly, the annotation ``__attribute__((ns_returns_not_retained))`` | |
specifies that the object is returned at ``+0`` and the ownership remains with | |
the callee. | |
The annotation ``__attribute__((ns_consumes_self))`` specifies that | |
the Objective-C method call consumes the reference to ``self``, e.g. by | |
attaching it to a supplied parameter. | |
Additionally, parameters can have an annotation | |
``__attribute__((ns_consumed))``, which specifies that passing an owned object | |
as that parameter effectively transfers the ownership, and the caller is no | |
longer responsible for it. | |
These attributes affect code generation when interacting with ARC code, and | |
they are used by the Clang Static Analyzer. | |
In C programs using CoreFoundation, a similar set of attributes: | |
``__attribute__((cf_returns_not_retained))``, | |
``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))`` | |
have the same respective semantics when applied to CoreFoundation objects. | |
These attributes affect code generation when interacting with ARC code, and | |
they are used by the Clang Static Analyzer. | |
Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), | |
the same attribute family is present: | |
``__attribute__((os_returns_not_retained))``, | |
``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``, | |
with the same respective semantics. | |
Similar to ``__attribute__((ns_consumes_self))``, | |
``__attribute__((os_consumes_this))`` specifies that the method call consumes | |
the reference to "this" (e.g., when attaching it to a different object supplied | |
as a parameter). | |
Out parameters (parameters the function is meant to write into, | |
either via pointers-to-pointers or references-to-pointers) | |
may be annotated with ``__attribute__((os_returns_retained))`` | |
or ``__attribute__((os_returns_not_retained))`` which specifies that the object | |
written into the out parameter should (or respectively should not) be released | |
after use. | |
Since often out parameters may or may not be written depending on the exit | |
code of the function, | |
annotations ``__attribute__((os_returns_retained_on_zero))`` | |
and ``__attribute__((os_returns_retained_on_non_zero))`` specify that | |
an out parameter at ``+1`` is written if and only if the function returns a zero | |
(respectively non-zero) error code. | |
Observe that return-code-dependent out parameter annotations are only | |
available for retained out parameters, as non-retained object do not have to be | |
released by the callee. | |
These attributes are only used by the Clang Static Analyzer. | |
The family of attributes ``X_returns_X_retained`` can be added to functions, | |
C++ methods, and Objective-C methods and properties. | |
Attributes ``X_consumed`` can be added to parameters of methods, functions, | |
and Objective-C methods. | |
}]; | |
} | |
def NoDebugDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``nodebug`` attribute allows you to suppress debugging information for a | |
function or method, for a variable that is not a parameter or a non-static | |
data member, or for a typedef or using declaration. | |
}]; | |
} | |
def StandaloneDebugDocs : Documentation { | |
let Category = DocCatVariable; | |
let Content = [{ | |
The ``standalone_debug`` attribute causes debug info to be emitted for a record | |
type regardless of the debug info optimizations that are enabled with | |
-fno-standalone-debug. This attribute only has an effect when debug info | |
optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only. | |
}]; | |
} | |
def NoDuplicateDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``noduplicate`` attribute can be placed on function declarations to control | |
whether function calls to this function can be duplicated or not as a result of | |
optimizations. This is required for the implementation of functions with | |
certain special requirements, like the OpenCL "barrier" function, that might | |
need to be run concurrently by all the threads that are executing in lockstep | |
on the hardware. For example this attribute applied on the function | |
"nodupfunc" in the code below avoids that: | |
.. code-block:: c | |
void nodupfunc() __attribute__((noduplicate)); | |
// Setting it as a C++11 attribute is also valid | |
// void nodupfunc() [[clang::noduplicate]]; | |
void foo(); | |
void bar(); | |
nodupfunc(); | |
if (a > n) { | |
foo(); | |
} else { | |
bar(); | |
} | |
gets possibly modified by some optimizations into code similar to this: | |
.. code-block:: c | |
if (a > n) { | |
nodupfunc(); | |
foo(); | |
} else { | |
nodupfunc(); | |
bar(); | |
} | |
where the call to "nodupfunc" is duplicated and sunk into the two branches | |
of the condition. | |
}]; | |
} | |
def ConvergentDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``convergent`` attribute can be placed on a function declaration. It is | |
translated into the LLVM ``convergent`` attribute, which indicates that the call | |
instructions of a function with this attribute cannot be made control-dependent | |
on any additional values. | |
In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA, | |
the call instructions of a function with this attribute must be executed by | |
all work items or threads in a work group or sub group. | |
This attribute is different from ``noduplicate`` because it allows duplicating | |
function calls if it can be proved that the duplicated function calls are | |
not made control-dependent on any additional values, e.g., unrolling a loop | |
executed by all work items. | |
Sample usage: | |
.. code-block:: c | |
void convfunc(void) __attribute__((convergent)); | |
// Setting it as a C++11 attribute is also valid in a C++ program. | |
// void convfunc(void) [[clang::convergent]]; | |
}]; | |
} | |
def NoSplitStackDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``no_split_stack`` attribute disables the emission of the split stack | |
preamble for a particular function. It has no effect if ``-fsplit-stack`` | |
is not specified. | |
}]; | |
} | |
def NoUniqueAddressDocs : Documentation { | |
let Category = DocCatField; | |
let Content = [{ | |
The ``no_unique_address`` attribute allows tail padding in a non-static data | |
member to overlap other members of the enclosing class (and in the special | |
case when the type is empty, permits it to fully overlap other members). | |
The field is laid out as if a base class were encountered at the corresponding | |
point within the class (except that it does not share a vptr with the enclosing | |
object). | |
Example usage: | |
.. code-block:: c++ | |
template<typename T, typename Alloc> struct my_vector { | |
T *p; | |
[[no_unique_address]] Alloc alloc; | |
// ... | |
}; | |
static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*)); | |
``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use | |
in C++11 onwards. | |
}]; | |
} | |
def ObjCRequiresSuperDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Some Objective-C classes allow a subclass to override a particular method in a | |
parent class but expect that the overriding method also calls the overridden | |
method in the parent class. For these cases, we provide an attribute to | |
designate that a method requires a "call to ``super``" in the overriding | |
method in the subclass. | |
**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only | |
be placed at the end of a method declaration: | |
.. code-block:: objc | |
- (void)foo __attribute__((objc_requires_super)); | |
This attribute can only be applied the method declarations within a class, and | |
not a protocol. Currently this attribute does not enforce any placement of | |
where the call occurs in the overriding method (such as in the case of | |
``-dealloc`` where the call must appear at the end). It checks only that it | |
exists. | |
Note that on both OS X and iOS that the Foundation framework provides a | |
convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this | |
attribute: | |
.. code-block:: objc | |
- (void)foo NS_REQUIRES_SUPER; | |
This macro is conditionally defined depending on the compiler's support for | |
this attribute. If the compiler does not support the attribute the macro | |
expands to nothing. | |
Operationally, when a method has this annotation the compiler will warn if the | |
implementation of an override in a subclass does not call super. For example: | |
.. code-block:: objc | |
warning: method possibly missing a [super AnnotMeth] call | |
- (void) AnnotMeth{}; | |
^ | |
}]; | |
} | |
def ObjCRuntimeNameDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
By default, the Objective-C interface or protocol identifier is used | |
in the metadata name for that object. The ``objc_runtime_name`` | |
attribute allows annotated interfaces or protocols to use the | |
specified string argument in the object's metadata name instead of the | |
default name. | |
**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute | |
can only be placed before an @protocol or @interface declaration: | |
.. code-block:: objc | |
__attribute__((objc_runtime_name("MyLocalName"))) | |
@interface Message | |
@end | |
}]; | |
} | |
def ObjCRuntimeVisibleDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
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. | |
}]; | |
} | |
def ObjCClassStubDocs : Documentation { | |
let Category = DocCatType; | |
let Content = [{ | |
This attribute specifies that the Objective-C class to which it applies is | |
instantiated at runtime. | |
Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute | |
still has a "class stub" that is visible to the linker. This allows categories | |
to be defined. Static message sends with the class as a receiver use a special | |
access pattern to ensure the class is lazily instantiated from the class stub. | |
Classes annotated with this attribute cannot be subclassed and cannot have | |
implementations defined for them. This attribute is intended for use in | |
Swift-generated headers for classes defined in Swift. | |
Adding or removing this attribute to a class is an ABI-breaking change. | |
}]; | |
} | |
def ObjCBoxableDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
Structs and unions marked with the ``objc_boxable`` attribute can be used | |
with the Objective-C boxed expression syntax, ``@(...)``. | |
**Usage**: ``__attribute__((objc_boxable))``. This attribute | |
can only be placed on a declaration of a trivially-copyable struct or union: | |
.. code-block:: objc | |
struct __attribute__((objc_boxable)) some_struct { | |
int i; | |
}; | |
union __attribute__((objc_boxable)) some_union { | |
int i; | |
float f; | |
}; | |
typedef struct __attribute__((objc_boxable)) _some_struct some_struct; | |
// ... | |
some_struct ss; | |
NSValue *boxed = @(ss); | |
}]; | |
} | |
def AvailabilityDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``availability`` attribute can be placed on declarations to describe the | |
lifecycle of that declaration relative to operating system versions. Consider | |
the function declaration for a hypothetical function ``f``: | |
.. code-block:: c++ | |
void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7))); | |
The availability attribute states that ``f`` was introduced in macOS 10.4, | |
deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information | |
is used by Clang to determine when it is safe to use ``f``: for example, if | |
Clang is instructed to compile code for macOS 10.5, a call to ``f()`` | |
succeeds. If Clang is instructed to compile code for macOS 10.6, the call | |
succeeds but Clang emits a warning specifying that the function is deprecated. | |
Finally, if Clang is instructed to compile code for macOS 10.7, the call | |
fails because ``f()`` is no longer available. | |
The availability attribute is a comma-separated list starting with the | |
platform name and then including clauses specifying important milestones in the | |
declaration's lifetime (in any order) along with additional information. Those | |
clauses can be: | |
introduced=\ *version* | |
The first version in which this declaration was introduced. | |
deprecated=\ *version* | |
The first version in which this declaration was deprecated, meaning that | |
users should migrate away from this API. | |
obsoleted=\ *version* | |
The first version in which this declaration was obsoleted, meaning that it | |
was removed completely and can no longer be used. | |
unavailable | |
This declaration is never available on this platform. | |
message=\ *string-literal* | |
Additional message text that Clang will provide when emitting a warning or | |
error about use of a deprecated or obsoleted declaration. Useful to direct | |
users to replacement APIs. | |
replacement=\ *string-literal* | |
Additional message text that Clang will use to provide Fix-It when emitting | |
a warning about use of a deprecated declaration. The Fix-It will replace | |
the deprecated declaration with the new declaration specified. | |
Multiple availability attributes can be placed on a declaration, which may | |
correspond to different platforms. For most platforms, the availability | |
attribute with the platform corresponding to the target platform will be used; | |
any others will be ignored. However, the availability for ``watchOS`` and | |
``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute. | |
Any explicit availability attributes for those platforms are still preferred over | |
the implicitly inferred availability attributes. If no availability attribute | |
specifies availability for the current target platform, the availability | |
attributes are ignored. Supported platforms are: | |
``ios`` | |
Apple's iOS operating system. The minimum deployment target is specified by | |
the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` | |
command-line arguments. | |
``macos`` | |
Apple's macOS operating system. The minimum deployment target is | |
specified by the ``-mmacosx-version-min=*version*`` command-line argument. | |
``macosx`` is supported for backward-compatibility reasons, but it is | |
deprecated. | |
``tvos`` | |
Apple's tvOS operating system. The minimum deployment target is specified by | |
the ``-mtvos-version-min=*version*`` command-line argument. | |
``watchos`` | |
Apple's watchOS operating system. The minimum deployment target is specified by | |
the ``-mwatchos-version-min=*version*`` command-line argument. | |
``driverkit`` | |
Apple's DriverKit userspace kernel extensions. The minimum deployment target | |
is specified as part of the triple. | |
A declaration can typically be used even when deploying back to a platform | |
version prior to when the declaration was introduced. When this happens, the | |
declaration is `weakly linked | |
<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, | |
as if the ``weak_import`` attribute were added to the declaration. A | |
weakly-linked declaration may or may not be present a run-time, and a program | |
can determine whether the declaration is present by checking whether the | |
address of that declaration is non-NULL. | |
The flag ``strict`` disallows using API when deploying back to a | |
platform version prior to when the declaration was introduced. An | |
attempt to use such API before its introduction causes a hard error. | |
Weakly-linking is almost always a better API choice, since it allows | |
users to query availability at runtime. | |
If there are multiple declarations of the same entity, the availability | |
attributes must either match on a per-platform basis or later | |
declarations must not have availability attributes for that | |
platform. For example: | |
.. code-block:: c | |
void g(void) __attribute__((availability(macos,introduced=10.4))); | |
void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches | |
void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform | |
void g(void); // okay, inherits both macos and ios availability from above. | |
void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch | |
When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: | |
.. code-block:: objc | |
@interface A | |
- (id)method __attribute__((availability(macos,introduced=10.4))); | |
- (id)method2 __attribute__((availability(macos,introduced=10.4))); | |
@end | |
@interface B : A | |
- (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later | |
- (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4 | |
@end | |
Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from | |
``<os/availability.h>`` can simplify the spelling: | |
.. code-block:: objc | |
@interface A | |
- (id)method API_AVAILABLE(macos(10.11))); | |
- (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0)); | |
@end | |
Availability attributes can also be applied using a ``#pragma clang attribute``. | |
Any explicit availability attribute whose platform corresponds to the target | |
platform is applied to a declaration regardless of the availability attributes | |
specified in the pragma. For example, in the code below, | |
``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability | |
attribute that is specified with the declaration, whereas | |
``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability | |
attribute that is applied by the pragma. | |
.. code-block:: c | |
#pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function) | |
void getsThePragmaAvailabilityAttribute(void); | |
void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4))); | |
#pragma clang attribute pop | |
For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can | |
be implicitly inferred from an ``iOS`` availability attribute, the logic is | |
slightly more complex. The explicit and the pragma-applied availability | |
attributes whose platform corresponds to the target platform are applied as | |
described in the previous paragraph. However, the implicitly inferred attributes | |
are applied to a declaration only when there is no explicit or pragma-applied | |
availability attribute whose platform corresponds to the target platform. For | |
example, the function below will receive the ``tvOS`` availability from the | |
pragma rather than using the inferred ``iOS`` availability from the declaration: | |
.. code-block:: c | |
#pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function) | |
void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0))); | |
#pragma clang attribute pop | |
The compiler is also able to apply implicitly inferred attributes from a pragma | |
as well. For example, when targeting ``tvOS``, the function below will receive | |
a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS`` | |
availability attribute applied by the pragma: | |
.. code-block:: c | |
#pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function) | |
void infersTVOSAvailabilityFromPragma(void); | |
#pragma clang attribute pop | |
The implicit attributes that are inferred from explicitly specified attributes | |
whose platform corresponds to the target platform are applied to the declaration | |
even if there is an availability attribute that can be inferred from a pragma. | |
For example, the function below will receive the ``tvOS, introduced=11.0`` | |
availability that is inferred from the attribute on the declaration rather than | |
inferring availability from the pragma: | |
.. code-block:: c | |
#pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function) | |
void infersTVOSAvailabilityFromAttributeNextToDeclaration(void) | |
__attribute__((availability(iOS,introduced=11.0))); | |
#pragma clang attribute pop | |
Also see the documentation for `@available | |
<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_ | |
}]; | |
} | |
def ExternalSourceSymbolDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
The ``external_source_symbol`` attribute specifies that a declaration originates | |
from an external source and describes the nature of that source. | |
The fact that Clang is capable of recognizing declarations that were defined | |
externally can be used to provide better tooling support for mixed-language | |
projects or projects that rely on auto-generated code. For instance, an IDE that | |
uses Clang and that supports mixed-language projects can use this attribute to | |
provide a correct 'jump-to-definition' feature. For a concrete example, | |
consider a protocol that's defined in a Swift file: | |
.. code-block:: swift | |
@objc public protocol SwiftProtocol { | |
func method() | |
} | |
This protocol can be used from Objective-C code by including a header file that | |
was generated by the Swift compiler. The declarations in that header can use | |
the ``external_source_symbol`` attribute to make Clang aware of the fact | |
that ``SwiftProtocol`` actually originates from a Swift module: | |
.. code-block:: objc | |
__attribute__((external_source_symbol(language="Swift",defined_in="module"))) | |
@protocol SwiftProtocol | |
@required | |
- (void) method; | |
@end | |
Consequently, when 'jump-to-definition' is performed at a location that | |
references ``SwiftProtocol``, the IDE can jump to the original definition in | |
the Swift source file rather than jumping to the Objective-C declaration in the | |
auto-generated header file. | |
The ``external_source_symbol`` attribute is a comma-separated list that includes | |
clauses that describe the origin and the nature of the particular declaration. | |
Those clauses can be: | |
language=\ *string-literal* | |
The name of the source language in which this declaration was defined. | |
defined_in=\ *string-literal* | |
The name of the source container in which the declaration was defined. The | |
exact definition of source container is language-specific, e.g. Swift's | |
source containers are modules, so ``defined_in`` should specify the Swift | |
module name. | |
USR=\ *string-literal* | |
String that specifies a unified symbol resolution (USR) value for this | |
declaration. USR string uniquely identifies this particular declaration, and | |
is typically used when constructing an index of a codebase. | |
The USR value in this attribute is expected to be generated by an external | |
compiler that compiled the native declaration using its original source | |
language. The exact format of the USR string and its other attributes | |
are determined by the specification of this declaration's source language. | |
When not specified, Clang's indexer will use the Clang USR for this symbol. | |
User can query to see if Clang supports the use of the ``USR`` clause in | |
the ``external_source_symbol`` attribute with | |
``__has_attribute(external_source_symbol) >= 20230206``. | |
generated_declaration | |
This declaration was automatically generated by some tool. | |
The clauses can be specified in any order. The clauses that are listed above are | |
all optional, but the attribute has to have at least one clause. | |
}]; | |
} | |
def ConstInitDocs : Documentation { | |
let Category = DocCatVariable; | |
let Heading = "require_constant_initialization, constinit (C++20)"; | |
let Content = [{ | |
This attribute specifies that the variable to which it is attached is intended | |
to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_ | |
according to the rules of [basic.start.static]. The variable is required to | |
have static or thread storage duration. If the initialization of the variable | |
is not a constant initializer an error will be produced. This attribute may | |
only be used in C++; the ``constinit`` spelling is only accepted in C++20 | |
onwards. | |
Note that in C++03 strict constant expression checking is not done. Instead | |
the attribute reports if Clang can emit the variable as a constant, even if it's | |
not technically a 'constant initializer'. This behavior is non-portable. | |
Static storage duration variables with constant initializers avoid hard-to-find | |
bugs caused by the indeterminate order of dynamic initialization. They can also | |
be safely used during dynamic initialization across translation units. | |
This attribute acts as a compile time assertion that the requirements | |
for constant initialization have been met. Since these requirements change | |
between dialects and have subtle pitfalls it's important to fail fast instead | |
of silently falling back on dynamic initialization. | |
The first use of the attribute on a variable must be part of, or precede, the | |
initializing declaration of the variable. C++20 requires the ``constinit`` | |
spelling of the attribute to be present on the initializing declaration if it | |
is used anywhere. The other spellings can be specified on a forward declaration | |
and omitted on a later initializing declaration. | |
.. code-block:: c++ | |
// -std=c++14 | |
#define SAFE_STATIC [[clang::require_constant_initialization]] | |
struct T { | |
constexpr T(int) {} | |
~T(); // non-trivial | |
}; | |
SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor. | |
SAFE_STATIC T y = 42; // error: variable does not have a constant initializer | |
// copy initialization is not a constant expression on a non-literal type. | |
}]; | |
} | |
def WarnMaybeUnusedDocs : Documentation { | |
let Category = DocCatVariable; | |
let Heading = "maybe_unused, unused"; | |
let Content = [{ | |
When passing the ``-Wunused`` flag to Clang, entities that are unused by the | |
program may be diagnosed. The ``[[maybe_unused]]`` (or | |
``__attribute__((unused))``) attribute can be used to silence such diagnostics | |
when the entity cannot be removed. For instance, a local variable may exist | |
solely for use in an ``assert()`` statement, which makes the local variable | |
unused when ``NDEBUG`` is defined. | |
The attribute may be applied to the declaration of a class, a typedef, a | |
variable, a function or method, a function parameter, an enumeration, an | |
enumerator, a non-static data member, or a label. | |
.. code-block: c++ | |
#include <cassert> | |
[[maybe_unused]] void f([[maybe_unused]] bool thing1, | |
[[maybe_unused]] bool thing2) { | |
[[maybe_unused]] bool b = thing1 && thing2; | |
assert(b); | |
} | |
}]; | |
} | |
def WarnUnusedResultsDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "nodiscard, warn_unused_result"; | |
let Content = [{ | |
Clang supports the ability to diagnose when the results of a function call | |
expression are discarded under suspicious circumstances. A diagnostic is | |
generated when a function or its return type is marked with ``[[nodiscard]]`` | |
(or ``__attribute__((warn_unused_result))``) and the function call appears as a | |
potentially-evaluated discarded-value expression that is not explicitly cast to | |
``void``. | |
A string literal may optionally be provided to the attribute, which will be | |
reproduced in any resulting diagnostics. Redeclarations using different forms | |
of the attribute (with or without the string literal or with different string | |
literal contents) are allowed. If there are redeclarations of the entity with | |
differing string literals, it is unspecified which one will be used by Clang | |
in any resulting diagnostics. | |
.. code-block: c++ | |
struct [[nodiscard]] error_info { /*...*/ }; | |
error_info enable_missile_safety_mode(); | |
void launch_missiles(); | |
void test_missiles() { | |
enable_missile_safety_mode(); // diagnoses | |
launch_missiles(); | |
} | |
error_info &foo(); | |
void f() { foo(); } // Does not diagnose, error_info is a reference. | |
Additionally, discarded temporaries resulting from a call to a constructor | |
marked with ``[[nodiscard]]`` or a constructor of a type marked | |
``[[nodiscard]]`` will also diagnose. This also applies to type conversions that | |
use the annotated ``[[nodiscard]]`` constructor or result in an annotated type. | |
.. code-block: c++ | |
struct [[nodiscard]] marked_type {/*..*/ }; | |
struct marked_ctor { | |
[[nodiscard]] marked_ctor(); | |
marked_ctor(int); | |
}; | |
struct S { | |
operator marked_type() const; | |
[[nodiscard]] operator int() const; | |
}; | |
void usages() { | |
marked_type(); // diagnoses. | |
marked_ctor(); // diagnoses. | |
marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard. | |
S s; | |
static_cast<marked_type>(s); // diagnoses | |
(int)s; // diagnoses | |
} | |
}]; | |
} | |
def FallthroughDocs : Documentation { | |
let Category = DocCatStmt; | |
let Heading = "fallthrough"; | |
let Content = [{ | |
The ``fallthrough`` (or ``clang::fallthrough``) attribute is used | |
to annotate intentional fall-through | |
between switch labels. It can only be applied to a null statement placed at a | |
point of execution between any statement and the next switch label. It is | |
common to mark these places with a specific comment, but this attribute is | |
meant to replace comments with a more strict annotation, which can be checked | |
by the compiler. This attribute doesn't change semantics of the code and can | |
be used wherever an intended fall-through occurs. It is designed to mimic | |
control-flow statements like ``break;``, so it can be placed in most places | |
where ``break;`` can, but only if there are no statements on the execution path | |
between it and the next switch label. | |
By default, Clang does not warn on unannotated fallthrough from one ``switch`` | |
case to another. Diagnostics on fallthrough without a corresponding annotation | |
can be enabled with the ``-Wimplicit-fallthrough`` argument. | |
Here is an example: | |
.. code-block:: c++ | |
// compile with -Wimplicit-fallthrough | |
switch (n) { | |
case 22: | |
case 33: // no warning: no statements between case labels | |
f(); | |
case 44: // warning: unannotated fall-through | |
g(); | |
[[clang::fallthrough]]; | |
case 55: // no warning | |
if (x) { | |
h(); | |
break; | |
} | |
else { | |
i(); | |
[[clang::fallthrough]]; | |
} | |
case 66: // no warning | |
p(); | |
[[clang::fallthrough]]; // warning: fallthrough annotation does not | |
// directly precede case label | |
q(); | |
case 77: // warning: unannotated fall-through | |
r(); | |
} | |
}]; | |
} | |
def LikelihoodDocs : Documentation { | |
let Category = DocCatStmt; | |
let Heading = "likely and unlikely"; | |
let Content = [{ | |
The ``likely`` and ``unlikely`` attributes are used as compiler hints. | |
The attributes are used to aid the compiler to determine which branch is | |
likely or unlikely to be taken. This is done by marking the branch substatement | |
with one of the two attributes. | |
It isn't allowed to annotate a single statement with both ``likely`` and | |
``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if`` | |
statement with the same likelihood attribute will result in a diagnostic and | |
the attributes are ignored on both branches. | |
In a ``switch`` statement it's allowed to annotate multiple ``case`` labels | |
or the ``default`` label with the same likelihood attribute. This makes | |
* all labels without an attribute have a neutral likelihood, | |
* all labels marked ``[[likely]]`` have an equally positive likelihood, and | |
* all labels marked ``[[unlikely]]`` have an equally negative likelihood. | |
The neutral likelihood is the more likely of path execution than the negative | |
likelihood. The positive likelihood is the more likely of path of execution | |
than the neutral likelihood. | |
These attributes have no effect on the generated code when using | |
PGO (Profile-Guided Optimization) or at optimization level 0. | |
In Clang, the attributes will be ignored if they're not placed on | |
* the ``case`` or ``default`` label of a ``switch`` statement, | |
* or on the substatement of an ``if`` or ``else`` statement, | |
* or on the substatement of an ``for`` or ``while`` statement. | |
The C++ Standard recommends to honor them on every statement in the | |
path of execution, but that can be confusing: | |
.. code-block:: c++ | |
if (b) { | |
[[unlikely]] --b; // In the path of execution, | |
// this branch is considered unlikely. | |
} | |
if (b) { | |
--b; | |
if(b) | |
return; | |
[[unlikely]] --b; // Not in the path of execution, | |
} // the branch has no likelihood information. | |
if (b) { | |
--b; | |
foo(b); | |
// Whether or not the next statement is in the path of execution depends | |
// on the declaration of foo(): | |
// In the path of execution: void foo(int); | |
// Not in the path of execution: [[noreturn]] void foo(int); | |
// This means the likelihood of the branch depends on the declaration | |
// of foo(). | |
[[unlikely]] --b; | |
} | |
Below are some example usages of the likelihood attributes and their effects: | |
.. code-block:: c++ | |
if (b) [[likely]] { // Placement on the first statement in the branch. | |
// The compiler will optimize to execute the code here. | |
} else { | |
} | |
if (b) | |
[[unlikely]] b++; // Placement on the first statement in the branch. | |
else { | |
// The compiler will optimize to execute the code here. | |
} | |
if (b) { | |
[[unlikely]] b++; // Placement on the second statement in the branch. | |
} // The attribute will be ignored. | |
if (b) [[likely]] { | |
[[unlikely]] b++; // No contradiction since the second attribute | |
} // is ignored. | |
if (b) | |
; | |
else [[likely]] { | |
// The compiler will optimize to execute the code here. | |
} | |
if (b) | |
; | |
else | |
// The compiler will optimize to execute the next statement. | |
[[likely]] b = f(); | |
if (b) [[likely]]; // Both branches are likely. A diagnostic is issued | |
else [[likely]]; // and the attributes are ignored. | |
if (b) | |
[[likely]] int i = 5; // Issues a diagnostic since the attribute | |
// isn't allowed on a declaration. | |
switch (i) { | |
[[likely]] case 1: // This value is likely | |
... | |
break; | |
[[unlikely]] case 2: // This value is unlikely | |
... | |
[[fallthrough]]; | |
case 3: // No likelihood attribute | |
... | |
[[likely]] break; // No effect | |
case 4: [[likely]] { // attribute on substatement has no effect | |
... | |
break; | |
} | |
[[unlikely]] default: // All other values are unlikely | |
... | |
break; | |
} | |
switch (i) { | |
[[likely]] case 0: // This value and code path is likely | |
... | |
[[fallthrough]]; | |
case 1: // No likelihood attribute, code path is neutral | |
break; // falling through has no effect on the likelihood | |
case 2: // No likelihood attribute, code path is neutral | |
[[fallthrough]]; | |
[[unlikely]] default: // This value and code path are both unlikely | |
break; | |
} | |
for(int i = 0; i != size; ++i) [[likely]] { | |
... // The loop is the likely path of execution | |
} | |
for(const auto &E : Elements) [[likely]] { | |
... // The loop is the likely path of execution | |
} | |
while(i != size) [[unlikely]] { | |
... // The loop is the unlikely path of execution | |
} // The generated code will optimize to skip the loop body | |
while(true) [[unlikely]] { | |
... // The attribute has no effect | |
} // Clang elides the comparison and generates an infinite | |
// loop | |
}]; | |
} | |
def ARMInterruptDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "interrupt (ARM)"; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on | |
ARM targets. This attribute may be attached to a function definition and | |
instructs the backend to generate appropriate function entry/exit code so that | |
it can be used directly as an interrupt service routine. | |
The parameter passed to the interrupt attribute is optional, but if | |
provided it must be a string literal with one of the following values: "IRQ", | |
"FIQ", "SWI", "ABORT", "UNDEF". | |
The semantics are as follows: | |
- If the function is AAPCS, Clang instructs the backend to realign the stack to | |
8 bytes on entry. This is a general requirement of the AAPCS at public | |
interfaces, but may not hold when an exception is taken. Doing this allows | |
other AAPCS functions to be called. | |
- If the CPU is M-class this is all that needs to be done since the architecture | |
itself is designed in such a way that functions obeying the normal AAPCS ABI | |
constraints are valid exception handlers. | |
- If the CPU is not M-class, the prologue and epilogue are modified to save all | |
non-banked registers that are used, so that upon return the user-mode state | |
will not be corrupted. Note that to avoid unnecessary overhead, only | |
general-purpose (integer) registers are saved in this way. If VFP operations | |
are needed, that state must be saved manually. | |
Specifically, interrupt kinds other than "FIQ" will save all core registers | |
except "lr" and "sp". "FIQ" interrupts will save r0-r7. | |
- If the CPU is not M-class, the return instruction is changed to one of the | |
canonical sequences permitted by the architecture for exception return. Where | |
possible the function itself will make the necessary "lr" adjustments so that | |
the "preferred return address" is selected. | |
Unfortunately the compiler is unable to make this guarantee for an "UNDEF" | |
handler, where the offset from "lr" to the preferred return address depends on | |
the execution state of the code which generated the exception. In this case | |
a sequence equivalent to "movs pc, lr" will be used. | |
}]; | |
} | |
def BPFPreserveAccessIndexDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the ``__attribute__((preserve_access_index))`` | |
attribute for the BPF target. This attribute may be attached to a | |
struct or union declaration, where if -g is specified, it enables | |
preserving struct or union member access debuginfo indices of this | |
struct or union, similar to clang ``__builtin_preserve_access_index()``. | |
}]; | |
} | |
def BTFDeclTagDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for | |
all targets. This attribute may be attached to a struct/union, struct/union | |
field, function, function parameter, variable or typedef declaration. If -g is | |
specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to | |
dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF | |
section too. | |
}]; | |
} | |
def BTFTypeTagDocs : Documentation { | |
let Category = DocCatType; | |
let Content = [{ | |
Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for | |
all targets. It only has effect when ``-g`` is specified on the command line and | |
is currently silently ignored when not applied to a pointer type (note: this | |
scenario may be diagnosed in the future). | |
The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the | |
types used in variable declarations, function declarations, or typedef | |
declarations. | |
For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF | |
section. | |
}]; | |
} | |
def MipsInterruptDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "interrupt (MIPS)"; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on | |
MIPS targets. This attribute may be attached to a function definition and instructs | |
the backend to generate appropriate function entry/exit code so that it can be used | |
directly as an interrupt service routine. | |
By default, the compiler will produce a function prologue and epilogue suitable for | |
an interrupt service routine that handles an External Interrupt Controller (eic) | |
generated interrupt. This behavior can be explicitly requested with the "eic" | |
argument. | |
Otherwise, for use with vectored interrupt mode, the argument passed should be | |
of the form "vector=LEVEL" where LEVEL is one of the following values: | |
"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will | |
then set the interrupt mask to the corresponding level which will mask all | |
interrupts up to and including the argument. | |
The semantics are as follows: | |
- The prologue is modified so that the Exception Program Counter (EPC) and | |
Status coprocessor registers are saved to the stack. The interrupt mask is | |
set so that the function can only be interrupted by a higher priority | |
interrupt. The epilogue will restore the previous values of EPC and Status. | |
- The prologue and epilogue are modified to save and restore all non-kernel | |
registers as necessary. | |
- The FPU is disabled in the prologue, as the floating pointer registers are not | |
spilled to the stack. | |
- The function return sequence is changed to use an exception return instruction. | |
- The parameter sets the interrupt mask for the function corresponding to the | |
interrupt level specified. If no mask is specified the interrupt mask | |
defaults to "eic". | |
}]; | |
} | |
def MicroMipsDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((micromips))`` and | |
``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes | |
may be attached to a function definition and instructs the backend to generate | |
or not to generate microMIPS code for that function. | |
These attributes override the ``-mmicromips`` and ``-mno-micromips`` options | |
on the command line. | |
}]; | |
} | |
def MipsLongCallStyleDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "long_call, far"; | |
let Content = [{ | |
Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, | |
and ``__attribute__((near))`` attributes on MIPS targets. These attributes may | |
only be added to function declarations and change the code generated | |
by the compiler when directly calling the function. The ``near`` attribute | |
allows calls to the function to be made using the ``jal`` instruction, which | |
requires the function to be located in the same naturally aligned 256MB | |
segment as the caller. The ``long_call`` and ``far`` attributes are synonyms | |
and require the use of a different call sequence that works regardless | |
of the distance between the functions. | |
These attributes have no effect for position-independent code. | |
These attributes take priority over command line switches such | |
as ``-mlong-calls`` and ``-mno-long-calls``. | |
}]; | |
} | |
def MipsShortCallStyleDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "short_call, near"; | |
let Content = [{ | |
Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``, | |
``__attribute__((short__call))``, and ``__attribute__((near))`` attributes | |
on MIPS targets. These attributes may only be added to function declarations | |
and change the code generated by the compiler when directly calling | |
the function. The ``short_call`` and ``near`` attributes are synonyms and | |
allow calls to the function to be made using the ``jal`` instruction, which | |
requires the function to be located in the same naturally aligned 256MB segment | |
as the caller. The ``long_call`` and ``far`` attributes are synonyms and | |
require the use of a different call sequence that works regardless | |
of the distance between the functions. | |
These attributes have no effect for position-independent code. | |
These attributes take priority over command line switches such | |
as ``-mlong-calls`` and ``-mno-long-calls``. | |
}]; | |
} | |
def RISCVInterruptDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "interrupt (RISC-V)"; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV | |
targets. This attribute may be attached to a function definition and instructs | |
the backend to generate appropriate function entry/exit code so that it can be | |
used directly as an interrupt service routine. | |
Permissible values for this parameter are ``user``, ``supervisor``, | |
and ``machine``. If there is no parameter, then it defaults to machine. | |
Repeated interrupt attribute on the same declaration will cause a warning | |
to be emitted. In case of repeated declarations, the last one prevails. | |
Refer to: | |
https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html | |
https://riscv.org/specifications/privileged-isa/ | |
The RISC-V Instruction Set Manual Volume II: Privileged Architecture | |
Version 1.10. | |
}]; | |
} | |
def RISCVRVVVectorBitsDocs : Documentation { | |
let Category = DocCatType; | |
let Content = [{ | |
On RISC-V targets, the ``riscv_rvv_vector_bits(N)`` attribute is used to define | |
fixed-length variants of sizeless types. | |
For example: | |
.. code-block:: c | |
#include <riscv_vector.h> | |
#if defined(__riscv_v_fixed_vlen) | |
typedef vint8m1_t fixed_vint8m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen))); | |
#endif | |
Creates a type ``fixed_vint8m1_t_t`` that is a fixed-length variant of | |
``vint8m1_t`` that contains exactly 512 bits. Unlike ``vint8m1_t``, this type | |
can be used in globals, structs, unions, and arrays, all of which are | |
unsupported for sizeless types. | |
The attribute can be attached to a single RVV vector (such as ``vint8m1_t``). | |
The attribute will be rejected unless | |
``N==(__riscv_v_fixed_vlen*LMUL)``, the implementation defined feature macro that | |
is enabled under the ``-mrvv-vector-bits`` flag. ``__riscv_v_fixed_vlen`` can | |
only be a power of 2 between 64 and 65536. | |
For types where LMUL!=1, ``__riscv_v_fixed_vlen`` needs to be scaled by the LMUL | |
of the type before passing to the attribute. | |
``vbool*_t`` types are not supported at this time. | |
}]; | |
} | |
def AVRInterruptDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "interrupt (AVR)"; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((interrupt))`` attribute on | |
AVR targets. This attribute may be attached to a function definition and instructs | |
the backend to generate appropriate function entry/exit code so that it can be used | |
directly as an interrupt service routine. | |
On the AVR, the hardware globally disables interrupts when an interrupt is executed. | |
The first instruction of an interrupt handler declared with this attribute is a SEI | |
instruction to re-enable interrupts. See also the signal attribute that | |
does not insert a SEI instruction. | |
}]; | |
} | |
def AVRSignalDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((signal))`` attribute on | |
AVR targets. This attribute may be attached to a function definition and instructs | |
the backend to generate appropriate function entry/exit code so that it can be used | |
directly as an interrupt service routine. | |
Interrupt handler functions defined with the signal attribute do not re-enable interrupts. | |
}]; | |
} | |
def TargetDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute. | |
This attribute may be attached to a function definition and instructs | |
the backend to use different code generation options than were passed on the | |
command line. | |
The current set of options correspond to the existing "subtarget features" for | |
the target with or without a "-mno-" in front corresponding to the absence | |
of the feature, as well as ``arch="CPU"`` which will change the default "CPU" | |
for the function. | |
For X86, the attribute also allows ``tune="CPU"`` to optimize the generated | |
code for the given CPU without changing the available instructions. | |
For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march | |
command line options. ``cpu="CPU"`` can be used to select a specific cpu, | |
as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the | |
"branch-protection=<args>" option, where the permissible arguments and their | |
effect on code generation are the same as for the command-line option | |
``-mbranch-protection``. | |
Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", | |
"avx", "xop" and largely correspond to the machine specific options handled by | |
the front end. | |
Additionally, this attribute supports function multiversioning for ELF based | |
x86/x86-64 targets, which can be used to create multiple implementations of the | |
same function that will be resolved at runtime based on the priority of their | |
``target`` attribute strings. A function is considered a multiversioned function | |
if either two declarations of the function have different ``target`` attribute | |
strings, or if it has a ``target`` attribute string of ``default``. For | |
example: | |
.. code-block:: c++ | |
__attribute__((target("arch=atom"))) | |
void foo() {} // will be called on 'atom' processors. | |
__attribute__((target("default"))) | |
void foo() {} // will be called on any other processors. | |
All multiversioned functions must contain a ``default`` (fallback) | |
implementation, otherwise usages of the function are considered invalid. | |
Additionally, a function may not become multiversioned after its first use. | |
}]; | |
} | |
def TargetVersionDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
For AArch64 target clang supports function multiversioning by | |
``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a | |
function it instructs compiler to emit multiple function versions based on | |
``target_version`` attribute strings, which resolved at runtime depend on their | |
priority and target features availability. One of the versions is always | |
( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can | |
contain dependent features names joined by the "+" sign. | |
}]; | |
} | |
def TargetClonesDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be | |
attached to a function declaration and causes function multiversioning, where | |
multiple versions of the function will be emitted with different code | |
generation options. Additionally, these versions will be resolved at runtime | |
based on the priority of their attribute options. All ``target_clone`` functions | |
are considered multiversioned functions. | |
For AArch64 target: | |
The attribute contains comma-separated strings of target features joined by "+" | |
sign. For example: | |
.. code-block:: c++ | |
__attribute__((target_clones("sha2+memtag2", "fcma+sve2-pmull128"))) | |
void foo() {} | |
For every multiversioned function a ``default`` (fallback) implementation | |
always generated if not specified directly. | |
For x86/x86-64 targets: | |
All multiversioned functions must contain a ``default`` (fallback) | |
implementation, otherwise usages of the function are considered invalid. | |
Additionally, a function may not become multiversioned after its first use. | |
The options to ``target_clones`` can either be a target-specific architecture | |
(specified as ``arch=CPU``), or one of a list of subtarget features. | |
Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", | |
"avx", "xop" and largely correspond to the machine specific options handled by | |
the front end. | |
The versions can either be listed as a comma-separated sequence of string | |
literals or as a single string literal containing a comma-separated list of | |
versions. For compatibility with GCC, the two formats can be mixed. For | |
example, the following will emit 4 versions of the function: | |
.. code-block:: c++ | |
__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default"))) | |
void foo() {} | |
}]; | |
} | |
def MinVectorWidthDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This | |
attribute may be attached to a function and informs the backend that this | |
function desires vectors of at least this width to be generated. Target-specific | |
maximum vector widths still apply. This means even if you ask for something | |
larger than the target supports, you will only get what the target supports. | |
This attribute is meant to be a hint to control target heuristics that may | |
generate narrower vectors than what the target hardware supports. | |
This is currently used by the X86 target to allow some CPUs that support 512-bit | |
vectors to be limited to using 256-bit vectors to avoid frequency penalties. | |
This is currently enabled with the ``-prefer-vector-width=256`` command line | |
option. The ``min_vector_width`` attribute can be used to prevent the backend | |
from trying to split vector operations to match the ``prefer-vector-width``. All | |
X86 vector intrinsics from x86intrin.h already set this attribute. Additionally, | |
use of any of the X86-specific vector builtins will implicitly set this | |
attribute on the calling function. The intent is that explicitly writing vector | |
code using the X86 intrinsics will prevent ``prefer-vector-width`` from | |
affecting the code. | |
}]; | |
} | |
def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">; | |
def AMDGPUFlatWorkGroupSizeDocs : Documentation { | |
let Category = DocCatAMDGPUAttributes; | |
let Content = [{ | |
The flat work-group size is the number of work-items in the work-group size | |
specified when the kernel is dispatched. It is the product of the sizes of the | |
x, y, and z dimension of the work-group. | |
Clang supports the | |
``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the | |
AMDGPU target. This attribute may be attached to a kernel function definition | |
and is an optimization hint. | |
``<min>`` parameter specifies the minimum flat work-group size, and ``<max>`` | |
parameter specifies the maximum flat work-group size (must be greater than | |
``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0`` | |
as ``<min>, <max>`` implies the default behavior (``128, 256``). | |
If specified, the AMDGPU target backend might be able to produce better machine | |
code for barriers and perform scratch promotion by estimating available group | |
segment size. | |
An error will be given if: | |
- Specified values violate subtarget specifications; | |
- Specified values are not compatible with values provided through other | |
attributes. | |
}]; | |
} | |
def AMDGPUWavesPerEUDocs : Documentation { | |
let Category = DocCatAMDGPUAttributes; | |
let Content = [{ | |
A compute unit (CU) is responsible for executing the wavefronts of a work-group. | |
It is composed of one or more execution units (EU), which are responsible for | |
executing the wavefronts. An EU can have enough resources to maintain the state | |
of more than one executing wavefront. This allows an EU to hide latency by | |
switching between wavefronts in a similar way to symmetric multithreading on a | |
CPU. In order to allow the state for multiple wavefronts to fit on an EU, the | |
resources used by a single wavefront have to be limited. For example, the number | |
of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding, | |
but can result in having to spill some register state to memory. | |
Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`` | |
attribute for the AMDGPU target. This attribute may be attached to a kernel | |
function definition and is an optimization hint. | |
``<min>`` parameter specifies the requested minimum number of waves per EU, and | |
*optional* ``<max>`` parameter specifies the requested maximum number of waves | |
per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted, | |
then there is no restriction on the maximum number of waves per EU other than | |
the one dictated by the hardware for which the kernel is compiled. Passing | |
``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits). | |
If specified, this attribute allows an advanced developer to tune the number of | |
wavefronts that are capable of fitting within the resources of an EU. The AMDGPU | |
target backend can use this information to limit resources, such as number of | |
SGPRs, number of VGPRs, size of available group and private memory segments, in | |
such a way that guarantees that at least ``<min>`` wavefronts and at most | |
``<max>`` wavefronts are able to fit within the resources of an EU. Requesting | |
more wavefronts can hide memory latency but limits available registers which | |
can result in spilling. Requesting fewer wavefronts can help reduce cache | |
thrashing, but can reduce memory latency hiding. | |
This attribute controls the machine code generated by the AMDGPU target backend | |
to ensure it is capable of meeting the requested values. However, when the | |
kernel is executed, there may be other reasons that prevent meeting the request, | |
for example, there may be wavefronts from other kernels executing on the EU. | |
An error will be given if: | |
- Specified values violate subtarget specifications; | |
- Specified values are not compatible with values provided through other | |
attributes; | |
- The AMDGPU target backend is unable to create machine code that can meet the | |
request. | |
}]; | |
} | |
def AMDGPUNumSGPRNumVGPRDocs : Documentation { | |
let Category = DocCatAMDGPUAttributes; | |
let Content = [{ | |
Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and | |
``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU | |
target. These attributes may be attached to a kernel function definition and are | |
an optimization hint. | |
If these attributes are specified, then the AMDGPU target backend will attempt | |
to limit the number of SGPRs and/or VGPRs used to the specified value(s). The | |
number of used SGPRs and/or VGPRs may further be rounded up to satisfy the | |
allocation requirements or constraints of the subtarget. Passing ``0`` as | |
``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits). | |
These attributes can be used to test the AMDGPU target backend. It is | |
recommended that the ``amdgpu_waves_per_eu`` attribute be used to control | |
resources such as SGPRs and VGPRs since it is aware of the limits for different | |
subtargets. | |
An error will be given if: | |
- Specified values violate subtarget specifications; | |
- Specified values are not compatible with values provided through other | |
attributes; | |
- The AMDGPU target backend is unable to create machine code that can meet the | |
request. | |
}]; | |
} | |
def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> { | |
let Content = [{ | |
Clang supports several different calling conventions, depending on the target | |
platform and architecture. The calling convention used for a function determines | |
how parameters are passed, how results are returned to the caller, and other | |
low-level details of calling a function. | |
}]; | |
} | |
def PcsDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On ARM targets, this attribute can be used to select calling conventions | |
similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and | |
"aapcs-vfp". | |
}]; | |
} | |
def AArch64VectorPcsDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On AArch64 targets, this attribute changes the calling convention of a | |
function to preserve additional floating-point and Advanced SIMD registers | |
relative to the default calling convention used for AArch64. | |
This means it is more efficient to call such functions from code that performs | |
extensive floating-point and vector calculations, because fewer live SIMD and FP | |
registers need to be saved. This property makes it well-suited for e.g. | |
floating-point or vector math library functions, which are typically leaf | |
functions that require a small number of registers. | |
However, using this attribute also means that it is more expensive to call | |
a function that adheres to the default calling convention from within such | |
a function. Therefore, it is recommended that this attribute is only used | |
for leaf functions. | |
For more information, see the documentation for `aarch64_vector_pcs`_ on | |
the Arm Developer website. | |
.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi | |
}]; | |
} | |
def AArch64SVEPcsDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On AArch64 targets, this attribute changes the calling convention of a | |
function to preserve additional Scalable Vector registers and Scalable | |
Predicate registers relative to the default calling convention used for | |
AArch64. | |
This means it is more efficient to call such functions from code that performs | |
extensive scalable vector and scalable predicate calculations, because fewer | |
live SVE registers need to be saved. This property makes it well-suited for SVE | |
math library functions, which are typically leaf functions that require a small | |
number of registers. | |
However, using this attribute also means that it is more expensive to call | |
a function that adheres to the default calling convention from within such | |
a function. Therefore, it is recommended that this attribute is only used | |
for leaf functions. | |
For more information, see the documentation for `aarch64_sve_pcs` in the | |
ARM C Language Extension (ACLE) documentation. | |
.. _`aarch64_sve_pcs`: https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute | |
}]; | |
} | |
def RegparmDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On 32-bit x86 targets, the regparm attribute causes the compiler to pass | |
the first three integer parameters in EAX, EDX, and ECX instead of on the | |
stack. This attribute has no effect on variadic functions, and all parameters | |
are passed via the stack as normal. | |
}]; | |
} | |
def SysVABIDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On Windows x86_64 targets, this attribute changes the calling convention of a | |
function to match the default convention used on Sys V targets such as Linux, | |
Mac, and BSD. This attribute has no effect on other targets. | |
}]; | |
} | |
def MSABIDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On non-Windows x86_64 targets, this attribute changes the calling convention of | |
a function to match the default convention used on Windows x86_64. This | |
attribute has no effect on Windows targets or non-x86_64 targets. | |
}]; | |
} | |
def StdCallDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On 32-bit x86 targets, this attribute changes the calling convention of a | |
function to clear parameters off of the stack on return. This convention does | |
not support variadic calls or unprototyped functions in C, and has no effect on | |
x86_64 targets. This calling convention is used widely by the Windows API and | |
COM applications. See the documentation for `__stdcall`_ on MSDN. | |
.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx | |
}]; | |
} | |
def FastCallDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On 32-bit x86 targets, this attribute changes the calling convention of a | |
function to use ECX and EDX as register parameters and clear parameters off of | |
the stack on return. This convention does not support variadic calls or | |
unprototyped functions in C, and has no effect on x86_64 targets. This calling | |
convention is supported primarily for compatibility with existing code. Users | |
seeking register parameters should use the ``regparm`` attribute, which does | |
not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN. | |
.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx | |
}]; | |
} | |
def RegCallDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On x86 targets, this attribute changes the calling convention to | |
`__regcall`_ convention. This convention aims to pass as many arguments | |
as possible in registers. It also tries to utilize registers for the | |
return value whenever it is possible. | |
.. _`__regcall`: https://software.intel.com/en-us/node/693069 | |
}]; | |
} | |
def ThisCallDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On 32-bit x86 targets, this attribute changes the calling convention of a | |
function to use ECX for the first parameter (typically the implicit ``this`` | |
parameter of C++ methods) and clear parameters off of the stack on return. This | |
convention does not support variadic calls or unprototyped functions in C, and | |
has no effect on x86_64 targets. See the documentation for `__thiscall`_ on | |
MSDN. | |
.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx | |
}]; | |
} | |
def VectorCallDocs : Documentation { | |
let Category = DocCatCallingConvs; | |
let Content = [{ | |
On 32-bit x86 *and* x86_64 targets, this attribute changes the calling | |
convention of a function to pass vector parameters in SSE registers. | |
On 32-bit x86 targets, this calling convention is similar to ``__fastcall``. | |
The first two integer parameters are passed in ECX and EDX. Subsequent integer | |
parameters are passed in memory, and callee clears the stack. On x86_64 | |
targets, the callee does *not* clear the stack, and integer parameters are | |
passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling | |
convention. | |
On both 32-bit x86 and x86_64 targets, vector and floating point arguments are | |
passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are | |
passed in sequential SSE registers if enough are available. If AVX is enabled, | |
256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that | |
cannot be passed in registers for any reason is passed by reference, which | |
allows the caller to align the parameter memory. | |
See the documentation for `__vectorcall`_ on MSDN for more details. | |
.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx | |
}]; | |
} | |
def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> { | |
let Content = [{ | |
Clang supports additional attributes for checking basic resource management | |
properties, specifically for unique objects that have a single owning reference. | |
The following attributes are currently supported, although **the implementation | |
for these annotations is currently in development and are subject to change.** | |
}]; | |
} | |
def SetTypestateDocs : Documentation { | |
let Category = DocCatConsumed; | |
let Content = [{ | |
Annotate methods that transition an object into a new state with | |
``__attribute__((set_typestate(new_state)))``. The new state must be | |
unconsumed, consumed, or unknown. | |
}]; | |
} | |
def CallableWhenDocs : Documentation { | |
let Category = DocCatConsumed; | |
let Content = [{ | |
Use ``__attribute__((callable_when(...)))`` to indicate what states a method | |
may be called in. Valid states are unconsumed, consumed, or unknown. Each | |
argument to this attribute must be a quoted string. E.g.: | |
``__attribute__((callable_when("unconsumed", "unknown")))`` | |
}]; | |
} | |
def TestTypestateDocs : Documentation { | |
let Category = DocCatConsumed; | |
let Content = [{ | |
Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method | |
returns true if the object is in the specified state.. | |
}]; | |
} | |
def ParamTypestateDocs : Documentation { | |
let Category = DocCatConsumed; | |
let Content = [{ | |
This attribute specifies expectations about function parameters. Calls to an | |
function with annotated parameters will issue a warning if the corresponding | |
argument isn't in the expected state. The attribute is also used to set the | |
initial state of the parameter when analyzing the function's body. | |
}]; | |
} | |
def ReturnTypestateDocs : Documentation { | |
let Category = DocCatConsumed; | |
let Content = [{ | |
The ``return_typestate`` attribute can be applied to functions or parameters. | |
When applied to a function the attribute specifies the state of the returned | |
value. The function's body is checked to ensure that it always returns a value | |
in the specified state. On the caller side, values returned by the annotated | |
function are initialized to the given state. | |
When applied to a function parameter it modifies the state of an argument after | |
a call to the function returns. The function's body is checked to ensure that | |
the parameter is in the expected state before returning. | |
}]; | |
} | |
def ConsumableDocs : Documentation { | |
let Category = DocCatConsumed; | |
let Content = [{ | |
Each ``class`` that uses any of the typestate annotations must first be marked | |
using the ``consumable`` attribute. Failure to do so will result in a warning. | |
This attribute accepts a single parameter that must be one of the following: | |
``unknown``, ``consumed``, or ``unconsumed``. | |
}]; | |
} | |
def NoProfileInstrumentFunctionDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Use the ``no_profile_instrument_function`` attribute on a function declaration | |
to denote that the compiler should not instrument the function with | |
profile-related instrumentation, such as via the | |
``-fprofile-generate`` / ``-fprofile-instr-generate`` / | |
``-fcs-profile-generate`` / ``-fprofile-arcs`` flags. | |
}]; | |
} | |
def NoSanitizeDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Use the ``no_sanitize`` attribute on a function or a global variable | |
declaration to specify that a particular instrumentation or set of | |
instrumentations should not be applied. | |
The attribute takes a list of string literals with the following accepted | |
values: | |
* all values accepted by ``-fno-sanitize=``; | |
* ``coverage``, to disable SanitizerCoverage instrumentation. | |
For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies | |
that AddressSanitizer and ThreadSanitizer should not be applied to the function | |
or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that | |
SanitizerCoverage should not be applied to the function. | |
See :ref:`Controlling Code Generation <controlling-code-generation>` for a | |
full list of supported sanitizer flags. | |
}]; | |
} | |
def DisableSanitizerInstrumentationDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Use the ``disable_sanitizer_instrumentation`` attribute on a function, | |
Objective-C method, or global variable, to specify that no sanitizer | |
instrumentation should be applied. | |
This is not the same as ``__attribute__((no_sanitize(...)))``, which depending | |
on the tool may still insert instrumentation to prevent false positive reports. | |
}]; | |
} | |
def NoSanitizeAddressDocs : Documentation { | |
let Category = DocCatFunction; | |
// This function has multiple distinct spellings, and so it requires a custom | |
// heading to be specified. The most common spelling is sufficient. | |
let Heading = "no_sanitize_address, no_address_safety_analysis"; | |
let Content = [{ | |
.. _langext-address_sanitizer: | |
Use ``__attribute__((no_sanitize_address))`` on a function or a global | |
variable declaration to specify that address safety instrumentation | |
(e.g. AddressSanitizer) should not be applied. | |
}]; | |
} | |
def NoSanitizeThreadDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "no_sanitize_thread"; | |
let Content = [{ | |
.. _langext-thread_sanitizer: | |
Use ``__attribute__((no_sanitize_thread))`` on a function declaration to | |
specify that checks for data races on plain (non-atomic) memory accesses should | |
not be inserted by ThreadSanitizer. The function is still instrumented by the | |
tool to avoid false positives and provide meaningful stack traces. | |
}]; | |
} | |
def NoSanitizeMemoryDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "no_sanitize_memory"; | |
let Content = [{ | |
.. _langext-memory_sanitizer: | |
Use ``__attribute__((no_sanitize_memory))`` on a function declaration to | |
specify that checks for uninitialized memory should not be inserted | |
(e.g. by MemorySanitizer). The function may still be instrumented by the tool | |
to avoid false positives in other places. | |
}]; | |
} | |
def CFICanonicalJumpTableDocs : Documentation { | |
let Category = DocCatFunction; | |
let Heading = "cfi_canonical_jump_table"; | |
let Content = [{ | |
.. _langext-cfi_canonical_jump_table: | |
Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to | |
make the function's CFI jump table canonical. See :ref:`the CFI documentation | |
<cfi-canonical-jump-tables>` for more details. | |
}]; | |
} | |
def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> { | |
let Content = [{ | |
Clang supports additional attributes to enable checking type safety properties | |
that can't be enforced by the C type system. To see warnings produced by these | |
checks, ensure that -Wtype-safety is enabled. Use cases include: | |
* MPI library implementations, where these attributes enable checking that | |
the buffer type matches the passed ``MPI_Datatype``; | |
* for HDF5 library there is a similar use case to MPI; | |
* checking types of variadic functions' arguments for functions like | |
``fcntl()`` and ``ioctl()``. | |
You can detect support for these attributes with ``__has_attribute()``. For | |
example: | |
.. code-block:: c++ | |
#if defined(__has_attribute) | |
# if __has_attribute(argument_with_type_tag) && \ | |
__has_attribute(pointer_with_type_tag) && \ | |
__has_attribute(type_tag_for_datatype) | |
# define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) | |
/* ... other macros ... */ | |
# endif | |
#endif | |
#if !defined(ATTR_MPI_PWT) | |
# define ATTR_MPI_PWT(buffer_idx, type_idx) | |
#endif | |
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) | |
ATTR_MPI_PWT(1,3); | |
}]; | |
} | |
def ArgumentWithTypeTagDocs : Documentation { | |
let Category = DocCatTypeSafety; | |
let Heading = "argument_with_type_tag"; | |
let Content = [{ | |
Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, | |
type_tag_idx)))`` on a function declaration to specify that the function | |
accepts a type tag that determines the type of some other argument. | |
This attribute is primarily useful for checking arguments of variadic functions | |
(``pointer_with_type_tag`` can be used in most non-variadic cases). | |
In the attribute prototype above: | |
* ``arg_kind`` is an identifier that should be used when annotating all | |
applicable type tags. | |
* ``arg_idx`` provides the position of a function argument. The expected type of | |
this function argument will be determined by the function argument specified | |
by ``type_tag_idx``. In the code example below, "3" means that the type of the | |
function's third argument will be determined by ``type_tag_idx``. | |
* ``type_tag_idx`` provides the position of a function argument. This function | |
argument will be a type tag. The type tag will determine the expected type of | |
the argument specified by ``arg_idx``. In the code example below, "2" means | |
that the type tag associated with the function's second argument should agree | |
with the type of the argument specified by ``arg_idx``. | |
For example: | |
.. code-block:: c++ | |
int fcntl(int fd, int cmd, ...) | |
__attribute__(( argument_with_type_tag(fcntl,3,2) )); | |
// The function's second argument will be a type tag; this type tag will | |
// determine the expected type of the function's third argument. | |
}]; | |
} | |
def PointerWithTypeTagDocs : Documentation { | |
let Category = DocCatTypeSafety; | |
let Heading = "pointer_with_type_tag"; | |
let Content = [{ | |
Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` | |
on a function declaration to specify that the function accepts a type tag that | |
determines the pointee type of some other pointer argument. | |
In the attribute prototype above: | |
* ``ptr_kind`` is an identifier that should be used when annotating all | |
applicable type tags. | |
* ``ptr_idx`` provides the position of a function argument; this function | |
argument will have a pointer type. The expected pointee type of this pointer | |
type will be determined by the function argument specified by | |
``type_tag_idx``. In the code example below, "1" means that the pointee type | |
of the function's first argument will be determined by ``type_tag_idx``. | |
* ``type_tag_idx`` provides the position of a function argument; this function | |
argument will be a type tag. The type tag will determine the expected pointee | |
type of the pointer argument specified by ``ptr_idx``. In the code example | |
below, "3" means that the type tag associated with the function's third | |
argument should agree with the pointee type of the pointer argument specified | |
by ``ptr_idx``. | |
For example: | |
.. code-block:: c++ | |
typedef int MPI_Datatype; | |
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) | |
__attribute__(( pointer_with_type_tag(mpi,1,3) )); | |
// The function's 3rd argument will be a type tag; this type tag will | |
// determine the expected pointee type of the function's 1st argument. | |
}]; | |
} | |
def TypeTagForDatatypeDocs : Documentation { | |
let Category = DocCatTypeSafety; | |
let Content = [{ | |
When declaring a variable, use | |
``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that | |
is tied to the ``type`` argument given to the attribute. | |
In the attribute prototype above: | |
* ``kind`` is an identifier that should be used when annotating all applicable | |
type tags. | |
* ``type`` indicates the name of the type. | |
Clang supports annotating type tags of two forms. | |
* **Type tag that is a reference to a declared identifier.** | |
Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that | |
identifier: | |
.. code-block:: c++ | |
typedef int MPI_Datatype; | |
extern struct mpi_datatype mpi_datatype_int | |
__attribute__(( type_tag_for_datatype(mpi,int) )); | |
#define MPI_INT ((MPI_Datatype) &mpi_datatype_int) | |
// &mpi_datatype_int is a type tag. It is tied to type "int". | |
* **Type tag that is an integral literal.** | |
Declare a ``static const`` variable with an initializer value and attach | |
``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration: | |
.. code-block:: c++ | |
typedef int MPI_Datatype; | |
static const MPI_Datatype mpi_datatype_int | |
__attribute__(( type_tag_for_datatype(mpi,int) )) = 42; | |
#define MPI_INT ((MPI_Datatype) 42) | |
// The number 42 is a type tag. It is tied to type "int". | |
The ``type_tag_for_datatype`` attribute also accepts an optional third argument | |
that determines how the type of the function argument specified by either | |
``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type | |
tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the | |
function argument specified by ``arg_idx`` is compared against the type | |
associated with the type tag. Also recall that for the ``pointer_with_type_tag`` | |
attribute, the pointee type of the function argument specified by ``ptr_idx`` is | |
compared against the type associated with the type tag.) There are two supported | |
values for this optional third argument: | |
* ``layout_compatible`` will cause types to be compared according to | |
layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the | |
layout-compatibility rules for two standard-layout struct types and for two | |
standard-layout union types). This is useful when creating a type tag | |
associated with a struct or union type. For example: | |
.. code-block:: c++ | |
/* In mpi.h */ | |
typedef int MPI_Datatype; | |
struct internal_mpi_double_int { double d; int i; }; | |
extern struct mpi_datatype mpi_datatype_double_int | |
__attribute__(( type_tag_for_datatype(mpi, | |
struct internal_mpi_double_int, layout_compatible) )); | |
#define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) | |
int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) | |
__attribute__(( pointer_with_type_tag(mpi,1,3) )); | |
/* In user code */ | |
struct my_pair { double a; int b; }; | |
struct my_pair *buffer; | |
MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the | |
// layout of my_pair is | |
// compatible with that of | |
// internal_mpi_double_int | |
struct my_int_pair { int a; int b; } | |
struct my_int_pair *buffer2; | |
MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the | |
// layout of my_int_pair | |
// does not match that of | |
// internal_mpi_double_int | |
* ``must_be_null`` specifies that the function argument specified by either | |
``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for | |
the ``pointer_with_type_tag`` attribute) should be a null pointer constant. | |
The second argument to the ``type_tag_for_datatype`` attribute is ignored. For | |
example: | |
.. code-block:: c++ | |
/* In mpi.h */ | |
typedef int MPI_Datatype; | |
extern struct mpi_datatype mpi_datatype_null | |
__attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); | |
#define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) | |
int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) | |
__attribute__(( pointer_with_type_tag(mpi,1,3) )); | |
/* In user code */ | |
struct my_pair { double a; int b; }; | |
struct my_pair *buffer; | |
MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL | |
// was specified but buffer | |
// is not a null pointer | |
}]; | |
} | |
def FlattenDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
The ``flatten`` attribute causes calls within the attributed function to | |
be inlined unless it is impossible to do so, for example if the body of the | |
callee is unavailable or if the callee has the ``noinline`` attribute. | |
}]; | |
} | |
def FormatDocs : Documentation { | |
let Category = DocCatFunction; | |
let Content = [{ | |
Clang supports the ``format`` attribute, which indicates that the function | |
accepts (among other possibilities) a ``printf`` or ``scanf``-like format string | |
and corresponding arguments or a ``va_list`` that contains these arguments. | |
Please see `GCC documentation about format attribute | |
<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details | |
about attribute syntax. | |
Clang implements two kinds of checks with this attribute. | |
#. Clang checks that the function with the ``format`` attribute is called with | |
a format string that uses format specifiers that are allowed, and that | |
arguments match the format string. This is the ``-Wformat`` warning, it is | |
on by default. | |
#. Clang checks that the format string argument is a literal string. This is | |
the ``-Wformat-nonliteral`` warning, it is off by default. | |
Clang implements this mostly the same way as GCC, but there is a difference | |
for functions that accept a ``va_list`` argument (for example, ``vprintf``). | |
GCC does not emit ``-Wformat-nonliteral`` warning for calls to such | |
functions. Clang does not warn if the format string comes from a function | |
parameter, where the function is annotated with a compatible attribute, | |
otherwise it warns. For example: | |
.. code-block:: c | |
__attribute__((__format__ (__scanf__, 1, 3))) | |
void foo(const char* s, char *buf, ...) { | |
va_list ap; | |
va_start(ap, buf); | |
vprintf(s, ap); // warning: format string is not a string literal | |
} | |
In this case we warn because ``s`` contains a format string for a | |
``scanf``-like function, but it is passed to a ``printf``-like function. | |
If the attribute is removed, clang still warns, because the format string is | |
not a string literal. | |
Another example: | |
.. code-block:: c | |
__attribute__((__format__ (__printf__, 1, 3))) | |
void foo(const char* s, char *buf, ...) { | |
va_list ap; | |
va_start(ap, buf); | |
vprintf(s, ap); // warning | |
} | |
In this case Clang does not warn because the format string ``s`` and | |
the corresponding arguments are annotated. If the arguments are | |
incorrect, the caller of ``foo`` will receive a warning. | |
As an extension to GCC's behavior, Clang accepts the ``format`` attribute on | |
non-variadic functions. Clang checks non-variadic format functions for the same | |
classes of issues that can be found on variadic functions, as controlled by the | |
same warning flags, except that the types of formatted arguments is forced by | |
the function signature. For example: | |
.. code-block:: c | |
__attribute__((__format__(__printf__, 1, 2))) | |
void fmt(const char *s, const char *a, int b); | |
void bar(void) { | |
fmt("%s %i", "hello", 123); // OK | |
fmt("%i %g", "hello", 123); // warning: arguments don't match format | |
extern const char *fmt; | |
fmt(fmt, "hello", 123); // warning: format string is not a string literal | |
} | |
When using the format attribute on a variadic function, the first data parameter | |
_must_ be the index of the ellipsis in the parameter list. Clang will generate | |
a diagnostic otherwise, as it wouldn't be possible to forward that argument list | |
to `printf`-family functions. For instance, this is an error: | |
.. code-block:: c | |
__attribute__((__format__(__printf__, 1, 2))) | |
void fmt(const char *s, int b, ...); | |
// ^ error: format attribute parameter 3 is out of bounds | |
// (must be __printf__, 1, 3) | |
Using the ``format`` attribute on a non-variadic function emits a GCC | |
compatibility diagnostic. | |
}]; | |
} | |
def AlignValueDocs : Documentation { | |
let Category = DocCatType; | |
let Content = [{ | |
The align_value attribute can be added to the typedef of a pointer type or the | |
declaration of a variable of pointer or reference type. It specifies that the | |
pointer will point to, or the reference will bind to, only objects with at | |
least the provided alignment. This alignment value must be some positive power | |
of 2. | |
.. code-block:: c | |
typedef double * aligned_double_ptr __attribute__((align_value(64))); | |
void foo(double & x __attribute__((align_value(128)), | |
aligned_double_ptr y) { ... } | |
If the pointer value does not have the specified alignment at runtime, the | |
behavior of the program is undefined. | |
}]; | |
} | |
def FlagEnumDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
This attribute can be added to an enumerator to signal to the compiler that it | |
is intended to be used as a flag type. This will cause the compiler to assume | |
that the range of the type includes all of the values that you can get by | |
manipulating bits of the enumerator when issuing warnings. | |
}]; | |
} | |
def AsmLabelDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
This attribute can be used on a function or variable to specify its symbol name. | |
On some targets, all C symbols are prefixed by default with a single character, | |
typically ``_``. This was done historically to distinguish them from symbols | |
used by other languages. (This prefix is also added to the standard Itanium | |
C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true | |
symbol name for a C++ variable declared as ``int cppvar;`` would be | |
``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the | |
symbol names specified by the ``asm`` attribute; programmers wishing to match a | |
C symbol name must compensate for this. | |
For example, consider the following C code: | |
.. code-block:: c | |
int var1 asm("altvar") = 1; // "altvar" in symbol table. | |
int var2 = 1; // "_var2" in symbol table. | |
void func1(void) asm("altfunc"); | |
void func1(void) {} // "altfunc" in symbol table. | |
void func2(void) {} // "_func2" in symbol table. | |
Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_. | |
While it is possible to use this attribute to name a special symbol used | |
internally by the compiler, such as an LLVM intrinsic, this is neither | |
recommended nor supported and may cause the compiler to crash or miscompile. | |
Users who wish to gain access to intrinsic behavior are strongly encouraged to | |
request new builtin functions. | |
}]; | |
} | |
def EnumExtensibilityDocs : Documentation { | |
let Category = DocCatDecl; | |
let Content = [{ | |
Attribute ``enum_extensibility`` is used to distinguish between enum definitions | |
that are extensible and those that are not. The attribute can take either | |
``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the | |
enum type takes a value that corresponds to one of the enumerators listed in the | |
enum definition or, when the enum is annotated with ``flag_enum``, a value that | |
can be constructed using values corresponding to the enumerators. ``open`` | |
indicates a variable of the enum type can take any values allowed by the | |
standard and instructs clang to be more lenient when issuing warnings. | |
.. code-block:: c | |
enum __attribute__((enum_extensibility(closed))) ClosedEnum { | |
A0, A1 | |
}; | |
enum __attribute__((enum_extensibility(open))) OpenEnum { | |
B0, B1 | |
}; | |
enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum { | |
C0 = 1 << 0, C1 = 1 << 1 | |
}; | |
enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum { | |
D0 = 1 << 0, D1 = 1 << 1 | |
}; | |
void foo1() { | |
enum ClosedEnum ce; | |
enum OpenEnum oe; | |
enum ClosedFlagEnum cfe; | |
enum OpenFlagEnum ofe; | |
ce = A1; // no warnings | |
ce = 100; // warning issued | |
oe = B1; // no warnings | |
oe = 100; // no warnings | |
cfe = C0 | C1; // no warnings | |
cfe = C0 | C1 | 4; // warning issued | |
ofe = D0 | D1; // no warnings | |
ofe = D0 | D1 | 4; // no warnings | |
} | |