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