1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* Clang attribute documentation *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* From: Attr.td *|
7|* *|
8\*===----------------------------------------------------------------------===*/
9
10
11static const char AttrDoc_AArch64SVEPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a
12function to preserve additional Scalable Vector registers and Scalable
13Predicate registers relative to the default calling convention used for
14AArch64.
15
16This means it is more efficient to call such functions from code that performs
17extensive scalable vector and scalable predicate calculations, because fewer
18live SVE registers need to be saved. This property makes it well-suited for SVE
19math library functions, which are typically leaf functions that require a small
20number of registers.
21
22However, using this attribute also means that it is more expensive to call
23a function that adheres to the default calling convention from within such
24a function. Therefore, it is recommended that this attribute is only used
25for leaf functions.
26
27For more information, see the documentation for `aarch64_sve_pcs` in the
28ARM C Language Extension (ACLE) documentation.
29
30.. _`aarch64_sve_pcs`: https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute)reST";
31
32static const char AttrDoc_AArch64VectorPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a
33function to preserve additional floating-point and Advanced SIMD registers
34relative to the default calling convention used for AArch64.
35
36This means it is more efficient to call such functions from code that performs
37extensive floating-point and vector calculations, because fewer live SIMD and FP
38registers need to be saved. This property makes it well-suited for e.g.
39floating-point or vector math library functions, which are typically leaf
40functions that require a small number of registers.
41
42However, using this attribute also means that it is more expensive to call
43a function that adheres to the default calling convention from within such
44a function. Therefore, it is recommended that this attribute is only used
45for leaf functions.
46
47For more information, see the documentation for `aarch64_vector_pcs`_ on
48the Arm Developer website.
49
50.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi)reST";
51
52static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size
53specified when the kernel is dispatched. It is the product of the sizes of the
54x, y, and z dimension of the work-group.
55
56Clang supports the
57``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
58AMDGPU target. This attribute may be attached to a kernel function definition
59and is an optimization hint.
60
61``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
62parameter specifies the maximum flat work-group size (must be greater than
63``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
64as ``<min>, <max>`` implies the default behavior (``128, 256``).
65
66If specified, the AMDGPU target backend might be able to produce better machine
67code for barriers and perform scratch promotion by estimating available group
68segment size.
69
70An error will be given if:
71 - Specified values violate subtarget specifications;
72 - Specified values are not compatible with values provided through other
73 attributes.)reST";
74
75static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel
76is dispatched.
77
78Clang supports the
79``__attribute__((amdgpu_max_num_work_groups(<x>, <y>, <z>)))`` or
80``[[clang::amdgpu_max_num_work_groups(<x>, <y>, <z>)]]`` attribute for the
81AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
82definitions and is an optimization hint.
83
84The ``<x>`` parameter specifies the maximum number of work groups in the x dimension.
85Similarly ``<y>`` and ``<z>`` are for the y and z dimensions respectively.
86Each of the three values must be greater than 0 when provided. The ``<x>`` parameter
87is required, while ``<y>`` and ``<z>`` are optional with default value of 1.
88
89If specified, the AMDGPU target backend might be able to produce better machine
90code.
91
92An error will be given if:
93 - Specified values violate subtarget specifications;
94 - Specified values are not compatible with values provided through other
95 attributes.)reST";
96
97static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
98``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
99target. These attributes may be attached to a kernel function definition and are
100an optimization hint.
101
102If these attributes are specified, then the AMDGPU target backend will attempt
103to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
104number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
105allocation requirements or constraints of the subtarget. Passing ``0`` as
106``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
107
108These attributes can be used to test the AMDGPU target backend. It is
109recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
110resources such as SGPRs and VGPRs since it is aware of the limits for different
111subtargets.
112
113An error will be given if:
114 - Specified values violate subtarget specifications;
115 - Specified values are not compatible with values provided through other
116 attributes;
117 - The AMDGPU target backend is unable to create machine code that can meet the
118 request.)reST";
119
120static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
121``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
122target. These attributes may be attached to a kernel function definition and are
123an optimization hint.
124
125If these attributes are specified, then the AMDGPU target backend will attempt
126to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
127number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
128allocation requirements or constraints of the subtarget. Passing ``0`` as
129``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
130
131These attributes can be used to test the AMDGPU target backend. It is
132recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
133resources such as SGPRs and VGPRs since it is aware of the limits for different
134subtargets.
135
136An error will be given if:
137 - Specified values violate subtarget specifications;
138 - Specified values are not compatible with values provided through other
139 attributes;
140 - The AMDGPU target backend is unable to create machine code that can meet the
141 request.)reST";
142
143static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
144It is composed of one or more execution units (EU), which are responsible for
145executing the wavefronts. An EU can have enough resources to maintain the state
146of more than one executing wavefront. This allows an EU to hide latency by
147switching between wavefronts in a similar way to symmetric multithreading on a
148CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
149resources used by a single wavefront have to be limited. For example, the number
150of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
151but can result in having to spill some register state to memory.
152
153Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
154attribute for the AMDGPU target. This attribute may be attached to a kernel
155function definition and is an optimization hint.
156
157``<min>`` parameter specifies the requested minimum number of waves per EU, and
158*optional* ``<max>`` parameter specifies the requested maximum number of waves
159per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
160then there is no restriction on the maximum number of waves per EU other than
161the one dictated by the hardware for which the kernel is compiled. Passing
162``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
163
164If specified, this attribute allows an advanced developer to tune the number of
165wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
166target backend can use this information to limit resources, such as number of
167SGPRs, number of VGPRs, size of available group and private memory segments, in
168such a way that guarantees that at least ``<min>`` wavefronts and at most
169``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
170more wavefronts can hide memory latency but limits available registers which
171can result in spilling. Requesting fewer wavefronts can help reduce cache
172thrashing, but can reduce memory latency hiding.
173
174This attribute controls the machine code generated by the AMDGPU target backend
175to ensure it is capable of meeting the requested values. However, when the
176kernel is executed, there may be other reasons that prevent meeting the request,
177for example, there may be wavefronts from other kernels executing on the EU.
178
179An error will be given if:
180 - Specified values violate subtarget specifications;
181 - Specified values are not compatible with values provided through other
182 attributes;
183
184The AMDGPU target backend will emit a warning whenever it is unable to
185create machine code that meets the request.)reST";
186
187static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
188ARM targets. This attribute may be attached to a function definition and
189instructs the backend to generate appropriate function entry/exit code so that
190it can be used directly as an interrupt service routine.
191
192The parameter passed to the interrupt attribute is optional, but if
193provided it must be a string literal with one of the following values: "IRQ",
194"FIQ", "SWI", "ABORT", "UNDEF".
195
196The semantics are as follows:
197
198- If the function is AAPCS, Clang instructs the backend to realign the stack to
199 8 bytes on entry. This is a general requirement of the AAPCS at public
200 interfaces, but may not hold when an exception is taken. Doing this allows
201 other AAPCS functions to be called.
202- If the CPU is M-class this is all that needs to be done since the architecture
203 itself is designed in such a way that functions obeying the normal AAPCS ABI
204 constraints are valid exception handlers.
205- If the CPU is not M-class, the prologue and epilogue are modified to save all
206 non-banked registers that are used, so that upon return the user-mode state
207 will not be corrupted. Note that to avoid unnecessary overhead, only
208 general-purpose (integer) registers are saved in this way. If VFP operations
209 are needed, that state must be saved manually.
210
211 Specifically, interrupt kinds other than "FIQ" will save all core registers
212 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
213- If the CPU is not M-class, the return instruction is changed to one of the
214 canonical sequences permitted by the architecture for exception return. Where
215 possible the function itself will make the necessary "lr" adjustments so that
216 the "preferred return address" is selected.
217
218 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
219 handler, where the offset from "lr" to the preferred return address depends on
220 the execution state of the code which generated the exception. In this case
221 a sequence equivalent to "movs pc, lr" will be used.)reST";
222
223static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt_save_fp("TYPE")))``
224on ARM targets. This attribute behaves the same way as the ARM interrupt
225attribute, except the general purpose floating point registers are also saved,
226along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
227point context can be automatically saved depending on the FPCCR, the general
228purpose floating point registers will be saved.)reST";
229
230static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
231
232static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
233AVR targets. This attribute may be attached to a function definition and instructs
234the backend to generate appropriate function entry/exit code so that it can be used
235directly as an interrupt service routine.
236
237On the AVR, the hardware globally disables interrupts when an interrupt is executed.
238The first instruction of an interrupt handler declared with this attribute is a SEI
239instruction to re-enable interrupts. See also the signal attribute that
240does not insert a SEI instruction.)reST";
241
242static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style ``__attribute__((signal))`` attribute on
243AVR targets. This attribute may be attached to a function definition and instructs
244the backend to generate appropriate function entry/exit code so that it can be used
245directly as an interrupt service routine.
246
247Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
248
249static const char AttrDoc_AbiTag[] = R"reST(The ``abi_tag`` attribute can be applied to a function, variable, class or
250inline namespace declaration to modify the mangled name of the entity. It gives
251the ability to distinguish between different versions of the same entity but
252with different ABI versions supported. For example, a newer version of a class
253could have a different set of data members and thus have a different size. Using
254the ``abi_tag`` attribute, it is possible to have different mangled names for
255a global variable of the class type. Therefore, the old code could keep using
256the old mangled name and the new code will use the new mangled name with tags.)reST";
257
258static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
259
260static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
261a new handle. In case this annotation is on an output parameter,
262the function is assumed to fill the corresponding argument with a new
263handle. The attribute requires a string literal argument which used to
264identify the handle with later uses of ``use_handle`` or
265``release_handle``.
266
267.. code-block:: c++
268
269 // Output arguments from Zircon.
270 zx_status_t zx_socket_create(uint32_t options,
271 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
272 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
273
274
275 // Returned handle.
276 [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
277 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));)reST";
278
279static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
280
281static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
282
283static const char AttrDoc_AddressSpace[] = R"reST(.. Note:: This attribute is mainly intended to be used by target headers
284 provided by the toolchain. End users should prefer the documented, named
285 address space annotations for their platform, such as the
286 `OpenCL address spaces`_, ``__global__``, ``__local__``, or something else.
287
288The ``address_space`` attribute functions as a type qualifier that allows the
289programmer to specify the address space for a pointer or reference type.
290Qualified pointer types are considered distinct types for the purposes of
291overload resolution. The attribute takes a single, non-negative integer
292constant expression identifying the address space. For example:
293
294.. code-block:: c
295
296 int * __attribute__((address_space(1))) ptr;
297
298 void foo(__attribute__((address_space(2))) float *buf);
299
300
301Only one address space qualifier may be applied to a given pointer or reference
302type. Where address spaces are allowed (e.g., variables, parameters, return
303types) and what values are valid depends on the target and language mode.
304
305The meaning of each value is defined by the target; multiple address spaces are
306used in environments such as OpenCL, CUDA, HIP, and other GPU programming
307models to distinguish global, local, constant, and private memory. See for
308example the address spaces defined in the `NVPTX Usage Guide`_ and the
309`AMDGPU Usage Guide`_.
310
311.. _`NVPTX Usage Guide`: https://llvm.org/docs/NVPTXUsage.html#address-spaces
312.. _`AMDGPU Usage Guide`: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
313
314Address spaces may partially overlap or be entirely distinct. The compiler may
315reject attempts to convert between distinct, incompatible address spaces.
316Pointer width may vary between different address spaces, so some explicit casts
317may truncate.
318
319For more information, refer to `ISO TR18037`_, which covers embedded C language
320extensions. Section 5 covers named address spaces.
321
322.. _`ISO TR18037`: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip)reST";
323
324static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
325
326static const char AttrDoc_AlignMac68k[] = R"reST()reST";
327
328static const char AttrDoc_AlignNatural[] = R"reST()reST";
329
330static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
331declaration of a variable of pointer or reference type. It specifies that the
332pointer will point to, or the reference will bind to, only objects with at
333least the provided alignment. This alignment value must be some positive power
334of 2.
335
336 .. code-block:: c
337
338 typedef double * aligned_double_ptr __attribute__((align_value(64)));
339 void foo(double & x __attribute__((align_value(128))),
340 aligned_double_ptr y) { ... }
341
342If the pointer value does not have the specified alignment at runtime, the
343behavior of the program is undefined.)reST";
344
345static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
346
347static const char AttrDoc_AllocAlign[] = R"reST(Use ``__attribute__((alloc_align(<alignment>))`` on a function
348declaration to specify that the return value of the function (which must be a
349pointer type) is at least as aligned as the value of the indicated parameter. The
350parameter is given by its index in the list of formal parameters; the first
351parameter has index 1 unless the function is a C++ non-static member function,
352in which case the first parameter has index 2 to account for the implicit ``this``
353parameter.
354
355.. code-block:: c++
356
357 // The returned pointer has the alignment specified by the first parameter.
358 void *a(size_t align) __attribute__((alloc_align(1)));
359
360 // The returned pointer has the alignment specified by the second parameter.
361 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
362
363 // The returned pointer has the alignment specified by the second visible
364 // parameter, however it must be adjusted for the implicit 'this' parameter.
365 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
366
367Note that this attribute merely informs the compiler that a function always
368returns a sufficiently aligned pointer. It does not cause the compiler to
369emit code to enforce that alignment. The behavior is undefined if the returned
370pointer is not sufficiently aligned.)reST";
371
372static const char AttrDoc_AllocSize[] = R"reST(The ``alloc_size`` attribute can be placed on functions that return pointers in
373order to hint to the compiler how many bytes of memory will be available at the
374returned pointer. ``alloc_size`` takes one or two arguments.
375
376- ``alloc_size(N)`` implies that argument number N equals the number of
377 available bytes at the returned pointer.
378- ``alloc_size(N, M)`` implies that the product of argument number N and
379 argument number M equals the number of available bytes at the returned
380 pointer.
381
382Argument numbers are 1-based.
383
384An example of how to use ``alloc_size``
385
386.. code-block:: c
387
388 void *my_malloc(int a) __attribute__((alloc_size(1)));
389 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
390
391 int main() {
392 void *const p = my_malloc(100);
393 assert(__builtin_object_size(p, 0) == 100);
394 void *const a = my_calloc(20, 5);
395 assert(__builtin_object_size(a, 0) == 100);
396 }
397
398When ``-Walloc-size`` is enabled, this attribute allows the compiler to
399diagnose cases when the allocated memory is insufficient for the size of the
400type the returned pointer is cast to.
401
402.. code-block:: c
403
404 void *my_malloc(int a) __attribute__((alloc_size(1)));
405 void consumer_func(int *);
406
407 int main() {
408 int *ptr = my_malloc(sizeof(int)); // no warning
409 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
410 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
411 }
412
413.. Note:: This attribute works differently in clang than it does in GCC.
414 Specifically, clang will only trace ``const`` pointers (as above); we give up
415 on pointers that are not marked as ``const``. In the vast majority of cases,
416 this is unimportant, because LLVM has support for the ``alloc_size``
417 attribute. However, this may cause mildly unintuitive behavior when used with
418 other attributes, such as ``enable_if``.)reST";
419
420static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
421of ``nonallocating`` by the compiler.)reST";
422
423static const char AttrDoc_AlwaysDestroy[] = R"reST(The ``always_destroy`` attribute specifies that a variable with static or thread
424storage duration should have its exit-time destructor run. This attribute is the
425default unless clang was invoked with -fno-c++-static-destructors.
426
427If a variable is explicitly declared with this attribute, Clang will silence
428otherwise applicable ``-Wexit-time-destructors`` warnings.)reST";
429
430static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
431optimization level.
432
433``[[clang::always_inline]]`` spelling can be used as a statement attribute; other
434spellings of the attribute are not supported on statements. If a statement is
435marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts
436to inline those calls.
437
438.. code-block:: c
439
440 int example(void) {
441 int i;
442 [[clang::always_inline]] foo(); // attempts to inline foo
443 [[clang::always_inline]] i = bar(); // attempts to inline bar
444 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
445 }
446
447A declaration statement, which is a statement, is not a statement that can have an
448attribute associated with it (the attribute applies to the declaration, not the
449statement in that case). So this use case will not work:
450
451.. code-block:: c
452
453 int example(void) {
454 [[clang::always_inline]] int i = bar();
455 return i;
456 }
457
458This attribute does not guarantee that inline substitution actually occurs.
459
460<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
461has no effect; other optimization levels may only partially inline and result in a
462diagnostic.</ins>
463
464See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
465Attribute docs`_, and `the GCC Inline docs`_.
466
467.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
468.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
469.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html)reST";
470
471static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
472
473static const char AttrDoc_Annotate[] = R"reST(No documentation.)reST";
474
475static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
476analysis tools that are not integrated into the core Clang compiler (e.g.,
477Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
478`annotate` attribute, which serves the same purpose, but for declarations.
479
480The attribute takes a mandatory string literal argument specifying the
481annotation category and an arbitrary number of optional arguments that provide
482additional information specific to the annotation category. The optional
483arguments must be constant expressions of arbitrary type.
484
485For example:
486
487.. code-block:: c++
488
489 int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
490
491The attribute does not have any effect on the semantics of the type system,
492neither type checking rules, nor runtime semantics. In particular:
493
494- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types
495 ``T``.
496
497- It is not permissible for overloaded functions or template specializations
498 to differ merely by an ``annotate_type`` attribute.
499
500- The presence of an ``annotate_type`` attribute will not affect name
501 mangling.)reST";
502
503static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
504targets. This attribute may be attached to a function definition and instructs
505the backend to generate appropriate function entry/exit code so that it can be
506used directly as an interrupt service routine.
507
508Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
509and return using the ``IRET`` instruction. All registers in an interrupt handler are callee-saved.
510Exception handlers also have access to the error code pushed onto the stack by the processor,
511when applicable.
512
513An interrupt handler must take the following arguments:
514
515 .. code-block:: c
516
517 __attribute__ ((interrupt))
518 void f (struct stack_frame *frame) {
519 ...
520 }
521
522 Where ``struct stack_frame`` is a suitable struct matching the stack frame pushed by the
523 processor.
524
525An exception handler must take the following arguments:
526
527 .. code-block:: c
528
529 __attribute__ ((interrupt))
530 void g (struct stack_frame *frame, unsigned long code) {
531 ...
532 }
533
534 On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
535
536Exception handlers should only be used when an error code is pushed by the processor.
537Using the incorrect handler type will crash the system.
538
539Interrupt and exception handlers cannot be called by other functions and must have return type ``void``.
540
541Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
542attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
543non-GPR registers.)reST";
544
545static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
546caller-saved registers. That is, all registers are callee-saved except for
547registers used for passing parameters to the function or returning parameters
548from the function.
549The compiler saves and restores any modified registers that were not used for
550passing or returning arguments to the function.
551
552The user can call functions specified with the 'no_caller_saved_registers'
553attribute from an interrupt handler without saving and restoring all
554call-clobbered registers.
555
556Functions specified with the 'no_caller_saved_registers' attribute should only
557call other functions with the 'no_caller_saved_registers' attribute, or should be
558compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
559
560Note that 'no_caller_saved_registers' attribute is not a calling convention.
561In fact, it only overrides the decision of which registers should be saved by
562the caller, but not how the parameters are passed from the caller to the callee.
563
564For example:
565
566 .. code-block:: c
567
568 __attribute__ ((no_caller_saved_registers, fastcall))
569 void f (int arg1, int arg2) {
570 ...
571 }
572
573 In this case parameters 'arg1' and 'arg2' will be passed in registers.
574 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
575 register parameters. However, it will not assume any scratch registers and
576 should save and restore any modified registers except for ECX and EDX.)reST";
577
578static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
579indirect call / jmp, e.g. redirect control-flow to non-programmer
580intended bytes in the binary.
581X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
582Enforcement Technology (CET). IBT instruments ENDBR instructions used to
583specify valid targets of indirect call / jmp.
584The ``nocf_check`` attribute has two roles:
5851. Appertains to a function - do not add ENDBR instruction at the beginning of
586the function.
5872. Appertains to a function pointer - do not track the target function of this
588pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
589
590static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
591
592static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
593type_tag_idx)))`` on a function declaration to specify that the function
594accepts a type tag that determines the type of some other argument.
595
596This attribute is primarily useful for checking arguments of variadic functions
597(``pointer_with_type_tag`` can be used in most non-variadic cases).
598
599In the attribute prototype above:
600 * ``arg_kind`` is an identifier that should be used when annotating all
601 applicable type tags.
602 * ``arg_idx`` provides the position of a function argument. The expected type of
603 this function argument will be determined by the function argument specified
604 by ``type_tag_idx``. In the code example below, "3" means that the type of the
605 function's third argument will be determined by ``type_tag_idx``.
606 * ``type_tag_idx`` provides the position of a function argument. This function
607 argument will be a type tag. The type tag will determine the expected type of
608 the argument specified by ``arg_idx``. In the code example below, "2" means
609 that the type tag associated with the function's second argument should agree
610 with the type of the argument specified by ``arg_idx``.
611
612For example:
613
614.. code-block:: c++
615
616 int fcntl(int fd, int cmd, ...)
617 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
618 // The function's second argument will be a type tag; this type tag will
619 // determine the expected type of the function's third argument.)reST";
620
621static const char AttrDoc_ArmAgnostic[] = R"reST(The ``__arm_agnostic`` keyword applies to prototyped function types and
622affects the function's calling convention for a given state S. This
623attribute allows the user to describe a function that preserves S, without
624requiring the function to share S with its callers and without making
625the assumption that S exists.
626
627If a function has the ``__arm_agnostic(S)`` attribute and calls a function
628without this attribute, then the function's object code will contain code
629to preserve state S. Otherwise, the function's object code will be the same
630as if it did not have the attribute.
631
632The attribute takes string arguments to describe state S. The supported
633states are:
634
635* ``"sme_za_state"`` for state enabled by PSTATE.ZA, such as ZA and ZT0.
636
637The attribute ``__arm_agnostic("sme_za_state")`` cannot be used in conjunction
638with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
639``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
640such as "za" or "zt0".)reST";
641
642static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
643It allows the intrinsic functions to
644be declared using the names defined in ACLE, and still be recognized
645as clang builtins equivalent to the underlying name. For example,
646``arm_mve.h`` declares the function ``vaddq_u32`` with
647``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
648and similarly, one of the type-overloaded declarations of ``vaddq``
649will have the same attribute. This ensures that both functions are
650recognized as that clang builtin, and in the latter case, the choice
651of which builtin to identify the function as can be deferred until
652after overload resolution.
653
654This attribute can only be used to set up the aliases for certain Arm
655intrinsic functions; it is intended for use only inside ``arm_*.h``
656and is not a general mechanism for declaring arbitrary aliases for
657clang builtin functions.
658
659In order to avoid duplicating the attribute definitions for similar
660purpose for other architecture, there is a general form for the
661attribute `clang_builtin_alias`.)reST";
662
663static const char AttrDoc_ArmIn[] = R"reST(The ``__arm_in`` keyword applies to prototyped function types and specifies
664that the function shares a given state S with its caller. For ``__arm_in``, the
665function takes the state S as input and returns with the state S unchanged.
666
667The attribute takes string arguments to instruct the compiler which state
668is shared. The supported states for S are:
669
670* ``"za"`` for Matrix Storage (requires SME)
671
672The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
673``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
674
675static const char AttrDoc_ArmInOut[] = R"reST(The ``__arm_inout`` keyword applies to prototyped function types and specifies
676that the function shares a given state S with its caller. For ``__arm_inout``,
677the function takes the state S as input and returns new state for S.
678
679The attribute takes string arguments to instruct the compiler which state
680is shared. The supported states for S are:
681
682* ``"za"`` for Matrix Storage (requires SME)
683
684The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
685``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
686
687static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The ``__arm_locally_streaming`` keyword applies to function declarations
688and specifies that all the statements in the function are executed in
689streaming mode. This means that:
690
691* the function requires that the target processor implements the Scalable Matrix
692 Extension (SME).
693
694* the program automatically puts the machine into streaming mode before
695 executing the statements and automatically restores the previous mode
696 afterwards.
697
698Clang manages PSTATE.SM automatically; it is not the source code's
699responsibility to do this. For example, Clang will emit code to enable
700streaming mode at the start of the function, and disable streaming mode
701at the end of the function.)reST";
702
703static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
704MVE instruction set. It is used to define the vector types used by the MVE
705intrinsics.
706
707Its effect is to modify the behavior of a vector type with respect to function
708overloading. If a candidate function for overload resolution has a parameter
709type with this attribute, then the selection of that candidate function will be
710disallowed if the actual argument can only be converted via a lax vector
711conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
712intrinsics.
713
714.. code-block:: c++
715
716 void overloaded(uint16x8_t vector, uint16_t scalar);
717 void overloaded(int32x4_t vector, int32_t scalar);
718 uint16x8_t myVector;
719 uint16_t myScalar;
720
721 // myScalar is promoted to int32_t as a side effect of the addition,
722 // so if lax vector conversions are considered for myVector, then
723 // the two overloads are equally good (one argument conversion
724 // each). But if the vector has the __clang_arm_mve_strict_polymorphism
725 // attribute, only the uint16x8_t,uint16_t overload will match.
726 overloaded(myVector, myScalar + 1);
727
728However, this attribute does not prohibit lax vector conversions in contexts
729other than overloading.
730
731.. code-block:: c++
732
733 uint16x8_t function();
734
735 // This is still permitted with lax vector conversion enabled, even
736 // if the vector types have __clang_arm_mve_strict_polymorphism
737 int32x4_t result = function();)reST";
738
739static const char AttrDoc_ArmNew[] = R"reST(The ``__arm_new`` keyword applies to function declarations and specifies
740that the function will create a new scope for state S.
741
742The attribute takes string arguments to instruct the compiler for which state
743to create new scope. The supported states for S are:
744
745* ``"za"`` for Matrix Storage (requires SME)
746
747For state ``"za"``, this means that:
748
749* the function requires that the target processor implements the Scalable Matrix
750 Extension (SME).
751
752* the function will commit any lazily saved ZA data.
753
754* the function will create a new ZA context and enable PSTATE.ZA.
755
756* the function will disable PSTATE.ZA (by setting it to 0) before returning.
757
758For ``__arm_new("za")`` functions Clang will set up the ZA context automatically
759on entry to the function and disable it before returning. For example, if ZA is
760in a dormant state Clang will generate the code to commit a lazy-save and set up
761a new ZA state before executing user code.)reST";
762
763static const char AttrDoc_ArmOut[] = R"reST(The ``__arm_out`` keyword applies to prototyped function types and specifies
764that the function shares a given state S with its caller. For ``__arm_out``,
765the function ignores the incoming state for S and returns new state for S.
766
767The attribute takes string arguments to instruct the compiler which state
768is shared. The supported states for S are:
769
770* ``"za"`` for Matrix Storage (requires SME)
771
772The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
773``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
774
775static const char AttrDoc_ArmPreserves[] = R"reST(The ``__arm_preserves`` keyword applies to prototyped function types and
776specifies that the function does not read a given state S and returns
777with state S unchanged.
778
779The attribute takes string arguments to instruct the compiler which state
780is shared. The supported states for S are:
781
782* ``"za"`` for Matrix Storage (requires SME)
783
784The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
785``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
786
787static const char AttrDoc_ArmStreaming[] = R"reST(The ``__arm_streaming`` keyword applies to prototyped function types and specifies
788that the function has a "streaming interface". This means that:
789
790* the function requires that the processor implements the Scalable Matrix
791 Extension (SME).
792
793* the function must be entered in streaming mode (that is, with PSTATE.SM
794 set to 1)
795
796* the function must return in streaming mode
797
798Clang manages PSTATE.SM automatically; it is not the source code's
799responsibility to do this. For example, if a non-streaming
800function calls an ``__arm_streaming`` function, Clang generates code
801that switches into streaming mode before calling the function and
802switches back to non-streaming mode on return.)reST";
803
804static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The ``__arm_streaming_compatible`` keyword applies to prototyped function types and
805specifies that the function has a "streaming compatible interface". This
806means that:
807
808* the function may be entered in either non-streaming mode (PSTATE.SM=0) or
809 in streaming mode (PSTATE.SM=1).
810
811* the function must return in the same mode as it was entered.
812
813* the code executed in the function is compatible with either mode.
814
815Clang manages PSTATE.SM automatically; it is not the source code's
816responsibility to do this. Clang will ensure that the generated code in
817streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
818PSTATE.SM=1). For example, if an ``__arm_streaming_compatible`` function calls a
819non-streaming function, Clang generates code to temporarily switch out of streaming
820mode before calling the function and switch back to streaming-mode on return if
821``PSTATE.SM`` is ``1`` on entry of the caller. If ``PSTATE.SM`` is ``0`` on
822entry to the ``__arm_streaming_compatible`` function, the call will be executed
823without changing modes.)reST";
824
825static const char AttrDoc_Artificial[] = R"reST(The ``artificial`` attribute can be applied to an inline function. If such a
826function is inlined, the attribute indicates that debuggers should associate
827the resulting instructions with the call site, rather than with the
828corresponding line within the inlined callee.)reST";
829
830static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
831
832On some targets, all C symbols are prefixed by default with a single character,
833typically ``_``. This was done historically to distinguish them from symbols
834used by other languages. (This prefix is also added to the standard Itanium
835C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
836symbol name for a C++ variable declared as ``int cppvar;`` would be
837``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the
838symbol names specified by the ``__asm`` attribute; programmers wishing to match
839a C symbol name must compensate for this.
840
841For example, consider the following C code:
842
843.. code-block:: c
844
845 int var1 __asm("altvar") = 1; // "altvar" in symbol table.
846 int var2 = 1; // "_var2" in symbol table.
847
848 void func1(void) __asm("altfunc");
849 void func1(void) {} // "altfunc" in symbol table.
850 void func2(void) {} // "_func2" in symbol table.
851
852Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
853
854While it is possible to use this attribute to name a special symbol used
855internally by the compiler, such as an LLVM intrinsic, this is neither
856recommended nor supported and may cause the compiler to crash or miscompile.
857Users who wish to gain access to intrinsic behavior are strongly encouraged to
858request new builtin functions.)reST";
859
860static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
861the program if it is not held.)reST";
862
863static const char AttrDoc_AssumeAligned[] = R"reST(Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
864declaration to specify that the return value of the function (which must be a
865pointer type) has the specified offset, in bytes, from an address with the
866specified alignment. The offset is taken to be zero if omitted.
867
868.. code-block:: c++
869
870 // The returned pointer value has 32-byte alignment.
871 void *a() __attribute__((assume_aligned (32)));
872
873 // The returned pointer value is 4 bytes greater than an address having
874 // 32-byte alignment.
875 void *b() __attribute__((assume_aligned (32, 4)));
876
877Note that this attribute provides information to the compiler regarding a
878condition that the code already ensures is true. It does not cause the compiler
879to enforce the provided alignment assumption.)reST";
880
881static const char AttrDoc_Atomic[] = R"reST(The ``atomic`` attribute can be applied to *compound statements* to override or
882further specify the default atomic code-generation behavior, especially on
883targets such as AMDGPU. You can annotate compound statements with options
884to modify how atomic instructions inside that statement are emitted at the IR
885level.
886
887For details, see the documentation for `@atomic
888<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-controlling-atomic-code-generation>`_)reST";
889
890static const char AttrDoc_Availability[] = R"reST(The ``availability`` attribute can be placed on declarations to describe the
891lifecycle of that declaration relative to operating system versions. Consider
892the function declaration for a hypothetical function ``f``:
893
894.. code-block:: c++
895
896 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
897
898The availability attribute states that ``f`` was introduced in macOS 10.4,
899deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
900is used by Clang to determine when it is safe to use ``f``: for example, if
901Clang is instructed to compile code for macOS 10.5, a call to ``f()``
902succeeds. If Clang is instructed to compile code for macOS 10.6, the call
903succeeds but Clang emits a warning specifying that the function is deprecated.
904Finally, if Clang is instructed to compile code for macOS 10.7, the call
905fails because ``f()`` is no longer available.
906
907Clang is instructed to compile code for a minimum deployment version using
908the ``-target`` or ``-mtargetos`` command line arguments. For example,
909macOS 10.7 would be specified as ``-target x86_64-apple-macos10.7`` or
910``-mtargetos=macos10.7``. Variants like Mac Catalyst are specified as
911``-target arm64-apple-ios15.0-macabi`` or ``-mtargetos=ios15.0-macabi``
912
913The availability attribute is a comma-separated list starting with the
914platform name and then including clauses specifying important milestones in the
915declaration's lifetime (in any order) along with additional information. Those
916clauses can be:
917
918introduced=\ *version*
919 The first version in which this declaration was introduced.
920
921deprecated=\ *version*
922 The first version in which this declaration was deprecated, meaning that
923 users should migrate away from this API.
924
925obsoleted=\ *version*
926 The first version in which this declaration was obsoleted, meaning that it
927 was removed completely and can no longer be used.
928
929unavailable
930 This declaration is never available on this platform.
931
932message=\ *string-literal*
933 Additional message text that Clang will provide when emitting a warning or
934 error about use of a deprecated or obsoleted declaration. Useful to direct
935 users to replacement APIs.
936
937replacement=\ *string-literal*
938 Additional message text that Clang will use to provide Fix-It when emitting
939 a warning about use of a deprecated declaration. The Fix-It will replace
940 the deprecated declaration with the new declaration specified.
941
942environment=\ *identifier*
943 Target environment in which this declaration is available. If present,
944 the availability attribute applies only to targets with the same platform
945 and environment. The parameter is currently supported only in HLSL.
946
947Multiple availability attributes can be placed on a declaration, which may
948correspond to different platforms. For most platforms, the availability
949attribute with the platform corresponding to the target platform will be used;
950any others will be ignored. However, the availability for ``watchOS`` and
951``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
952Any explicit availability attributes for those platforms are still preferred over
953the implicitly inferred availability attributes. If no availability attribute
954specifies availability for the current target platform, the availability
955attributes are ignored. Supported platforms are:
956
957``iOS``
958``macOS``
959``tvOS``
960``watchOS``
961``iOSApplicationExtension``
962``macOSApplicationExtension``
963``tvOSApplicationExtension``
964``watchOSApplicationExtension``
965``macCatalyst``
966``macCatalystApplicationExtension``
967``visionOS``
968``visionOSApplicationExtension``
969``driverkit``
970``swift``
971``android``
972``fuchsia``
973``ohos``
974``zos``
975``ShaderModel``
976
977Some platforms have alias names:
978
979``ios``
980``macos``
981``macosx (deprecated)``
982``tvos``
983``watchos``
984``ios_app_extension``
985``macos_app_extension``
986``macosx_app_extension (deprecated)``
987``tvos_app_extension``
988``watchos_app_extension``
989``maccatalyst``
990``maccatalyst_app_extension``
991``visionos``
992``visionos_app_extension``
993``shadermodel``
994
995Supported environment names for the ShaderModel platform:
996
997``pixel``
998``vertex``
999``geometry``
1000``hull``
1001``domain``
1002``compute``
1003``raygeneration``
1004``intersection``
1005``anyhit``
1006``closesthit``
1007``miss``
1008``callable``
1009``mesh``
1010``amplification``
1011``library``
1012
1013A declaration can typically be used even when deploying back to a platform
1014version prior to when the declaration was introduced. When this happens, the
1015declaration is `weakly linked
1016<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1017as if the ``weak_import`` attribute were added to the declaration. A
1018weakly-linked declaration may or may not be present a run-time, and a program
1019can determine whether the declaration is present by checking whether the
1020address of that declaration is non-NULL.
1021
1022The flag ``strict`` disallows using API when deploying back to a
1023platform version prior to when the declaration was introduced. An
1024attempt to use such API before its introduction causes a hard error.
1025Weakly-linking is almost always a better API choice, since it allows
1026users to query availability at runtime.
1027
1028If there are multiple declarations of the same entity, the availability
1029attributes must either match on a per-platform basis or later
1030declarations must not have availability attributes for that
1031platform. For example:
1032
1033.. code-block:: c
1034
1035 void g(void) __attribute__((availability(macos,introduced=10.4)));
1036 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1037 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1038 void g(void); // okay, inherits both macos and ios availability from above.
1039 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1040
1041When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1042
1043.. code-block:: objc
1044
1045 @interface A
1046 - (id)method __attribute__((availability(macos,introduced=10.4)));
1047 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1048 @end
1049
1050 @interface B : A
1051 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1052 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1053 @end
1054
1055Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1056``<os/availability.h>`` can simplify the spelling:
1057
1058.. code-block:: objc
1059
1060 @interface A
1061 - (id)method API_AVAILABLE(macos(10.11)));
1062 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1063 @end
1064
1065Availability attributes can also be applied using a ``#pragma clang attribute``.
1066Any explicit availability attribute whose platform corresponds to the target
1067platform is applied to a declaration regardless of the availability attributes
1068specified in the pragma. For example, in the code below,
1069``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1070attribute that is specified with the declaration, whereas
1071``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1072attribute that is applied by the pragma.
1073
1074.. code-block:: c
1075
1076 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1077 void getsThePragmaAvailabilityAttribute(void);
1078 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1079 #pragma clang attribute pop
1080
1081For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1082be implicitly inferred from an ``iOS`` availability attribute, the logic is
1083slightly more complex. The explicit and the pragma-applied availability
1084attributes whose platform corresponds to the target platform are applied as
1085described in the previous paragraph. However, the implicitly inferred attributes
1086are applied to a declaration only when there is no explicit or pragma-applied
1087availability attribute whose platform corresponds to the target platform. For
1088example, the function below will receive the ``tvOS`` availability from the
1089pragma rather than using the inferred ``iOS`` availability from the declaration:
1090
1091.. code-block:: c
1092
1093 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1094 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1095 #pragma clang attribute pop
1096
1097The compiler is also able to apply implicitly inferred attributes from a pragma
1098as well. For example, when targeting ``tvOS``, the function below will receive
1099a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1100availability attribute applied by the pragma:
1101
1102.. code-block:: c
1103
1104 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1105 void infersTVOSAvailabilityFromPragma(void);
1106 #pragma clang attribute pop
1107
1108The implicit attributes that are inferred from explicitly specified attributes
1109whose platform corresponds to the target platform are applied to the declaration
1110even if there is an availability attribute that can be inferred from a pragma.
1111For example, the function below will receive the ``tvOS, introduced=11.0``
1112availability that is inferred from the attribute on the declaration rather than
1113inferring availability from the pragma:
1114
1115.. code-block:: c
1116
1117 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1118 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1119 __attribute__((availability(iOS,introduced=11.0)));
1120 #pragma clang attribute pop
1121
1122Also see the documentation for `@available
1123<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_)reST";
1124
1125static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1126
1127static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1128It is assumed that inlined implementation uses less caller saved registers,
1129than a regular function.
1130Specifically, the following registers are likely to be preserved:
1131- ``R0`` if function return value is ``void``;
1132- ``R2-R5` if function takes 1 argument;
1133- ``R3-R5` if function takes 2 arguments;
1134- ``R4-R5` if function takes 3 arguments;
1135- ``R5`` if function takes 4 arguments;
1136
1137For such functions Clang generates code pattern that allows BPF JIT
1138to recognize and remove unnecessary spills and fills of the preserved
1139registers.)reST";
1140
1141static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the ``__attribute__((preserve_access_index))``
1142attribute for the BPF target. This attribute may be attached to a
1143struct or union declaration, where if -g is specified, it enables
1144preserving struct or union member access debuginfo indices of this
1145struct or union, similar to clang ``__builtin_preserve_access_index()``.)reST";
1146
1147static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the ``__attribute__((preserve_static_offset))``
1148attribute for the BPF target. This attribute may be attached to a
1149struct or union declaration. Reading or writing fields of types having
1150such annotation is guaranteed to generate LDX/ST/STX instruction with
1151offset corresponding to the field.
1152
1153For example:
1154
1155.. code-block:: c
1156
1157 struct foo {
1158 int a;
1159 int b;
1160 };
1161
1162 struct bar {
1163 int a;
1164 struct foo b;
1165 } __attribute__((preserve_static_offset));
1166
1167 void buz(struct bar *g) {
1168 g->b.a = 42;
1169 }
1170
1171The assignment to ``g``'s field would produce an ST instruction with
1172offset 8: ``*(u32)(r1 + 8) = 42;``.
1173
1174Without this attribute generated instructions might be different,
1175depending on optimizations behavior. E.g. the example above could be
1176rewritten as ``r1 += 8; *(u32)(r1 + 0) = 42;``.)reST";
1177
1178static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
1179all targets. This attribute may be attached to a struct/union, struct/union
1180field, function, function parameter, variable or typedef declaration. If -g is
1181specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
1182dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
1183section too.)reST";
1184
1185static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for
1186all targets. It only has effect when ``-g`` is specified on the command line and
1187is currently silently ignored when not applied to a pointer type (note: this
1188scenario may be diagnosed in the future).
1189
1190The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the
1191types used in variable declarations, function declarations, or typedef
1192declarations.
1193
1194For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF
1195section.)reST";
1196
1197static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of ``nonblocking``
1198by the compiler.)reST";
1199
1200static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1201
1202static const char AttrDoc_Builtin[] = R"reST()reST";
1203
1204static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1205It allows the C intrinsic functions to be declared using the names defined
1206in target builtins, and still be recognized as clang builtins equivalent to the
1207underlying name. For example, ``riscv_vector.h`` declares the function ``vadd``
1208with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``.
1209This ensures that both functions are recognized as that clang builtin,
1210and in the latter case, the choice of which builtin to identify the
1211function as can be deferred until after overload resolution.
1212
1213This attribute can only be used to set up the aliases for certain ARM/RISC-V
1214C intrinsic functions; it is intended for use only inside ``arm_*.h`` and
1215``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases
1216for clang builtin functions.)reST";
1217
1218static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as ``_Noreturn`` shall not return to its caller. The
1219compiler will generate a diagnostic for a function declared as ``_Noreturn``
1220that appears to be capable of returning to its caller. Despite being a type
1221specifier, the ``_Noreturn`` attribute cannot be specified on a function
1222pointer type.)reST";
1223
1224static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1225
1226static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1227
1228static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1229(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1230convention (e.g. functions starting with "get" are assumed to return at
1231``+0``).
1232
1233It can be overridden using a family of the following attributes. In
1234Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1235a function communicates that the object is returned at ``+1``, and the caller
1236is responsible for freeing it.
1237Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1238specifies that the object is returned at ``+0`` and the ownership remains with
1239the callee.
1240The annotation ``__attribute__((ns_consumes_self))`` specifies that
1241the Objective-C method call consumes the reference to ``self``, e.g. by
1242attaching it to a supplied parameter.
1243Additionally, parameters can have an annotation
1244``__attribute__((ns_consumed))``, which specifies that passing an owned object
1245as that parameter effectively transfers the ownership, and the caller is no
1246longer responsible for it.
1247These attributes affect code generation when interacting with ARC code, and
1248they are used by the Clang Static Analyzer.
1249
1250In C programs using CoreFoundation, a similar set of attributes:
1251``__attribute__((cf_returns_not_retained))``,
1252``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1253have the same respective semantics when applied to CoreFoundation objects.
1254These attributes affect code generation when interacting with ARC code, and
1255they are used by the Clang Static Analyzer.
1256
1257Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1258the same attribute family is present:
1259``__attribute__((os_returns_not_retained))``,
1260``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1261with the same respective semantics.
1262Similar to ``__attribute__((ns_consumes_self))``,
1263``__attribute__((os_consumes_this))`` specifies that the method call consumes
1264the reference to "this" (e.g., when attaching it to a different object supplied
1265as a parameter).
1266Out parameters (parameters the function is meant to write into,
1267either via pointers-to-pointers or references-to-pointers)
1268may be annotated with ``__attribute__((os_returns_retained))``
1269or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1270written into the out parameter should (or respectively should not) be released
1271after use.
1272Since often out parameters may or may not be written depending on the exit
1273code of the function,
1274annotations ``__attribute__((os_returns_retained_on_zero))``
1275and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1276an out parameter at ``+1`` is written if and only if the function returns a zero
1277(respectively non-zero) error code.
1278Observe that return-code-dependent out parameter annotations are only
1279available for retained out parameters, as non-retained object do not have to be
1280released by the callee.
1281These attributes are only used by the Clang Static Analyzer.
1282
1283The family of attributes ``X_returns_X_retained`` can be added to functions,
1284C++ methods, and Objective-C methods and properties.
1285Attributes ``X_consumed`` can be added to parameters of methods, functions,
1286and Objective-C methods.)reST";
1287
1288static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
1289attribute. This directs the compiler to not insert any CFG checks for the entire
1290function. This approach is typically used only sparingly in specific situations
1291where the programmer has manually inserted "CFG-equivalent" protection. The
1292programmer knows that they are calling through some read-only function table
1293whose address is obtained through read-only memory references and for which the
1294index is masked to the function table limit. This approach may also be applied
1295to small wrapper functions that are not inlined and that do nothing more than
1296make a call through a function pointer. Since incorrect usage of this directive
1297can compromise the security of CFG, the programmer must be very careful using
1298the directive. Typically, this usage is limited to very small functions that
1299only call one function.
1300
1301`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1302
1303static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
1304make the function's CFI jump table canonical. See :ref:`the CFI documentation
1305<cfi-canonical-jump-tables>` for more details.)reST";
1306
1307static const char AttrDoc_CFISalt[] = R"reST(The ``cfi_salt`` attribute specifies a string literal that is used as a salt
1308for Control-Flow Integrity (CFI) checks to distinguish between functions with
1309the same type signature. This attribute can be applied to function declarations,
1310function definitions, and function pointer typedefs.
1311
1312The attribute prevents function pointers from being replaced with pointers to
1313functions that have a compatible type, which can be a CFI bypass vector.
1314
1315**Syntax:**
1316
1317* GNU-style: ``__attribute__((cfi_salt("<salt_string>")))``
1318* C++11-style: ``[[clang::cfi_salt("<salt_string>")]]``
1319
1320**Usage:**
1321
1322The attribute takes a single string literal argument that serves as the salt.
1323Functions or function types with different salt values will have different CFI
1324hashes, even if they have identical type signatures.
1325
1326**Motivation:**
1327
1328In large codebases like the Linux kernel, there are often hundreds of functions
1329with identical type signatures that are called indirectly:
1330
1331.. code-block::
1332
1333 1662 functions with void (*)(void)
1334 1179 functions with int (*)(void)
1335 ...
1336
1337By salting the CFI hashes, you can make CFI more robust by ensuring that
1338functions intended for different purposes have distinct CFI identities.
1339
1340**Type Compatibility:**
1341
1342* Functions with different salt values are considered to have incompatible types
1343* Function pointers with different salt values cannot be assigned to each other
1344* All declarations of the same function must use the same salt value
1345
1346**Example:**
1347
1348.. code-block:: c
1349
1350 // Header file - define convenience macros
1351 #define __cfi_salt(s) __attribute__((cfi_salt(s)))
1352
1353 // Typedef for regular function pointers
1354 typedef int (*fptr_t)(void);
1355
1356 // Typedef for salted function pointers
1357 typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1358
1359 struct widget_ops {
1360 fptr_t init; // Regular CFI
1361 fptr_salted_t exec; // Salted CFI
1362 fptr_t cleanup; // Regular CFI
1363 };
1364
1365 // Function implementations
1366 static int widget_init(void) { return 0; }
1367 static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1368 static int widget_cleanup(void) { return 0; }
1369
1370 static struct widget_ops ops = {
1371 .init = widget_init, // OK - compatible types
1372 .exec = widget_exec, // OK - both use "pepper" salt
1373 .cleanup = widget_cleanup // OK - compatible types
1374 };
1375
1376 // Using C++11 attribute syntax
1377 void secure_callback(void) [[clang::cfi_salt("secure")]];
1378
1379 // This would cause a compilation error:
1380 // fptr_t bad_ptr = widget_exec; // Error: incompatible types
1381
1382**Notes:**
1383
1384* The salt string can contain non-NULL ASCII characters, including spaces and
1385 quotes
1386* This attribute only applies to function types; using it on non-function
1387 types will generate a warning
1388* All declarations and definitions of the same function must use identical
1389 salt values
1390* The attribute affects type compatibility during compilation and CFI hash
1391 generation during code generation)reST";
1392
1393static const char AttrDoc_CFIUncheckedCallee[] = R"reST(``cfi_unchecked_callee`` is a function type attribute which prevents the compiler from instrumenting
1394`Control Flow Integrity <https://clang.llvm.org/docs/ControlFlowIntegrity.html>`_ checks on indirect
1395function calls. This also includes control flow checks added by
1396`-fsanitize=function <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks>`.
1397Specifically, the attribute has the following semantics:
1398
13991. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1400 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1401 on pointers to function types having this attribute. It does not prevent all indirect function calls
1402 for a given type from being checked.
14032. All direct references to a function whose type has this attribute will always reference the
1404 function definition rather than an entry in the CFI jump table.
14053. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1406 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1407 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1408 direct references to a function with a ``cfi_unchecked_callee`` attribute will still reference the
1409 function definition rather than the CFI jump table.
1410
1411.. code-block:: c
1412
1413 #define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1414
1415 void no_cfi() CFI_UNCHECKED_CALLEE {}
1416
1417 void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1418 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1419 // its jump table entry.
1420
1421 void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1422 func(); // CFI will not instrument this indirect call.
1423
1424 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1425
1426 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1427 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1428 // fail because the reference will be to the function definition rather than the CFI jump
1429 // table entry.
1430 }
1431
1432This attribute can only be applied on functions or member functions. This attribute can be a good
1433alternative to ``no_sanitize("cfi")`` if you only want to disable innstrumentation for specific indirect
1434calls rather than applying ``no_sanitize("cfi")`` on the whole function containing indirect call. Note
1435that ``cfi_unchecked_attribute`` is a type attribute doesn't disable CFI instrumentation on a function
1436body.)reST";
1437
1438static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1439(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1440convention (e.g. functions starting with "get" are assumed to return at
1441``+0``).
1442
1443It can be overridden using a family of the following attributes. In
1444Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1445a function communicates that the object is returned at ``+1``, and the caller
1446is responsible for freeing it.
1447Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1448specifies that the object is returned at ``+0`` and the ownership remains with
1449the callee.
1450The annotation ``__attribute__((ns_consumes_self))`` specifies that
1451the Objective-C method call consumes the reference to ``self``, e.g. by
1452attaching it to a supplied parameter.
1453Additionally, parameters can have an annotation
1454``__attribute__((ns_consumed))``, which specifies that passing an owned object
1455as that parameter effectively transfers the ownership, and the caller is no
1456longer responsible for it.
1457These attributes affect code generation when interacting with ARC code, and
1458they are used by the Clang Static Analyzer.
1459
1460In C programs using CoreFoundation, a similar set of attributes:
1461``__attribute__((cf_returns_not_retained))``,
1462``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1463have the same respective semantics when applied to CoreFoundation objects.
1464These attributes affect code generation when interacting with ARC code, and
1465they are used by the Clang Static Analyzer.
1466
1467Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1468the same attribute family is present:
1469``__attribute__((os_returns_not_retained))``,
1470``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1471with the same respective semantics.
1472Similar to ``__attribute__((ns_consumes_self))``,
1473``__attribute__((os_consumes_this))`` specifies that the method call consumes
1474the reference to "this" (e.g., when attaching it to a different object supplied
1475as a parameter).
1476Out parameters (parameters the function is meant to write into,
1477either via pointers-to-pointers or references-to-pointers)
1478may be annotated with ``__attribute__((os_returns_retained))``
1479or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1480written into the out parameter should (or respectively should not) be released
1481after use.
1482Since often out parameters may or may not be written depending on the exit
1483code of the function,
1484annotations ``__attribute__((os_returns_retained_on_zero))``
1485and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1486an out parameter at ``+1`` is written if and only if the function returns a zero
1487(respectively non-zero) error code.
1488Observe that return-code-dependent out parameter annotations are only
1489available for retained out parameters, as non-retained object do not have to be
1490released by the callee.
1491These attributes are only used by the Clang Static Analyzer.
1492
1493The family of attributes ``X_returns_X_retained`` can be added to functions,
1494C++ methods, and Objective-C methods and properties.
1495Attributes ``X_consumed`` can be added to parameters of methods, functions,
1496and Objective-C methods.)reST";
1497
1498static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1499(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1500convention (e.g. functions starting with "get" are assumed to return at
1501``+0``).
1502
1503It can be overridden using a family of the following attributes. In
1504Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1505a function communicates that the object is returned at ``+1``, and the caller
1506is responsible for freeing it.
1507Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1508specifies that the object is returned at ``+0`` and the ownership remains with
1509the callee.
1510The annotation ``__attribute__((ns_consumes_self))`` specifies that
1511the Objective-C method call consumes the reference to ``self``, e.g. by
1512attaching it to a supplied parameter.
1513Additionally, parameters can have an annotation
1514``__attribute__((ns_consumed))``, which specifies that passing an owned object
1515as that parameter effectively transfers the ownership, and the caller is no
1516longer responsible for it.
1517These attributes affect code generation when interacting with ARC code, and
1518they are used by the Clang Static Analyzer.
1519
1520In C programs using CoreFoundation, a similar set of attributes:
1521``__attribute__((cf_returns_not_retained))``,
1522``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1523have the same respective semantics when applied to CoreFoundation objects.
1524These attributes affect code generation when interacting with ARC code, and
1525they are used by the Clang Static Analyzer.
1526
1527Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1528the same attribute family is present:
1529``__attribute__((os_returns_not_retained))``,
1530``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1531with the same respective semantics.
1532Similar to ``__attribute__((ns_consumes_self))``,
1533``__attribute__((os_consumes_this))`` specifies that the method call consumes
1534the reference to "this" (e.g., when attaching it to a different object supplied
1535as a parameter).
1536Out parameters (parameters the function is meant to write into,
1537either via pointers-to-pointers or references-to-pointers)
1538may be annotated with ``__attribute__((os_returns_retained))``
1539or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1540written into the out parameter should (or respectively should not) be released
1541after use.
1542Since often out parameters may or may not be written depending on the exit
1543code of the function,
1544annotations ``__attribute__((os_returns_retained_on_zero))``
1545and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1546an out parameter at ``+1`` is written if and only if the function returns a zero
1547(respectively non-zero) error code.
1548Observe that return-code-dependent out parameter annotations are only
1549available for retained out parameters, as non-retained object do not have to be
1550released by the callee.
1551These attributes are only used by the Clang Static Analyzer.
1552
1553The family of attributes ``X_returns_X_retained`` can be added to functions,
1554C++ methods, and Objective-C methods and properties.
1555Attributes ``X_consumed`` can be added to parameters of methods, functions,
1556and Objective-C methods.)reST";
1557
1558static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1559
1560static const char AttrDoc_CPUDispatch[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1561resolve multiversioned functions. This form of multiversioning provides a
1562mechanism for declaring versions across translation units and manually
1563specifying the resolved function list. A specified CPU defines a set of minimum
1564features that are required for the function to be called. The result of this is
1565that future processors execute the most restrictive version of the function the
1566new processor can execute.
1567
1568In addition, unlike the ICC implementation of this feature, the selection of the
1569version does not consider the manufacturer or microarchitecture of the processor.
1570It tests solely the list of features that are both supported by the specified
1571processor and present in the compiler-rt library. This can be surprising at times,
1572as the runtime processor may be from a completely different manufacturer, as long
1573as it supports the same feature set.
1574
1575This can additionally be surprising, as some processors are indistringuishable from
1576others based on the list of testable features. When this happens, the variant
1577is selected in an unspecified manner.
1578
1579Function versions are defined with ``cpu_specific``, which takes one or more CPU
1580names as a parameter. For example:
1581
1582.. code-block:: c
1583
1584 // Declares and defines the ivybridge version of single_cpu.
1585 __attribute__((cpu_specific(ivybridge)))
1586 void single_cpu(void){}
1587
1588 // Declares and defines the atom version of single_cpu.
1589 __attribute__((cpu_specific(atom)))
1590 void single_cpu(void){}
1591
1592 // Declares and defines both the ivybridge and atom version of multi_cpu.
1593 __attribute__((cpu_specific(ivybridge, atom)))
1594 void multi_cpu(void){}
1595
1596A dispatching (or resolving) function can be declared anywhere in a project's
1597source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1598as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1599are not expected to be defined, only declared. If such a marked function has a
1600definition, any side effects of the function are ignored; trivial function
1601bodies are permissible for ICC compatibility.
1602
1603.. code-block:: c
1604
1605 // Creates a resolver for single_cpu above.
1606 __attribute__((cpu_dispatch(ivybridge, atom)))
1607 void single_cpu(void){}
1608
1609 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1610 // translation unit.
1611 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1612 void multi_cpu(void){}
1613
1614Note that it is possible to have a resolving function that dispatches based on
1615more or fewer options than are present in the program. Specifying fewer will
1616result in the omitted options not being considered during resolution. Specifying
1617a version for resolution that isn't defined in the program will result in a
1618linking failure.
1619
1620It is also possible to specify a CPU name of ``generic`` which will be resolved
1621if the executing processor doesn't satisfy the features required in the CPU
1622name. The behavior of a program executing on a processor that doesn't satisfy
1623any option of a multiversioned function is undefined.)reST";
1624
1625static const char AttrDoc_CPUSpecific[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1626resolve multiversioned functions. This form of multiversioning provides a
1627mechanism for declaring versions across translation units and manually
1628specifying the resolved function list. A specified CPU defines a set of minimum
1629features that are required for the function to be called. The result of this is
1630that future processors execute the most restrictive version of the function the
1631new processor can execute.
1632
1633In addition, unlike the ICC implementation of this feature, the selection of the
1634version does not consider the manufacturer or microarchitecture of the processor.
1635It tests solely the list of features that are both supported by the specified
1636processor and present in the compiler-rt library. This can be surprising at times,
1637as the runtime processor may be from a completely different manufacturer, as long
1638as it supports the same feature set.
1639
1640This can additionally be surprising, as some processors are indistringuishable from
1641others based on the list of testable features. When this happens, the variant
1642is selected in an unspecified manner.
1643
1644Function versions are defined with ``cpu_specific``, which takes one or more CPU
1645names as a parameter. For example:
1646
1647.. code-block:: c
1648
1649 // Declares and defines the ivybridge version of single_cpu.
1650 __attribute__((cpu_specific(ivybridge)))
1651 void single_cpu(void){}
1652
1653 // Declares and defines the atom version of single_cpu.
1654 __attribute__((cpu_specific(atom)))
1655 void single_cpu(void){}
1656
1657 // Declares and defines both the ivybridge and atom version of multi_cpu.
1658 __attribute__((cpu_specific(ivybridge, atom)))
1659 void multi_cpu(void){}
1660
1661A dispatching (or resolving) function can be declared anywhere in a project's
1662source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1663as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1664are not expected to be defined, only declared. If such a marked function has a
1665definition, any side effects of the function are ignored; trivial function
1666bodies are permissible for ICC compatibility.
1667
1668.. code-block:: c
1669
1670 // Creates a resolver for single_cpu above.
1671 __attribute__((cpu_dispatch(ivybridge, atom)))
1672 void single_cpu(void){}
1673
1674 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1675 // translation unit.
1676 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1677 void multi_cpu(void){}
1678
1679Note that it is possible to have a resolving function that dispatches based on
1680more or fewer options than are present in the program. Specifying fewer will
1681result in the omitted options not being considered during resolution. Specifying
1682a version for resolution that isn't defined in the program will result in a
1683linking failure.
1684
1685It is also possible to specify a CPU name of ``generic`` which will be resolved
1686if the executing processor doesn't satisfy the features required in the CPU
1687name. The behavior of a program executing on a processor that doesn't satisfy
1688any option of a multiversioned function is undefined.)reST";
1689
1690static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the ``cluster_dims`` attribute, conventionally exposed as the
1691``__cluster_dims__`` macro, can be applied to a kernel function to set the dimensions of a
1692thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1693``__cluster_dims__`` defines the cluster size as ``(X, Y, Z)``, where each value is the number
1694of thread blocks in that dimension. The ``cluster_dims`` and `no_cluster`` attributes are
1695mutually exclusive.
1696
1697.. code::
1698
1699 __global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1700 ...
1701 })reST";
1702
1703static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1704
1705static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1706
1707static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The ``device_builtin_surface_type`` attribute can be applied to a class
1708template when declaring the surface reference. A surface reference variable
1709could be accessed on the host side and, on the device side, might be translated
1710into an internal surface object, which is established through surface bind and
1711unbind runtime APIs.)reST";
1712
1713static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The ``device_builtin_texture_type`` attribute can be applied to a class
1714template when declaring the texture reference. A texture reference variable
1715could be accessed on the host side and, on the device side, might be translated
1716into an internal texture object, which is established through texture bind and
1717unbind runtime APIs.)reST";
1718
1719static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1720
1721static const char AttrDoc_CUDAGridConstant[] = R"reST(The ``__grid_constant__`` attribute can be applied to a ``const``-qualified kernel
1722function argument and allows compiler to take the address of that argument without
1723making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1724with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1725
1726static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1727
1728static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1729
1730static const char AttrDoc_CUDALaunchBounds[] = R"reST(No documentation.)reST";
1731
1732static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1733at runtime, even without being annotated with ``__cluster_dims__``. The LLVM/Clang-exclusive
1734``no_cluster`` attribute, conventionally exposed as the ``__no_cluster__`` macro, can be applied to
1735a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1736compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1737without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1738kernel annotated with ``__no_cluster__`` if the cluster feature is enabled at runtime.
1739The ``cluster_dims`` and ``no_cluster`` attributes are mutually exclusive.
1740
1741.. code::
1742
1743 __global__ __no_cluster__ void kernel(...) {
1744 ...
1745 })reST";
1746
1747static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1748
1749static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as ``[[noreturn]]`` shall not return to its caller. The
1750compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
1751that appears to be capable of returning to its caller.
1752
1753The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code
1754migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``.)reST";
1755
1756static const char AttrDoc_CXXAssume[] = R"reST(The ``assume`` attribute is used to indicate to the optimizer that a
1757certain condition is assumed to be true at a certain point in the
1758program. If this condition is violated at runtime, the behavior is
1759undefined. ``assume`` can only be applied to a null statement.
1760
1761Different optimisers are likely to react differently to the presence of
1762this attribute; in some cases, adding ``assume`` may affect performance
1763negatively. It should be used with parsimony and care.
1764
1765Example:
1766
1767.. code-block:: c++
1768
1769 int f(int x, int y) {
1770 [[assume(x == 27)]];
1771 [[assume(x == y)]];
1772 return y + 1; // May be optimised to `return 28`.
1773 })reST";
1774
1775static const char AttrDoc_CallableWhen[] = R"reST(Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1776may be called in. Valid states are unconsumed, consumed, or unknown. Each
1777argument to this attribute must be a quoted string. E.g.:
1778
1779``__attribute__((callable_when("unconsumed", "unknown")))``)reST";
1780
1781static const char AttrDoc_Callback[] = R"reST(The ``callback`` attribute specifies that the annotated function may invoke the
1782specified callback zero or more times. The callback, as well as the passed
1783arguments, are identified by their parameter name or position (starting with
17841!) in the annotated function. The first position in the attribute identifies
1785the callback callee, the following positions declare describe its arguments.
1786The callback callee is required to be callable with the number, and order, of
1787the specified arguments. The index ``0``, or the identifier ``this``, is used to
1788represent an implicit "this" pointer in class methods. If there is no implicit
1789"this" pointer it shall not be referenced. The index '-1', or the name "__",
1790represents an unknown callback callee argument. This can be a value which is
1791not present in the declared parameter list, or one that is, but is potentially
1792inspected, captured, or modified. Parameter names and indices can be mixed in
1793the callback attribute.
1794
1795The ``callback`` attribute, which is directly translated to ``callback``
1796metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
1797connection between the call to the annotated function and the callback callee.
1798This can enable interprocedural optimizations which were otherwise impossible.
1799If a function parameter is mentioned in the ``callback`` attribute, through its
1800position, it is undefined if that parameter is used for anything other than the
1801actual callback. Inspected, captured, or modified parameters shall not be
1802listed in the ``callback`` metadata.
1803
1804Example encodings for the callback performed by ``pthread_create`` are shown
1805below. The explicit attribute annotation indicates that the third parameter
1806(``start_routine``) is called zero or more times by the ``pthread_create`` function,
1807and that the fourth parameter (``arg``) is passed along. Note that the callback
1808behavior of ``pthread_create`` is automatically recognized by Clang. In addition,
1809the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for
1810``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also
1811automatically recognized as broker functions. Further functions might be added
1812in the future.
1813
1814 .. code-block:: c
1815
1816 __attribute__((callback (start_routine, arg)))
1817 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1818 void *(*start_routine) (void *), void *arg);
1819
1820 __attribute__((callback (3, 4)))
1821 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1822 void *(*start_routine) (void *), void *arg);)reST";
1823
1824static const char AttrDoc_CalledOnce[] = R"reST(The ``called_once`` attribute specifies that the annotated function or method
1825parameter is invoked exactly once on all execution paths. It only applies
1826to parameters with function-like types, i.e. function pointers or blocks. This
1827concept is particularly useful for asynchronous programs.
1828
1829Clang implements a check for ``called_once`` parameters,
1830``-Wcalled-once-parameter``. It is on by default and finds the following
1831violations:
1832
1833* Parameter is not called at all.
1834
1835* Parameter is called more than once.
1836
1837* Parameter is not called on one of the execution paths.
1838
1839In the latter case, Clang pinpoints the path where parameter is not invoked
1840by showing the control-flow statement where the path diverges.
1841
1842.. code-block:: objc
1843
1844 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1845 if (somePredicate()) {
1846 ...
1847 callback();
1848 } else {
1849 callback(); // OK: callback is called on every path
1850 }
1851 }
1852
1853 void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1854 if (somePredicate()) {
1855 ...
1856 callback(); // note: previous call is here
1857 }
1858 callback(); // warning: callback is called twice
1859 }
1860
1861 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1862 if (somePredicate()) { // warning: callback is not called when condition is false
1863 ...
1864 callback();
1865 }
1866 }
1867
1868This attribute is useful for API developers who want to double-check if they
1869implemented their method correctly.)reST";
1870
1871static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
1872
1873static const char AttrDoc_CapturedRecord[] = R"reST()reST";
1874
1875static const char AttrDoc_CarriesDependency[] = R"reST(The ``carries_dependency`` attribute specifies dependency propagation into and
1876out of functions.
1877
1878When specified on a function or Objective-C method, the ``carries_dependency``
1879attribute means that the return value carries a dependency out of the function,
1880so that the implementation need not constrain ordering upon return from that
1881function. Implementations of the function and its caller may choose to preserve
1882dependencies instead of emitting memory ordering instructions such as fences.
1883
1884Note, this attribute does not change the meaning of the program, but may result
1885in generation of more efficient code.)reST";
1886
1887static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
1888scope. The attribute takes the identifier of a function with a parameter type
1889that is a pointer to the type with the attribute.
1890
1891.. code-block:: c
1892
1893 static void foo (int *) { ... }
1894 static void bar (int *) { ... }
1895 void baz (void) {
1896 int x __attribute__((cleanup(foo)));
1897 {
1898 int y __attribute__((cleanup(bar)));
1899 }
1900 }
1901
1902The above example will result in a call to ``bar`` being passed the address of
1903``y`` when ``y`` goes out of scope, then a call to ``foo`` being passed the
1904address of ``x`` when ``x`` goes out of scope. If two or more variables share
1905the same scope, their ``cleanup`` callbacks are invoked in the reverse order
1906the variables were declared in. It is not possible to check the return value
1907(if any) of these ``cleanup`` callback functions.)reST";
1908
1909static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by `clspv`_ (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from `libclc`_ (OpenCL-C builtin library).
1910
1911.. code-block:: c
1912
1913 void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
1914
1915.. _`clspv`: https://github.com/google/clspv
1916.. _`libclc`: https://libclc.llvm.org)reST";
1917
1918static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
1919state, a call to such a function would switch from secure to non-secure state.
1920All non-secure function calls must happen only through a function pointer, and
1921a non-secure function type should only be used as a base type of a pointer.
1922See `ARMv8-M Security Extensions: Requirements on Development
1923Tools - Engineering Specification Documentation
1924<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1925
1926static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
1927from secure state. Entering from and returning to non-secure state would switch
1928to and from secure state, respectively, and prevent flow of information
1929to non-secure state, except via return values. See `ARMv8-M Security Extensions:
1930Requirements on Development Tools - Engineering Specification Documentation
1931<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1932
1933static const char AttrDoc_CodeAlign[] = R"reST(The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
1934alignment for a loop. The attribute accepts a positive integer constant
1935initialization expression indicating the number of bytes for the minimum
1936alignment boundary. Its value must be a power of 2, between 1 and 4096
1937(inclusive).
1938
1939.. code-block:: c++
1940
1941 void foo() {
1942 int var = 0;
1943 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
1944 }
1945
1946 void Array(int *array, size_t n) {
1947 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
1948 }
1949
1950 void count () {
1951 int a1[10], int i = 0;
1952 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
1953 }
1954
1955 void check() {
1956 int a = 10;
1957 [[clang::code_align(8)]] do {
1958 a = a + 1;
1959 } while (a < 20);
1960 }
1961
1962 template<int A>
1963 void func() {
1964 [[clang::code_align(A)]] for(;;) { }
1965 })reST";
1966
1967static const char AttrDoc_CodeModel[] = R"reST(The ``model`` attribute allows overriding the translation unit's
1968code model (specified by ``-mcmodel``) for a specific global variable.
1969
1970On LoongArch, allowed values are "normal", "medium", "extreme".
1971
1972On x86-64, allowed values are ``"small"`` and ``"large"``. ``"small"`` is
1973roughly equivalent to ``-mcmodel=small``, meaning the global is considered
1974"small" placed closer to the ``.text`` section relative to "large" globals, and
1975to prefer using 32-bit relocations to access the global. ``"large"`` is roughly
1976equivalent to ``-mcmodel=large``, meaning the global is considered "large" and
1977placed further from the ``.text`` section relative to "small" globals, and
197864-bit relocations must be used to access the global.)reST";
1979
1980static const char AttrDoc_CodeSeg[] = R"reST(The ``__declspec(code_seg)`` attribute enables the placement of code into separate
1981named segments that can be paged or locked in memory individually. This attribute
1982is used to control the placement of instantiated templates and compiler-generated
1983code. See the documentation for `__declspec(code_seg)`_ on MSDN.
1984
1985.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
1986
1987static const char AttrDoc_Cold[] = R"reST(``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data.
1988If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).)reST";
1989
1990static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
1991
1992static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
1993
1994static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
1995to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1996according to the rules of [basic.start.static]. The variable is required to
1997have static or thread storage duration. If the initialization of the variable
1998is not a constant initializer an error will be produced. This attribute may
1999only be used in C++; the ``constinit`` spelling is only accepted in C++20
2000onwards.
2001
2002Note that in C++03 strict constant expression checking is not done. Instead
2003the attribute reports if Clang can emit the variable as a constant, even if it's
2004not technically a 'constant initializer'. This behavior is non-portable.
2005
2006Static storage duration variables with constant initializers avoid hard-to-find
2007bugs caused by the indeterminate order of dynamic initialization. They can also
2008be safely used during dynamic initialization across translation units.
2009
2010This attribute acts as a compile time assertion that the requirements
2011for constant initialization have been met. Since these requirements change
2012between dialects and have subtle pitfalls it's important to fail fast instead
2013of silently falling back on dynamic initialization.
2014
2015The first use of the attribute on a variable must be part of, or precede, the
2016initializing declaration of the variable. C++20 requires the ``constinit``
2017spelling of the attribute to be present on the initializing declaration if it
2018is used anywhere. The other spellings can be specified on a forward declaration
2019and omitted on a later initializing declaration.
2020
2021.. code-block:: c++
2022
2023 // -std=c++14
2024 #define SAFE_STATIC [[clang::require_constant_initialization]]
2025 struct T {
2026 constexpr T(int) {}
2027 ~T(); // non-trivial
2028 };
2029 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2030 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2031 // copy initialization is not a constant expression on a non-literal type.)reST";
2032
2033static const char AttrDoc_Constructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2034``main()``, and the ``destructor`` attribute causes the function to be called
2035after returning from ``main()`` or when the ``exit()`` function has been
2036called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2037marked ``destructor`` from being called.
2038
2039The constructor or destructor function should not accept any arguments and its
2040return type should be ``void``.
2041
2042The attributes accept an optional argument used to specify the priority order
2043in which to execute constructor and destructor functions. The priority is
2044given as an integer constant expression between 101 and 65535 (inclusive).
2045Priorities outside of that range are reserved for use by the implementation. A
2046lower value indicates a higher priority of initialization. Note that only the
2047relative ordering of values is important. For example:
2048
2049.. code-block:: c++
2050
2051 __attribute__((constructor(200))) void foo(void);
2052 __attribute__((constructor(101))) void bar(void);
2053
2054``bar()`` will be called before ``foo()``, and both will be called before
2055``main()``. If no argument is given to the ``constructor`` or ``destructor``
2056attribute, they default to the value ``65535``.)reST";
2057
2058static const char AttrDoc_Consumable[] = R"reST(Each ``class`` that uses any of the typestate annotations must first be marked
2059using the ``consumable`` attribute. Failure to do so will result in a warning.
2060
2061This attribute accepts a single parameter that must be one of the following:
2062``unknown``, ``consumed``, or ``unconsumed``.)reST";
2063
2064static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2065
2066static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2067
2068static const char AttrDoc_Convergent[] = R"reST(The ``convergent`` attribute can be placed on a function declaration. It is
2069translated into the LLVM ``convergent`` attribute, which indicates that the call
2070instructions of a function with this attribute cannot be made control-dependent
2071on any additional values.
2072
2073This attribute is different from ``noduplicate`` because it allows duplicating
2074function calls if it can be proved that the duplicated function calls are
2075not made control-dependent on any additional values, e.g., unrolling a loop
2076executed by all work items.
2077
2078Sample usage:
2079
2080.. code-block:: c
2081
2082 void convfunc(void) __attribute__((convergent));
2083 // Setting it as a C++11 attribute is also valid in a C++ program.
2084 // void convfunc(void) [[clang::convergent]];)reST";
2085
2086static const char AttrDoc_CoroAwaitElidable[] = R"reST(The ``[[clang::coro_await_elidable]]`` is a class attribute which can be
2087applied to a coroutine return type. It provides a hint to the compiler to apply
2088Heap Allocation Elision more aggressively.
2089
2090When a coroutine function returns such a type, a direct call expression therein
2091that returns a prvalue of a type attributed ``[[clang::coro_await_elidable]]``
2092is said to be under a safe elide context if one of the following is true:
2093- it is the immediate right-hand side operand to a co_await expression.
2094- it is an argument to a ``[[clang::coro_await_elidable_argument]]`` parameter
2095or parameter pack of another direct call expression under a safe elide context.
2096
2097Do note that the safe elide context applies only to the call expression itself,
2098and the context does not transitively include any of its subexpressions unless
2099exceptional rules of ``[[clang::coro_await_elidable_argument]]`` apply.
2100
2101The compiler performs heap allocation elision on call expressions under a safe
2102elide context, if the callee is a coroutine.
2103
2104Example:
2105
2106.. code-block:: c++
2107
2108 class [[clang::coro_await_elidable]] Task { ... };
2109
2110 Task foo();
2111 Task bar() {
2112 co_await foo(); // foo()'s coroutine frame on this line is elidable
2113 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2114 co_await t;
2115 }
2116
2117Such elision replaces the heap allocated activation frame of the callee coroutine
2118with a local variable within the enclosing braces in the caller's stack frame.
2119The local variable, like other variables in coroutines, may be collected into the
2120coroutine frame, which may be allocated on the heap. The behavior is undefined
2121if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2122
2123static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The ``[[clang::coro_await_elidable_argument]]`` is a function parameter attribute.
2124It works in conjunction with ``[[clang::coro_await_elidable]]`` to propagate a
2125safe elide context to a parameter or parameter pack if the function is called
2126under a safe elide context.
2127
2128This is sometimes necessary on utility functions used to compose or modify the
2129behavior of a callee coroutine.
2130
2131Example:
2132
2133.. code-block:: c++
2134
2135 template <typename T>
2136 class [[clang::coro_await_elidable]] Task { ... };
2137
2138 template <typename... T>
2139 class [[clang::coro_await_elidable]] WhenAll { ... };
2140
2141 // `when_all` is a utility function that composes coroutines. It does not
2142 // need to be a coroutine to propagate.
2143 template <typename... T>
2144 WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2145
2146 Task<int> foo();
2147 Task<int> bar();
2148 Task<void> example1() {
2149 // `when_all``, `foo``, and `bar` are all elide safe because `when_all` is
2150 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2151 // attribute, such context is propagated to foo and bar.
2152 co_await when_all(foo(), bar());
2153 }
2154
2155 Task<void> example2() {
2156 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2157 auto f = foo();
2158 co_await when_all(f, bar());
2159 }
2160
2161
2162 Task<void> example3() {
2163 // None of the calls are elide safe.
2164 auto t = when_all(foo(), bar());
2165 co_await t;
2166 })reST";
2167
2168static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2169to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2170it should also be annotated with ``[[clang::coro_return_type]]``).
2171
2172All parameters of a function are considered to be lifetime bound if the function returns a
2173coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2174This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2175with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2176See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2177
2178
2179Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2180
2181For example,
2182
2183.. code-block:: c++
2184
2185 task<int> coro(const int& a) { co_return a + 1; }
2186 task<int> dangling_refs(int a) {
2187 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2188 auto foo = coro(1);
2189 // `coro` captures reference to local variable `a` which is destroyed after the return.
2190 return coro(a);
2191 }
2192
2193Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2194which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2195``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2196temporaries or return address of a local variable.
2197
2198Both coroutines and coroutine wrappers are part of this analysis.
2199
2200.. code-block:: c++
2201
2202 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2203 using promise_type = some_promise_type;
2204 };
2205
2206 Task<int> coro(const int& a) { co_return a + 1; }
2207 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2208 return a > b ? coro(a) : coro(b);
2209 }
2210 Task<int> temporary_reference() {
2211 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2212
2213 int a = 1;
2214 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2215
2216 co_return co_await coro(1); // fine.
2217 }
2218 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2219 return coro(a); // warning: returning address of stack variable `a`.
2220 }
2221
2222This analysis can be disabled for all calls to a particular function by annotating the function
2223with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2224For example, this could be useful for coroutine wrappers which accept reference parameters
2225but do not pass them to the underlying coroutine or pass them by value.
2226
2227.. code-block:: c++
2228
2229 Task<int> coro(int a) { co_return a + 1; }
2230 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2231 return coro(a + 1);
2232 }
2233 void use() {
2234 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2235 })reST";
2236
2237static const char AttrDoc_CoroLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2238to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2239it should also be annotated with ``[[clang::coro_return_type]]``).
2240
2241All parameters of a function are considered to be lifetime bound if the function returns a
2242coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2243This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2244with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2245See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2246
2247
2248Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2249
2250For example,
2251
2252.. code-block:: c++
2253
2254 task<int> coro(const int& a) { co_return a + 1; }
2255 task<int> dangling_refs(int a) {
2256 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2257 auto foo = coro(1);
2258 // `coro` captures reference to local variable `a` which is destroyed after the return.
2259 return coro(a);
2260 }
2261
2262Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2263which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2264``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2265temporaries or return address of a local variable.
2266
2267Both coroutines and coroutine wrappers are part of this analysis.
2268
2269.. code-block:: c++
2270
2271 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2272 using promise_type = some_promise_type;
2273 };
2274
2275 Task<int> coro(const int& a) { co_return a + 1; }
2276 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2277 return a > b ? coro(a) : coro(b);
2278 }
2279 Task<int> temporary_reference() {
2280 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2281
2282 int a = 1;
2283 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2284
2285 co_return co_await coro(1); // fine.
2286 }
2287 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2288 return coro(a); // warning: returning address of stack variable `a`.
2289 }
2290
2291This analysis can be disabled for all calls to a particular function by annotating the function
2292with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2293For example, this could be useful for coroutine wrappers which accept reference parameters
2294but do not pass them to the underlying coroutine or pass them by value.
2295
2296.. code-block:: c++
2297
2298 Task<int> coro(int a) { co_return a + 1; }
2299 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2300 return coro(a + 1);
2301 }
2302 void use() {
2303 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2304 })reST";
2305
2306static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2307whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2308reached the final suspend point.
2309
2310This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2311
2312For example,
2313
2314.. code-block:: c++
2315
2316 A foo() {
2317 dtor d;
2318 co_await something();
2319 dtor d1;
2320 co_await something();
2321 dtor d2;
2322 co_return 43;
2323 }
2324
2325The compiler may generate the following pseudocode:
2326
2327.. code-block:: c++
2328
2329 void foo.destroy(foo.Frame *frame) {
2330 switch(frame->suspend_index()) {
2331 case 1:
2332 frame->d.~dtor();
2333 break;
2334 case 2:
2335 frame->d.~dtor();
2336 frame->d1.~dtor();
2337 break;
2338 case 3:
2339 frame->d.~dtor();
2340 frame->d1.~dtor();
2341 frame->d2.~dtor();
2342 break;
2343 default: // coroutine completed or haven't started
2344 break;
2345 }
2346
2347 frame->promise.~promise_type();
2348 delete frame;
2349 }
2350
2351The `foo.destroy()` function's purpose is to release all of the resources
2352initialized for the coroutine when it is destroyed in a suspended state.
2353However, if the coroutine is only ever destroyed at the final suspend state,
2354the rest of the conditions are superfluous.
2355
2356The user can use the `coro_only_destroy_when_complete` attributo suppress
2357generation of the other destruction cases, optimizing the above `foo.destroy` to:
2358
2359.. code-block:: c++
2360
2361 void foo.destroy(foo.Frame *frame) {
2362 frame->promise.~promise_type();
2363 delete frame;
2364 })reST";
2365
2366static const char AttrDoc_CoroReturnType[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2367coroutines from the function signatures.
2368
2369The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2370a **coroutine return type (CRT)**.
2371
2372A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2373is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2374(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2375
2376If the return type of a function is a ``CRT`` then the function must be a coroutine.
2377Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2378if the function is marked with ``[[clang::coro_wrapper]]``.
2379
2380The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2381a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2382is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2383
2384Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2385with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2386
2387From a language perspective, it is not possible to differentiate between a coroutine and a
2388function returning a CRT by merely looking at the function signature.
2389
2390Coroutine wrappers, in particular, are susceptible to capturing
2391references to temporaries and other lifetime issues. This allows to avoid such lifetime
2392issues with coroutine wrappers.
2393
2394For example,
2395
2396.. code-block:: c++
2397
2398 // This is a CRT.
2399 template <typename T> struct [[clang::coro_return_type]] Task {
2400 using promise_type = some_promise_type;
2401 };
2402
2403 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2404 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2405
2406 // Fine for a coroutine wrapper to return a CRT.
2407 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2408
2409 void bar() {
2410 // Invalid. This intantiates a function which returns a CRT but is not marked as
2411 // a coroutine wrapper.
2412 std::function<Task<int>(int)> f = increment;
2413 }
2414
2415Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2416implementation detail of any coroutine library.)reST";
2417
2418static const char AttrDoc_CoroWrapper[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2419coroutines from the function signatures.
2420
2421The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2422a **coroutine return type (CRT)**.
2423
2424A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2425is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2426(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2427
2428If the return type of a function is a ``CRT`` then the function must be a coroutine.
2429Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2430if the function is marked with ``[[clang::coro_wrapper]]``.
2431
2432The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2433a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2434is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2435
2436Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2437with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2438
2439From a language perspective, it is not possible to differentiate between a coroutine and a
2440function returning a CRT by merely looking at the function signature.
2441
2442Coroutine wrappers, in particular, are susceptible to capturing
2443references to temporaries and other lifetime issues. This allows to avoid such lifetime
2444issues with coroutine wrappers.
2445
2446For example,
2447
2448.. code-block:: c++
2449
2450 // This is a CRT.
2451 template <typename T> struct [[clang::coro_return_type]] Task {
2452 using promise_type = some_promise_type;
2453 };
2454
2455 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2456 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2457
2458 // Fine for a coroutine wrapper to return a CRT.
2459 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2460
2461 void bar() {
2462 // Invalid. This intantiates a function which returns a CRT but is not marked as
2463 // a coroutine wrapper.
2464 std::function<Task<int>(int)> f = increment;
2465 }
2466
2467Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2468implementation detail of any coroutine library.)reST";
2469
2470static const char AttrDoc_CountedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2471structure in C. The argument for the attribute is the name of a field member
2472holding the count of elements in the flexible array. This information can be
2473used to improve the results of the array bound sanitizer and the
2474``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2475within the same non-anonymous, enclosing struct as the flexible array member.
2476
2477This example specifies that the flexible array member ``array`` has the number
2478of elements allocated for it in ``count``:
2479
2480.. code-block:: c
2481
2482 struct bar;
2483
2484 struct foo {
2485 size_t count;
2486 char other;
2487 struct bar *array[] __attribute__((counted_by(count)));
2488 };
2489
2490This establishes a relationship between ``array`` and ``count``. Specifically,
2491``array`` must have at least ``count`` number of elements available. It's the
2492user's responsibility to ensure that this relationship is maintained through
2493changes to the structure.
2494
2495In the following example, the allocated array erroneously has fewer elements
2496than what's specified by ``p->count``. This would result in an out-of-bounds
2497access not being detected.
2498
2499.. code-block:: c
2500
2501 #define SIZE_INCR 42
2502
2503 struct foo *p;
2504
2505 void foo_alloc(size_t count) {
2506 p = malloc(MAX(sizeof(struct foo),
2507 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2508 p->count = count + SIZE_INCR;
2509 }
2510
2511The next example updates ``p->count``, but breaks the relationship requirement
2512that ``p->array`` must have at least ``p->count`` number of elements available:
2513
2514.. code-block:: c
2515
2516 #define SIZE_INCR 42
2517
2518 struct foo *p;
2519
2520 void foo_alloc(size_t count) {
2521 p = malloc(MAX(sizeof(struct foo),
2522 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2523 p->count = count;
2524 }
2525
2526 void use_foo(int index, int val) {
2527 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2528 p->array[index] = val; /* The sanitizer can't properly check this access. */
2529 }
2530
2531In this example, an update to ``p->count`` maintains the relationship
2532requirement:
2533
2534.. code-block:: c
2535
2536 void use_foo(int index, int val) {
2537 if (p->count == 0)
2538 return;
2539 --p->count;
2540 p->array[index] = val;
2541 })reST";
2542
2543static const char AttrDoc_CountedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2544structure in C. The argument for the attribute is the name of a field member
2545holding the count of elements in the flexible array. This information can be
2546used to improve the results of the array bound sanitizer and the
2547``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2548within the same non-anonymous, enclosing struct as the flexible array member.
2549
2550This example specifies that the flexible array member ``array`` has the number
2551of elements allocated for it in ``count``:
2552
2553.. code-block:: c
2554
2555 struct bar;
2556
2557 struct foo {
2558 size_t count;
2559 char other;
2560 struct bar *array[] __attribute__((counted_by(count)));
2561 };
2562
2563This establishes a relationship between ``array`` and ``count``. Specifically,
2564``array`` must have at least ``count`` number of elements available. It's the
2565user's responsibility to ensure that this relationship is maintained through
2566changes to the structure.
2567
2568In the following example, the allocated array erroneously has fewer elements
2569than what's specified by ``p->count``. This would result in an out-of-bounds
2570access not being detected.
2571
2572.. code-block:: c
2573
2574 #define SIZE_INCR 42
2575
2576 struct foo *p;
2577
2578 void foo_alloc(size_t count) {
2579 p = malloc(MAX(sizeof(struct foo),
2580 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2581 p->count = count + SIZE_INCR;
2582 }
2583
2584The next example updates ``p->count``, but breaks the relationship requirement
2585that ``p->array`` must have at least ``p->count`` number of elements available:
2586
2587.. code-block:: c
2588
2589 #define SIZE_INCR 42
2590
2591 struct foo *p;
2592
2593 void foo_alloc(size_t count) {
2594 p = malloc(MAX(sizeof(struct foo),
2595 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2596 p->count = count;
2597 }
2598
2599 void use_foo(int index, int val) {
2600 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2601 p->array[index] = val; /* The sanitizer can't properly check this access. */
2602 }
2603
2604In this example, an update to ``p->count`` maintains the relationship
2605requirement:
2606
2607.. code-block:: c
2608
2609 void use_foo(int index, int val) {
2610 if (p->count == 0)
2611 return;
2612 --p->count;
2613 p->array[index] = val;
2614 })reST";
2615
2616static const char AttrDoc_DLLExport[] = R"reST(The ``__declspec(dllexport)`` attribute declares a variable, function, or
2617Objective-C interface to be exported from the module. It is available under the
2618``-fdeclspec`` flag for compatibility with various compilers. The primary use
2619is for COFF object files which explicitly specify what interfaces are available
2620for external use. See the dllexport_ documentation on MSDN for more
2621information.
2622
2623.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2624
2625static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2626
2627static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2628
2629static const char AttrDoc_DLLImport[] = R"reST(The ``__declspec(dllimport)`` attribute declares a variable, function, or
2630Objective-C interface to be imported from an external module. It is available
2631under the ``-fdeclspec`` flag for compatibility with various compilers. The
2632primary use is for COFF object files which explicitly specify what interfaces
2633are imported from external modules. See the dllimport_ documentation on MSDN
2634for more information.
2635
2636Note that a dllimport function may still be inlined, if its definition is
2637available and it doesn't reference any non-dllimport functions or global
2638variables.
2639
2640.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2641
2642static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2643
2644static const char AttrDoc_Deprecated[] = R"reST(The ``deprecated`` attribute can be applied to a function, a variable, or a
2645type. This is useful when identifying functions, variables, or types that are
2646expected to be removed in a future version of a program.
2647
2648Consider the function declaration for a hypothetical function ``f``:
2649
2650.. code-block:: c++
2651
2652 void f(void) __attribute__((deprecated("message", "replacement")));
2653
2654When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have
2655two optional string arguments. The first one is the message to display when
2656emitting the warning; the second one enables the compiler to provide a Fix-It
2657to replace the deprecated name with a new name. Otherwise, when spelled as
2658``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional
2659string argument which is the message to display when emitting the warning.)reST";
2660
2661static const char AttrDoc_Destructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2662``main()``, and the ``destructor`` attribute causes the function to be called
2663after returning from ``main()`` or when the ``exit()`` function has been
2664called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2665marked ``destructor`` from being called.
2666
2667The constructor or destructor function should not accept any arguments and its
2668return type should be ``void``.
2669
2670The attributes accept an optional argument used to specify the priority order
2671in which to execute constructor and destructor functions. The priority is
2672given as an integer constant expression between 101 and 65535 (inclusive).
2673Priorities outside of that range are reserved for use by the implementation. A
2674lower value indicates a higher priority of initialization. Note that only the
2675relative ordering of values is important. For example:
2676
2677.. code-block:: c++
2678
2679 __attribute__((constructor(200))) void foo(void);
2680 __attribute__((constructor(101))) void bar(void);
2681
2682``bar()`` will be called before ``foo()``, and both will be called before
2683``main()``. If no argument is given to the ``constructor`` or ``destructor``
2684attribute, they default to the value ``65535``.)reST";
2685
2686static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2687The specific semantics depend on the offloading language, target, and attribute spelling.
2688Here is a code example using the attribute to mark a function as a kernel:
2689
2690.. code-block:: c++
2691
2692 [[clang::device_kernel]] int foo(int x) { return ++x; })reST";
2693
2694static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
2695be applied to the declared function as if it were the function specified by the
2696attribute. The builtin function whose diagnostics are to be mimicked should be
2697given. In addition, the order in which arguments should be applied must also
2698be given.
2699
2700For example, the attribute can be used as follows.
2701
2702.. code-block:: c
2703
2704 __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2705 void *mymemset(int n, int c, void *s) {
2706 // ...
2707 }
2708
2709This indicates that calls to ``mymemset`` should be diagnosed as if they were
2710calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
2711order in which arguments of ``mymemset`` should be applied to
2712``__builtin_memset``. The third argument should be applied first, then the
2713second, and then the first. Thus (when Fortify warnings are enabled) the call
2714``mymemset(n, c, s)`` will diagnose overflows as if it were the call
2715``__builtin_memset(s, c, n)``.
2716
2717For variadic functions, the variadic arguments must come in the same order as
2718they would to the builtin function, after all normal arguments. For instance,
2719to diagnose a new function as if it were `sscanf`, we can use the attribute as
2720follows.
2721
2722.. code-block:: c
2723
2724 __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2725 int mysscanf(const char *str, const char *format, ...) {
2726 // ...
2727 }
2728
2729Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2730if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2731
2732This attribute cannot be applied to non-static member functions.)reST";
2733
2734static const char AttrDoc_DiagnoseIf[] = R"reST(The ``diagnose_if`` attribute can be placed on function declarations to emit
2735warnings or errors at compile-time if calls to the attributed function meet
2736certain user-defined criteria. For example:
2737
2738.. code-block:: c
2739
2740 int abs(int a)
2741 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2742 int must_abs(int a)
2743 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2744
2745 int val = abs(1); // warning: Redundant abs call
2746 int val2 = must_abs(1); // error: Redundant abs call
2747 int val3 = abs(val);
2748 int val4 = must_abs(val); // Because run-time checks are not emitted for
2749 // diagnose_if attributes, this executes without
2750 // issue.
2751
2752
2753``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
2754
2755* Overload resolution is not aware of ``diagnose_if`` attributes: they're
2756 considered only after we select the best candidate from a given candidate set.
2757* Function declarations that differ only in their ``diagnose_if`` attributes are
2758 considered to be redeclarations of the same function (not overloads).
2759* If the condition provided to ``diagnose_if`` cannot be evaluated, no
2760 diagnostic will be emitted.
2761
2762Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
2763
2764As a result of bullet number two, ``diagnose_if`` attributes will stack on the
2765same function. For example:
2766
2767.. code-block:: c
2768
2769 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2770 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2771
2772 int bar = foo(); // warning: diag1
2773 // warning: diag2
2774 int (*fooptr)(void) = foo; // warning: diag1
2775 // warning: diag2
2776
2777 constexpr int supportsAPILevel(int N) { return N < 5; }
2778 int baz(int a)
2779 __attribute__((diagnose_if(!supportsAPILevel(10),
2780 "Upgrade to API level 10 to use baz", "error")));
2781 int baz(int a)
2782 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2783
2784 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2785 int v = baz(0); // error: Upgrade to API level 10 to use baz
2786
2787Query for this feature with ``__has_attribute(diagnose_if)``.)reST";
2788
2789static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the ``disable_sanitizer_instrumentation`` attribute on a function,
2790Objective-C method, or global variable, to specify that no sanitizer
2791instrumentation should be applied.
2792
2793This is not the same as ``__attribute__((no_sanitize(...)))``, which depending
2794on the tool may still insert instrumentation to prevent false positive reports.)reST";
2795
2796static const char AttrDoc_DisableTailCalls[] = R"reST(The ``disable_tail_calls`` attribute instructs the backend to not perform tail
2797call optimization inside the marked function.
2798
2799For example:
2800
2801 .. code-block:: c
2802
2803 int callee(int);
2804
2805 int foo(int a) __attribute__((disable_tail_calls)) {
2806 return callee(a); // This call is not tail-call optimized.
2807 }
2808
2809Marking virtual functions as ``disable_tail_calls`` is legal.
2810
2811 .. code-block:: c++
2812
2813 int callee(int);
2814
2815 class Base {
2816 public:
2817 [[clang::disable_tail_calls]] virtual int foo1() {
2818 return callee(); // This call is not tail-call optimized.
2819 }
2820 };
2821
2822 class Derived1 : public Base {
2823 public:
2824 int foo1() override {
2825 return callee(); // This call is tail-call optimized.
2826 }
2827 };)reST";
2828
2829static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2830empty-base-optimization more frequently.
2831This attribute only applies to struct, class, and union types.
2832It is only supported when using the Microsoft C++ ABI.)reST";
2833
2834static const char AttrDoc_EnableIf[] = R"reST(.. Note:: Some features of this attribute are experimental. The meaning of
2835 multiple enable_if attributes on a single declaration is subject to change in
2836 a future version of clang. Also, the ABI is not standardized and the name
2837 mangling may change in future versions. To avoid that, use asm labels.
2838
2839The ``enable_if`` attribute can be placed on function declarations to control
2840which overload is selected based on the values of the function's arguments.
2841When combined with the ``overloadable`` attribute, this feature is also
2842available in C.
2843
2844.. code-block:: c++
2845
2846 int isdigit(int c);
2847 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")));
2848
2849 void foo(char c) {
2850 isdigit(c);
2851 isdigit(10);
2852 isdigit(-10); // results in a compile-time error.
2853 }
2854
2855The enable_if attribute takes two arguments, the first is an expression written
2856in terms of the function parameters, the second is a string explaining why this
2857overload candidate could not be selected to be displayed in diagnostics. The
2858expression is part of the function signature for the purposes of determining
2859whether it is a redeclaration (following the rules used when determining
2860whether a C++ template specialization is ODR-equivalent), but is not part of
2861the type.
2862
2863The enable_if expression is evaluated as if it were the body of a
2864bool-returning constexpr function declared with the arguments of the function
2865it is being applied to, then called with the parameters at the call site. If the
2866result is false or could not be determined through constant expression
2867evaluation, then this overload will not be chosen and the provided string may
2868be used in a diagnostic if the compile fails as a result.
2869
2870Because the enable_if expression is an unevaluated context, there are no global
2871state changes, nor the ability to pass information from the enable_if
2872expression to the function body. For example, suppose we want calls to
2873strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
2874strbuf) only if the size of strbuf can be determined:
2875
2876.. code-block:: c++
2877
2878 __attribute__((always_inline))
2879 static inline size_t strnlen(const char *s, size_t maxlen)
2880 __attribute__((overloadable))
2881 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
2882 "chosen when the buffer size is known but 'maxlen' is not")))
2883 {
2884 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
2885 }
2886
2887Multiple enable_if attributes may be applied to a single declaration. In this
2888case, the enable_if expressions are evaluated from left to right in the
2889following manner. First, the candidates whose enable_if expressions evaluate to
2890false or cannot be evaluated are discarded. If the remaining candidates do not
2891share ODR-equivalent enable_if expressions, the overload resolution is
2892ambiguous. Otherwise, enable_if overload resolution continues with the next
2893enable_if attribute on the candidates that have not been discarded and have
2894remaining enable_if attributes. In this way, we pick the most specific
2895overload out of a number of viable overloads using enable_if.
2896
2897.. code-block:: c++
2898
2899 void f() __attribute__((enable_if(true, ""))); // #1
2900 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
2901
2902 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
2903 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
2904
2905In this example, a call to f() is always resolved to #2, as the first enable_if
2906expression is ODR-equivalent for both declarations, but #1 does not have another
2907enable_if expression to continue evaluating, so the next round of evaluation has
2908only a single candidate. In a call to g(1, 1), the call is ambiguous even though
2909#2 has more enable_if attributes, because the first enable_if expressions are
2910not ODR-equivalent.
2911
2912Query for this feature with ``__has_attribute(enable_if)``.
2913
2914Note that functions with one or more ``enable_if`` attributes may not have
2915their address taken, unless all of the conditions specified by said
2916``enable_if`` are constants that evaluate to ``true``. For example:
2917
2918.. code-block:: c
2919
2920 const int TrueConstant = 1;
2921 const int FalseConstant = 0;
2922 int f(int a) __attribute__((enable_if(a > 0, "")));
2923 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
2924 int h(int a) __attribute__((enable_if(1, "")));
2925 int i(int a) __attribute__((enable_if(TrueConstant, "")));
2926 int j(int a) __attribute__((enable_if(FalseConstant, "")));
2927
2928 void fn() {
2929 int (*ptr)(int);
2930 ptr = &f; // error: 'a > 0' is not always true
2931 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
2932 ptr = &h; // OK: 1 is a truthy constant
2933 ptr = &i; // OK: 'TrueConstant' is a truthy constant
2934 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
2935 }
2936
2937Because ``enable_if`` evaluation happens during overload resolution,
2938``enable_if`` may give unintuitive results when used with templates, depending
2939on when overloads are resolved. In the example below, clang will emit a
2940diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
2941
2942.. code-block:: c++
2943
2944 double foo(int i) __attribute__((enable_if(i > 0, "")));
2945 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
2946 template <int I>
2947 auto bar() { return foo(I); }
2948
2949 template <typename T>
2950 auto baz() { return foo(T::number); }
2951
2952 struct WithNumber { constexpr static int number = 1; };
2953 void callThem() {
2954 bar<sizeof(WithNumber)>();
2955 baz<WithNumber>();
2956 }
2957
2958This is because, in ``bar``, ``foo`` is resolved prior to template
2959instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
2960conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
2961template instantiation, so the value for ``T::number`` is known.)reST";
2962
2963static const char AttrDoc_EnforceTCB[] = R"reST(The ``enforce_tcb`` attribute can be placed on functions to enforce that a
2964 trusted compute base (TCB) does not call out of the TCB. This generates a
2965 warning every time a function not marked with an ``enforce_tcb`` attribute is
2966 called from a function with the ``enforce_tcb`` attribute. A function may be a
2967 part of multiple TCBs. Invocations through function pointers are currently
2968 not checked. Builtins are considered to a part of every TCB.
2969
2970 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
2971
2972static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
2973 ``enforce_tcb`` for the marked function to be in the named TCB but does not
2974 continue to check the functions called from within the leaf function.
2975
2976 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
2977
2978static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2979that are extensible and those that are not. The attribute can take either
2980``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2981enum type takes a value that corresponds to one of the enumerators listed in the
2982enum definition or, when the enum is annotated with ``flag_enum``, a value that
2983can be constructed using values corresponding to the enumerators. ``open``
2984indicates a variable of the enum type can take any values allowed by the
2985standard and instructs clang to be more lenient when issuing warnings.
2986
2987.. code-block:: c
2988
2989 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2990 A0, A1
2991 };
2992
2993 enum __attribute__((enum_extensibility(open))) OpenEnum {
2994 B0, B1
2995 };
2996
2997 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2998 C0 = 1 << 0, C1 = 1 << 1
2999 };
3000
3001 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3002 D0 = 1 << 0, D1 = 1 << 1
3003 };
3004
3005 void foo1() {
3006 enum ClosedEnum ce;
3007 enum OpenEnum oe;
3008 enum ClosedFlagEnum cfe;
3009 enum OpenFlagEnum ofe;
3010
3011 ce = A1; // no warnings
3012 ce = 100; // warning issued
3013 oe = B1; // no warnings
3014 oe = 100; // no warnings
3015 cfe = C0 | C1; // no warnings
3016 cfe = C0 | C1 | 4; // warning issued
3017 ofe = D0 | D1; // no warnings
3018 ofe = D0 | D1 | 4; // no warnings
3019 })reST";
3020
3021static const char AttrDoc_Error[] = R"reST(The ``error`` and ``warning`` function attributes can be used to specify a
3022custom diagnostic to be emitted when a call to such a function is not
3023eliminated via optimizations. This can be used to create compile time
3024assertions that depend on optimizations, while providing diagnostics
3025pointing to precise locations of the call site in the source.
3026
3027.. code-block:: c++
3028
3029 __attribute__((warning("oh no"))) void dontcall();
3030 void foo() {
3031 if (someCompileTimeAssertionThatsTrue)
3032 dontcall(); // Warning
3033
3034 dontcall(); // Warning
3035
3036 if (someCompileTimeAssertionThatsFalse)
3037 dontcall(); // No Warning
3038 sizeof(dontcall()); // No Warning
3039 })reST";
3040
3041static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
3042class template from being part of explicit template instantiations of that
3043class template. This means that an explicit instantiation will not instantiate
3044members of the class template marked with the attribute, but also that code
3045where an extern template declaration of the enclosing class template is visible
3046will not take for granted that an external instantiation of the class template
3047would provide those members (which would otherwise be a link error, since the
3048explicit instantiation won't provide those members). For example, let's say we
3049don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
3050is not exported from the dylib, we give it hidden visibility:
3051
3052 .. code-block:: c++
3053
3054 // in <string>
3055 template <class CharT>
3056 class basic_string {
3057 public:
3058 __attribute__((__visibility__("hidden")))
3059 const value_type* data() const noexcept { ... }
3060 };
3061
3062 template class basic_string<char>;
3063
3064Since an explicit template instantiation declaration for ``basic_string<char>``
3065is provided, the compiler is free to assume that ``basic_string<char>::data()``
3066will be provided by another translation unit, and it is free to produce an
3067external call to this function. However, since ``data()`` has hidden visibility
3068and the explicit template instantiation is provided in a shared library (as
3069opposed to simply another translation unit), ``basic_string<char>::data()``
3070won't be found and a link error will ensue. This happens because the compiler
3071assumes that ``basic_string<char>::data()`` is part of the explicit template
3072instantiation declaration, when it really isn't. To tell the compiler that
3073``data()`` is not part of the explicit template instantiation declaration, the
3074``exclude_from_explicit_instantiation`` attribute can be used:
3075
3076 .. code-block:: c++
3077
3078 // in <string>
3079 template <class CharT>
3080 class basic_string {
3081 public:
3082 __attribute__((__visibility__("hidden")))
3083 __attribute__((exclude_from_explicit_instantiation))
3084 const value_type* data() const noexcept { ... }
3085 };
3086
3087 template class basic_string<char>;
3088
3089Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
3090externally despite there being an explicit template instantiation declaration:
3091the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
3092TUs where it is used.
3093
3094This attribute can be used on static and non-static member functions of class
3095templates, static data members of class templates and member classes of class
3096templates.
3097
3098**Interaction with __declspec(dllexport/dllimport)**
3099
3100For a DLL platform (i.e., Windows), this attribute also means "this member will
3101never be exported or imported". Despite its name, this semantics applies to
3102implicit instantiations and non-template entities as well.
3103
3104 .. code-block:: c++
3105
3106 // in <exception>
3107 class __declspec(dllimport) nested_exception {
3108 ...
3109 public:
3110 __attribute__((exclude_from_explicit_instantiation))
3111 exception_ptr nested_ptr() const noexcept { ... }
3112 };
3113
3114In this case, ``nested_exception::nested_ptr`` will never be attempted to be
3115imported.)reST";
3116
3117static const char AttrDoc_ExplicitInit[] = R"reST(The ``clang::require_explicit_initialization`` attribute indicates that a
3118field of an aggregate must be initialized explicitly by the user when an object
3119of the aggregate type is constructed. The attribute supports both C and C++,
3120but its usage is invalid on non-aggregates.
3121
3122Note that this attribute is *not* a memory safety feature, and is *not* intended
3123to guard against use of uninitialized memory.
3124
3125Rather, it is intended for use in "parameter-objects", used to simulate,
3126for example, the passing of named parameters.
3127Except inside unevaluated contexts, the attribute generates a warning when
3128explicit initializers for such variables are not provided (this occurs
3129regardless of whether any in-class field initializers exist):
3130
3131.. code-block:: c++
3132
3133 struct Buffer {
3134 void *address [[clang::require_explicit_initialization]];
3135 size_t length [[clang::require_explicit_initialization]] = 0;
3136 };
3137
3138 struct ArrayIOParams {
3139 size_t count [[clang::require_explicit_initialization]];
3140 size_t element_size [[clang::require_explicit_initialization]];
3141 int flags = 0;
3142 };
3143
3144 size_t ReadArray(FILE *file, struct Buffer buffer,
3145 struct ArrayIOParams params);
3146
3147 int main() {
3148 unsigned int buf[512];
3149 ReadArray(stdin, {
3150 buf
3151 // warning: field 'length' is not explicitly initialized
3152 }, {
3153 .count = sizeof(buf) / sizeof(*buf),
3154 // warning: field 'element_size' is not explicitly initialized
3155 // (Note that a missing initializer for 'flags' is not diagnosed, because
3156 // the field is not marked as requiring explicit initialization.)
3157 });
3158 })reST";
3159
3160static const char AttrDoc_ExtVectorType[] = R"reST(The ``ext_vector_type(N)`` attribute specifies that a type is a vector with N
3161elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3162allows element access the array subscript operator ``[]``, ``sN`` where N is
3163a hexadecimal value, or ``x, y, z, w`` for graphics-style indexing.
3164This attribute enables efficient SIMD operations and is usable in
3165general-purpose code.
3166
3167.. code-block:: c++
3168
3169 template <typename T, uint32_t N>
3170 constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3171 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3172 if constexpr (N == 1)
3173 return v[0];
3174 else
3175 return simd_reduce<T, N / 2>(v.hi + v.lo);
3176 }
3177
3178The vector type also supports swizzling up to sixteen elements. This can be done
3179using the object accessors. The OpenCL documentation lists all of the accepted
3180values.
3181
3182.. code-block:: c++
3183
3184 using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3185
3186 f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3187
3188See the OpenCL documentation for some more complete examples.)reST";
3189
3190static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The ``external_source_symbol`` attribute specifies that a declaration originates
3191from an external source and describes the nature of that source.
3192
3193The fact that Clang is capable of recognizing declarations that were defined
3194externally can be used to provide better tooling support for mixed-language
3195projects or projects that rely on auto-generated code. For instance, an IDE that
3196uses Clang and that supports mixed-language projects can use this attribute to
3197provide a correct 'jump-to-definition' feature. For a concrete example,
3198consider a protocol that's defined in a Swift file:
3199
3200.. code-block:: swift
3201
3202 @objc public protocol SwiftProtocol {
3203 func method()
3204 }
3205
3206This protocol can be used from Objective-C code by including a header file that
3207was generated by the Swift compiler. The declarations in that header can use
3208the ``external_source_symbol`` attribute to make Clang aware of the fact
3209that ``SwiftProtocol`` actually originates from a Swift module:
3210
3211.. code-block:: objc
3212
3213 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
3214 @protocol SwiftProtocol
3215 @required
3216 - (void) method;
3217 @end
3218
3219Consequently, when 'jump-to-definition' is performed at a location that
3220references ``SwiftProtocol``, the IDE can jump to the original definition in
3221the Swift source file rather than jumping to the Objective-C declaration in the
3222auto-generated header file.
3223
3224The ``external_source_symbol`` attribute is a comma-separated list that includes
3225clauses that describe the origin and the nature of the particular declaration.
3226Those clauses can be:
3227
3228language=\ *string-literal*
3229 The name of the source language in which this declaration was defined.
3230
3231defined_in=\ *string-literal*
3232 The name of the source container in which the declaration was defined. The
3233 exact definition of source container is language-specific, e.g. Swift's
3234 source containers are modules, so ``defined_in`` should specify the Swift
3235 module name.
3236
3237USR=\ *string-literal*
3238 String that specifies a unified symbol resolution (USR) value for this
3239 declaration. USR string uniquely identifies this particular declaration, and
3240 is typically used when constructing an index of a codebase.
3241 The USR value in this attribute is expected to be generated by an external
3242 compiler that compiled the native declaration using its original source
3243 language. The exact format of the USR string and its other attributes
3244 are determined by the specification of this declaration's source language.
3245 When not specified, Clang's indexer will use the Clang USR for this symbol.
3246 User can query to see if Clang supports the use of the ``USR`` clause in
3247 the ``external_source_symbol`` attribute with
3248 ``__has_attribute(external_source_symbol) >= 20230206``.
3249
3250generated_declaration
3251 This declaration was automatically generated by some tool.
3252
3253The clauses can be specified in any order. The clauses that are listed above are
3254all optional, but the attribute has to have at least one clause.)reST";
3255
3256static const char AttrDoc_FallThrough[] = R"reST(The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
3257to annotate intentional fall-through
3258between switch labels. It can only be applied to a null statement placed at a
3259point of execution between any statement and the next switch label. It is
3260common to mark these places with a specific comment, but this attribute is
3261meant to replace comments with a more strict annotation, which can be checked
3262by the compiler. This attribute doesn't change semantics of the code and can
3263be used wherever an intended fall-through occurs. It is designed to mimic
3264control-flow statements like ``break;``, so it can be placed in most places
3265where ``break;`` can, but only if there are no statements on the execution path
3266between it and the next switch label.
3267
3268By default, Clang does not warn on unannotated fallthrough from one ``switch``
3269case to another. Diagnostics on fallthrough without a corresponding annotation
3270can be enabled with the ``-Wimplicit-fallthrough`` argument.
3271
3272Here is an example:
3273
3274.. code-block:: c++
3275
3276 // compile with -Wimplicit-fallthrough
3277 switch (n) {
3278 case 22:
3279 case 33: // no warning: no statements between case labels
3280 f();
3281 case 44: // warning: unannotated fall-through
3282 g();
3283 [[clang::fallthrough]];
3284 case 55: // no warning
3285 if (x) {
3286 h();
3287 break;
3288 }
3289 else {
3290 i();
3291 [[clang::fallthrough]];
3292 }
3293 case 66: // no warning
3294 p();
3295 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3296 // directly precede case label
3297 q();
3298 case 77: // warning: unannotated fall-through
3299 r();
3300 })reST";
3301
3302static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3303function to use ECX and EDX as register parameters and clear parameters off of
3304the stack on return. This convention does not support variadic calls or
3305unprototyped functions in C, and has no effect on x86_64 targets. This calling
3306convention is supported primarily for compatibility with existing code. Users
3307seeking register parameters should use the ``regparm`` attribute, which does
3308not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
3309
3310.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3311
3312static const char AttrDoc_Final[] = R"reST()reST";
3313
3314static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3315is intended to be used as a flag type. This will cause the compiler to assume
3316that the range of the type includes all of the values that you can get by
3317manipulating bits of the enumerator when issuing warnings.)reST";
3318
3319static const char AttrDoc_Flatten[] = R"reST(The ``flatten`` attribute causes calls within the attributed function to
3320be inlined unless it is impossible to do so, for example if the body of the
3321callee is unavailable or if the callee has the ``noinline`` attribute.)reST";
3322
3323static const char AttrDoc_Format[] = R"reST(Clang supports the ``format`` attribute, which indicates that the function
3324accepts (among other possibilities) a ``printf`` or ``scanf``-like format string
3325and corresponding arguments or a ``va_list`` that contains these arguments.
3326
3327Please see `GCC documentation about format attribute
3328<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
3329about attribute syntax.
3330
3331Clang implements two kinds of checks with this attribute.
3332
3333#. Clang checks that the function with the ``format`` attribute is called with
3334 a format string that uses format specifiers that are allowed, and that
3335 arguments match the format string. This is the ``-Wformat`` warning, it is
3336 on by default.
3337
3338#. Clang checks that the format string argument is a literal string. This is
3339 the ``-Wformat-nonliteral`` warning, it is off by default.
3340
3341 Clang implements this mostly the same way as GCC, but there is a difference
3342 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
3343 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
3344 functions. Clang does not warn if the format string comes from a function
3345 parameter, where the function is annotated with a compatible attribute,
3346 otherwise it warns. For example:
3347
3348 .. code-block:: c
3349
3350 __attribute__((__format__ (__scanf__, 1, 3)))
3351 void foo(const char* s, char *buf, ...) {
3352 va_list ap;
3353 va_start(ap, buf);
3354
3355 vprintf(s, ap); // warning: format string is not a string literal
3356 }
3357
3358 In this case we warn because ``s`` contains a format string for a
3359 ``scanf``-like function, but it is passed to a ``printf``-like function.
3360
3361 If the attribute is removed, clang still warns, because the format string is
3362 not a string literal.
3363
3364 Another example:
3365
3366 .. code-block:: c
3367
3368 __attribute__((__format__ (__printf__, 1, 3)))
3369 void foo(const char* s, char *buf, ...) {
3370 va_list ap;
3371 va_start(ap, buf);
3372
3373 vprintf(s, ap); // warning
3374 }
3375
3376 In this case Clang does not warn because the format string ``s`` and
3377 the corresponding arguments are annotated. If the arguments are
3378 incorrect, the caller of ``foo`` will receive a warning.
3379
3380As an extension to GCC's behavior, Clang accepts the ``format`` attribute on
3381non-variadic functions. Clang checks non-variadic format functions for the same
3382classes of issues that can be found on variadic functions, as controlled by the
3383same warning flags, except that the types of formatted arguments is forced by
3384the function signature. For example:
3385
3386.. code-block:: c
3387
3388 __attribute__((__format__(__printf__, 1, 2)))
3389 void fmt(const char *s, const char *a, int b);
3390
3391 void bar(void) {
3392 fmt("%s %i", "hello", 123); // OK
3393 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3394 extern const char *fmt;
3395 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3396 }
3397
3398When using the format attribute on a variadic function, the first data parameter
3399_must_ be the index of the ellipsis in the parameter list. Clang will generate
3400a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3401to `printf`-family functions. For instance, this is an error:
3402
3403.. code-block:: c
3404
3405 __attribute__((__format__(__printf__, 1, 2)))
3406 void fmt(const char *s, int b, ...);
3407 // ^ error: format attribute parameter 3 is out of bounds
3408 // (must be __printf__, 1, 3)
3409
3410Using the ``format`` attribute on a non-variadic function emits a GCC
3411compatibility diagnostic.)reST";
3412
3413static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3414
3415static const char AttrDoc_FormatMatches[] = R"reST(The ``format`` attribute is the basis for the enforcement of diagnostics in the
3416``-Wformat`` family, but it only handles the case where the format string is
3417passed along with the arguments it is going to format. It cannot handle the case
3418where the format string and the format arguments are passed separately from each
3419other. For instance:
3420
3421.. code-block:: c
3422
3423 static const char *first_name;
3424 static double todays_temperature;
3425 static int wind_speed;
3426
3427 void say_hi(const char *fmt) {
3428 printf(fmt, first_name, todays_temperature);
3429 // ^ warning: format string is not a string literal
3430 printf(fmt, first_name, wind_speed);
3431 // ^ warning: format string is not a string literal
3432 }
3433
3434 int main() {
3435 say_hi("hello %s, it is %g degrees outside");
3436 say_hi("hello %s, it is %d degrees outside!");
3437 // ^ no diagnostic, but %d cannot format doubles
3438 }
3439
3440In this example, ``fmt`` is expected to format a ``const char *`` and a
3441``double``, but these values are not passed to ``say_hi``. Without the
3442``format`` attribute (which cannot apply in this case), the -Wformat-nonliteral
3443diagnostic unnecessarily triggers in the body of ``say_hi``, and incorrect
3444``say_hi`` call sites do not trigger a diagnostic.
3445
3446To complement the ``format`` attribute, Clang also defines the
3447``format_matches`` attribute. Its syntax is similar to the ``format``
3448attribute's, but instead of taking the index of the first formatted value
3449argument, it takes a C string literal with the expected specifiers:
3450
3451.. code-block:: c
3452
3453 static const char *first_name;
3454 static double todays_temperature;
3455 static int wind_speed;
3456
3457 __attribute__((__format_matches__(printf, 1, "%s %g")))
3458 void say_hi(const char *fmt) {
3459 printf(fmt, first_name, todays_temperature); // no dignostic
3460 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3461 }
3462
3463 int main() {
3464 say_hi("hello %s, it is %g degrees outside");
3465 say_hi("it is %g degrees outside, have a good day %s!");
3466 // warning: format specifies 'double' where 'const char *' is required
3467 // warning: format specifies 'const char *' where 'double' is required
3468 }
3469
3470The third argument to ``format_matches`` is expected to evaluate to a **C string
3471literal** even when the format string would normally be a different type for the
3472given flavor, like a ``CFStringRef`` or a ``NSString *``.
3473
3474The only requirement on the format string literal is that it has specifiers
3475that are compatible with the arguments that will be used. It can contain
3476arbitrary non-format characters. For instance, for the purposes of compile-time
3477validation, ``"%s scored %g%% on her test"`` and ``"%s%g"`` are interchangeable
3478as the format string argument. As a means of self-documentation, users may
3479prefer the former when it provides a useful example of an expected format
3480string.
3481
3482In the implementation of a function with the ``format_matches`` attribute,
3483format verification works as if the format string was identical to the one
3484specified in the attribute.
3485
3486.. code-block:: c
3487
3488 __attribute__((__format_matches__(printf, 1, "%s %g")))
3489 void say_hi(const char *fmt) {
3490 printf(fmt, "person", 546);
3491 // ^ warning: format specifies type 'double' but the
3492 // argument has type 'int'
3493 // note: format string is defined here:
3494 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3495 // ^~
3496 }
3497
3498
3499At the call sites of functions with the ``format_matches`` attribute, format
3500verification instead compares the two format strings to evaluate their
3501equivalence. Each format flavor defines equivalence between format specifiers.
3502Generally speaking, two specifiers are equivalent if they format the same type.
3503For instance, in the ``printf`` flavor, ``%2i`` and ``%-0.5d`` are compatible.
3504When ``-Wformat-signedness`` is disabled, ``%d`` and ``%u`` are compatible. For
3505a negative example, ``%ld`` is incompatible with ``%d``.
3506
3507Do note the following un-obvious cases:
3508
3509* Passing ``NULL`` as the format string does not trigger format diagnostics.
3510* When the format string is not NULL, it cannot _miss_ specifiers, even in
3511 trailing positions. For instance, ``%d`` is not accepted when the required
3512 format is ``%d %d %d``.
3513* While checks for the ``format`` attribute tolerate sone size mismatches
3514 that standard argument promotion renders immaterial (such as formatting an
3515 ``int`` with ``%hhd``, which specifies a ``char``-sized integer), checks for
3516 ``format_matches`` require specified argument sizes to match exactly.
3517* Format strings expecting a variable modifier (such as ``%*s``) are
3518 incompatible with format strings that would itemize the variable modifiers
3519 (such as ``%i %s``), even if the two specify ABI-compatible argument lists.
3520* All pointer specifiers, modifiers aside, are mutually incompatible. For
3521 instance, ``%s`` is not compatible with ``%p``, and ``%p`` is not compatible
3522 with ``%n``, and ``%hhn`` is incompatible with ``%s``, even if the pointers
3523 are ABI-compatible or identical on the selected platform. However, ``%0.5s``
3524 is compatible with ``%s``, since the difference only exists in modifier flags.
3525 This is not overridable with ``-Wformat-pedantic`` or its inverse, which
3526 control similar behavior in ``-Wformat``.
3527
3528At this time, clang implements ``format_matches`` only for format types in the
3529``printf`` family. This includes variants such as Apple's NSString format and
3530the FreeBSD ``kprintf``, but excludes ``scanf``. Using a known but unsupported
3531format silently fails in order to be compatible with other implementations that
3532would support these formats.)reST";
3533
3534static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute ``function_return`` can replace return instructions with jumps to
3535target-specific symbols. This attribute supports 2 possible values,
3536corresponding to the values supported by the ``-mfunction-return=`` command
3537line flag:
3538
3539* ``__attribute__((function_return("keep")))`` to disable related transforms.
3540 This is useful for undoing global setting from ``-mfunction-return=`` locally
3541 for individual functions.
3542* ``__attribute__((function_return("thunk-extern")))`` to replace returns with
3543 jumps, while NOT emitting the thunk.
3544
3545The values ``thunk`` and ``thunk-inline`` from GCC are not supported.
3546
3547The symbol used for ``thunk-extern`` is target specific:
3548* X86: ``__x86_return_thunk``
3549
3550As such, this function attribute is currently only supported on X86 targets.)reST";
3551
3552static const char AttrDoc_GCCStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
3553special record layout compatibility mode which mimics the layout of Microsoft or
3554Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3555requested ABI, the attribute does nothing. However, if it does not, annotated
3556structure or class is laid out in a special compatibility mode, which slightly
3557changes offsets for fields and bit-fields. The intention is to match the layout
3558of the requested ABI for structures which only use C features.
3559
3560Note that the default behavior can be controlled by ``-mms-bitfields`` and
3561``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
3562
3563The primary difference is for bitfields, where the MS variant only packs
3564adjacent fields into the same allocation unit if they have integral types
3565of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3566tightly.)reST";
3567
3568static const char AttrDoc_GNUInline[] = R"reST(The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
3569semantics, meaning:
3570
3571* If any declaration that is declared ``inline`` is not declared ``extern``,
3572 then the ``inline`` keyword is just a hint. In particular, an out-of-line
3573 definition is still emitted for a function with external linkage, even if all
3574 call sites are inlined, unlike in C99 and C++ inline semantics.
3575
3576* If all declarations that are declared ``inline`` are also declared
3577 ``extern``, then the function body is present only for inlining and no
3578 out-of-line version is emitted.
3579
3580Some important consequences: ``static inline`` emits an out-of-line
3581version if needed, a plain ``inline`` definition emits an out-of-line version
3582always, and an ``extern inline`` definition (in a header) followed by a
3583(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
3584version of the function in that source file but provides the function body for
3585inlining to all includers of the header.
3586
3587Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
3588``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
3589exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
3590function attribute can be used to get GNU inline semantics on a per function
3591basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
3592already being compiled with GNU inline semantics as the implied default. It is
3593unspecified which macro is defined in a C++ compilation.
3594
3595GNU inline semantics are the default behavior with ``-std=gnu89``,
3596``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.)reST";
3597
3598static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3599
3600static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3601
3602static const char AttrDoc_HIPManaged[] = R"reST(The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
3603A managed variable is emitted as an undefined global symbol in the device binary and is
3604registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
3605managed memory and uses it to define the symbol when loading the device binary.
3606A managed variable can be accessed in both device and host code.)reST";
3607
3608static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3609
3610static const char AttrDoc_HLSLContainedType[] = R"reST()reST";
3611
3612static const char AttrDoc_HLSLControlFlowHint[] = R"reST()reST";
3613
3614static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3615HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3616and so on to ensure the correct ordering of reads and writes to shared memory
3617in the shader and to avoid data races.
3618Here's an example to declare a groupshared variable.
3619.. code-block:: c++
3620
3621 groupshared GSData data[5*5*1];
3622
3623The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared)reST";
3624
3625static const char AttrDoc_HLSLIsCounter[] = R"reST()reST";
3626
3627static const char AttrDoc_HLSLLoopHint[] = R"reST(The ``[loop]`` directive allows loop optimization hints to be
3628specified for the subsequent loop. The directive allows unrolling to
3629be disabled and is not compatible with [unroll(x)].
3630
3631Specifying the parameter, ``[loop]``, directs the
3632unroller to not unroll the loop.
3633
3634.. code-block:: hlsl
3635
3636 [loop]
3637 for (...) {
3638 ...
3639 }
3640
3641.. code-block:: hlsl
3642
3643 [loop]
3644 while (...) {
3645 ...
3646 }
3647
3648.. code-block:: hlsl
3649
3650 [loop]
3651 do {
3652 ...
3653 } while (...)
3654
3655See `hlsl loop extensions <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for>`_
3656for details.)reST";
3657
3658static const char AttrDoc_HLSLNumThreads[] = R"reST(The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts
3659are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute
3660dictate the thread id. Total number of threads executed is ``X * Y * Z``.
3661
3662The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)reST";
3663
3664static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3665Attribute spelling in HLSL is: ``packoffset( c[Subcomponent][.component] )``.
3666A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3667
3668Examples:
3669
3670.. code-block:: hlsl
3671
3672 cbuffer A {
3673 float3 a : packoffset(c0.y);
3674 float4 b : packoffset(c4);
3675 }
3676
3677The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset)reST";
3678
3679static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3680three qualifiers to denote parameter passing behavior. The three qualifiers are
3681`in`, `out` and `inout`.
3682
3683Parameters annotated with `in` or with no annotation are passed by value from
3684the caller to the callee.
3685
3686Parameters annotated with `out` are written to the argument after the callee
3687returns (Note: arguments values passed into `out` parameters *are not* copied
3688into the callee).
3689
3690Parameters annotated with `inout` are copied into the callee via a temporary,
3691and copied back to the argument after the callee returns.)reST";
3692
3693static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3694
3695static const char AttrDoc_HLSLROV[] = R"reST()reST";
3696
3697static const char AttrDoc_HLSLRawBuffer[] = R"reST()reST";
3698
3699static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3700Attribute spelling in HLSL is: ``register(slot [, space])``.
3701``slot`` takes the format ``[type][number]``,
3702where ``type`` is a single character specifying the resource type and ``number`` is the virtual register number.
3703
3704Register types are:
3705t for shader resource views (SRV),
3706s for samplers,
3707u for unordered access views (UAV),
3708b for constant buffer views (CBV).
3709
3710Register space is specified in the format ``space[number]`` and defaults to ``space0`` if omitted.
3711Here're resource binding examples with and without space:
3712
3713.. code-block:: hlsl
3714
3715 RWBuffer<float> Uav : register(u3, space1);
3716 Buffer<float> Buf : register(t1);
3717
3718The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl)reST";
3719
3720static const char AttrDoc_HLSLResourceClass[] = R"reST()reST";
3721
3722static const char AttrDoc_HLSLResourceDimension[] = R"reST()reST";
3723
3724static const char AttrDoc_HLSLShader[] = R"reST(The ``shader`` type attribute applies to HLSL shader entry functions to
3725identify the shader type for the entry function.
3726The syntax is:
3727
3728.. code-block:: text
3729
3730 ``[shader(string-literal)]``
3731
3732where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3733"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3734"miss", "callable", "mesh", "amplification". Normally the shader type is set
3735by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
3736library target like ``lib_6_3``, the shader type attribute can help the
3737compiler to identify the shader type. It is mostly used by Raytracing shaders
3738where shaders must be compiled into a library and linked at runtime.)reST";
3739
3740static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
3741
3742static const char AttrDoc_HLSLVkBinding[] = R"reST(The ``[[vk::binding]]`` attribute allows you to explicitly specify the descriptor
3743set and binding for a resource when targeting SPIR-V. This is particularly
3744useful when you need different bindings for SPIR-V and DXIL, as the ``register``
3745attribute can be used for DXIL-specific bindings.
3746
3747The attribute takes two integer arguments: the binding and the descriptor set.
3748The descriptor set is optional and defaults to 0 if not provided.
3749
3750.. code-block:: c++
3751
3752 // A structured buffer with binding 23 in descriptor set 102.
3753 [[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
3754
3755 // A structured buffer with binding 14 in descriptor set 0.
3756 [[vk::binding(14)]] StructuredBuffer<float> Buf2;
3757
3758 // A cbuffer with binding 1 in descriptor set 2.
3759 [[vk::binding(1, 2)]] cbuffer MyCBuffer {
3760 float4x4 worldViewProj;
3761 };)reST";
3762
3763static const char AttrDoc_HLSLVkConstantId[] = R"reST(The ``vk::constant_id`` attribute specifies the id for a SPIR-V specialization
3764constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
3765In SPIR-V, the
3766variable will be replaced with an `OpSpecConstant` with the given id.
3767The syntax is:
3768
3769.. code-block:: text
3770
3771 ``[[vk::constant_id(<Id>)]] const T Name = <Init>``)reST";
3772
3773static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
3774initialized by the driver/pipeline, but each copy is private to the current
3775lane.
3776
3777Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
3778like follows:
3779
3780.. code-block:: c++
3781
3782 [[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
3783 static const uint3 groupid;
3784
3785This variable will be lowered into a module-level variable, with the `Input`
3786storage class, and the `BuiltIn 26` decoration.
3787
3788The full documentation for this inline SPIR-V attribute can be found here:
3789https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3790
3791static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
3792variables. Allowed on function parameters, function returns, and struct
3793fields. This parameter has no effect when used outside of an entrypoint
3794parameter/parameter field/return value.
3795
3796This attribute maps to the 'Location' SPIR-V decoration.)reST";
3797
3798static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
3799
3800The ``[[vk::push_constant]]`` attribute allows you to declare this
3801global variable as a push constant when targeting Vulkan.
3802This attribute is ignored otherwise.
3803
3804This attribute must be applied to the variable, not underlying type.
3805The variable type must be a struct, per the requirements of Vulkan, "there
3806must be no more than one push constant block statically used per shader entry
3807point.")reST";
3808
3809static const char AttrDoc_HLSLWaveSize[] = R"reST(The ``WaveSize`` attribute specify a wave size on a shader entry point in order
3810to indicate either that a shader depends on or strongly prefers a specific wave
3811size.
3812There're 2 versions of the attribute: ``WaveSize`` and ``RangedWaveSize``.
3813The syntax for ``WaveSize`` is:
3814
3815.. code-block:: text
3816
3817 ``[WaveSize(<numLanes>)]``
3818
3819The allowed wave sizes that an HLSL shader may specify are the powers of 2
3820between 4 and 128, inclusive.
3821In other words, the set: [4, 8, 16, 32, 64, 128].
3822
3823The syntax for ``RangedWaveSize`` is:
3824
3825.. code-block:: text
3826
3827 ``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
3828
3829Where minWaveSize is the minimum wave size supported by the shader representing
3830the beginning of the allowed range, maxWaveSize is the maximum wave size
3831supported by the shader representing the end of the allowed range, and
3832prefWaveSize is the optional preferred wave size representing the size expected
3833to be the most optimal for this shader.
3834
3835``WaveSize`` is available for HLSL shader model 6.6 and later.
3836``RangedWaveSize`` available for HLSL shader model 6.8 and later.
3837
3838The full documentation is available here: https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html
3839and https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html)reST";
3840
3841static const char AttrDoc_Hot[] = R"reST(``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data.
3842If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``).)reST";
3843
3844static const char AttrDoc_HybridPatchable[] = R"reST(The ``hybrid_patchable`` attribute declares an ARM64EC function with an additional
3845x86-64 thunk, which may be patched at runtime.
3846
3847For more information see
3848`ARM64EC ABI documentation <https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi>`_.)reST";
3849
3850static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
3851
3852static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
3853
3854static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
3855
3856static const char AttrDoc_IFunc[] = R"reST(``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
3857declaration should be resolved at runtime by calling a resolver function.
3858
3859The symbol name of the resolver function is given in quotes. A function with
3860this name (after mangling) must be defined in the current translation unit; it
3861may be ``static``. The resolver function should return a pointer.
3862
3863The ``ifunc`` attribute may only be used on a function declaration. A function
3864declaration with an ``ifunc`` attribute is considered to be a definition of the
3865declared entity. The entity must not have weak linkage; for example, in C++,
3866it cannot be applied to a declaration if a definition at that location would be
3867considered inline.
3868
3869Not all targets support this attribute:
3870
3871- ELF target support depends on both the linker and runtime linker, and is
3872 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
3873 v2.11.1 and later, and FreeBSD 9.1 and later.
3874- Mach-O targets support it, but with slightly different semantics: the resolver
3875 is run at first call, instead of at load time by the runtime linker.
3876- Windows target supports it on AArch64, but with different semantics: the
3877 ``ifunc`` is replaced with a global function pointer, and the call is replaced
3878 with an indirect call. The function pointer is initialized by a constructor
3879 that calls the resolver.
3880- Baremetal target supports it on AVR.
3881- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
3882 regular function (has an entry point ``.foo[PR]`` and a function descriptor
3883 ``foo[DS]``). The entry point is a stub that branches to the function address
3884 in the descriptor, and the descriptor is initialized via a constructor
3885 function (``__init_ifuncs``) that is linked into every shared object and
3886 executable. ``__init_ifuncs`` calls the resolver of each ifunc and stores the
3887 result in the corresponding descriptor.
3888- Other targets currently do not support this attribute.)reST";
3889
3890static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
3891
3892static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
3893units is unspecified, unlike the ordering within a single translation unit. The
3894``init_priority`` attribute allows you to specify a relative ordering for the
3895initialization of objects declared at namespace scope in C++ within a single
3896linked image on supported platforms. The priority is given as an integer constant
3897expression between 101 and 65535 (inclusive). Priorities outside of that range are
3898reserved for use by the implementation. A lower value indicates a higher priority
3899of initialization. Note that only the relative ordering of values is important.
3900For example:
3901
3902.. code-block:: c++
3903
3904 struct SomeType { SomeType(); };
3905 __attribute__((init_priority(200))) SomeType Obj1;
3906 __attribute__((init_priority(101))) SomeType Obj2;
3907
3908``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
3909initialization being the opposite.
3910
3911Note that this attribute does not control the initialization order of objects
3912across final linked image boundaries like shared objects and executables.
3913
3914On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and
3915``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)``
3916uses the default 65535 priority.
3917
3918On MachO platforms, this attribute also does not control the order of initialization
3919across translation units, where it only affects the order within a single TU.
3920
3921This attribute is only supported for C++ and Objective-C++ and is ignored in
3922other language modes. Currently, this attribute is not implemented on z/OS.)reST";
3923
3924static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by ``pragma init_seg()`` controls the section into
3925which global initialization function pointers are emitted. It is only
3926available with ``-fms-extensions``. Typically, this function pointer is
3927emitted into ``.CRT$XCU`` on Windows. The user can change the order of
3928initialization by using a different section name with the same
3929``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
3930after the standard ``.CRT$XCU`` sections. See the init_seg_
3931documentation on MSDN for more information.
3932
3933.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
3934
3935static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
3936
3937static const char AttrDoc_InternalLinkage[] = R"reST(The ``internal_linkage`` attribute changes the linkage type of the declaration
3938to internal. This is similar to C-style ``static``, but can be used on classes
3939and class methods. When applied to a class definition, this attribute affects
3940all methods and static data members of that class. This can be used to contain
3941the ABI of a C++ library by excluding unwanted class methods from the export
3942tables.)reST";
3943
3944static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See :doc:`LTOVisibility`.)reST";
3945
3946static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
3947layout rules of a particular compiler version.
3948This attribute only applies to struct, class, and union types.
3949It is only supported when using the Microsoft C++ ABI.)reST";
3950
3951static const char AttrDoc_Leaf[] = R"reST(The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
3952in library functions. Functions marked with the ``leaf`` attribute are not allowed
3953to jump back into the caller's translation unit, whether through invoking a
3954callback function, an external function call, use of ``longjmp``, or other means.
3955Therefore, they cannot use or modify any data that does not escape the caller function's
3956compilation unit.
3957
3958For more information see
3959`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
3960
3961static const char AttrDoc_LifetimeBound[] = R"reST(The ``lifetimebound`` attribute on a function parameter or implicit object
3962parameter indicates that objects that are referred to by that parameter may
3963also be referred to by the return value of the annotated function (or, for a
3964parameter of a constructor, by the value of the constructed object).
3965
3966By default, a reference is considered to refer to its referenced object, a
3967pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
3968is considered to refer to its underlying array, and aggregates (arrays and
3969simple ``struct``\s) are considered to refer to all objects that their
3970transitive subobjects refer to.
3971
3972Clang warns if it is able to detect that an object or reference refers to
3973another object with a shorter lifetime. For example, Clang will warn if a
3974function returns a reference to a local variable, or if a reference is bound to
3975a temporary object whose lifetime is not extended. By using the
3976``lifetimebound`` attribute, this determination can be extended to look through
3977user-declared functions. For example:
3978
3979.. code-block:: c++
3980
3981 #include <map>
3982 #include <string>
3983
3984 using namespace std::literals;
3985
3986 // Returns m[key] if key is present, or default_value if not.
3987 template<typename T, typename U>
3988 const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
3989 const T &key, /* note, not lifetimebound */
3990 const U &default_value [[clang::lifetimebound]]) {
3991 if (auto iter = m.find(key); iter != m.end()) return iter->second;
3992 else return default_value;
3993 }
3994
3995 int main() {
3996 std::map<std::string, std::string> m;
3997 // warning: temporary bound to local reference 'val1' will be destroyed
3998 // at the end of the full-expression
3999 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4000
4001 // No warning in this case.
4002 std::string def_val = "bar"s;
4003 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4004
4005 return 0;
4006 }
4007
4008The attribute can be applied to the implicit ``this`` parameter of a member
4009function by writing the attribute after the function type:
4010
4011.. code-block:: c++
4012
4013 struct string {
4014 // The returned pointer should not outlive ``*this``.
4015 const char *data() const [[clang::lifetimebound]];
4016 };
4017
4018This attribute is inspired by the C++ committee paper `P0936R0
4019<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects
4020have their lifetimes extended.)reST";
4021
4022static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to `lifetimebound`_, the ``lifetime_capture_by(X)`` attribute on a
4023function parameter or implicit object parameter indicates that the capturing
4024entity ``X`` may refer to the object referred by that parameter.
4025
4026Below is a list of types of the parameters and what they're considered to refer to:
4027
4028- A reference param (of non-view type) is considered to refer to its referenced object.
4029- A pointer param (of non-view type) is considered to refer to its pointee.
4030- View type param (type annotated with ``[[gsl::Pointer()]]``) is considered to refer
4031 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4032 in the parameter. For example, both ``std::string_view`` and
4033 ``const std::string_view &`` are considered to refer to a ``std::string``.
4034- A ``std::initializer_list<T>`` is considered to refer to its underlying array.
4035- Aggregates (arrays and simple ``struct``\s) are considered to refer to all
4036 objects that their transitive subobjects refer to.
4037
4038Clang would diagnose when a temporary object is used as an argument to such an
4039annotated parameter.
4040In this case, the capturing entity ``X`` could capture a dangling reference to this
4041temporary object.
4042
4043.. code-block:: c++
4044
4045 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4046 s.insert(a);
4047 }
4048 void use() {
4049 std::set<std::string_view> s;
4050 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4051 // ^^^^^^^^^^^^^
4052 std::string local;
4053 addToSet(local, s); // Ok.
4054 }
4055
4056The capturing entity ``X`` can be one of the following:
4057
4058- Another (named) function parameter.
4059
4060 .. code-block:: c++
4061
4062 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4063 s.insert(a);
4064 }
4065
4066- ``this`` (in case of member functions).
4067
4068 .. code-block:: c++
4069
4070 class S {
4071 void addToSet(std::string_view a [[clang::lifetime_capture_by(this)]]) {
4072 s.insert(a);
4073 }
4074 std::set<std::string_view> s;
4075 };
4076
4077 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by(this)]]` is just an alias of `[[clang::lifetimebound]]`.
4078
4079- `global`, `unknown`.
4080
4081 .. code-block:: c++
4082
4083 std::set<std::string_view> s;
4084 void addToSet(std::string_view a [[clang::lifetime_capture_by(global)]]) {
4085 s.insert(a);
4086 }
4087 void addSomewhere(std::string_view a [[clang::lifetime_capture_by(unknown)]]);
4088
4089The attribute can be applied to the implicit ``this`` parameter of a member
4090function by writing the attribute after the function type:
4091
4092.. code-block:: c++
4093
4094 struct S {
4095 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4096 s.insert(this);
4097 }
4098 };
4099
4100The attribute supports specifying more than one capturing entities:
4101
4102.. code-block:: c++
4103
4104 void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4105 std::set<std::string_view>& s1,
4106 std::set<std::string_view>& s2) {
4107 s1.insert(a);
4108 s2.insert(a);
4109 }
4110
4111Limitation: The capturing entity ``X`` is not used by the analysis and is
4112used for documentation purposes only. This is because the analysis is
4113statement-local and only detects use of a temporary as an argument to the
4114annotated parameter.
4115
4116.. code-block:: c++
4117
4118 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4119 void use() {
4120 std::set<std::string_view> s;
4121 if (foo()) {
4122 std::string str;
4123 addToSet(str, s); // Not detected.
4124 }
4125 })reST";
4126
4127static const char AttrDoc_Likely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
4128The attributes are used to aid the compiler to determine which branch is
4129likely or unlikely to be taken. This is done by marking the branch substatement
4130with one of the two attributes.
4131
4132It isn't allowed to annotate a single statement with both ``likely`` and
4133``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
4134statement with the same likelihood attribute will result in a diagnostic and
4135the attributes are ignored on both branches.
4136
4137In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
4138or the ``default`` label with the same likelihood attribute. This makes
4139* all labels without an attribute have a neutral likelihood,
4140* all labels marked ``[[likely]]`` have an equally positive likelihood, and
4141* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
4142The neutral likelihood is the more likely of path execution than the negative
4143likelihood. The positive likelihood is the more likely of path of execution
4144than the neutral likelihood.
4145
4146These attributes have no effect on the generated code when using
4147PGO (Profile-Guided Optimization) or at optimization level 0.
4148
4149In Clang, the attributes will be ignored if they're not placed on
4150* the ``case`` or ``default`` label of a ``switch`` statement,
4151* or on the substatement of an ``if`` or ``else`` statement,
4152* or on the substatement of an ``for`` or ``while`` statement.
4153The C++ Standard recommends to honor them on every statement in the
4154path of execution, but that can be confusing:
4155
4156.. code-block:: c++
4157
4158 if (b) {
4159 [[unlikely]] --b; // Per the standard this is in the path of
4160 // execution, so this branch should be considered
4161 // unlikely. However, Clang ignores the attribute
4162 // here since it is not on the substatement.
4163 }
4164
4165 if (b) {
4166 --b;
4167 if(b)
4168 return;
4169 [[unlikely]] --b; // Not in the path of execution,
4170 } // the branch has no likelihood information.
4171
4172 if (b) {
4173 --b;
4174 foo(b);
4175 // Whether or not the next statement is in the path of execution depends
4176 // on the declaration of foo():
4177 // In the path of execution: void foo(int);
4178 // Not in the path of execution: [[noreturn]] void foo(int);
4179 // This means the likelihood of the branch depends on the declaration
4180 // of foo().
4181 [[unlikely]] --b;
4182 }
4183
4184
4185Below are some example usages of the likelihood attributes and their effects:
4186
4187.. code-block:: c++
4188
4189 if (b) [[likely]] { // Placement on the first statement in the branch.
4190 // The compiler will optimize to execute the code here.
4191 } else {
4192 }
4193
4194 if (b)
4195 [[unlikely]] b++; // Placement on the first statement in the branch.
4196 else {
4197 // The compiler will optimize to execute the code here.
4198 }
4199
4200 if (b) {
4201 [[unlikely]] b++; // Placement on the second statement in the branch.
4202 } // The attribute will be ignored.
4203
4204 if (b) [[likely]] {
4205 [[unlikely]] b++; // No contradiction since the second attribute
4206 } // is ignored.
4207
4208 if (b)
4209 ;
4210 else [[likely]] {
4211 // The compiler will optimize to execute the code here.
4212 }
4213
4214 if (b)
4215 ;
4216 else
4217 // The compiler will optimize to execute the next statement.
4218 [[likely]] b = f();
4219
4220 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4221 else [[likely]]; // and the attributes are ignored.
4222
4223 if (b)
4224 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4225 // isn't allowed on a declaration.
4226
4227 switch (i) {
4228 [[likely]] case 1: // This value is likely
4229 ...
4230 break;
4231
4232 [[unlikely]] case 2: // This value is unlikely
4233 ...
4234 [[fallthrough]];
4235
4236 case 3: // No likelihood attribute
4237 ...
4238 [[likely]] break; // No effect
4239
4240 case 4: [[likely]] { // attribute on substatement has no effect
4241 ...
4242 break;
4243 }
4244
4245 [[unlikely]] default: // All other values are unlikely
4246 ...
4247 break;
4248 }
4249
4250 switch (i) {
4251 [[likely]] case 0: // This value and code path is likely
4252 ...
4253 [[fallthrough]];
4254
4255 case 1: // No likelihood attribute, code path is neutral
4256 break; // falling through has no effect on the likelihood
4257
4258 case 2: // No likelihood attribute, code path is neutral
4259 [[fallthrough]];
4260
4261 [[unlikely]] default: // This value and code path are both unlikely
4262 break;
4263 }
4264
4265 for(int i = 0; i != size; ++i) [[likely]] {
4266 ... // The loop is the likely path of execution
4267 }
4268
4269 for(const auto &E : Elements) [[likely]] {
4270 ... // The loop is the likely path of execution
4271 }
4272
4273 while(i != size) [[unlikely]] {
4274 ... // The loop is the unlikely path of execution
4275 } // The generated code will optimize to skip the loop body
4276
4277 while(true) [[unlikely]] {
4278 ... // The attribute has no effect
4279 } // Clang elides the comparison and generates an infinite
4280 // loop)reST";
4281
4282static const char AttrDoc_LoaderUninitialized[] = R"reST(The ``loader_uninitialized`` attribute can be placed on global variables to
4283indicate that the variable does not need to be zero initialized by the loader.
4284On most targets, zero-initialization does not incur any additional cost.
4285For example, most general purpose operating systems deliberately ensure
4286that all memory is properly initialized in order to avoid leaking privileged
4287information from the kernel or other programs. However, some targets
4288do not make this guarantee, and on these targets, avoiding an unnecessary
4289zero-initialization can have a significant impact on load times and/or code
4290size.
4291
4292A declaration with this attribute is a non-tentative definition just as if it
4293provided an initializer. Variables with this attribute are considered to be
4294uninitialized in the same sense as a local variable, and the programs must
4295write to them before reading from them. If the variable's type is a C++ class
4296type with a non-trivial default constructor, or an array thereof, this attribute
4297only suppresses the static zero-initialization of the variable, not the dynamic
4298initialization provided by executing the default constructor.)reST";
4299
4300static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4301
4302static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4303
4304static const char AttrDoc_LoopHint[] = R"reST(The ``#pragma clang loop`` directive allows loop optimization hints to be
4305specified for the subsequent loop. The directive allows pipelining to be
4306disabled, or vectorization, vector predication, interleaving, and unrolling to
4307be enabled or disabled. Vector width, vector predication, interleave count,
4308unrolling count, and the initiation interval for pipelining can be explicitly
4309specified. See `language extensions
4310<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
4311for details.)reST";
4312
4313static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4314
4315static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4316to clear parameters off the stack on return. In other words, callee is
4317responsible for cleaning out the stack space allocated for incoming paramters.
4318This convention does not support variadic calls or unprototyped functions in C.
4319When targeting M68010 or newer CPUs, this calling convention is implemented
4320using the `rtd` instruction.)reST";
4321
4322static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4323functions that follow it to only release arguments passed to them when they
4324return "success" (a ``kern_return_t`` error code that indicates that
4325no errors have occurred). Otherwise the release is performed by the MIG client
4326that called the function. The annotation ``__attribute__((mig_server_routine))``
4327is applied in order to specify which functions are expected to follow the
4328convention. This allows the Static Analyzer to find bugs caused by violations of
4329that convention. The attribute would normally appear on the forward declaration
4330of the actual server routine in the MIG server header, but it may also be
4331added to arbitrary functions that need to follow the same convention - for
4332example, a user can add them to auxiliary functions called by the server routine
4333that have their return value of type ``kern_return_t`` unconditionally returned
4334from the routine. The attribute can be applied to C++ methods, and in this case
4335it will be automatically applied to overrides if the method is virtual. The
4336attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.)reST";
4337
4338static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4339a function to match the default convention used on Windows. This
4340attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4341
4342static const char AttrDoc_MSAllocator[] = R"reST(The ``__declspec(allocator)`` attribute is applied to functions that allocate
4343memory, such as operator new in C++. When CodeView debug information is emitted
4344(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4345record the code offset of heap allocation call sites in the debug info. It will
4346also record the type being allocated using some local heuristics. The Visual
4347Studio debugger uses this information to `profile memory usage`_.
4348
4349.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4350
4351This attribute does not affect optimizations in any way, unlike GCC's
4352``__attribute__((malloc))``.)reST";
4353
4354static const char AttrDoc_MSConstexpr[] = R"reST(The ``[[msvc::constexpr]]`` attribute can be applied only to a function
4355definition or a ``return`` statement. It does not impact function declarations.
4356A ``[[msvc::constexpr]]`` function cannot be ``constexpr`` or ``consteval``.
4357A ``[[msvc::constexpr]]`` function is treated as if it were a ``constexpr`` function
4358when it is evaluated in a constant context of ``[[msvc::constexpr]] return`` statement.
4359Otherwise, it is treated as a regular function.
4360
4361Semantics of this attribute are enabled only under MSVC compatibility
4362(``-fms-compatibility-version``) 19.33 and later.)reST";
4363
4364static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under ``-fms-extensions`` and controls
4365the pointer-to-member representation used on ``*-*-win32`` targets.
4366
4367The ``*-*-win32`` targets utilize a pointer-to-member representation which
4368varies in size and alignment depending on the definition of the underlying
4369class.
4370
4371However, this is problematic when a forward declaration is only available and
4372no definition has been made yet. In such cases, Clang is forced to utilize the
4373most general representation that is available to it.
4374
4375These keywords make it possible to use a pointer-to-member representation other
4376than the most general one regardless of whether or not the definition will ever
4377be present in the current translation unit.
4378
4379This family of keywords belong between the ``class-key`` and ``class-name``:
4380
4381.. code-block:: c++
4382
4383 struct __single_inheritance S;
4384 int S::*i;
4385 struct S {};
4386
4387This keyword can be applied to class templates but only has an effect when used
4388on full specializations:
4389
4390.. code-block:: c++
4391
4392 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4393 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4394 template <> struct __single_inheritance A<int, float>;
4395
4396Note that choosing an inheritance model less general than strictly necessary is
4397an error:
4398
4399.. code-block:: c++
4400
4401 struct __multiple_inheritance S; // error: inheritance model does not match definition
4402 int S::*i;
4403 struct S {};)reST";
4404
4405static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4406the compiler that constructors and destructors will not reference the virtual
4407function table. It is only supported when using the Microsoft C++ ABI.)reST";
4408
4409static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4410
4411static const char AttrDoc_MSStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
4412special record layout compatibility mode which mimics the layout of Microsoft or
4413Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4414requested ABI, the attribute does nothing. However, if it does not, annotated
4415structure or class is laid out in a special compatibility mode, which slightly
4416changes offsets for fields and bit-fields. The intention is to match the layout
4417of the requested ABI for structures which only use C features.
4418
4419Note that the default behavior can be controlled by ``-mms-bitfields`` and
4420``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
4421
4422The primary difference is for bitfields, where the MS variant only packs
4423adjacent fields into the same allocation unit if they have integral types
4424of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4425tightly.)reST";
4426
4427static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4428
4429static const char AttrDoc_MallocSpan[] = R"reST(The ``malloc_span`` attribute can be used to mark that a function which acts
4430like a system memory allocation function and returns a span-like structure,
4431where the returned memory range does not alias storage from any other object
4432accessible to the caller.
4433
4434In this context, a span-like structure is assumed to have two non-static data
4435members, one of which is a pointer to the start of the allocated memory and
4436the other one is either an integer type containing the size of the actually
4437allocated memory or a pointer to the end of the allocated region. Note, static
4438data members do not impact whether a type is span-like or not.)reST";
4439
4440static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4441
4442static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4443
4444static const char AttrDoc_MaybeUndef[] = R"reST(The ``maybe_undef`` attribute can be placed on a function parameter. It indicates
4445that the parameter is allowed to use undef values. It informs the compiler
4446to insert a freeze LLVM IR instruction on the function parameter.
4447Please note that this is an attribute that is used as an internal
4448implementation detail and not intended to be used by external users.
4449
4450In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4451it is enough for only one or some threads to provide defined arguments.
4452Depending on semantics, undef arguments in some threads don't produce
4453undefined results in the function call. Since, these functions accept undefined
4454arguments, ``maybe_undef`` attribute can be placed.
4455
4456Sample usage:
4457.. code-block:: c
4458
4459 void maybeundeffunc(int __attribute__((maybe_undef))param);)reST";
4460
4461static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
4462``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
4463may be attached to a function definition and instructs the backend to generate
4464or not to generate microMIPS code for that function.
4465
4466These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
4467on the command line.)reST";
4468
4469static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4470make choices that keep the function code size as small as possible. Optimizations may
4471also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4472
4473static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
4474attribute may be attached to a function and informs the backend that this
4475function desires vectors of at least this width to be generated. Target-specific
4476maximum vector widths still apply. This means even if you ask for something
4477larger than the target supports, you will only get what the target supports.
4478This attribute is meant to be a hint to control target heuristics that may
4479generate narrower vectors than what the target hardware supports.
4480
4481This is currently used by the X86 target to allow some CPUs that support 512-bit
4482vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4483This is currently enabled with the ``-prefer-vector-width=256`` command line
4484option. The ``min_vector_width`` attribute can be used to prevent the backend
4485from trying to split vector operations to match the ``prefer-vector-width``. All
4486X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4487use of any of the X86-specific vector builtins will implicitly set this
4488attribute on the calling function. The intent is that explicitly writing vector
4489code using the X86 intrinsics will prevent ``prefer-vector-width`` from
4490affecting the code.)reST";
4491
4492static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4493
4494static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
4495MIPS targets. This attribute may be attached to a function definition and instructs
4496the backend to generate appropriate function entry/exit code so that it can be used
4497directly as an interrupt service routine.
4498
4499By default, the compiler will produce a function prologue and epilogue suitable for
4500an interrupt service routine that handles an External Interrupt Controller (eic)
4501generated interrupt. This behavior can be explicitly requested with the "eic"
4502argument.
4503
4504Otherwise, for use with vectored interrupt mode, the argument passed should be
4505of the form "vector=LEVEL" where LEVEL is one of the following values:
4506"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4507then set the interrupt mask to the corresponding level which will mask all
4508interrupts up to and including the argument.
4509
4510The semantics are as follows:
4511
4512- The prologue is modified so that the Exception Program Counter (EPC) and
4513 Status coprocessor registers are saved to the stack. The interrupt mask is
4514 set so that the function can only be interrupted by a higher priority
4515 interrupt. The epilogue will restore the previous values of EPC and Status.
4516
4517- The prologue and epilogue are modified to save and restore all non-kernel
4518 registers as necessary.
4519
4520- The FPU is disabled in the prologue, as the floating pointer registers are not
4521 spilled to the stack.
4522
4523- The function return sequence is changed to use an exception return instruction.
4524
4525- The parameter sets the interrupt mask for the function corresponding to the
4526 interrupt level specified. If no mask is specified the interrupt mask
4527 defaults to "eic".)reST";
4528
4529static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4530and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
4531only be added to function declarations and change the code generated
4532by the compiler when directly calling the function. The ``near`` attribute
4533allows calls to the function to be made using the ``jal`` instruction, which
4534requires the function to be located in the same naturally aligned 256MB
4535segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
4536and require the use of a different call sequence that works regardless
4537of the distance between the functions.
4538
4539These attributes have no effect for position-independent code.
4540
4541These attributes take priority over command line switches such
4542as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4543
4544static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4545``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
4546on MIPS targets. These attributes may only be added to function declarations
4547and change the code generated by the compiler when directly calling
4548the function. The ``short_call`` and ``near`` attributes are synonyms and
4549allow calls to the function to be made using the ``jal`` instruction, which
4550requires the function to be located in the same naturally aligned 256MB segment
4551as the caller. The ``long_call`` and ``far`` attributes are synonyms and
4552require the use of a different call sequence that works regardless
4553of the distance between the functions.
4554
4555These attributes have no effect for position-independent code.
4556
4557These attributes take priority over command line switches such
4558as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4559
4560static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4561
4562static const char AttrDoc_ModularFormat[] = R"reST(The ``modular_format`` attribute can be applied to a function that bears the
4563``format`` attribute (or standard library functions) to indicate that the
4564implementation is "modular", that is, that the implementation is logically
4565divided into a number of named aspects. When the compiler can determine that
4566not all aspects of the implementation are needed for a given call, the compiler
4567may redirect the call to the identifier given as the first argument to the
4568attribute (the modular implementation function).
4569
4570The second argument is a implementation name, and the remaining arguments are
4571aspects of the format string for the compiler to report. The implementation
4572name is an unevaluated identifier be in the C namespace.
4573
4574The compiler reports that a call requires an aspect by issuing a relocation for
4575the symbol ``<impl_name>_<aspect>`` at the point of the call. This arranges for
4576code and data needed to support the aspect of the implementation to be brought
4577into the link to satisfy weak references in the modular implemenation function.
4578If the compiler does not understand an aspect, it must summarily consider any
4579call to require that aspect.
4580
4581For example, say ``printf`` is annotated with
4582``modular_format(__modular_printf, "__printf", "float")``. Then, a call to
4583``printf(var, 42)`` would be untouched. A call to ``printf("%d", 42)`` would
4584become a call to ``__modular_printf`` with the same arguments, as would
4585``printf("%f", 42.0)``. The latter would be accompanied with a strong
4586relocation against the symbol ``__printf_float``, which would bring floating
4587point support for ``printf`` into the link.
4588
4589If the attribute appears more than once on a declaration, or across a chain of
4590redeclarations, it is an error for the attributes to have different arguments,
4591excepting that the aspects may be in any order.
4592
4593The following aspects are currently supported:
4594
4595- ``float``: The call has a floating point argument)reST";
4596
4597static const char AttrDoc_MustTail[] = R"reST(If a ``return`` statement is marked ``musttail``, this indicates that the
4598compiler must generate a tail call for the program to be correct, even when
4599optimizations are disabled. This guarantees that the call will not cause
4600unbounded stack growth if it is part of a recursive cycle in the call graph.
4601
4602If the callee is a virtual function that is implemented by a thunk, there is
4603no guarantee in general that the thunk tail-calls the implementation of the
4604virtual function, so such a call in a recursive cycle can still result in
4605unbounded stack growth.
4606
4607``clang::musttail`` can only be applied to a ``return`` statement whose value
4608is the result of a function call (even functions returning void must use
4609``return``, although no value is returned). The target function must have the
4610same number of arguments as the caller. The types of the return value and all
4611arguments must be similar according to C++ rules (differing only in cv
4612qualifiers or array size), including the implicit "this" argument, if any.
4613Any variables in scope, including all arguments to the function and the
4614return value must be trivially destructible. The calling convention of the
4615caller and callee must match, and they must not be variadic functions or have
4616old style K&R C function declarations.
4617
4618The lifetimes of all local variables and function parameters end immediately
4619before the call to the function. This means that it is undefined behaviour to
4620pass a pointer or reference to a local variable to the called function, which
4621is not the case without the attribute. Clang will emit a warning in common
4622cases where this happens.
4623
4624``clang::musttail`` provides assurances that the tail call can be optimized on
4625all targets, not just one.)reST";
4626
4627static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4628(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4629convention (e.g. functions starting with "get" are assumed to return at
4630``+0``).
4631
4632It can be overridden using a family of the following attributes. In
4633Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4634a function communicates that the object is returned at ``+1``, and the caller
4635is responsible for freeing it.
4636Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4637specifies that the object is returned at ``+0`` and the ownership remains with
4638the callee.
4639The annotation ``__attribute__((ns_consumes_self))`` specifies that
4640the Objective-C method call consumes the reference to ``self``, e.g. by
4641attaching it to a supplied parameter.
4642Additionally, parameters can have an annotation
4643``__attribute__((ns_consumed))``, which specifies that passing an owned object
4644as that parameter effectively transfers the ownership, and the caller is no
4645longer responsible for it.
4646These attributes affect code generation when interacting with ARC code, and
4647they are used by the Clang Static Analyzer.
4648
4649In C programs using CoreFoundation, a similar set of attributes:
4650``__attribute__((cf_returns_not_retained))``,
4651``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4652have the same respective semantics when applied to CoreFoundation objects.
4653These attributes affect code generation when interacting with ARC code, and
4654they are used by the Clang Static Analyzer.
4655
4656Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4657the same attribute family is present:
4658``__attribute__((os_returns_not_retained))``,
4659``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4660with the same respective semantics.
4661Similar to ``__attribute__((ns_consumes_self))``,
4662``__attribute__((os_consumes_this))`` specifies that the method call consumes
4663the reference to "this" (e.g., when attaching it to a different object supplied
4664as a parameter).
4665Out parameters (parameters the function is meant to write into,
4666either via pointers-to-pointers or references-to-pointers)
4667may be annotated with ``__attribute__((os_returns_retained))``
4668or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4669written into the out parameter should (or respectively should not) be released
4670after use.
4671Since often out parameters may or may not be written depending on the exit
4672code of the function,
4673annotations ``__attribute__((os_returns_retained_on_zero))``
4674and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4675an out parameter at ``+1`` is written if and only if the function returns a zero
4676(respectively non-zero) error code.
4677Observe that return-code-dependent out parameter annotations are only
4678available for retained out parameters, as non-retained object do not have to be
4679released by the callee.
4680These attributes are only used by the Clang Static Analyzer.
4681
4682The family of attributes ``X_returns_X_retained`` can be added to functions,
4683C++ methods, and Objective-C methods and properties.
4684Attributes ``X_consumed`` can be added to parameters of methods, functions,
4685and Objective-C methods.)reST";
4686
4687static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4688(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4689convention (e.g. functions starting with "get" are assumed to return at
4690``+0``).
4691
4692It can be overridden using a family of the following attributes. In
4693Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4694a function communicates that the object is returned at ``+1``, and the caller
4695is responsible for freeing it.
4696Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4697specifies that the object is returned at ``+0`` and the ownership remains with
4698the callee.
4699The annotation ``__attribute__((ns_consumes_self))`` specifies that
4700the Objective-C method call consumes the reference to ``self``, e.g. by
4701attaching it to a supplied parameter.
4702Additionally, parameters can have an annotation
4703``__attribute__((ns_consumed))``, which specifies that passing an owned object
4704as that parameter effectively transfers the ownership, and the caller is no
4705longer responsible for it.
4706These attributes affect code generation when interacting with ARC code, and
4707they are used by the Clang Static Analyzer.
4708
4709In C programs using CoreFoundation, a similar set of attributes:
4710``__attribute__((cf_returns_not_retained))``,
4711``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4712have the same respective semantics when applied to CoreFoundation objects.
4713These attributes affect code generation when interacting with ARC code, and
4714they are used by the Clang Static Analyzer.
4715
4716Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4717the same attribute family is present:
4718``__attribute__((os_returns_not_retained))``,
4719``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4720with the same respective semantics.
4721Similar to ``__attribute__((ns_consumes_self))``,
4722``__attribute__((os_consumes_this))`` specifies that the method call consumes
4723the reference to "this" (e.g., when attaching it to a different object supplied
4724as a parameter).
4725Out parameters (parameters the function is meant to write into,
4726either via pointers-to-pointers or references-to-pointers)
4727may be annotated with ``__attribute__((os_returns_retained))``
4728or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4729written into the out parameter should (or respectively should not) be released
4730after use.
4731Since often out parameters may or may not be written depending on the exit
4732code of the function,
4733annotations ``__attribute__((os_returns_retained_on_zero))``
4734and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4735an out parameter at ``+1`` is written if and only if the function returns a zero
4736(respectively non-zero) error code.
4737Observe that return-code-dependent out parameter annotations are only
4738available for retained out parameters, as non-retained object do not have to be
4739released by the callee.
4740These attributes are only used by the Clang Static Analyzer.
4741
4742The family of attributes ``X_returns_X_retained`` can be added to functions,
4743C++ methods, and Objective-C methods and properties.
4744Attributes ``X_consumed`` can be added to parameters of methods, functions,
4745and Objective-C methods.)reST";
4746
4747static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
4748and categorize these enums with error domains.
4749
4750The ``ns_error_domain`` attribute indicates a global ``NSString`` or
4751``CFString`` constant representing the error domain that an error code belongs
4752to. For pointer uniqueness and code size this is a constant symbol, not a
4753literal.
4754
4755The domain and error code need to be used together. The ``ns_error_domain``
4756attribute links error codes to their domain at the source level.
4757
4758This metadata is useful for documentation purposes, for static analysis, and for
4759improving interoperability between Objective-C and Swift. It is not used for
4760code generation in Objective-C.
4761
4762For example:
4763
4764 .. code-block:: objc
4765
4766 #define NS_ERROR_ENUM(_type, _name, _domain) \
4767 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
4768
4769 extern NSString *const MyErrorDomain;
4770 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
4771 MyErrFirst,
4772 MyErrSecond,
4773 };)reST";
4774
4775static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4776(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4777convention (e.g. functions starting with "get" are assumed to return at
4778``+0``).
4779
4780It can be overridden using a family of the following attributes. In
4781Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4782a function communicates that the object is returned at ``+1``, and the caller
4783is responsible for freeing it.
4784Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4785specifies that the object is returned at ``+0`` and the ownership remains with
4786the callee.
4787The annotation ``__attribute__((ns_consumes_self))`` specifies that
4788the Objective-C method call consumes the reference to ``self``, e.g. by
4789attaching it to a supplied parameter.
4790Additionally, parameters can have an annotation
4791``__attribute__((ns_consumed))``, which specifies that passing an owned object
4792as that parameter effectively transfers the ownership, and the caller is no
4793longer responsible for it.
4794These attributes affect code generation when interacting with ARC code, and
4795they are used by the Clang Static Analyzer.
4796
4797In C programs using CoreFoundation, a similar set of attributes:
4798``__attribute__((cf_returns_not_retained))``,
4799``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4800have the same respective semantics when applied to CoreFoundation objects.
4801These attributes affect code generation when interacting with ARC code, and
4802they are used by the Clang Static Analyzer.
4803
4804Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4805the same attribute family is present:
4806``__attribute__((os_returns_not_retained))``,
4807``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4808with the same respective semantics.
4809Similar to ``__attribute__((ns_consumes_self))``,
4810``__attribute__((os_consumes_this))`` specifies that the method call consumes
4811the reference to "this" (e.g., when attaching it to a different object supplied
4812as a parameter).
4813Out parameters (parameters the function is meant to write into,
4814either via pointers-to-pointers or references-to-pointers)
4815may be annotated with ``__attribute__((os_returns_retained))``
4816or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4817written into the out parameter should (or respectively should not) be released
4818after use.
4819Since often out parameters may or may not be written depending on the exit
4820code of the function,
4821annotations ``__attribute__((os_returns_retained_on_zero))``
4822and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4823an out parameter at ``+1`` is written if and only if the function returns a zero
4824(respectively non-zero) error code.
4825Observe that return-code-dependent out parameter annotations are only
4826available for retained out parameters, as non-retained object do not have to be
4827released by the callee.
4828These attributes are only used by the Clang Static Analyzer.
4829
4830The family of attributes ``X_returns_X_retained`` can be added to functions,
4831C++ methods, and Objective-C methods and properties.
4832Attributes ``X_consumed`` can be added to parameters of methods, functions,
4833and Objective-C methods.)reST";
4834
4835static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4836(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4837convention (e.g. functions starting with "get" are assumed to return at
4838``+0``).
4839
4840It can be overridden using a family of the following attributes. In
4841Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4842a function communicates that the object is returned at ``+1``, and the caller
4843is responsible for freeing it.
4844Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4845specifies that the object is returned at ``+0`` and the ownership remains with
4846the callee.
4847The annotation ``__attribute__((ns_consumes_self))`` specifies that
4848the Objective-C method call consumes the reference to ``self``, e.g. by
4849attaching it to a supplied parameter.
4850Additionally, parameters can have an annotation
4851``__attribute__((ns_consumed))``, which specifies that passing an owned object
4852as that parameter effectively transfers the ownership, and the caller is no
4853longer responsible for it.
4854These attributes affect code generation when interacting with ARC code, and
4855they are used by the Clang Static Analyzer.
4856
4857In C programs using CoreFoundation, a similar set of attributes:
4858``__attribute__((cf_returns_not_retained))``,
4859``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4860have the same respective semantics when applied to CoreFoundation objects.
4861These attributes affect code generation when interacting with ARC code, and
4862they are used by the Clang Static Analyzer.
4863
4864Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4865the same attribute family is present:
4866``__attribute__((os_returns_not_retained))``,
4867``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4868with the same respective semantics.
4869Similar to ``__attribute__((ns_consumes_self))``,
4870``__attribute__((os_consumes_this))`` specifies that the method call consumes
4871the reference to "this" (e.g., when attaching it to a different object supplied
4872as a parameter).
4873Out parameters (parameters the function is meant to write into,
4874either via pointers-to-pointers or references-to-pointers)
4875may be annotated with ``__attribute__((os_returns_retained))``
4876or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4877written into the out parameter should (or respectively should not) be released
4878after use.
4879Since often out parameters may or may not be written depending on the exit
4880code of the function,
4881annotations ``__attribute__((os_returns_retained_on_zero))``
4882and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4883an out parameter at ``+1`` is written if and only if the function returns a zero
4884(respectively non-zero) error code.
4885Observe that return-code-dependent out parameter annotations are only
4886available for retained out parameters, as non-retained object do not have to be
4887released by the callee.
4888These attributes are only used by the Clang Static Analyzer.
4889
4890The family of attributes ``X_returns_X_retained`` can be added to functions,
4891C++ methods, and Objective-C methods and properties.
4892Attributes ``X_consumed`` can be added to parameters of methods, functions,
4893and Objective-C methods.)reST";
4894
4895static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4896(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4897convention (e.g. functions starting with "get" are assumed to return at
4898``+0``).
4899
4900It can be overridden using a family of the following attributes. In
4901Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4902a function communicates that the object is returned at ``+1``, and the caller
4903is responsible for freeing it.
4904Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4905specifies that the object is returned at ``+0`` and the ownership remains with
4906the callee.
4907The annotation ``__attribute__((ns_consumes_self))`` specifies that
4908the Objective-C method call consumes the reference to ``self``, e.g. by
4909attaching it to a supplied parameter.
4910Additionally, parameters can have an annotation
4911``__attribute__((ns_consumed))``, which specifies that passing an owned object
4912as that parameter effectively transfers the ownership, and the caller is no
4913longer responsible for it.
4914These attributes affect code generation when interacting with ARC code, and
4915they are used by the Clang Static Analyzer.
4916
4917In C programs using CoreFoundation, a similar set of attributes:
4918``__attribute__((cf_returns_not_retained))``,
4919``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4920have the same respective semantics when applied to CoreFoundation objects.
4921These attributes affect code generation when interacting with ARC code, and
4922they are used by the Clang Static Analyzer.
4923
4924Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4925the same attribute family is present:
4926``__attribute__((os_returns_not_retained))``,
4927``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4928with the same respective semantics.
4929Similar to ``__attribute__((ns_consumes_self))``,
4930``__attribute__((os_consumes_this))`` specifies that the method call consumes
4931the reference to "this" (e.g., when attaching it to a different object supplied
4932as a parameter).
4933Out parameters (parameters the function is meant to write into,
4934either via pointers-to-pointers or references-to-pointers)
4935may be annotated with ``__attribute__((os_returns_retained))``
4936or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4937written into the out parameter should (or respectively should not) be released
4938after use.
4939Since often out parameters may or may not be written depending on the exit
4940code of the function,
4941annotations ``__attribute__((os_returns_retained_on_zero))``
4942and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4943an out parameter at ``+1`` is written if and only if the function returns a zero
4944(respectively non-zero) error code.
4945Observe that return-code-dependent out parameter annotations are only
4946available for retained out parameters, as non-retained object do not have to be
4947released by the callee.
4948These attributes are only used by the Clang Static Analyzer.
4949
4950The family of attributes ``X_returns_X_retained`` can be added to functions,
4951C++ methods, and Objective-C methods and properties.
4952Attributes ``X_consumed`` can be added to parameters of methods, functions,
4953and Objective-C methods.)reST";
4954
4955static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
4956
4957static const char AttrDoc_NoAlias[] = R"reST(The ``noalias`` attribute indicates that the only memory accesses inside
4958function are loads and stores from objects pointed to by its pointer-typed
4959arguments, with arbitrary offsets.)reST";
4960
4961static const char AttrDoc_NoBuiltin[] = R"reST(The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
4962except it is specific to the body of a function. The attribute may also be
4963applied to a virtual function but has no effect on the behavior of overriding
4964functions in a derived class.
4965
4966It accepts one or more strings corresponding to the specific names of the
4967builtins to disable (e.g. "memcpy", "memset").
4968If the attribute is used without parameters it will disable all buitins at
4969once.
4970
4971.. code-block:: c++
4972
4973 // The compiler is not allowed to add any builtin to foo's body.
4974 void foo(char* data, size_t count) __attribute__((no_builtin)) {
4975 // The compiler is not allowed to convert the loop into
4976 // `__builtin_memset(data, 0xFE, count);`.
4977 for (size_t i = 0; i < count; ++i)
4978 data[i] = 0xFE;
4979 }
4980
4981 // The compiler is not allowed to add the `memcpy` builtin to bar's body.
4982 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
4983 // The compiler is allowed to convert the loop into
4984 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
4985 // `__builtin_memcpy`
4986 for (size_t i = 0; i < count; ++i)
4987 data[i] = 0xFE;
4988 })reST";
4989
4990static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
4991
4992static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
4993function is marked ``noconvergent``, calls to that function are not
4994automatically assumed to be convergent, unless such calls are explicitly marked
4995as ``convergent``. If a statement is marked as ``noconvergent``, any calls to
4996inline ``asm`` in that statement are no longer treated as convergent.
4997
4998In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
4999declarations and inline asm calls are treated as convergent by default for
5000correctness. This ``noconvergent`` attribute is helpful for developers to
5001prevent them from being treated as convergent when it's safe.
5002
5003.. code-block:: c
5004
5005 __device__ float bar(float);
5006 __device__ float foo(float) __attribute__((noconvergent)) {}
5007
5008 __device__ int example(void) {
5009 float x;
5010 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5011 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5012 })reST";
5013
5014static const char AttrDoc_NoDebug[] = R"reST(The ``nodebug`` attribute allows you to suppress debugging information for a
5015function or method, for a variable that is not a parameter or a non-static
5016data member, or for a typedef or using declaration.)reST";
5017
5018static const char AttrDoc_NoDeref[] = R"reST(The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
5019This is ideally used with pointers that point to special memory which cannot be read
5020from or written to, but allowing for the pointer to be used in pointer arithmetic.
5021The following are examples of valid expressions where dereferences are diagnosed:
5022
5023.. code-block:: c
5024
5025 int __attribute__((noderef)) *p;
5026 int x = *p; // warning
5027
5028 int __attribute__((noderef)) **p2;
5029 x = **p2; // warning
5030
5031 int * __attribute__((noderef)) *p3;
5032 p = *p3; // warning
5033
5034 struct S {
5035 int a;
5036 };
5037 struct S __attribute__((noderef)) *s;
5038 x = s->a; // warning
5039 x = (*s).a; // warning
5040
5041Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5042accessed. The following are examples of valid expressions where may not be diagnosed:
5043
5044.. code-block:: c
5045
5046 int *q;
5047 int __attribute__((noderef)) *p;
5048 q = &*p;
5049 q = *&p;
5050
5051 struct S {
5052 int a;
5053 };
5054 struct S __attribute__((noderef)) *s;
5055 p = &s->a;
5056 p = &(*s).a;
5057
5058``noderef`` is currently only supported for pointers and arrays and not usable
5059for references or Objective-C object pointers.
5060
5061.. code-block:: c++
5062
5063 int x = 2;
5064 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5065
5066.. code-block:: objc
5067
5068 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type)reST";
5069
5070static const char AttrDoc_NoDestroy[] = R"reST(The ``no_destroy`` attribute specifies that a variable with static or thread
5071storage duration shouldn't have its exit-time destructor run. Annotating every
5072static and thread duration variable with this attribute is equivalent to
5073invoking clang with -fno-c++-static-destructors.
5074
5075If a variable is declared with this attribute, clang doesn't access check or
5076generate the type's destructor. If you have a type that you only want to be
5077annotated with ``no_destroy``, you can therefore declare the destructor private:
5078
5079.. code-block:: c++
5080
5081 struct only_no_destroy {
5082 only_no_destroy();
5083 private:
5084 ~only_no_destroy();
5085 };
5086
5087 [[clang::no_destroy]] only_no_destroy global; // fine!
5088
5089Note that destructors are still required for subobjects of aggregates annotated
5090with this attribute. This is because previously constructed subobjects need to
5091be destroyed if an exception gets thrown before the initialization of the
5092complete object is complete. For instance:
5093
5094.. code-block:: c++
5095
5096 void f() {
5097 try {
5098 [[clang::no_destroy]]
5099 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5100 } catch (...) {
5101 // Handle the error
5102 }
5103 }
5104
5105Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]``
5106will be destroyed, so the element's destructor needs to be accessible.)reST";
5107
5108static const char AttrDoc_NoDuplicate[] = R"reST(The ``noduplicate`` attribute can be placed on function declarations to control
5109whether function calls to this function can be duplicated or not as a result of
5110optimizations. This is required for the implementation of functions with
5111certain special requirements, like the OpenCL "barrier" function, that might
5112need to be run concurrently by all the threads that are executing in lockstep
5113on the hardware. For example this attribute applied on the function
5114"nodupfunc" in the code below avoids that:
5115
5116.. code-block:: c
5117
5118 void nodupfunc() __attribute__((noduplicate));
5119 // Setting it as a C++11 attribute is also valid
5120 // void nodupfunc() [[clang::noduplicate]];
5121 void foo();
5122 void bar();
5123
5124 nodupfunc();
5125 if (a > n) {
5126 foo();
5127 } else {
5128 bar();
5129 }
5130
5131gets possibly modified by some optimizations into code similar to this:
5132
5133.. code-block:: c
5134
5135 if (a > n) {
5136 nodupfunc();
5137 foo();
5138 } else {
5139 nodupfunc();
5140 bar();
5141 }
5142
5143where the call to "nodupfunc" is duplicated and sunk into the two branches
5144of the condition.)reST";
5145
5146static const char AttrDoc_NoEscape[] = R"reST(``noescape`` placed on a function parameter of a pointer type is used to inform
5147the compiler that the pointer cannot escape: that is, no reference to the object
5148the pointer points to that is derived from the parameter value will survive
5149after the function returns. Users are responsible for making sure parameters
5150annotated with ``noescape`` do not actually escape. Calling ``free()`` on such
5151a parameter does not constitute an escape.
5152
5153For example:
5154
5155.. code-block:: c
5156
5157 int *gp;
5158
5159 void nonescapingFunc(__attribute__((noescape)) int *p) {
5160 *p += 100; // OK.
5161 }
5162
5163 void escapingFunc(__attribute__((noescape)) int *p) {
5164 gp = p; // Not OK.
5165 }
5166
5167Additionally, when the parameter is a `block pointer
5168<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
5169applies to copies of the block. For example:
5170
5171.. code-block:: c
5172
5173 typedef void (^BlockTy)();
5174 BlockTy g0, g1;
5175
5176 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5177 block(); // OK.
5178 }
5179
5180 void escapingFunc(__attribute__((noescape)) BlockTy block) {
5181 g0 = block; // Not OK.
5182 g1 = Block_copy(block); // Not OK either.
5183 })reST";
5184
5185static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5186
5187static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5188of the function.
5189
5190``[[clang::noinline]]`` spelling can be used as a statement attribute; other
5191spellings of the attribute are not supported on statements. If a statement is
5192marked ``[[clang::noinline]]`` and contains calls, those calls inside the
5193statement will not be inlined by the compiler.
5194
5195``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to
5196avoid diagnostics due to usage of ``__attribute__((__noinline__))``
5197with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``.
5198
5199.. code-block:: c
5200
5201 int example(void) {
5202 int r;
5203 [[clang::noinline]] foo();
5204 [[clang::noinline]] r = bar();
5205 return r;
5206 })reST";
5207
5208static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5209
5210static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked ``nomerge`` and contains call expressions, those call
5211expressions inside the statement will not be merged during optimization. This
5212attribute can be used to prevent the optimizer from obscuring the source
5213location of certain calls. For example, it will prevent tail merging otherwise
5214identical code sequences that raise an exception or terminate the program. Tail
5215merging normally reduces the precision of source location information, making
5216stack traces less useful for debugging. This attribute gives the user control
5217over the tradeoff between code size and debug information precision.
5218
5219``nomerge`` attribute can also be used as function attribute to prevent all
5220calls to the specified function from merging. It has no effect on indirect
5221calls to such functions. For example:
5222
5223.. code-block:: c++
5224
5225 [[clang::nomerge]] void foo(int) {}
5226
5227 void bar(int x) {
5228 auto *ptr = foo;
5229 if (x) foo(1); else foo(2); // will not be merged
5230 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5231 }
5232
5233``nomerge`` attribute can also be used for pointers to functions to
5234prevent calls through such pointer from merging. In such case the
5235effect applies only to a specific function pointer. For example:
5236
5237.. code-block:: c++
5238
5239 [[clang::nomerge]] void (*foo)(int);
5240
5241 void bar(int x) {
5242 auto *ptr = foo;
5243 if (x) foo(1); else foo(2); // will not be merged
5244 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5245 })reST";
5246
5247static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
5248``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
5249may be attached to a function definition and instructs the backend to generate
5250or not to generate microMIPS code for that function.
5251
5252These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
5253on the command line.)reST";
5254
5255static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5256
5257static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5258
5259Outlining is the process where common parts of separate functions are extracted
5260into a separate function (or assembly snippet), and calls to that function or
5261snippet are inserted in the original functions. In this way, it can be seen as
5262the opposite of inlining. It can help to reduce code size.)reST";
5263
5264static const char AttrDoc_NoProfileFunction[] = R"reST(Use the ``no_profile_instrument_function`` attribute on a function declaration
5265to denote that the compiler should not instrument the function with
5266profile-related instrumentation, such as via the
5267``-fprofile-generate`` / ``-fprofile-instr-generate`` /
5268``-fcs-profile-generate`` / ``-fprofile-arcs`` flags.)reST";
5269
5270static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
5271for structure layout field randomization; a compile-time hardening technique. A
5272"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
5273For example:
5274
5275.. code-block:: bash
5276
5277 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5278 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5279
5280You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
5281For example:
5282
5283.. code-block:: bash
5284
5285 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5286 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5287
5288The randomization is deterministic based for a given seed, so the entire
5289program should be compiled with the same seed, but keep the seed safe
5290otherwise.
5291
5292The attribute ``no_randomize_layout``, when attached to a C structure,
5293instructs the compiler that this structure should not have its field layout
5294randomized.)reST";
5295
5296static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5297
5298static const char AttrDoc_NoSanitize[] = R"reST(Use the ``no_sanitize`` attribute on a function or a global variable
5299declaration to specify that a particular instrumentation or set of
5300instrumentations should not be applied.
5301
5302The attribute takes a list of string literals with the following accepted
5303values:
5304
5305* all values accepted by ``-fno-sanitize=``;
5306* ``coverage``, to disable SanitizerCoverage instrumentation.
5307
5308For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies
5309that AddressSanitizer and ThreadSanitizer should not be applied to the function
5310or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that
5311SanitizerCoverage should not be applied to the function.
5312
5313See :ref:`Controlling Code Generation <controlling-code-generation>` for a
5314full list of supported sanitizer flags.)reST";
5315
5316static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5317templates which should not be explicitly specialized by users. This is primarily
5318used to diagnose user specializations of standard library type traits.)reST";
5319
5320static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5321 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5322 is *not* needed for the function body. This can also be applied to a method
5323 in Objective C. This attribute will take precedence over the command line flag in
5324 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5325
5326 Warning: This attribute may not prevent Speculative Load Hardening from being
5327 enabled for a function which inlines a function that has the
5328 'speculative_load_hardening' attribute. This is intended to provide a
5329 maximally conservative model where the code that is marked with the
5330 'speculative_load_hardening' attribute will always (even when inlined)
5331 be hardened. A user of this attribute may want to mark functions called by
5332 a function they do not want to be hardened with the 'noinline' attribute.
5333
5334 For example:
5335
5336 .. code-block:: c
5337
5338 __attribute__((speculative_load_hardening))
5339 int foo(int i) {
5340 return i;
5341 }
5342
5343 // Note: bar() may still have speculative load hardening enabled if
5344 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5345 // to avoid this situation.
5346 __attribute__((no_speculative_load_hardening))
5347 int bar(int i) {
5348 return foo(i);
5349 })reST";
5350
5351static const char AttrDoc_NoSplitStack[] = R"reST(The ``no_split_stack`` attribute disables the emission of the split stack
5352preamble for a particular function. It has no effect if ``-fsplit-stack``
5353is not specified.)reST";
5354
5355static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style ``__attribute__((no_stack_protector))`` and Microsoft
5356style ``__declspec(safebuffers)`` attribute which disables
5357the stack protector on the specified function. This attribute is useful for
5358selectively disabling the stack protector on some functions when building with
5359``-fstack-protector`` compiler option.
5360
5361For example, it disables the stack protector for the function ``foo`` but function
5362``bar`` will still be built with the stack protector with the ``-fstack-protector``
5363option.
5364
5365.. code-block:: c
5366
5367 int __attribute__((no_stack_protector))
5368 foo (int x); // stack protection will be disabled for foo.
5369
5370 int bar(int y); // bar can be built with the stack protector.)reST";
5371
5372static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5373
5374static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
5375``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function
5376declarations. This attribute informs the compiler that the annotated function
5377does not throw an exception. This prevents exception-unwinding. This attribute
5378is particularly useful on functions in the C Standard Library that are
5379guaranteed to not throw an exception.)reST";
5380
5381static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The ``__declspec(no_init_all)`` attribute disables the automatic initialization that the
5382`-ftrivial-auto-var-init`_ flag would have applied to locals in a marked function, or instances of
5383a marked type. Note that this attribute has no effect for locals that are automatically initialized
5384without the `-ftrivial-auto-var-init`_ flag.
5385
5386.. _`-ftrivial-auto-var-init`: ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init)reST";
5387
5388static const char AttrDoc_NoUniqueAddress[] = R"reST(The ``no_unique_address`` attribute allows tail padding in a non-static data
5389member to overlap other members of the enclosing class (and in the special
5390case when the type is empty, permits it to fully overlap other members).
5391The field is laid out as if a base class were encountered at the corresponding
5392point within the class (except that it does not share a vptr with the enclosing
5393object).
5394
5395Example usage:
5396
5397.. code-block:: c++
5398
5399 template<typename T, typename Alloc> struct my_vector {
5400 T *p;
5401 [[no_unique_address]] Alloc alloc;
5402 // ...
5403 };
5404 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5405
5406``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
5407in C++11 onwards.
5408
5409On MSVC targets, ``[[no_unique_address]]`` is ignored; use
5410``[[msvc::no_unique_address]]`` instead. Currently there is no guarantee of ABI
5411compatibility or stability with MSVC.)reST";
5412
5413static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the ``nouwtable`` attribute which skips emitting
5414the unwind table entry for the specified function. This attribute is useful for
5415selectively emitting the unwind table entry on some functions when building with
5416``-funwind-tables`` compiler option.)reST";
5417
5418static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5419to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5420is false, the attribute is equivalent to ``allocating``.)reST";
5421
5422static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5423to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5424is false, the attribute is equivalent to ``blocking``.
5425
5426For the purposes of diagnostics, ``nonblocking`` is considered to include the
5427``nonallocating`` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5428
5429static const char AttrDoc_NonNull[] = R"reST(The ``nonnull`` attribute indicates that some function parameters must not be
5430null, and can be used in several different ways. It's original usage
5431(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
5432is as a function (or Objective-C method) attribute that specifies which
5433parameters of the function are nonnull in a comma-separated list. For example:
5434
5435 .. code-block:: c
5436
5437 extern void * my_memcpy (void *dest, const void *src, size_t len)
5438 __attribute__((nonnull (1, 2)));
5439
5440Here, the ``nonnull`` attribute indicates that parameters 1 and 2
5441cannot have a null value. Omitting the parenthesized list of parameter indices
5442means that all parameters of pointer type cannot be null:
5443
5444 .. code-block:: c
5445
5446 extern void * my_memcpy (void *dest, const void *src, size_t len)
5447 __attribute__((nonnull));
5448
5449Clang also allows the ``nonnull`` attribute to be placed directly on a function
5450(or Objective-C method) parameter, eliminating the need to specify the
5451parameter index ahead of type. For example:
5452
5453 .. code-block:: c
5454
5455 extern void * my_memcpy (void *dest __attribute__((nonnull)),
5456 const void *src __attribute__((nonnull)), size_t len);
5457
5458Note that the ``nonnull`` attribute indicates that passing null to a non-null
5459parameter is undefined behavior, which the optimizer may take advantage of to,
5460e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
5461pointer cannot be null in a more general manner (because it is part of the type
5462system) and does not imply undefined behavior, making it more widely applicable.)reST";
5463
5464static const char AttrDoc_NonString[] = R"reST(The ``nonstring`` attribute can be applied to the declaration of a variable or
5465a field whose type is a character pointer or character array to specify that
5466the buffer is not intended to behave like a null-terminated string. This will
5467silence diagnostics with code like:
5468
5469.. code-block:: c
5470
5471 char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5472 __attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed)reST";
5473
5474static const char AttrDoc_NotTailCalled[] = R"reST(The ``not_tail_called`` attribute prevents tail-call optimization on statically
5475bound calls. Objective-c methods, and functions marked as ``always_inline``
5476cannot be marked as ``not_tail_called``.
5477
5478For example, it prevents tail-call optimization in the following case:
5479
5480 .. code-block:: c
5481
5482 int __attribute__((not_tail_called)) foo1(int);
5483
5484 int foo2(int a) {
5485 return foo1(a); // No tail-call optimization on direct calls.
5486 }
5487
5488However, it doesn't prevent tail-call optimization in this case:
5489
5490 .. code-block:: c
5491
5492 int __attribute__((not_tail_called)) foo1(int);
5493
5494 int foo2(int a) {
5495 int (*fn)(int) = &foo1;
5496
5497 // not_tail_called has no effect on an indirect call even if the call can
5498 // be resolved at compile time.
5499 return (*fn)(a);
5500 }
5501
5502Generally, marking an overriding virtual function as ``not_tail_called`` is
5503not useful, because this attribute is a property of the static type. Calls
5504made through a pointer or reference to the base class type will respect
5505the ``not_tail_called`` attribute of the base class's member function,
5506regardless of the runtime destination of the call:
5507
5508 .. code-block:: c++
5509
5510 struct Foo { virtual void f(); };
5511 struct Bar : Foo {
5512 [[clang::not_tail_called]] void f() override;
5513 };
5514 void callera(Bar& bar) {
5515 Foo& foo = bar;
5516 // not_tail_called has no effect on here, even though the
5517 // underlying method is f from Bar.
5518 foo.f();
5519 bar.f(); // No tail-call optimization on here.
5520 })reST";
5521
5522static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5523
5524static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the ``[[omp::assume("assumption")]]`` attribute to
5525provide additional information to the optimizer. The string-literal, here
5526"assumption", will be attached to the function declaration such that later
5527analysis and optimization passes can assume the "assumption" to hold.
5528This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
5529instead of an expression that can be assumed to be non-zero, the assumption is
5530expressed as a string and it holds for the entire function.
5531
5532A function can have multiple assume attributes and they propagate from prior
5533declarations to later definitions. Multiple assumptions are aggregated into a
5534single comma separated string. Thus, one can provide multiple assumptions via
5535a comma separated string, i.a.,
5536``[[omp::assume("assumption1,assumption2")]]``.
5537
5538While LLVM plugins might provide more assumption strings, the default LLVM
5539optimization passes are aware of the following assumptions:
5540
5541 .. code-block:: none
5542
5543 "omp_no_openmp"
5544 "omp_no_openmp_routines"
5545 "omp_no_parallelism"
5546 "omp_no_openmp_constructs"
5547
5548The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5549spelled "XYZ" in the `OpenMP 5.1 Standard`_).
5550
5551.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5552
5553static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5554
5555static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5556
5557static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The ``declare simd`` construct can be applied to a function to enable the creation
5558of one or more versions that can process multiple arguments using SIMD
5559instructions from a single invocation in a SIMD loop. The ``declare simd``
5560directive is a declarative directive. There may be multiple ``declare simd``
5561directives for a function. The use of a ``declare simd`` construct on a function
5562enables the creation of SIMD versions of the associated function that can be
5563used to process multiple arguments from a single invocation from a SIMD loop
5564concurrently.
5565The syntax of the ``declare simd`` construct is as follows:
5566
5567 .. code-block:: none
5568
5569 #pragma omp declare simd [clause[[,] clause] ...] new-line
5570 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
5571 [...]
5572 function definition or declaration
5573
5574where clause is one of the following:
5575
5576 .. code-block:: none
5577
5578 simdlen(length)
5579 linear(argument-list[:constant-linear-step])
5580 aligned(argument-list[:alignment])
5581 uniform(argument-list)
5582 inbranch
5583 notinbranch)reST";
5584
5585static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The ``declare target`` directive specifies that variables and functions are mapped
5586to a device for OpenMP offload mechanism.
5587
5588The syntax of the declare target directive is as follows:
5589
5590 .. code-block:: c
5591
5592 #pragma omp declare target new-line
5593 declarations-definition-seq
5594 #pragma omp end declare target new-line
5595
5596or
5597
5598 .. code-block:: c
5599
5600 #pragma omp declare target (extended-list) new-line
5601
5602or
5603
5604 .. code-block:: c
5605
5606 #pragma omp declare target clause[ [,] clause ... ] new-line
5607
5608where clause is one of the following:
5609
5610
5611 .. code-block:: c
5612
5613 to(extended-list)
5614 link(list)
5615 device_type(host | nohost | any))reST";
5616
5617static const char AttrDoc_OMPDeclareVariant[] = R"reST(The ``declare variant`` directive declares a specialized variant of a base
5618function and specifies the context in which that specialized variant is used.
5619The declare variant directive is a declarative directive.
5620The syntax of the ``declare variant`` construct is as follows:
5621
5622 .. code-block:: none
5623
5624 #pragma omp declare variant(variant-func-id) clause new-line
5625 [#pragma omp declare variant(variant-func-id) clause new-line]
5626 [...]
5627 function definition or declaration
5628
5629where clause is one of the following:
5630
5631 .. code-block:: none
5632
5633 match(context-selector-specification)
5634
5635and where ``variant-func-id`` is the name of a function variant that is either a
5636base language identifier or, for C++, a template-id.
5637
5638Clang provides the following context selector extensions, used via
5639``implementation={extension(EXTENSION)}``:
5640
5641 .. code-block:: none
5642
5643 match_all
5644 match_any
5645 match_none
5646 disable_implicit_base
5647 allow_templates
5648 bind_to_declaration
5649
5650The match extensions change when the *entire* context selector is considered a
5651match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
5652selector is allowed to be in the OpenMP context, with ``any`` a single trait in
5653both the selector and OpenMP context is sufficient. Only a single match
5654extension trait is allowed per context selector.
5655The disable extensions remove default effects of the ``begin declare variant``
5656applied to a definition. If ``disable_implicit_base`` is given, we will not
5657introduce an implicit base function for a variant if no base function was
5658found. The variant is still generated but will never be called, due to the
5659absence of a base function and consequently calls to a base function.
5660The allow extensions change when the ``begin declare variant`` effect is
5661applied to a definition. If ``allow_templates`` is given, template function
5662definitions are considered as specializations of existing or assumed template
5663declarations with the same name. The template parameters for the base functions
5664are used to instantiate the specialization. If ``bind_to_declaration`` is given,
5665apply the same variant rules to function declarations. This allows the user to
5666override declarations with only a function declaration.)reST";
5667
5668static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
5669
5670static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
5671
5672static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
5673
5674static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
5675
5676static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5677(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5678convention (e.g. functions starting with "get" are assumed to return at
5679``+0``).
5680
5681It can be overridden using a family of the following attributes. In
5682Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5683a function communicates that the object is returned at ``+1``, and the caller
5684is responsible for freeing it.
5685Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5686specifies that the object is returned at ``+0`` and the ownership remains with
5687the callee.
5688The annotation ``__attribute__((ns_consumes_self))`` specifies that
5689the Objective-C method call consumes the reference to ``self``, e.g. by
5690attaching it to a supplied parameter.
5691Additionally, parameters can have an annotation
5692``__attribute__((ns_consumed))``, which specifies that passing an owned object
5693as that parameter effectively transfers the ownership, and the caller is no
5694longer responsible for it.
5695These attributes affect code generation when interacting with ARC code, and
5696they are used by the Clang Static Analyzer.
5697
5698In C programs using CoreFoundation, a similar set of attributes:
5699``__attribute__((cf_returns_not_retained))``,
5700``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5701have the same respective semantics when applied to CoreFoundation objects.
5702These attributes affect code generation when interacting with ARC code, and
5703they are used by the Clang Static Analyzer.
5704
5705Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5706the same attribute family is present:
5707``__attribute__((os_returns_not_retained))``,
5708``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5709with the same respective semantics.
5710Similar to ``__attribute__((ns_consumes_self))``,
5711``__attribute__((os_consumes_this))`` specifies that the method call consumes
5712the reference to "this" (e.g., when attaching it to a different object supplied
5713as a parameter).
5714Out parameters (parameters the function is meant to write into,
5715either via pointers-to-pointers or references-to-pointers)
5716may be annotated with ``__attribute__((os_returns_retained))``
5717or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5718written into the out parameter should (or respectively should not) be released
5719after use.
5720Since often out parameters may or may not be written depending on the exit
5721code of the function,
5722annotations ``__attribute__((os_returns_retained_on_zero))``
5723and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5724an out parameter at ``+1`` is written if and only if the function returns a zero
5725(respectively non-zero) error code.
5726Observe that return-code-dependent out parameter annotations are only
5727available for retained out parameters, as non-retained object do not have to be
5728released by the callee.
5729These attributes are only used by the Clang Static Analyzer.
5730
5731The family of attributes ``X_returns_X_retained`` can be added to functions,
5732C++ methods, and Objective-C methods and properties.
5733Attributes ``X_consumed`` can be added to parameters of methods, functions,
5734and Objective-C methods.)reST";
5735
5736static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5737(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5738convention (e.g. functions starting with "get" are assumed to return at
5739``+0``).
5740
5741It can be overridden using a family of the following attributes. In
5742Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5743a function communicates that the object is returned at ``+1``, and the caller
5744is responsible for freeing it.
5745Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5746specifies that the object is returned at ``+0`` and the ownership remains with
5747the callee.
5748The annotation ``__attribute__((ns_consumes_self))`` specifies that
5749the Objective-C method call consumes the reference to ``self``, e.g. by
5750attaching it to a supplied parameter.
5751Additionally, parameters can have an annotation
5752``__attribute__((ns_consumed))``, which specifies that passing an owned object
5753as that parameter effectively transfers the ownership, and the caller is no
5754longer responsible for it.
5755These attributes affect code generation when interacting with ARC code, and
5756they are used by the Clang Static Analyzer.
5757
5758In C programs using CoreFoundation, a similar set of attributes:
5759``__attribute__((cf_returns_not_retained))``,
5760``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5761have the same respective semantics when applied to CoreFoundation objects.
5762These attributes affect code generation when interacting with ARC code, and
5763they are used by the Clang Static Analyzer.
5764
5765Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5766the same attribute family is present:
5767``__attribute__((os_returns_not_retained))``,
5768``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5769with the same respective semantics.
5770Similar to ``__attribute__((ns_consumes_self))``,
5771``__attribute__((os_consumes_this))`` specifies that the method call consumes
5772the reference to "this" (e.g., when attaching it to a different object supplied
5773as a parameter).
5774Out parameters (parameters the function is meant to write into,
5775either via pointers-to-pointers or references-to-pointers)
5776may be annotated with ``__attribute__((os_returns_retained))``
5777or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5778written into the out parameter should (or respectively should not) be released
5779after use.
5780Since often out parameters may or may not be written depending on the exit
5781code of the function,
5782annotations ``__attribute__((os_returns_retained_on_zero))``
5783and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5784an out parameter at ``+1`` is written if and only if the function returns a zero
5785(respectively non-zero) error code.
5786Observe that return-code-dependent out parameter annotations are only
5787available for retained out parameters, as non-retained object do not have to be
5788released by the callee.
5789These attributes are only used by the Clang Static Analyzer.
5790
5791The family of attributes ``X_returns_X_retained`` can be added to functions,
5792C++ methods, and Objective-C methods and properties.
5793Attributes ``X_consumed`` can be added to parameters of methods, functions,
5794and Objective-C methods.)reST";
5795
5796static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5797(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5798convention (e.g. functions starting with "get" are assumed to return at
5799``+0``).
5800
5801It can be overridden using a family of the following attributes. In
5802Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5803a function communicates that the object is returned at ``+1``, and the caller
5804is responsible for freeing it.
5805Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5806specifies that the object is returned at ``+0`` and the ownership remains with
5807the callee.
5808The annotation ``__attribute__((ns_consumes_self))`` specifies that
5809the Objective-C method call consumes the reference to ``self``, e.g. by
5810attaching it to a supplied parameter.
5811Additionally, parameters can have an annotation
5812``__attribute__((ns_consumed))``, which specifies that passing an owned object
5813as that parameter effectively transfers the ownership, and the caller is no
5814longer responsible for it.
5815These attributes affect code generation when interacting with ARC code, and
5816they are used by the Clang Static Analyzer.
5817
5818In C programs using CoreFoundation, a similar set of attributes:
5819``__attribute__((cf_returns_not_retained))``,
5820``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5821have the same respective semantics when applied to CoreFoundation objects.
5822These attributes affect code generation when interacting with ARC code, and
5823they are used by the Clang Static Analyzer.
5824
5825Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5826the same attribute family is present:
5827``__attribute__((os_returns_not_retained))``,
5828``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5829with the same respective semantics.
5830Similar to ``__attribute__((ns_consumes_self))``,
5831``__attribute__((os_consumes_this))`` specifies that the method call consumes
5832the reference to "this" (e.g., when attaching it to a different object supplied
5833as a parameter).
5834Out parameters (parameters the function is meant to write into,
5835either via pointers-to-pointers or references-to-pointers)
5836may be annotated with ``__attribute__((os_returns_retained))``
5837or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5838written into the out parameter should (or respectively should not) be released
5839after use.
5840Since often out parameters may or may not be written depending on the exit
5841code of the function,
5842annotations ``__attribute__((os_returns_retained_on_zero))``
5843and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5844an out parameter at ``+1`` is written if and only if the function returns a zero
5845(respectively non-zero) error code.
5846Observe that return-code-dependent out parameter annotations are only
5847available for retained out parameters, as non-retained object do not have to be
5848released by the callee.
5849These attributes are only used by the Clang Static Analyzer.
5850
5851The family of attributes ``X_returns_X_retained`` can be added to functions,
5852C++ methods, and Objective-C methods and properties.
5853Attributes ``X_consumed`` can be added to parameters of methods, functions,
5854and Objective-C methods.)reST";
5855
5856static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5857(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5858convention (e.g. functions starting with "get" are assumed to return at
5859``+0``).
5860
5861It can be overridden using a family of the following attributes. In
5862Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5863a function communicates that the object is returned at ``+1``, and the caller
5864is responsible for freeing it.
5865Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5866specifies that the object is returned at ``+0`` and the ownership remains with
5867the callee.
5868The annotation ``__attribute__((ns_consumes_self))`` specifies that
5869the Objective-C method call consumes the reference to ``self``, e.g. by
5870attaching it to a supplied parameter.
5871Additionally, parameters can have an annotation
5872``__attribute__((ns_consumed))``, which specifies that passing an owned object
5873as that parameter effectively transfers the ownership, and the caller is no
5874longer responsible for it.
5875These attributes affect code generation when interacting with ARC code, and
5876they are used by the Clang Static Analyzer.
5877
5878In C programs using CoreFoundation, a similar set of attributes:
5879``__attribute__((cf_returns_not_retained))``,
5880``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5881have the same respective semantics when applied to CoreFoundation objects.
5882These attributes affect code generation when interacting with ARC code, and
5883they are used by the Clang Static Analyzer.
5884
5885Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5886the same attribute family is present:
5887``__attribute__((os_returns_not_retained))``,
5888``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5889with the same respective semantics.
5890Similar to ``__attribute__((ns_consumes_self))``,
5891``__attribute__((os_consumes_this))`` specifies that the method call consumes
5892the reference to "this" (e.g., when attaching it to a different object supplied
5893as a parameter).
5894Out parameters (parameters the function is meant to write into,
5895either via pointers-to-pointers or references-to-pointers)
5896may be annotated with ``__attribute__((os_returns_retained))``
5897or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5898written into the out parameter should (or respectively should not) be released
5899after use.
5900Since often out parameters may or may not be written depending on the exit
5901code of the function,
5902annotations ``__attribute__((os_returns_retained_on_zero))``
5903and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5904an out parameter at ``+1`` is written if and only if the function returns a zero
5905(respectively non-zero) error code.
5906Observe that return-code-dependent out parameter annotations are only
5907available for retained out parameters, as non-retained object do not have to be
5908released by the callee.
5909These attributes are only used by the Clang Static Analyzer.
5910
5911The family of attributes ``X_returns_X_retained`` can be added to functions,
5912C++ methods, and Objective-C methods and properties.
5913Attributes ``X_consumed`` can be added to parameters of methods, functions,
5914and Objective-C methods.)reST";
5915
5916static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5917(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5918convention (e.g. functions starting with "get" are assumed to return at
5919``+0``).
5920
5921It can be overridden using a family of the following attributes. In
5922Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5923a function communicates that the object is returned at ``+1``, and the caller
5924is responsible for freeing it.
5925Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5926specifies that the object is returned at ``+0`` and the ownership remains with
5927the callee.
5928The annotation ``__attribute__((ns_consumes_self))`` specifies that
5929the Objective-C method call consumes the reference to ``self``, e.g. by
5930attaching it to a supplied parameter.
5931Additionally, parameters can have an annotation
5932``__attribute__((ns_consumed))``, which specifies that passing an owned object
5933as that parameter effectively transfers the ownership, and the caller is no
5934longer responsible for it.
5935These attributes affect code generation when interacting with ARC code, and
5936they are used by the Clang Static Analyzer.
5937
5938In C programs using CoreFoundation, a similar set of attributes:
5939``__attribute__((cf_returns_not_retained))``,
5940``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5941have the same respective semantics when applied to CoreFoundation objects.
5942These attributes affect code generation when interacting with ARC code, and
5943they are used by the Clang Static Analyzer.
5944
5945Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5946the same attribute family is present:
5947``__attribute__((os_returns_not_retained))``,
5948``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5949with the same respective semantics.
5950Similar to ``__attribute__((ns_consumes_self))``,
5951``__attribute__((os_consumes_this))`` specifies that the method call consumes
5952the reference to "this" (e.g., when attaching it to a different object supplied
5953as a parameter).
5954Out parameters (parameters the function is meant to write into,
5955either via pointers-to-pointers or references-to-pointers)
5956may be annotated with ``__attribute__((os_returns_retained))``
5957or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5958written into the out parameter should (or respectively should not) be released
5959after use.
5960Since often out parameters may or may not be written depending on the exit
5961code of the function,
5962annotations ``__attribute__((os_returns_retained_on_zero))``
5963and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5964an out parameter at ``+1`` is written if and only if the function returns a zero
5965(respectively non-zero) error code.
5966Observe that return-code-dependent out parameter annotations are only
5967available for retained out parameters, as non-retained object do not have to be
5968released by the callee.
5969These attributes are only used by the Clang Static Analyzer.
5970
5971The family of attributes ``X_returns_X_retained`` can be added to functions,
5972C++ methods, and Objective-C methods and properties.
5973Attributes ``X_consumed`` can be added to parameters of methods, functions,
5974and Objective-C methods.)reST";
5975
5976static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5977(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5978convention (e.g. functions starting with "get" are assumed to return at
5979``+0``).
5980
5981It can be overridden using a family of the following attributes. In
5982Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5983a function communicates that the object is returned at ``+1``, and the caller
5984is responsible for freeing it.
5985Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5986specifies that the object is returned at ``+0`` and the ownership remains with
5987the callee.
5988The annotation ``__attribute__((ns_consumes_self))`` specifies that
5989the Objective-C method call consumes the reference to ``self``, e.g. by
5990attaching it to a supplied parameter.
5991Additionally, parameters can have an annotation
5992``__attribute__((ns_consumed))``, which specifies that passing an owned object
5993as that parameter effectively transfers the ownership, and the caller is no
5994longer responsible for it.
5995These attributes affect code generation when interacting with ARC code, and
5996they are used by the Clang Static Analyzer.
5997
5998In C programs using CoreFoundation, a similar set of attributes:
5999``__attribute__((cf_returns_not_retained))``,
6000``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6001have the same respective semantics when applied to CoreFoundation objects.
6002These attributes affect code generation when interacting with ARC code, and
6003they are used by the Clang Static Analyzer.
6004
6005Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6006the same attribute family is present:
6007``__attribute__((os_returns_not_retained))``,
6008``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6009with the same respective semantics.
6010Similar to ``__attribute__((ns_consumes_self))``,
6011``__attribute__((os_consumes_this))`` specifies that the method call consumes
6012the reference to "this" (e.g., when attaching it to a different object supplied
6013as a parameter).
6014Out parameters (parameters the function is meant to write into,
6015either via pointers-to-pointers or references-to-pointers)
6016may be annotated with ``__attribute__((os_returns_retained))``
6017or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6018written into the out parameter should (or respectively should not) be released
6019after use.
6020Since often out parameters may or may not be written depending on the exit
6021code of the function,
6022annotations ``__attribute__((os_returns_retained_on_zero))``
6023and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6024an out parameter at ``+1`` is written if and only if the function returns a zero
6025(respectively non-zero) error code.
6026Observe that return-code-dependent out parameter annotations are only
6027available for retained out parameters, as non-retained object do not have to be
6028released by the callee.
6029These attributes are only used by the Clang Static Analyzer.
6030
6031The family of attributes ``X_returns_X_retained`` can be added to functions,
6032C++ methods, and Objective-C methods and properties.
6033Attributes ``X_consumed`` can be added to parameters of methods, functions,
6034and Objective-C methods.)reST";
6035
6036static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the ``objc_boxable`` attribute can be used
6037with the Objective-C boxed expression syntax, ``@(...)``.
6038
6039**Usage**: ``__attribute__((objc_boxable))``. This attribute
6040can only be placed on a declaration of a trivially-copyable struct or union:
6041
6042.. code-block:: objc
6043
6044 struct __attribute__((objc_boxable)) some_struct {
6045 int i;
6046 };
6047 union __attribute__((objc_boxable)) some_union {
6048 int i;
6049 float f;
6050 };
6051 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6052
6053 // ...
6054
6055 some_struct ss;
6056 NSValue *boxed = @(ss);)reST";
6057
6058static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6059
6060static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6061
6062static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6063
6064static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6065instantiated at runtime.
6066
6067Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
6068still has a "class stub" that is visible to the linker. This allows categories
6069to be defined. Static message sends with the class as a receiver use a special
6070access pattern to ensure the class is lazily instantiated from the class stub.
6071
6072Classes annotated with this attribute cannot be subclassed and cannot have
6073implementations defined for them. This attribute is intended for use in
6074Swift-generated headers for classes defined in Swift.
6075
6076Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6077
6078static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6079
6080static const char AttrDoc_ObjCDirect[] = R"reST(The ``objc_direct`` attribute can be used to mark an Objective-C method as
6081being *direct*. A direct method is treated statically like an ordinary method,
6082but dynamically it behaves more like a C function. This lowers some of the costs
6083associated with the method but also sacrifices some of the ordinary capabilities
6084of Objective-C methods.
6085
6086A message send of a direct method calls the implementation directly, as if it
6087were a C function, rather than using ordinary Objective-C method dispatch. This
6088is substantially faster and potentially allows the implementation to be inlined,
6089but it also means the method cannot be overridden in subclasses or replaced
6090dynamically, as ordinary Objective-C methods can.
6091
6092Furthermore, a direct method is not listed in the class's method lists. This
6093substantially reduces the code-size overhead of the method but also means it
6094cannot be called dynamically using ordinary Objective-C method dispatch at all;
6095in particular, this means that it cannot override a superclass method or satisfy
6096a protocol requirement.
6097
6098Because a direct method cannot be overridden, it is an error to perform
6099a ``super`` message send of one.
6100
6101Although a message send of a direct method causes the method to be called
6102directly as if it were a C function, it still obeys Objective-C semantics in other
6103ways:
6104
6105- If the receiver is ``nil``, the message send does nothing and returns the zero value
6106 for the return type.
6107
6108- A message send of a direct class method will cause the class to be initialized,
6109 including calling the ``+initialize`` method if present.
6110
6111- The implicit ``_cmd`` parameter containing the method's selector is still defined.
6112 In order to minimize code-size costs, the implementation will not emit a reference
6113 to the selector if the parameter is unused within the method.
6114
6115Symbols for direct method implementations are implicitly given hidden
6116visibility, meaning that they can only be called within the same linkage unit.
6117
6118It is an error to do any of the following:
6119
6120- declare a direct method in a protocol,
6121- declare an override of a direct method with a method in a subclass,
6122- declare an override of a non-direct method with a direct method in a subclass,
6123- declare a method with different directness in different class interfaces, or
6124- implement a non-direct method (as declared in any class interface) with a direct method.
6125
6126If any of these rules would be violated if every method defined in an
6127``@implementation`` within a single linkage unit were declared in an
6128appropriate class interface, the program is ill-formed with no diagnostic
6129required. If a violation of this rule is not diagnosed, behavior remains
6130well-defined; this paragraph is simply reserving the right to diagnose such
6131conflicts in the future, not to treat them as undefined behavior.
6132
6133Additionally, Clang will warn about any ``@selector`` expression that
6134names a selector that is only known to be used for direct methods.
6135
6136For the purpose of these rules, a "class interface" includes a class's primary
6137``@interface`` block, its class extensions, its categories, its declared protocols,
6138and all the class interfaces of its superclasses.
6139
6140An Objective-C property can be declared with the ``direct`` property
6141attribute. If a direct property declaration causes an implicit declaration of
6142a getter or setter method (that is, if the given method is not explicitly
6143declared elsewhere), the method is declared to be direct.
6144
6145Some programmers may wish to make many methods direct at once. In order
6146to simplify this, the ``objc_direct_members`` attribute is provided; see its
6147documentation for more information.)reST";
6148
6149static const char AttrDoc_ObjCDirectMembers[] = R"reST(The ``objc_direct_members`` attribute can be placed on an Objective-C
6150``@interface`` or ``@implementation`` to mark that methods declared
6151therein should be considered direct by default. See the documentation
6152for ``objc_direct`` for more information about direct methods.
6153
6154When ``objc_direct_members`` is placed on an ``@interface`` block, every
6155method in the block is considered to be declared as direct. This includes any
6156implicit method declarations introduced by property declarations. If the method
6157redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6158method was annotated with the ``objc_direct`` attribute.
6159
6160When ``objc_direct_members`` is placed on an ``@implementation`` block,
6161methods defined in the block are considered to be declared as direct unless
6162they have been previously declared as non-direct in any interface of the class.
6163This includes the implicit method definitions introduced by synthesized
6164properties, including auto-synthesized properties.)reST";
6165
6166static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6167
6168static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6169
6170static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The ``objc_externally_retained`` attribute can be applied to strong local
6171variables, functions, methods, or blocks to opt into
6172`externally-retained semantics
6173<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
6174
6175When applied to the definition of a function, method, or block, every parameter
6176of the function with implicit strong retainable object pointer type is
6177considered externally-retained, and becomes ``const``. By explicitly annotating
6178a parameter with ``__strong``, you can opt back into the default
6179non-externally-retained behavior for that parameter. For instance,
6180``first_param`` is externally-retained below, but not ``second_param``:
6181
6182.. code-block:: objc
6183
6184 __attribute__((objc_externally_retained))
6185 void f(NSArray *first_param, __strong NSArray *second_param) {
6186 // ...
6187 }
6188
6189Likewise, when applied to a strong local variable, that variable becomes
6190``const`` and is considered externally-retained.
6191
6192When compiled without ``-fobjc-arc``, this attribute is ignored.)reST";
6193
6194static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6195
6196static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6197
6198static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6199
6200static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6201
6202static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6203selectors. It is sometimes useful to be able to mark a method as having a
6204particular conventional meaning despite not having the right selector, or as
6205not having the conventional meaning that its selector would suggest. For these
6206use cases, we provide an attribute to specifically describe the "method family"
6207that a method belongs to.
6208
6209**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
6210``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
6211attribute can only be placed at the end of a method declaration:
6212
6213.. code-block:: objc
6214
6215 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6216
6217Users who do not wish to change the conventional meaning of a method, and who
6218merely want to document its non-standard retain and release semantics, should
6219use the retaining behavior attributes (``ns_returns_retained``,
6220``ns_returns_not_retained``, etc).
6221
6222Query for this feature with ``__has_attribute(objc_method_family)``.)reST";
6223
6224static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6225
6226static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C ``@interface`` or
6227``@implementation`` declaration to add the class to the list of non-lazily
6228initialized classes. A non-lazy class will be initialized eagerly when the
6229Objective-C runtime is loaded. This is required for certain system classes which
6230have instances allocated in non-standard ways, such as the classes for blocks
6231and constant strings. Adding this attribute is essentially equivalent to
6232providing a trivial ``+load`` method but avoids the (fairly small) load-time
6233overheads associated with defining and calling such a method.)reST";
6234
6235static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The ``objc_non_runtime_protocol`` attribute can be used to mark that an
6236Objective-C protocol is only used during static type-checking and doesn't need
6237to be represented dynamically. This avoids several small code-size and run-time
6238overheads associated with handling the protocol's metadata. A non-runtime
6239protocol cannot be used as the operand of a ``@protocol`` expression, and
6240dynamic attempts to find it with ``objc_getProtocol`` will fail.
6241
6242If a non-runtime protocol inherits from any ordinary protocols, classes and
6243derived protocols that declare conformance to the non-runtime protocol will
6244dynamically list their conformance to those bare protocols.)reST";
6245
6246static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6247
6248static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6249
6250static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6251
6252static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6253parent class but expect that the overriding method also calls the overridden
6254method in the parent class. For these cases, we provide an attribute to
6255designate that a method requires a "call to ``super``" in the overriding
6256method in the subclass.
6257
6258**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
6259be placed at the end of a method declaration:
6260
6261.. code-block:: objc
6262
6263 - (void)foo __attribute__((objc_requires_super));
6264
6265This attribute can only be applied the method declarations within a class, and
6266not a protocol. Currently this attribute does not enforce any placement of
6267where the call occurs in the overriding method (such as in the case of
6268``-dealloc`` where the call must appear at the end). It checks only that it
6269exists.
6270
6271Note that on both OS X and iOS that the Foundation framework provides a
6272convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
6273attribute:
6274
6275.. code-block:: objc
6276
6277 - (void)foo NS_REQUIRES_SUPER;
6278
6279This macro is conditionally defined depending on the compiler's support for
6280this attribute. If the compiler does not support the attribute the macro
6281expands to nothing.
6282
6283Operationally, when a method has this annotation the compiler will warn if the
6284implementation of an override in a subclass does not call super. For example:
6285
6286.. code-block:: objc
6287
6288 warning: method possibly missing a [super AnnotMeth] call
6289 - (void) AnnotMeth{};
6290 ^)reST";
6291
6292static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6293
6294static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6295
6296static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6297in the metadata name for that object. The ``objc_runtime_name``
6298attribute allows annotated interfaces or protocols to use the
6299specified string argument in the object's metadata name instead of the
6300default name.
6301
6302**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
6303can only be placed before an @protocol or @interface declaration:
6304
6305.. code-block:: objc
6306
6307 __attribute__((objc_runtime_name("MyLocalName")))
6308 @interface Message
6309 @end)reST";
6310
6311static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6312visible to the Objective-C runtime but not to the linker. Classes annotated
6313with this attribute cannot be subclassed and cannot have categories defined for
6314them.)reST";
6315
6316static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C ``@interface`` declaration to
6317ensure that this class cannot be subclassed.)reST";
6318
6319static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6320
6321static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6322
6323static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6324to declare if they are being read or written by a kernel or function.
6325
6326The read_only/__read_only, write_only/__write_only and read_write/__read_write
6327names are reserved for use as access qualifiers and shall not be used otherwise.
6328
6329.. code-block:: c
6330
6331 kernel void
6332 foo (read_only image2d_t imageA,
6333 write_only image2d_t imageB) {
6334 ...
6335 }
6336
6337In the above example imageA is a read-only 2D image object, and imageB is a
6338write-only 2D image object.
6339
6340The read_write (or __read_write) qualifier can not be used with pipe.
6341
6342More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6343
6344static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6345a constant (non-modifiable) memory region. It is available to all work items.
6346Any type can be annotated with the constant address space attribute. Objects
6347with the constant address space qualifier can be declared in any scope and must
6348have an initializer.)reST";
6349
6350static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6351It can be used with pointer types. Variables in global and local scope and
6352function parameters in non-kernel functions can have the generic address space
6353type attribute. It is intended to be a placeholder for any other address space
6354except for '__constant' in OpenCL code which can be used with multiple address
6355spaces.)reST";
6356
6357static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6358global memory, which is accessible by all work items. The content stored in this
6359memory area persists between kernel executions. Pointer types to the global
6360address space are allowed as function parameters or local variables. Starting
6361with OpenCL v2.0, the global address space can be used with global (program
6362scope) variables and static local variable as well.)reST";
6363
6364static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6365an object is allocated in global memory on the device/host. It helps to
6366distinguish USM (Unified Shared Memory) pointers that access global device
6367memory from those that access global host memory. These new address spaces are
6368a subset of the ``__global/opencl_global`` address space, the full address space
6369set model for OpenCL 2.0 with the extension looks as follows:
6370
6371 | generic->global->host
6372 | ->device
6373 | ->private
6374 | ->local
6375 | constant
6376
6377As ``global_device`` and ``global_host`` are a subset of
6378``__global/opencl_global`` address spaces it is allowed to convert
6379``global_device`` and ``global_host`` address spaces to
6380``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6381"Address space nesting and rules for pointers").)reST";
6382
6383static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6384an object is allocated in global memory on the device/host. It helps to
6385distinguish USM (Unified Shared Memory) pointers that access global device
6386memory from those that access global host memory. These new address spaces are
6387a subset of the ``__global/opencl_global`` address space, the full address space
6388set model for OpenCL 2.0 with the extension looks as follows:
6389
6390 | generic->global->host
6391 | ->device
6392 | ->private
6393 | ->local
6394 | constant
6395
6396As ``global_device`` and ``global_host`` are a subset of
6397``__global/opencl_global`` address spaces it is allowed to convert
6398``global_device`` and ``global_host`` address spaces to
6399``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6400"Address space nesting and rules for pointers").)reST";
6401
6402static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6403the kernel must be compiled and executed with the specified subgroup size. When
6404this attribute is present, get_max_sub_group_size() is guaranteed to return the
6405specified integer value. This is important for the correctness of many subgroup
6406algorithms, and in some cases may be used by the compiler to generate more optimal
6407code. See `cl_intel_required_subgroup_size
6408<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6409for details.)reST";
6410
6411static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6412group) memory area, which is accessible to all work items in the same work
6413group. The content stored in this memory region is not accessible after
6414the kernel execution ends. In a kernel function scope, any variable can be in
6415the local address space. In other scopes, only pointer types to the local address
6416space are allowed. Local address space variables cannot have an initializer.)reST";
6417
6418static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6419(work item) memory. Other work items cannot access the same memory area and its
6420content is destroyed after work item execution ends. Local variables can be
6421declared in the private address space. Function arguments are always in the
6422private address space. Kernel function arguments of a pointer or an array type
6423cannot point to the private address space.)reST";
6424
6425static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6426(for, while and do loops) can be unrolled. This attribute qualifier can be
6427used to specify full unrolling or partial unrolling by a specified amount.
6428This is a compiler hint and the compiler may ignore this directive. See
6429`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
6430s6.11.5 for details.)reST";
6431
6432static const char AttrDoc_OptimizeNone[] = R"reST(The ``optnone`` attribute suppresses essentially all optimizations
6433on a function or method, regardless of the optimization level applied to
6434the compilation unit as a whole. This is particularly useful when you
6435need to debug a particular function, but it is infeasible to build the
6436entire application without optimization. Avoiding optimization on the
6437specified function can improve the quality of the debugging information
6438for that function.
6439
6440This attribute is incompatible with the ``always_inline`` and ``minsize``
6441attributes.
6442
6443Note that this attribute does not apply recursively to nested functions such as
6444lambdas or blocks when using declaration-specific attribute syntaxes such as double
6445square brackets (``[[]]``) or ``__attribute__``. The ``#pragma`` syntax can be
6446used to apply the attribute to all functions, including nested functions, in a
6447range of source code.)reST";
6448
6449static const char AttrDoc_OverflowBehavior[] = R"reST(No documentation.)reST";
6450
6451static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6452in C is introduced using the ``overloadable`` attribute. For example, one
6453might provide several overloaded versions of a ``tgsin`` function that invokes
6454the appropriate standard function computing the sine of a value with ``float``,
6455``double``, or ``long double`` precision:
6456
6457.. code-block:: c
6458
6459 #include <math.h>
6460 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6461 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6462 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6463
6464Given these declarations, one can call ``tgsin`` with a ``float`` value to
6465receive a ``float`` result, with a ``double`` to receive a ``double`` result,
6466etc. Function overloading in C follows the rules of C++ function overloading
6467to pick the best overload given the call arguments, with a few C-specific
6468semantics:
6469
6470* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
6471 floating-point promotion (per C99) rather than as a floating-point conversion
6472 (as in C++).
6473
6474* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
6475 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
6476 compatible types.
6477
6478* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
6479 and ``U`` are compatible types. This conversion is given "conversion" rank.
6480
6481* If no viable candidates are otherwise available, we allow a conversion from a
6482 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
6483 incompatible. This conversion is ranked below all other types of conversions.
6484 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
6485 for ``T`` and ``U`` to be incompatible.
6486
6487The declaration of ``overloadable`` functions is restricted to function
6488declarations and definitions. If a function is marked with the ``overloadable``
6489attribute, then all declarations and definitions of functions with that name,
6490except for at most one (see the note below about unmarked overloads), must have
6491the ``overloadable`` attribute. In addition, redeclarations of a function with
6492the ``overloadable`` attribute must have the ``overloadable`` attribute, and
6493redeclarations of a function without the ``overloadable`` attribute must *not*
6494have the ``overloadable`` attribute. e.g.,
6495
6496.. code-block:: c
6497
6498 int f(int) __attribute__((overloadable));
6499 float f(float); // error: declaration of "f" must have the "overloadable" attribute
6500 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6501
6502 int g(int) __attribute__((overloadable));
6503 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6504
6505 int h(int);
6506 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6507 // have the "overloadable" attribute
6508
6509Functions marked ``overloadable`` must have prototypes. Therefore, the
6510following code is ill-formed:
6511
6512.. code-block:: c
6513
6514 int h() __attribute__((overloadable)); // error: h does not have a prototype
6515
6516However, ``overloadable`` functions are allowed to use a ellipsis even if there
6517are no named parameters (as is permitted in C++). This feature is particularly
6518useful when combined with the ``unavailable`` attribute:
6519
6520.. code-block:: c++
6521
6522 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6523
6524Functions declared with the ``overloadable`` attribute have their names mangled
6525according to the same rules as C++ function names. For example, the three
6526``tgsin`` functions in our motivating example get the mangled names
6527``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
6528caveats to this use of name mangling:
6529
6530* Future versions of Clang may change the name mangling of functions overloaded
6531 in C, so you should not depend on an specific mangling. To be completely
6532 safe, we strongly urge the use of ``static inline`` with ``overloadable``
6533 functions.
6534
6535* The ``overloadable`` attribute has almost no meaning when used in C++,
6536 because names will already be mangled and functions are already overloadable.
6537 However, when an ``overloadable`` function occurs within an ``extern "C"``
6538 linkage specification, its name *will* be mangled in the same way as it
6539 would in C.
6540
6541For the purpose of backwards compatibility, at most one function with the same
6542name as other ``overloadable`` functions may omit the ``overloadable``
6543attribute. In this case, the function without the ``overloadable`` attribute
6544will not have its name mangled.
6545
6546For example:
6547
6548.. code-block:: c
6549
6550 // Notes with mangled names assume Itanium mangling.
6551 int f(int);
6552 int f(double) __attribute__((overloadable));
6553 void foo() {
6554 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6555 // was marked with overloadable).
6556 f(1.0); // Emits a call to _Z1fd.
6557 }
6558
6559Support for unmarked overloads is not present in some versions of clang. You may
6560query for it using ``__has_extension(overloadable_unmarked)``.
6561
6562Query for this attribute with ``__has_attribute(overloadable)``.)reST";
6563
6564static const char AttrDoc_Override[] = R"reST()reST";
6565
6566static const char AttrDoc_Owner[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6567 a future version of clang.
6568
6569The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
6570object of type ``T``:
6571
6572.. code::
6573
6574 class [[gsl::Owner(int)]] IntOwner {
6575 private:
6576 int value;
6577 public:
6578 int *getInt() { return &value; }
6579 };
6580
6581The argument ``T`` is optional and is ignored.
6582This attribute may be used by analysis tools and has no effect on code
6583generation. A ``void`` argument means that the class can own any type.
6584
6585See Pointer_ for an example.)reST";
6586
6587static const char AttrDoc_Ownership[] = R"reST(.. note::
6588
6589 In order for the Clang Static Analyzer to acknowledge these attributes, the
6590 ``Optimistic`` config needs to be set to true for the checker
6591 ``unix.DynamicMemoryModeling``:
6592
6593 ``-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true``
6594
6595These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6596facilities to mark custom allocating/deallocating functions.
6597
6598All 3 attributes' first parameter of type string is the type of the allocation:
6599``malloc``, ``new``, etc. to allow for catching :ref:`mismatched deallocation
6600<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6601a function annotated with
6602returning a piece of memory of type ``lasagna`` but freed with a function
6603annotated to release ``cheese`` typed memory will result in mismatched
6604deallocation warning.
6605
6606The (currently) only allocation type having special meaning is ``malloc`` --
6607the Clang Static Analyzer makes sure that allocating functions annotated with
6608``malloc`` are treated like they used the standard ``malloc()``, and can be
6609safely deallocated with the standard ``free()``.
6610
6611* Use ``ownership_returns`` to mark a function as an allocating function. Takes
6612 1 parameter to denote the allocation type.
6613* Use ``ownership_takes`` to mark a function as a deallocating function. Takes 2
6614 parameters: the allocation type, and the index of the parameter that is being
6615 deallocated (counting from 1).
6616* Use ``ownership_holds`` to mark that a function takes over the ownership of a
6617 piece of memory and will free it at some unspecified point in the future. Like
6618 ``ownership_takes``, this takes 2 parameters: the allocation type, and the
6619 index of the parameter whose ownership will be taken over (counting from 1).
6620
6621The annotations ``ownership_takes`` and ``ownership_holds`` both prevent memory
6622leak reports (concerning the specified argument); the difference between them
6623is that using taken memory is a use-after-free error, while using held memory
6624is assumed to be legitimate.
6625
6626Example:
6627
6628.. code-block:: c
6629
6630 // Denotes that my_malloc will return with a dynamically allocated piece of
6631 // memory using malloc().
6632 void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
6633
6634 // Denotes that my_free will deallocate its parameter using free().
6635 void __attribute((ownership_takes(malloc, 1))) my_free(void *);
6636
6637 // Denotes that my_hold will take over the ownership of its parameter that was
6638 // allocated via malloc().
6639 void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
6640
6641Further reading about dynamic memory modeling in the Clang Static Analyzer is
6642found in these checker docs:
6643:ref:`unix.Malloc <unix-Malloc>`, :ref:`unix.MallocSizeof <unix-MallocSizeof>`,
6644:ref:`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
6645:ref:`cplusplus.NewDelete <cplusplus-NewDelete>`,
6646:ref:`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
6647:ref:`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
6648Mind that many more checkers are affected by dynamic memory modeling changes to
6649some extent.
6650
6651Further reading for other annotations:
6652`Source Annotations in the Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/user-docs/Annotations.html>`_.)reST";
6653
6654static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
6655
6656static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
6657function with annotated parameters will issue a warning if the corresponding
6658argument isn't in the expected state. The attribute is also used to set the
6659initial state of the parameter when analyzing the function's body.)reST";
6660
6661static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
6662
6663static const char AttrDoc_PassObjectSize[] = R"reST(.. Note:: The mangling of functions with parameters that are annotated with
6664 ``pass_object_size`` is subject to change. You can get around this by
6665 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
6666 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
6667 not mangled.
6668
6669The ``pass_object_size(Type)`` attribute can be placed on function parameters to
6670instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
6671of said function, and implicitly pass the result of this call in as an invisible
6672argument of type ``size_t`` directly after the parameter annotated with
6673``pass_object_size``. Clang will also replace any calls to
6674``__builtin_object_size(param, Type)`` in the function by said implicit
6675parameter.
6676
6677Example usage:
6678
6679.. code-block:: c
6680
6681 int bzero1(char *const p __attribute__((pass_object_size(0))))
6682 __attribute__((noinline)) {
6683 int i = 0;
6684 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
6685 p[i] = 0;
6686 }
6687 return i;
6688 }
6689
6690 int main() {
6691 char chars[100];
6692 int n = bzero1(&chars[0]);
6693 assert(n == sizeof(chars));
6694 return 0;
6695 }
6696
6697If successfully evaluating ``__builtin_object_size(param, Type)`` at the
6698callsite is not possible, then the "failed" value is passed in. So, using the
6699definition of ``bzero1`` from above, the following code would exit cleanly:
6700
6701.. code-block:: c
6702
6703 int main2(int argc, char *argv[]) {
6704 int n = bzero1(argv);
6705 assert(n == -1);
6706 return 0;
6707 }
6708
6709``pass_object_size`` plays a part in overload resolution. If two overload
6710candidates are otherwise equally good, then the overload with one or more
6711parameters with ``pass_object_size`` is preferred. This implies that the choice
6712between two identical overloads both with ``pass_object_size`` on one or more
6713parameters will always be ambiguous; for this reason, having two such overloads
6714is illegal. For example:
6715
6716.. code-block:: c++
6717
6718 #define PS(N) __attribute__((pass_object_size(N)))
6719 // OK
6720 void Foo(char *a, char *b); // Overload A
6721 // OK -- overload A has no parameters with pass_object_size.
6722 void Foo(char *a PS(0), char *b PS(0)); // Overload B
6723 // Error -- Same signature (sans pass_object_size) as overload B, and both
6724 // overloads have one or more parameters with the pass_object_size attribute.
6725 void Foo(void *a PS(0), void *b);
6726
6727 // OK
6728 void Bar(void *a PS(0)); // Overload C
6729 // OK
6730 void Bar(char *c PS(1)); // Overload D
6731
6732 void main() {
6733 char known[10], *unknown;
6734 Foo(unknown, unknown); // Calls overload B
6735 Foo(known, unknown); // Calls overload B
6736 Foo(unknown, known); // Calls overload B
6737 Foo(known, known); // Calls overload B
6738
6739 Bar(known); // Calls overload D
6740 Bar(unknown); // Calls overload D
6741 }
6742
6743Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
6744
6745* Only one use of ``pass_object_size`` is allowed per parameter.
6746
6747* It is an error to take the address of a function with ``pass_object_size`` on
6748 any of its parameters. If you wish to do this, you can create an overload
6749 without ``pass_object_size`` on any parameters.
6750
6751* It is an error to apply the ``pass_object_size`` attribute to parameters that
6752 are not pointers. Additionally, any parameter that ``pass_object_size`` is
6753 applied to must be marked ``const`` at its function's definition.
6754
6755Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
6756identically to ``pass_object_size``, but evaluates a call to
6757``__builtin_dynamic_object_size`` at the callee instead of
6758``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
6759runtime checks when the object size can't be determined at compile-time. You can
6760read more about ``__builtin_dynamic_object_size`` `here
6761<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.)reST";
6762
6763static const char AttrDoc_PatchableFunctionEntry[] = R"reST(``__attribute__((patchable_function_entry(N,M,Section)))`` is used to generate M
6764NOPs before the function entry and N-M NOPs after the function entry, with a record of
6765the entry stored in section ``Section``. This attribute takes precedence over the
6766command line option ``-fpatchable-function-entry=N,M,Section``. ``M`` defaults to 0
6767if omitted.``Section`` defaults to the ``-fpatchable-function-entry`` section name if
6768set, or to ``__patchable_function_entries`` otherwise.
6769
6770This attribute is only supported on
6771aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
6772For ppc/ppc64 targets, AIX is still not supported.)reST";
6773
6774static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
6775similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
6776"aapcs-vfp".)reST";
6777
6778static const char AttrDoc_Personality[] = R"reST(``__attribute__((personality(<routine>)))`` is used to specify a personality
6779routine that is different from the language that is being used to implement the
6780function. This is a targeted, low-level feature aimed at language runtime
6781implementors who write runtime support code in C/C++ but need that code to
6782participate in a foreign language's exception-handling or unwinding model.
6783
6784A personality routine is a language-specific callback attached to each stack
6785frame that the unwinder invokes to determine whether that frame handles a given
6786exception and what cleanup actions to perform. It effectively colors the
6787language-agnostic unwinding mechanism with language-specific semantics, enabling
6788different languages to coexist on the same call stack while each interpreting
6789exceptions according to their own rules.)reST";
6790
6791static const char AttrDoc_Pointer[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6792 a future version of clang.
6793
6794The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
6795like pointers to an object of type ``T``:
6796
6797.. code::
6798
6799 class [[gsl::Pointer(int)]] IntPointer {
6800 private:
6801 int *valuePointer;
6802 public:
6803 IntPointer(const IntOwner&);
6804 int *getInt() { return valuePointer; }
6805 };
6806
6807The argument ``T`` is optional and is ignored.
6808This attribute may be used by analysis tools and has no effect on code
6809generation. A ``void`` argument means that the pointer can point to any type.
6810
6811Example:
6812When constructing an instance of a class annotated like this (a Pointer) from
6813an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
6814then the analysis will consider the Pointer to point inside the Owner.
6815When the Owner's lifetime ends, it will consider the Pointer to be dangling.
6816
6817.. code-block:: c++
6818
6819 int f() {
6820 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
6821 P.getInt(); // P is dangling
6822 }
6823
6824**Transparent Member Functions**
6825
6826The analysis automatically tracks certain member functions of ``[[gsl::Pointer]]`` types
6827that provide transparent access to the pointed-to object. These include:
6828
6829* Dereference operators: ``operator*``, ``operator->``
6830* Data access methods: ``data()``, ``c_str()``, ``get()``
6831* Iterator methods: ``begin()``, ``end()``, ``rbegin()``, ``rend()``, ``cbegin()``, ``cend()``, ``crbegin()``, ``crend()``
6832
6833When these methods return pointers, view types, or references, the analysis treats them as
6834transparently borrowing from the same object that the pointer itself borrows from,
6835enabling detection of use-after-free through these access patterns:
6836
6837.. code-block:: c++
6838
6839 // For example, .data() here returns a borrow to 's' instead of 'v'.
6840 const char* f() {
6841 std::string s = "hello";
6842 std::string_view v = s; // warning: address of stack memory returned
6843 return v.data(); // note: returned here
6844 }
6845
6846 const MyObj& g(MyObj obj) {
6847 View v = obj; // warning: address of stack memory returned
6848 return *v; // note: returned here
6849 }
6850
6851This tracking also applies to range-based for loops, where the ``begin()`` and ``end()``
6852iterators are used to access elements:
6853
6854.. code-block:: c++
6855
6856 std::string_view f(std::vector<std::string> vec) {
6857 for (const std::string& s : vec) { // warning: address of stack memory returned
6858 return s; // note: returned here
6859 }
6860 }
6861
6862**Container Template Specialization**
6863
6864If a template class is annotated with ``[[gsl::Owner]]``, and the first
6865instantiated template argument is a pointer type (raw pointer, or ``[[gsl::Pointer]]``),
6866the analysis will consider the instantiated class as a container of the pointer.
6867When constructing such an object from a GSL owner object, the analysis will
6868assume that the container holds a pointer to the owner object. Consequently,
6869when the owner object is destroyed, the pointer will be considered dangling.
6870
6871.. code-block:: c++
6872
6873 int f() {
6874 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
6875 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
6876 })reST";
6877
6878static const char AttrDoc_PointerAuth[] = R"reST(The ``__ptrauth`` qualifier allows the programmer to directly control
6879how pointers are signed when they are stored in a particular variable.
6880This can be used to strengthen the default protections of pointer
6881authentication and make it more difficult for an attacker to escalate
6882an ability to alter memory into full control of a process.
6883
6884.. code-block:: c
6885
6886 #include <ptrauth.h>
6887
6888 typedef void (*my_callback)(const void*);
6889 my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
6890
6891The first argument to ``__ptrauth`` is the name of the signing key.
6892Valid key names for the target are defined in ``<ptrauth.h>``.
6893
6894The second argument to ``__ptrauth`` is a flag (0 or 1) specifying whether
6895the object should use address discrimination.
6896
6897The third argument to ``__ptrauth`` is a 16-bit non-negative integer which
6898allows additional discrimination between objects.)reST";
6899
6900static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
6901
6902static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
6903
6904static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
6905
6906static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
6907
6908static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
6909
6910static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
6911
6912static const char AttrDoc_PreferredName[] = R"reST(The ``preferred_name`` attribute can be applied to a class template, and
6913specifies a preferred way of naming a specialization of the template. The
6914preferred name will be used whenever the corresponding template specialization
6915would otherwise be printed in a diagnostic or similar context.
6916
6917The preferred name must be a typedef or type alias declaration that refers to a
6918specialization of the class template (not including any type qualifiers). In
6919general this requires the template to be declared at least twice. For example:
6920
6921.. code-block:: c++
6922
6923 template<typename T> struct basic_string;
6924 using string = basic_string<char>;
6925 using wstring = basic_string<wchar_t>;
6926 template<typename T> struct [[clang::preferred_name(string),
6927 clang::preferred_name(wstring)]] basic_string {
6928 // ...
6929 };
6930
6931
6932Note that the ``preferred_name`` attribute will be ignored when the compiler
6933writes a C++20 Module interface now. This is due to a compiler issue
6934(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize
6935declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
6936
6937static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
6938This can be helpful when a bit-field is intended to store an enumeration value,
6939but has to be specified as having the enumeration's underlying type in order to
6940facilitate compiler optimizations or bit-field packing behavior. Normally, the
6941underlying type is what is emitted in debug information, which can make it hard
6942for debuggers to know to map a bit-field's value back to a particular enumeration.
6943
6944.. code-block:: c++
6945
6946 enum Colors { Red, Green, Blue };
6947
6948 struct S {
6949 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
6950 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
6951 } s = { Green, false };
6952
6953Without the attribute, a debugger is likely to display the value ``1`` for ``ColorVal``
6954and ``0`` for ``UseAlternateColorSpace``. With the attribute, the debugger may now
6955display ``Green`` and ``false`` instead.
6956
6957This can be used to map a bit-field to an arbitrary type that isn't integral
6958or an enumeration type. For example:
6959
6960.. code-block:: c++
6961
6962 struct A {
6963 short a1;
6964 short a2;
6965 };
6966
6967 struct B {
6968 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
6969 };
6970
6971will associate the type ``A`` with the ``b1`` bit-field and is intended to display
6972something like this in the debugger:
6973
6974.. code-block:: text
6975
6976 Process 2755547 stopped
6977 * thread #1, name = 'test-preferred-', stop reason = step in
6978 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
6979 10 int main()
6980 11 {
6981 12 B b;
6982 -> 13 return b.b1;
6983 14 }
6984 (lldb) v -T
6985 (B) b = {
6986 (A:32) b1 = {
6987 (short) a1 = 12
6988 (short) a2 = 15
6989 }
6990 }
6991
6992Note that debuggers may not be able to handle more complex mappings, and so
6993this usage is debugger-dependent.)reST";
6994
6995static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
6996a function. The ``preserve_all`` calling convention attempts to make the code
6997in the caller even less intrusive than the ``preserve_most`` calling convention.
6998This calling convention also behaves identical to the ``C`` calling convention
6999on how arguments and return values are passed, but it uses a different set of
7000caller/callee-saved registers. This removes the burden of saving and
7001recovering a large register set before and after the call in the caller. If
7002the arguments are passed in callee-saved registers, then they will be
7003preserved by the callee across the call. This doesn't apply for values
7004returned in callee-saved registers.
7005
7006- On X86-64 the callee preserves all general purpose registers, except for
7007 R11. R11 can be used as a scratch register. Furthermore it also preserves
7008 all floating-point registers (XMMs/YMMs).
7009
7010- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7011 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7012 point registers.
7013
7014The idea behind this convention is to support calls to runtime functions
7015that don't need to call out to any other functions.
7016
7017This calling convention, like the ``preserve_most`` calling convention, will be
7018used by a future version of the Objective-C runtime and should be considered
7019experimental at this time.)reST";
7020
7021static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7022a function. The ``preserve_most`` calling convention attempts to make the code
7023in the caller as unintrusive as possible. This convention behaves identically
7024to the ``C`` calling convention on how arguments and return values are passed,
7025but it uses a different set of caller/callee-saved registers. This alleviates
7026the burden of saving and recovering a large register set before and after the
7027call in the caller. If the arguments are passed in callee-saved registers,
7028then they will be preserved by the callee across the call. This doesn't
7029apply for values returned in callee-saved registers.
7030
7031- On X86-64 the callee preserves all general purpose registers, except for
7032 R11. R11 can be used as a scratch register. Floating-point registers
7033 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7034
7035- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7036 X16-X18.
7037
7038The idea behind this convention is to support calls to runtime functions
7039that have a hot path and a cold path. The hot path is usually a small piece
7040of code that doesn't use many registers. The cold path might need to call out to
7041another function and therefore only needs to preserve the caller-saved
7042registers, which haven't already been saved by the caller. The
7043``preserve_most`` calling convention is very similar to the ``cold`` calling
7044convention in terms of caller/callee-saved registers, but they are used for
7045different types of function calls. ``coldcc`` is for function calls that are
7046rarely executed, whereas ``preserve_most`` function calls are intended to be
7047on the hot path and definitely executed a lot. Furthermore ``preserve_most``
7048doesn't prevent the inliner from inlining the function call.
7049
7050This calling convention will be used by a future version of the Objective-C
7051runtime and should therefore still be considered experimental at this time.
7052Although this convention was created to optimize certain runtime calls to
7053the Objective-C runtime, it is not limited to this runtime and might be used
7054by other runtimes in the future too. The current implementation only
7055supports X86-64 and AArch64, but the intention is to support more architectures
7056in the future.)reST";
7057
7058static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7059The ``preserve_none`` calling convention tries to preserve as few general
7060registers as possible. So all general registers are caller saved registers. It
7061also uses more general registers to pass arguments. This attribute doesn't
7062impact floating-point registers. ``preserve_none``'s ABI is still unstable, and
7063may be changed in the future.
7064
7065- On X86-64, only RSP and RBP are preserved by the callee.
7066 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7067 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7068 follow the C calling convention.
7069- On AArch64, only LR and FP are preserved by the callee.
7070 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7071 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7072 convention. X15 is not available for argument passing on Windows, but is
7073 used to pass arguments on other platforms.)reST";
7074
7075static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7076
7077static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7078
7079static const char AttrDoc_Ptr32[] = R"reST(The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
708064-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
7081``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
7082is sign extended or zero extended. This qualifier is enabled under
7083``-fms-extensions``.)reST";
7084
7085static const char AttrDoc_Ptr64[] = R"reST(The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
708632-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
7087qualifier is enabled under ``-fms-extensions``.)reST";
7088
7089static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7090
7091static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
7092targets. This attribute may be attached to a function definition and instructs
7093the backend to generate appropriate function entry/exit code so that it can be
7094used directly as an interrupt service routine.
7095
7096Permissible values for this parameter are ``machine``, ``supervisor``,
7097``rnmi``, ``qci-nest``, ``qci-nonest``, ``SiFive-CLIC-preemptible``, and
7098``SiFive-CLIC-stack-swap``. If there is no parameter, then it defaults to
7099``machine``.
7100
7101The ``rnmi`` value is used for resumable non-maskable interrupts. It requires the
7102standard Smrnmi extension.
7103
7104The ``qci-nest`` and ``qci-nonest`` values require Qualcomm's Xqciint extension
7105and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7106interrupts. These use the following instructions from Xqciint to save and
7107restore interrupt state to the stack -- the ``qci-nest`` value will use
7108``qc.c.mienter.nest`` and the ``qci-nonest`` value will use ``qc.c.mienter`` to
7109begin the interrupt handler. Both of these will use ``qc.c.mileaveret`` to
7110restore the state and return to the previous context.
7111
7112The ``SiFive-CLIC-preemptible`` and ``SiFive-CLIC-stack-swap`` values are used
7113for machine-mode interrupts. For ``SiFive-CLIC-preemptible`` interrupts, the
7114values of ``mcause`` and ``mepc`` are saved onto the stack, and interrupts are
7115re-enabled. For ``SiFive-CLIC-stack-swap`` interrupts, the stack pointer is
7116swapped with ``mscratch`` before its first use and after its last use.
7117
7118The SiFive CLIC values may be combined with each other and with the ``machine``
7119attribute value. Any other combination of different values is not allowed.
7120
7121Repeated interrupt attribute on the same declaration will cause a warning
7122to be emitted. In case of repeated declarations, the last one prevails.
7123
7124Refer to:
7125https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
7126https://riscv.org/specifications/privileged-isa/
7127The RISC-V Instruction Set Manual Volume II: Privileged Architecture
7128Version 1.10.
7129https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0
7130https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf)reST";
7131
7132static const char AttrDoc_RISCVVLSCC[] = R"reST(The ``riscv_vls_cc`` attribute can be applied to a function. Functions
7133declared with this attribute will utilize the standard fixed-length vector
7134calling convention variant instead of the default calling convention defined by
7135the ABI. This variant aims to pass fixed-length vectors via vector registers,
7136if possible, rather than through general-purpose registers.)reST";
7137
7138static const char AttrDoc_RISCVVectorCC[] = R"reST(The ``riscv_vector_cc`` attribute can be applied to a function. It preserves 15
7139registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7140to save these registers before function calls, and callees only need to save
7141them if they use them.)reST";
7142
7143static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
7144for structure layout field randomization; a compile-time hardening technique. A
7145"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
7146For example:
7147
7148.. code-block:: bash
7149
7150 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7151 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7152
7153You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
7154For example:
7155
7156.. code-block:: bash
7157
7158 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7159 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7160
7161The randomization is deterministic based for a given seed, so the entire
7162program should be compiled with the same seed, but keep the seed safe
7163otherwise.
7164
7165The attribute ``no_randomize_layout``, when attached to a C structure,
7166instructs the compiler that this structure should not have its field layout
7167randomized.)reST";
7168
7169static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7170 When attached to a record declaration/definition, it checks if all instances
7171 of this type can be placed in the read-only data segment of the program. If it
7172 finds an instance that can not be placed in a read-only segment, the compiler
7173 emits a warning at the source location where the type was used.
7174
7175 Examples:
7176 * ``struct __attribute__((enforce_read_only_placement)) Foo;``
7177 * ``struct __attribute__((enforce_read_only_placement)) Bar { ... };``
7178
7179 Both ``Foo`` and ``Bar`` types have the ``enforce_read_only_placement`` attribute.
7180
7181 The goal of introducing this attribute is to assist developers with writing secure
7182 code. A ``const``-qualified global is generally placed in the read-only section
7183 of the memory that has additional run time protection from malicious writes. By
7184 attaching this attribute to a declaration, the developer can express the intent
7185 to place all instances of the annotated type in the read-only program memory.
7186
7187 Note 1: The attribute doesn't guarantee that the object will be placed in the
7188 read-only data segment as it does not instruct the compiler to ensure such
7189 a placement. It emits a warning if something in the code can be proven to prevent
7190 an instance from being placed in the read-only data segment.
7191
7192 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
7193 are ``const``-qualified. The following conditions would also prevent the data to be
7194 put into read only segment, but the corresponding warnings are not yet implemented.
7195
7196 1. An instance of type ``T`` is allocated on the heap/stack.
7197 2. Type ``T`` defines/inherits a mutable field.
7198 3. Type ``T`` defines/inherits non-constexpr constructor(s) for initialization.
7199 4. A field of type ``T`` is defined by type ``Q``, which does not bear the
7200 ``enforce_read_only_placement`` attribute.
7201 5. A type ``Q`` inherits from type ``T`` and it does not have the
7202 ``enforce_read_only_placement`` attribute.)reST";
7203
7204static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7205
7206static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7207`__regcall`_ convention. This convention aims to pass as many arguments
7208as possible in registers. It also tries to utilize registers for the
7209return value whenever it is possible.
7210
7211.. _`__regcall`: https://www.intel.com/content/www/us/en/docs/dpcpp-cpp-compiler/developer-guide-reference/2023-2/c-c-sycl-calling-conventions.html)reST";
7212
7213static const char AttrDoc_Reinitializes[] = R"reST(The ``reinitializes`` attribute can be applied to a non-static, non-const C++
7214member function to indicate that this member function reinitializes the entire
7215object to a known state, independent of the previous state of the object.
7216
7217This attribute can be interpreted by static analyzers that warn about uses of an
7218object that has been left in an indeterminate state by a move operation. If a
7219member function marked with the ``reinitializes`` attribute is called on a
7220moved-from object, the analyzer can conclude that the object is no longer in an
7221indeterminate state.
7222
7223A typical example where this attribute would be used is on functions that clear
7224a container class:
7225
7226.. code-block:: c++
7227
7228 template <class T>
7229 class Container {
7230 public:
7231 ...
7232 [[clang::reinitializes]] void Clear();
7233 ...
7234 };)reST";
7235
7236static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7237
7238static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with ``release_handle(tag)`` it is assumed to
7239close the handle. It is also assumed to require an open handle to work with. The
7240attribute requires a string literal argument to identify the handle being released.
7241
7242.. code-block:: c++
7243
7244 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);)reST";
7245
7246static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7247
7248static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7249
7250static const char AttrDoc_Restrict[] = R"reST(The ``malloc`` attribute has two forms with different functionality. The first
7251is when it is used without arguments, where it marks that a function acts like
7252a system memory allocation function, returning a pointer to allocated storage
7253that does not alias storage from any other object accessible to the caller.
7254
7255The second form is when ``malloc`` takes one or two arguments. The first
7256argument names a function that should be associated with this function as its
7257deallocation function. When this form is used, it enables the compiler to
7258diagnose when the incorrect deallocation function is used with this variable.
7259However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7260yet implemented in clang.)reST";
7261
7262static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7263section garbage collection in the linker. It does not prevent other discard
7264mechanisms, such as archive member selection, and COMDAT group resolution.
7265
7266If the compiler does not emit the definition, e.g. because it was not used in
7267the translation unit or the compiler was able to eliminate all of the uses,
7268this attribute has no effect. This attribute is typically combined with the
7269``used`` attribute to force the definition to be emitted and preserved into the
7270final linked image.
7271
7272This attribute is only necessary on ELF targets; other targets prevent section
7273garbage collection by the linker when using the ``used`` attribute alone.
7274Using the attributes together should result in consistent behavior across
7275targets.
7276
7277This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
7278This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as
7279well as in ``ld.lld`` 13.)reST";
7280
7281static const char AttrDoc_ReturnTypestate[] = R"reST(The ``return_typestate`` attribute can be applied to functions or parameters.
7282When applied to a function the attribute specifies the state of the returned
7283value. The function's body is checked to ensure that it always returns a value
7284in the specified state. On the caller side, values returned by the annotated
7285function are initialized to the given state.
7286
7287When applied to a function parameter it modifies the state of an argument after
7288a call to the function returns. The function's body is checked to ensure that
7289the parameter is in the expected state before returning.)reST";
7290
7291static const char AttrDoc_ReturnsNonNull[] = R"reST(The ``returns_nonnull`` attribute indicates that a particular function (or
7292Objective-C method) always returns a non-null pointer. For example, a
7293particular system ``malloc`` might be defined to terminate a process when
7294memory is not available rather than returning a null pointer:
7295
7296 .. code-block:: c
7297
7298 extern void * malloc (size_t size) __attribute__((returns_nonnull));
7299
7300The ``returns_nonnull`` attribute implies that returning a null pointer is
7301undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
7302type qualifier indicates that a pointer cannot be null in a more general manner
7303(because it is part of the type system) and does not imply undefined behavior,
7304making it more widely applicable)reST";
7305
7306static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7307
7308static const char AttrDoc_RootSignature[] = R"reST(The ``RootSignature`` attribute applies to HLSL entry functions to define what
7309types of resources are bound to the graphics pipeline.
7310
7311For details about the use and specification of Root Signatures please see here:
7312https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures)reST";
7313
7314static const char AttrDoc_SPtr[] = R"reST(The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
7315extended when converted to a 64-bit pointer.)reST";
7316
7317static const char AttrDoc_SYCLExternal[] = R"reST(The ``sycl_external`` attribute indicates that a function defined in another
7318translation unit may be called by a device function defined in the current
7319translation unit or, if defined in the current translation unit, the function
7320may be called by device functions defined in other translation units.
7321The attribute is intended for use in the implementation of the ``SYCL_EXTERNAL``
7322macro as specified in section 5.10.1, "SYCL functions and member functions
7323linkage", of the SYCL 2020 specification.
7324
7325The attribute only appertains to functions and only those that meet the
7326following requirements:
7327
7328* Has external linkage
7329* Is not explicitly defined as deleted (the function may be an explicitly
7330 defaulted function that is defined as deleted)
7331
7332The attribute shall be present on the first declaration of a function and
7333may optionally be present on subsequent declarations.
7334
7335When compiling for a SYCL device target that does not support the generic
7336address space, the function shall not specify a raw pointer or reference type
7337as the return type or as a parameter type.
7338See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7339The following examples demonstrate the use of this attribute:
7340
7341.. code-block:: c++
7342
7343 [[clang::sycl_external]] void Foo(); // Ok.
7344
7345 [[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7346
7347 [[clang::sycl_external]] extern void Baz(); // Ok.
7348
7349 [[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.)reST";
7350
7351static const char AttrDoc_SYCLKernel[] = R"reST(The ``sycl_kernel`` attribute specifies that a function template will be used
7352to outline device code and to generate an OpenCL kernel.
7353Here is a code example of the SYCL program, which demonstrates the compiler's
7354outlining job:
7355
7356.. code-block:: c++
7357
7358 int foo(int x) { return ++x; }
7359
7360 using namespace cl::sycl;
7361 queue Q;
7362 buffer<int, 1> a(range<1>{1024});
7363 Q.submit([&](handler& cgh) {
7364 auto A = a.get_access<access::mode::write>(cgh);
7365 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
7366 A[index] = index[0] + foo(42);
7367 });
7368 }
7369
7370A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
7371A SYCL kernel defines the entry point to the "device part" of the code. The
7372compiler will emit all symbols accessible from a "kernel". In this code
7373example, the compiler will emit "foo" function. More details about the
7374compilation of functions for the device part can be found in the SYCL 1.2.1
7375specification Section 6.4.
7376To show to the compiler entry point to the "device part" of the code, the SYCL
7377runtime can use the ``sycl_kernel`` attribute in the following way:
7378
7379.. code-block:: c++
7380
7381 namespace cl {
7382 namespace sycl {
7383 class handler {
7384 template <typename KernelName, typename KernelType/*, ...*/>
7385 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
7386 // ...
7387 KernelFuncObj();
7388 }
7389
7390 template <typename KernelName, typename KernelType, int Dims>
7391 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
7392 #ifdef __SYCL_DEVICE_ONLY__
7393 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
7394 #else
7395 // Host implementation
7396 #endif
7397 }
7398 };
7399 } // namespace sycl
7400 } // namespace cl
7401
7402The compiler will also generate an OpenCL kernel using the function marked with
7403the ``sycl_kernel`` attribute.
7404Here is the list of SYCL device compiler expectations with regard to the
7405function marked with the ``sycl_kernel`` attribute:
7406
7407- The function must be a template with at least two type template parameters.
7408 The compiler generates an OpenCL kernel and uses the first template parameter
7409 as a unique name for the generated OpenCL kernel. The host application uses
7410 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
7411 specialized by this name and second template parameter ``KernelType`` (which
7412 might be an unnamed function object type).
7413- The function must have at least one parameter. The first parameter is
7414 required to be a function object type (named or unnamed i.e. lambda). The
7415 compiler uses function object type fields to generate OpenCL kernel
7416 parameters.
7417- The function must return void. The compiler reuses the body of marked functions to
7418 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``.
7419
7420The SYCL kernel in the previous code sample meets these expectations.)reST";
7421
7422static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The ``sycl_kernel_entry_point`` attribute facilitates the launch of a SYCL
7423kernel and the generation of an offload kernel entry point, sometimes called
7424a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
7425offload device. The attribute is intended for use in the implementation of
7426SYCL kernel invocation functions like the ``single_task`` and ``parallel_for``
7427member functions of the ``sycl::handler`` class specified in section 4.9.4,
7428"Command group ``handler`` class", of the SYCL 2020 specification.
7429
7430The attribute requires a single type argument that meets the requirements for
7431a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
7432SYCL 2020 specification. A unique kernel name type is required for each
7433function declared with the attribute. The attribute may not first appear on a
7434declaration that follows a definition of the function.
7435
7436The attribute only appertains to functions and only those that meet the
7437following requirements.
7438
7439* Has a non-deduced ``void`` return type.
7440* Is not a constructor or destructor.
7441* Is not a non-static member function with an explicit object parameter.
7442* Is not a C variadic function.
7443* Is not a coroutine.
7444* Is not defined as deleted or as defaulted.
7445* Is not defined with a function try block.
7446* Is not declared with the ``constexpr`` or ``consteval`` specifiers.
7447* Is not declared with the ``[[noreturn]]`` attribute.
7448
7449Use in the implementation of a SYCL kernel invocation function might look as
7450follows.
7451
7452.. code-block:: c++
7453
7454 namespace sycl {
7455 class handler {
7456 template<typename KernelName, typename... Ts>
7457 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
7458 // This code will run on the host and is responsible for calling functions
7459 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
7460 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
7461 // to a device and to schedule an invocation of the offload kernel entry
7462 // point denoted by kernelSymbol with the copied arguments.
7463 }
7464
7465 template<typename KernelName, typename KernelType>
7466 [[ clang::sycl_kernel_entry_point(KernelName) ]]
7467 void kernel_entry_point(KernelType kernelFunc) {
7468 // This code will run on the device. The call to kernelFunc() invokes
7469 // the SYCL kernel.
7470 kernelFunc();
7471 }
7472
7473 public:
7474 template<typename KernelName, typename KernelType>
7475 void single_task(const KernelType& kernelFunc) {
7476 // This code will run on the host. kernel_entry_point() is called to
7477 // trigger generation of an offload kernel entry point and to schedule
7478 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
7479 // passed as a kernel argument. This call will result in an implicit call
7480 // to sycl_kernel_launch() with the symbol name for the generated offload
7481 // kernel entry point passed as the first function argument followed by
7482 // kernelFunc.
7483 kernel_entry_point<KernelName>(kernelFunc);
7484 }
7485 };
7486 } // namespace sycl
7487
7488A SYCL kernel object is a callable object of class type that is constructed on
7489a host, often via a lambda expression, and then passed to a SYCL kernel
7490invocation function to be executed on an offload device. The ``kernelFunc``
7491parameters in the example code above correspond to SYCL kernel objects.
7492
7493A SYCL kernel object type is required to satisfy the device copyability
7494requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
7495specification. Additionally, any data members of the kernel object type are
7496required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
7497For most types, these rules require that the type is trivially copyable.
7498However, the SYCL specification mandates that certain special SYCL types, such
7499as ``sycl::accessor`` and ``sycl::stream``, be device copyable even if they are
7500not trivially copyable. These types require special handling because they cannot
7501necessarily be copied to device memory as if by ``memcpy()``.
7502
7503The SYCL kernel object and its data members constitute the parameters of an
7504offload kernel. An offload kernel consists of an offload entry point function
7505and the set of all functions and variables that are directly or indirectly used
7506by the entry point function.
7507
7508A SYCL kernel invocation function is responsible for performing the following
7509tasks (likely with the help of an offload backend like OpenCL):
7510
7511#. Identifying the offload kernel entry point to be used for the SYCL kernel.
7512
7513#. Validating that the SYCL kernel object type and its data members meet the
7514 SYCL device copyability and kernel parameter requirements noted above.
7515
7516#. Copying the SYCL kernel object and any other kernel arguments to device
7517 memory including any special handling required for SYCL special types.
7518
7519#. Initiating execution of the offload kernel entry point.
7520
7521The offload kernel entry point for a SYCL kernel performs the following tasks:
7522
7523#. Calling the ``operator()`` member function of the SYCL kernel object.
7524
7525The ``sycl_kernel_entry_point`` attribute facilitates or automates these tasks
7526by providing generation of an offload kernel entry point with a unique symbol
7527name, type checking of kernel argument requirements, and initiation of kernel
7528execution via synthesized calls to a ``sycl_kernel_launch`` template.
7529
7530A function declared with the ``sycl_kernel_entry_point`` attribute specifies
7531the parameters and body of an offload entry point function. Consider the
7532following call to the ``single_task()`` SYCL kernel invocation function assuming
7533an implementation similar to the one shown above.
7534
7535.. code-block:: c++
7536
7537 struct S { int i; };
7538 void f(sycl::handler &handler, sycl::stream &sout, S s) {
7539 handler.single_task<struct KN>([=] {
7540 sout << "The value of s.i is " << s.i << "\n";
7541 });
7542 }
7543
7544The SYCL kernel object is the result of the lambda expression. The call to
7545``kernel_entry_point()`` via the call to ``single_task()`` triggers the
7546generation of an offload kernel entry point function that looks approximately
7547as follows.
7548
7549.. code-block:: c++
7550
7551 void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
7552 kernelFunc();
7553 }
7554
7555There are a few items worthy of note:
7556
7557#. ``sycl-kernel-caller-for-KN`` is an exposition only name; the actual name
7558 generated for an entry point is an implementation detail and subject to
7559 change. However, the name will incorporate the SYCL kernel name, ``KN``,
7560 that was passed as the ``KernelName`` template parameter to
7561 ``single_task()`` and eventually provided as the argument to the
7562 ``sycl_kernel_entry_point`` attribute in order to ensure that a unique
7563 name is generated for each entry point. There is a one-to-one correspondence
7564 between SYCL kernel names and offload kernel entry points.
7565
7566#. The SYCL kernel is a lambda closure type and therefore has no name;
7567 ``kernel-type`` is substituted above and corresponds to the ``KernelType``
7568 template parameter deduced in the call to ``single_task()``.
7569
7570#. The parameter and the call to ``kernelFunc()`` in the function body
7571 correspond to the definition of ``kernel_entry_point()`` as called by
7572 ``single_task()``.
7573
7574#. The parameter is type checked for conformance with the SYCL device
7575 copyability and kernel parameter requirements.
7576
7577Within ``single_task()``, the call to ``kernel_entry_point()`` is effectively
7578replaced with a synthesized call to a ''sycl_kernel_launch`` template that
7579looks approximately as follows.
7580
7581.. code-block:: c++
7582
7583 sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
7584
7585There are a few items worthy of note:
7586
7587#. Lookup for the ``sycl_kernel_launch`` template is performed as if from the
7588 body of the (possibly instantiated) definition of ``kernel_entry_point()``.
7589 If name lookup or overload resolution fails, the program is ill-formed.
7590 If the selected overload is a non-static member function, then ``this`` is
7591 passed as the implicit object parameter.
7592
7593#. Function arguments passed to ``sycl_kernel_launch()`` are passed
7594 as if by ``std::move(x)``.
7595
7596#. The ``sycl_kernel_launch`` template is expected to be provided by the SYCL
7597 library implementation. It is responsible for copying the kernel arguments
7598 to device memory and for scheduling execution of the generated offload
7599 kernel entry point identified by the symbol name passed as the first
7600 function argument. ``sycl-kernel-caller-for-KN`` is substituted above for
7601 the actual symbol name that would be generated for the offload kernel entry
7602 point.
7603
7604It is not necessary for a function declared with the ``sycl_kernel_entry_point``
7605attribute to be called for the offload kernel entry point to be emitted. For
7606inline functions and function templates, any ODR-use will suffice. For other
7607functions, an ODR-use is not required; the offload kernel entry point will be
7608emitted if the function is defined. In any case, a call to the function is
7609required for the synthesized call to ``sycl_kernel_launch()`` to occur.
7610
7611A function declared with the ``sycl_kernel_entry_point`` attribute may include
7612an exception specification. If a non-throwing exception specification is
7613present, an exception propagating from the implicit call to the
7614``sycl_kernel_launch`` template will result in a call to ``std::terminate()``.
7615Otherwise, such an exception will propagate normally.
7616
7617Functions declared with the ``sycl_kernel_entry_point`` attribute are not
7618limited to the simple example shown above. They may have additional template
7619parameters, declare additional function parameters, and have complex control
7620flow in the function body. The function must abide by the language feature
7621restrictions described in section 5.4, "Language restrictions for device
7622functions" in the SYCL 2020 specification. If the function is a non-static
7623member function, ``this`` shall not be used in a potentially evaluated
7624expression.)reST";
7625
7626static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
7627specific handling during the generation of the SPIR entry point.
7628The ``__attribute__((sycl_special_class))`` attribute is used in SYCL
7629headers to indicate that a class or a struct needs a specific handling when
7630it is passed from host to device.
7631Special classes will have a mandatory ``__init`` method and an optional
7632``__finalize`` method (the ``__finalize`` method is used only with the
7633``stream`` type). Kernel parameters types are extract from the ``__init`` method
7634parameters. The kernel function arguments list is derived from the
7635arguments of the ``__init`` method. The arguments of the ``__init`` method are
7636copied into the kernel function argument list and the ``__init`` and
7637``__finalize`` methods are called at the beginning and the end of the kernel,
7638respectively.
7639The ``__init`` and ``__finalize`` methods must be defined inside the
7640special class.
7641Please note that this is an attribute that is used as an internal
7642implementation detail and not intended to be used by external users.
7643
7644The syntax of the attribute is as follows:
7645
7646.. code-block:: text
7647
7648 class __attribute__((sycl_special_class)) accessor {};
7649 class [[clang::sycl_special_class]] accessor {};
7650
7651This is a code example that illustrates the use of the attribute:
7652
7653.. code-block:: c++
7654
7655 class __attribute__((sycl_special_class)) SpecialType {
7656 int F1;
7657 int F2;
7658 void __init(int f1) {
7659 F1 = f1;
7660 F2 = f1;
7661 }
7662 void __finalize() {}
7663 public:
7664 SpecialType() = default;
7665 int getF2() const { return F2; }
7666 };
7667
7668 int main () {
7669 SpecialType T;
7670 cgh.single_task([=] {
7671 T.getF2();
7672 });
7673 }
7674
7675This would trigger the following kernel entry point in the AST:
7676
7677.. code-block:: c++
7678
7679 void __sycl_kernel(int f1) {
7680 SpecialType T;
7681 T.__init(f1);
7682 ...
7683 T.__finalize()
7684 })reST";
7685
7686static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
7687
7688static const char AttrDoc_Section[] = R"reST(The ``section`` attribute allows you to specify a specific section a
7689global variable or function should be in after translation.)reST";
7690
7691static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
7692definition (
7693`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
7694), allowing the linker to select any definition.
7695
7696For more information see
7697`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
7698or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.)reST";
7699
7700static const char AttrDoc_Sentinel[] = R"reST(No documentation.)reST";
7701
7702static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
7703``__attribute__((set_typestate(new_state)))``. The new state must be
7704unconsumed, consumed, or unknown.)reST";
7705
7706static const char AttrDoc_SizedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7707structure in C. The argument for the attribute is the name of a field member
7708holding the count of elements in the flexible array. This information can be
7709used to improve the results of the array bound sanitizer and the
7710``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7711within the same non-anonymous, enclosing struct as the flexible array member.
7712
7713This example specifies that the flexible array member ``array`` has the number
7714of elements allocated for it in ``count``:
7715
7716.. code-block:: c
7717
7718 struct bar;
7719
7720 struct foo {
7721 size_t count;
7722 char other;
7723 struct bar *array[] __attribute__((counted_by(count)));
7724 };
7725
7726This establishes a relationship between ``array`` and ``count``. Specifically,
7727``array`` must have at least ``count`` number of elements available. It's the
7728user's responsibility to ensure that this relationship is maintained through
7729changes to the structure.
7730
7731In the following example, the allocated array erroneously has fewer elements
7732than what's specified by ``p->count``. This would result in an out-of-bounds
7733access not being detected.
7734
7735.. code-block:: c
7736
7737 #define SIZE_INCR 42
7738
7739 struct foo *p;
7740
7741 void foo_alloc(size_t count) {
7742 p = malloc(MAX(sizeof(struct foo),
7743 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7744 p->count = count + SIZE_INCR;
7745 }
7746
7747The next example updates ``p->count``, but breaks the relationship requirement
7748that ``p->array`` must have at least ``p->count`` number of elements available:
7749
7750.. code-block:: c
7751
7752 #define SIZE_INCR 42
7753
7754 struct foo *p;
7755
7756 void foo_alloc(size_t count) {
7757 p = malloc(MAX(sizeof(struct foo),
7758 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7759 p->count = count;
7760 }
7761
7762 void use_foo(int index, int val) {
7763 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
7764 p->array[index] = val; /* The sanitizer can't properly check this access. */
7765 }
7766
7767In this example, an update to ``p->count`` maintains the relationship
7768requirement:
7769
7770.. code-block:: c
7771
7772 void use_foo(int index, int val) {
7773 if (p->count == 0)
7774 return;
7775 --p->count;
7776 p->array[index] = val;
7777 })reST";
7778
7779static const char AttrDoc_SizedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7780structure in C. The argument for the attribute is the name of a field member
7781holding the count of elements in the flexible array. This information can be
7782used to improve the results of the array bound sanitizer and the
7783``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7784within the same non-anonymous, enclosing struct as the flexible array member.
7785
7786This example specifies that the flexible array member ``array`` has the number
7787of elements allocated for it in ``count``:
7788
7789.. code-block:: c
7790
7791 struct bar;
7792
7793 struct foo {
7794 size_t count;
7795 char other;
7796 struct bar *array[] __attribute__((counted_by(count)));
7797 };
7798
7799This establishes a relationship between ``array`` and ``count``. Specifically,
7800``array`` must have at least ``count`` number of elements available. It's the
7801user's responsibility to ensure that this relationship is maintained through
7802changes to the structure.
7803
7804In the following example, the allocated array erroneously has fewer elements
7805than what's specified by ``p->count``. This would result in an out-of-bounds
7806access not being detected.
7807
7808.. code-block:: c
7809
7810 #define SIZE_INCR 42
7811
7812 struct foo *p;
7813
7814 void foo_alloc(size_t count) {
7815 p = malloc(MAX(sizeof(struct foo),
7816 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7817 p->count = count + SIZE_INCR;
7818 }
7819
7820The next example updates ``p->count``, but breaks the relationship requirement
7821that ``p->array`` must have at least ``p->count`` number of elements available:
7822
7823.. code-block:: c
7824
7825 #define SIZE_INCR 42
7826
7827 struct foo *p;
7828
7829 void foo_alloc(size_t count) {
7830 p = malloc(MAX(sizeof(struct foo),
7831 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7832 p->count = count;
7833 }
7834
7835 void use_foo(int index, int val) {
7836 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
7837 p->array[index] = val; /* The sanitizer can't properly check this access. */
7838 }
7839
7840In this example, an update to ``p->count`` maintains the relationship
7841requirement:
7842
7843.. code-block:: c
7844
7845 void use_foo(int index, int val) {
7846 if (p->count == 0)
7847 return;
7848 --p->count;
7849 p->array[index] = val;
7850 })reST";
7851
7852static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
7853 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
7854 should be enabled for the function body. This can also be applied to a method
7855 in Objective C. This attribute will take precedence over the command line flag in
7856 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
7857
7858 Speculative Load Hardening is a best-effort mitigation against
7859 information leak attacks that make use of control flow
7860 miss-speculation - specifically miss-speculation of whether a branch
7861 is taken or not. Typically vulnerabilities enabling such attacks are
7862 classified as "Spectre variant #1". Notably, this does not attempt to
7863 mitigate against miss-speculation of branch target, classified as
7864 "Spectre variant #2" vulnerabilities.
7865
7866 When inlining, the attribute is sticky. Inlining a function that
7867 carries this attribute will cause the caller to gain the
7868 attribute. This is intended to provide a maximally conservative model
7869 where the code in a function annotated with this attribute will always
7870 (even after inlining) end up hardened.)reST";
7871
7872static const char AttrDoc_StackProtectorIgnore[] = R"reST(The ``stack_protector_ignore`` attribute skips analysis of the given local
7873variable when determining if a function should use a stack protector.
7874
7875The ``-fstack-protector`` option uses a heuristic to only add stack protectors
7876to functions which contain variables or buffers over some size threshold. This
7877attribute overrides that heuristic for the attached variable, opting
7878them out. If this results in no variables or buffers remaining over the stack
7879protector threshold, then the function will no longer use a stack protector.)reST";
7880
7881static const char AttrDoc_StandaloneDebug[] = R"reST(The ``standalone_debug`` attribute causes debug info to be emitted for a record
7882type regardless of the debug info optimizations that are enabled with
7883-fno-standalone-debug. This attribute only has an effect when debug info
7884optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
7885
7886static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
7887function to clear parameters off of the stack on return. This convention does
7888not support variadic calls or unprototyped functions in C, and has no effect on
7889x86_64 targets. This calling convention is used widely by the Windows API and
7890COM applications. See the documentation for `__stdcall`_ on MSDN.
7891
7892.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
7893
7894static const char AttrDoc_StrictFP[] = R"reST()reST";
7895
7896static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style ``__declspec((strict_gs_check))`` attribute
7897which upgrades the stack protector check from ``-fstack-protector`` to
7898``-fstack-protector-strong``.
7899
7900For example, it upgrades the stack protector for the function ``foo`` to
7901``-fstack-protector-strong`` but function ``bar`` will still be built with the
7902stack protector with the ``-fstack-protector`` option.
7903
7904.. code-block:: c
7905
7906 __declspec((strict_gs_check))
7907 int foo(int x); // stack protection will be upgraded for foo.
7908
7909 int bar(int y); // bar can be built with the standard stack protector checks.)reST";
7910
7911static const char AttrDoc_Suppress[] = R"reST(The ``suppress`` attribute suppresses unwanted warnings coming from static
7912analysis tools such as the Clang Static Analyzer. The tool will not report
7913any issues in source code annotated with the attribute.
7914
7915The attribute cannot be used to suppress traditional Clang warnings, because
7916many such warnings are emitted before the attribute is fully parsed.
7917Consider using ``#pragma clang diagnostic`` to control such diagnostics,
7918as described in `Controlling Diagnostics via Pragmas
7919<https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas>`_.
7920
7921The ``suppress`` attribute can be placed on an individual statement in order to
7922suppress warnings about undesirable behavior occurring at that statement:
7923
7924.. code-block:: c++
7925
7926 int foo() {
7927 int *x = nullptr;
7928 ...
7929 [[clang::suppress]]
7930 return *x; // null pointer dereference warning suppressed here
7931 }
7932
7933Putting the attribute on a compound statement suppresses all warnings in scope:
7934
7935.. code-block:: c++
7936
7937 int foo() {
7938 [[clang::suppress]] {
7939 int *x = nullptr;
7940 ...
7941 return *x; // warnings suppressed in the entire scope
7942 }
7943 }
7944
7945The attribute can also be placed on entire declarations of functions, classes,
7946variables, member variables, and so on, to suppress warnings related
7947to the declarations themselves. When used this way, the attribute additionally
7948suppresses all warnings in the lexical scope of the declaration:
7949
7950.. code-block:: c++
7951
7952 class [[clang::suppress]] C {
7953 int foo() {
7954 int *x = nullptr;
7955 ...
7956 return *x; // warnings suppressed in the entire class scope
7957 }
7958
7959 int bar();
7960 };
7961
7962 int C::bar() {
7963 int *x = nullptr;
7964 ...
7965 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
7966 }
7967
7968Some static analysis warnings are accompanied by one or more notes, and the
7969line of code against which the warning is emitted isn't necessarily the best
7970for suppression purposes. In such cases the tools are allowed to implement
7971additional ways to suppress specific warnings based on the attribute attached
7972to a note location.
7973
7974For example, the Clang Static Analyzer suppresses memory leak warnings when
7975the suppression attribute is placed at the allocation site (highlited by
7976a "note: memory is allocated"), which may be different from the line of code
7977at which the program "loses track" of the pointer (where the warning
7978is ultimately emitted):
7979
7980.. code-block:: c
7981
7982 int bar1(bool coin_flip) {
7983 __attribute__((suppress))
7984 int *result = (int *)malloc(sizeof(int));
7985 if (coin_flip)
7986 return 1; // warning about this leak path is suppressed
7987
7988 return *result; // warning about this leak path is also suppressed
7989 }
7990
7991 int bar2(bool coin_flip) {
7992 int *result = (int *)malloc(sizeof(int));
7993 if (coin_flip)
7994 return 1; // leak warning on this path NOT suppressed
7995
7996 __attribute__((suppress))
7997 return *result; // leak warning is suppressed only on this path
7998 }
7999
8000
8001When written as ``[[gsl::suppress]]``, this attribute suppresses specific
8002clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
8003way. The attribute can be attached to declarations, statements, and at
8004namespace scope.
8005
8006.. code-block:: c++
8007
8008 [[gsl::suppress("Rh-public")]]
8009 void f_() {
8010 int *p;
8011 [[gsl::suppress("type")]] {
8012 p = reinterpret_cast<int*>(7);
8013 }
8014 }
8015 namespace N {
8016 [[clang::suppress("type", "bounds")]];
8017 ...
8018 }
8019
8020.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8021
8022static const char AttrDoc_SwiftAsync[] = R"reST(The ``swift_async`` attribute specifies if and how a particular function or
8023Objective-C method is imported into a swift async method. For instance:
8024
8025.. code-block:: objc
8026
8027 @interface MyClass : NSObject
8028 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8029 __attribute__((swift_async(none)));
8030
8031 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8032 __attribute__((swift_async(swift_private, 1)));
8033 @end
8034
8035Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
8036``async`` (because it's last parameter's selector piece is
8037``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
8038Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
8039``async`` if not for the ``swift_async`` attribute because it doesn't match the
8040naming convention.
8041
8042When using ``swift_async`` to enable importing, the first argument to the
8043attribute is either ``swift_private`` or ``not_swift_private`` to indicate
8044whether the function/method is private to the current framework, and the second
8045argument is the index of the completion handler parameter.)reST";
8046
8047static const char AttrDoc_SwiftAsyncCall[] = R"reST(The ``swiftasynccall`` attribute indicates that a function is
8048compatible with the low-level conventions of Swift async functions,
8049provided it declares the right formal arguments.
8050
8051In most respects, this is similar to the ``swiftcall`` attribute, except for
8052the following:
8053
8054- A parameter may be marked ``swift_async_context``, ``swift_context``
8055 or ``swift_indirect_result`` (with the same restrictions on parameter
8056 ordering as ``swiftcall``) but the parameter attribute
8057 ``swift_error_result`` is not permitted.
8058
8059- A ``swiftasynccall`` function must have return type ``void``.
8060
8061- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall``
8062 function that is the immediate operand of a ``return`` statement is
8063 guaranteed to be performed as a tail call. This syntax is allowed even
8064 in C as an extension (a call to a void-returning function cannot be a
8065 return operand in standard C). If something in the calling function would
8066 semantically be performed after a guaranteed tail call, such as the
8067 non-trivial destruction of a local variable or temporary,
8068 then the program is ill-formed.
8069
8070Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
8071the target supports the calling convention with
8072``__has_extension(swiftasynccc)``.)reST";
8073
8074static const char AttrDoc_SwiftAsyncContext[] = R"reST(The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall``
8075function as having the special asynchronous context-parameter ABI treatment.
8076
8077If the function is not ``swiftasynccall``, this attribute only generates
8078extended frame information.
8079
8080A context parameter must have pointer or reference type.)reST";
8081
8082static const char AttrDoc_SwiftAsyncError[] = R"reST(The ``swift_async_error`` attribute specifies how an error state will be
8083represented in a swift async method. It's a bit analogous to the ``swift_error``
8084attribute for the generated async method. The ``swift_async_error`` attribute
8085can indicate a variety of different ways of representing an error.
8086
8087- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the
8088 async method is considered to have failed if the Nth argument to the
8089 completion handler is zero.
8090
8091- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that
8092 the async method is considered to have failed if the Nth argument to the
8093 completion handler is non-zero.
8094
8095- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the
8096 async method is considered to have failed if the ``NSError *`` argument to the
8097 completion handler is non-null.
8098
8099- ``__attribute__((swift_async_error(none)))``, specifies that the async method
8100 cannot fail.
8101
8102
8103For instance:
8104
8105.. code-block:: objc
8106
8107 @interface MyClass : NSObject
8108 -(void)asyncMethod:(void (^)(char, int, float))handler
8109 __attribute__((swift_async(swift_private, 1)))
8110 __attribute__((swift_async_error(zero_argument, 2)));
8111 @end
8112
8113Here, the ``swift_async`` attribute specifies that ``handler`` is the completion
8114handler for this method, and the ``swift_async_error`` attribute specifies that
8115the ``int`` parameter is the one that represents the error.)reST";
8116
8117static const char AttrDoc_SwiftAsyncName[] = R"reST(The ``swift_async_name`` attribute provides the name of the ``async`` overload for
8118the given declaration in Swift. If this attribute is absent, the name is
8119transformed according to the algorithm built into the Swift compiler.
8120
8121The argument is a string literal that contains the Swift name of the function or
8122method. The name may be a compound Swift name. The function or method with such
8123an attribute must have more than zero parameters, as its last parameter is
8124assumed to be a callback that's eliminated in the Swift ``async`` name.
8125
8126 .. code-block:: objc
8127
8128 @interface URL
8129 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8130 @end)reST";
8131
8132static const char AttrDoc_SwiftAttr[] = R"reST(The ``swift_attr`` provides a Swift-specific annotation for the declaration
8133or type to which the attribute appertains to. It can be used on any declaration
8134or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
8135semantic meaning in languages supported by Clang. The Swift compiler can
8136interpret these annotations according to its own rules when importing C or
8137Objective-C declarations.)reST";
8138
8139static const char AttrDoc_SwiftBridge[] = R"reST(The ``swift_bridge`` attribute indicates that the declaration to which the
8140attribute appertains is bridged to the named Swift type.
8141
8142 .. code-block:: objc
8143
8144 __attribute__((__objc_root__))
8145 @interface Base
8146 - (instancetype)init;
8147 @end
8148
8149 __attribute__((__swift_bridge__("BridgedI")))
8150 @interface I : Base
8151 @end
8152
8153In this example, the Objective-C interface ``I`` will be made available to Swift
8154with the name ``BridgedI``. It would be possible for the compiler to refer to
8155``I`` still in order to bridge the type back to Objective-C.)reST";
8156
8157static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
8158the attribute appertains is imported into Swift, it should refer to the bridged
8159Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
8160(e.g. ``NSString``).
8161
8162 .. code-block:: objc
8163
8164 @interface NSString;
8165 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
8166
8167 extern void acceptsAliasedString(AliasedString _Nonnull parameter);
8168
8169In this case, the function ``acceptsAliasedString`` will be imported into Swift
8170as a function which accepts a ``String`` type parameter.)reST";
8171
8172static const char AttrDoc_SwiftCall[] = R"reST(The ``swiftcall`` attribute indicates that a function should be called
8173using the Swift calling convention for a function or function pointer.
8174
8175The lowering for the Swift calling convention, as described by the Swift
8176ABI documentation, occurs in multiple phases. The first, "high-level"
8177phase breaks down the formal parameters and results into innately direct
8178and indirect components, adds implicit parameters for the generic
8179signature, and assigns the context and error ABI treatments to parameters
8180where applicable. The second phase breaks down the direct parameters
8181and results from the first phase and assigns them to registers or the
8182stack. The ``swiftcall`` convention only handles this second phase of
8183lowering; the C function type must accurately reflect the results
8184of the first phase, as follows:
8185
8186- Results classified as indirect by high-level lowering should be
8187 represented as parameters with the ``swift_indirect_result`` attribute.
8188
8189- Results classified as direct by high-level lowering should be represented
8190 as follows:
8191
8192 - First, remove any empty direct results.
8193
8194 - If there are no direct results, the C result type should be ``void``.
8195
8196 - If there is one direct result, the C result type should be a type with
8197 the exact layout of that result type.
8198
8199 - If there are a multiple direct results, the C result type should be
8200 a struct type with the exact layout of a tuple of those results.
8201
8202- Parameters classified as indirect by high-level lowering should be
8203 represented as parameters of pointer type.
8204
8205- Parameters classified as direct by high-level lowering should be
8206 omitted if they are empty types; otherwise, they should be represented
8207 as a parameter type with a layout exactly matching the layout of the
8208 Swift parameter type.
8209
8210- The context parameter, if present, should be represented as a trailing
8211 parameter with the ``swift_context`` attribute.
8212
8213- The error result parameter, if present, should be represented as a
8214 trailing parameter (always following a context parameter) with the
8215 ``swift_error_result`` attribute.
8216
8217``swiftcall`` does not support variadic arguments or unprototyped functions.
8218
8219The parameter ABI treatment attributes are aspects of the function type.
8220A function type which applies an ABI treatment attribute to a
8221parameter is a different type from an otherwise-identical function type
8222that does not. A single parameter may not have multiple ABI treatment
8223attributes.
8224
8225Support for this feature is target-dependent, although it should be
8226supported on every target that Swift supports. Query for this attribute
8227with ``__has_attribute(swiftcall)``. Query if the target supports the
8228calling convention with ``__has_extension(swiftcc)``. This implies
8229support for the ``swift_context``, ``swift_error_result``, and
8230``swift_indirect_result`` attributes.)reST";
8231
8232static const char AttrDoc_SwiftContext[] = R"reST(The ``swift_context`` attribute marks a parameter of a ``swiftcall``
8233or ``swiftasynccall`` function as having the special context-parameter
8234ABI treatment.
8235
8236This treatment generally passes the context value in a special register
8237which is normally callee-preserved.
8238
8239A ``swift_context`` parameter must either be the last parameter or must be
8240followed by a ``swift_error_result`` parameter (which itself must always be
8241the last parameter).
8242
8243A context parameter must have pointer or reference type.)reST";
8244
8245static const char AttrDoc_SwiftError[] = R"reST(The ``swift_error`` attribute controls whether a particular function (or
8246Objective-C method) is imported into Swift as a throwing function, and if so,
8247which dynamic convention it uses.
8248
8249All of these conventions except ``none`` require the function to have an error
8250parameter. Currently, the error parameter is always the last parameter of type
8251``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
8252the imported API. When calling the API, Swift will always pass a valid address
8253initialized to a null pointer.
8254
8255* ``swift_error(none)`` means that the function should not be imported as
8256 throwing. The error parameter and result type will be imported normally.
8257
8258* ``swift_error(null_result)`` means that calls to the function should be
8259 considered to have thrown if they return a null value. The return type must be
8260 a pointer type, and it will be imported into Swift with a non-optional type.
8261 This is the default error convention for Objective-C methods that return
8262 pointers.
8263
8264* ``swift_error(zero_result)`` means that calls to the function should be
8265 considered to have thrown if they return a zero result. The return type must be
8266 an integral type. If the return type would have been imported as ``Bool``, it
8267 is instead imported as ``Void``. This is the default error convention for
8268 Objective-C methods that return a type that would be imported as ``Bool``.
8269
8270* ``swift_error(nonzero_result)`` means that calls to the function should be
8271 considered to have thrown if they return a non-zero result. The return type must
8272 be an integral type. If the return type would have been imported as ``Bool``,
8273 it is instead imported as ``Void``.
8274
8275* ``swift_error(nonnull_error)`` means that calls to the function should be
8276 considered to have thrown if they leave a non-null error in the error parameter.
8277 The return type is left unmodified.)reST";
8278
8279static const char AttrDoc_SwiftErrorResult[] = R"reST(The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
8280function as having the special error-result ABI treatment.
8281
8282This treatment generally passes the underlying error value in and out of
8283the function through a special register which is normally callee-preserved.
8284This is modeled in C by pretending that the register is addressable memory:
8285
8286- The caller appears to pass the address of a variable of pointer type.
8287 The current value of this variable is copied into the register before
8288 the call; if the call returns normally, the value is copied back into the
8289 variable.
8290
8291- The callee appears to receive the address of a variable. This address
8292 is actually a hidden location in its own stack, initialized with the
8293 value of the register upon entry. When the function returns normally,
8294 the value in that hidden location is written back to the register.
8295
8296A ``swift_error_result`` parameter must be the last parameter, and it must be
8297preceded by a ``swift_context`` parameter.
8298
8299A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
8300type T. Note that no qualifiers are permitted on the intermediate level.
8301
8302It is undefined behavior if the caller does not pass a pointer or
8303reference to a valid object.
8304
8305The standard convention is that the error value itself (that is, the
8306value stored in the apparent argument) will be null upon function entry,
8307but this is not enforced by the ABI.)reST";
8308
8309static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
8310
8311static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
8312
8313static const char AttrDoc_SwiftIndirectResult[] = R"reST(The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
8314or ``swiftasynccall`` function as having the special indirect-result ABI
8315treatment.
8316
8317This treatment gives the parameter the target's normal indirect-result
8318ABI treatment, which may involve passing it differently from an ordinary
8319parameter. However, only the first indirect result will receive this
8320treatment. Furthermore, low-level lowering may decide that a direct result
8321must be returned indirectly; if so, this will take priority over the
8322``swift_indirect_result`` parameters.
8323
8324A ``swift_indirect_result`` parameter must either be the first parameter or
8325follow another ``swift_indirect_result`` parameter.
8326
8327A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
8328some object type ``T``. If ``T`` is a complete type at the point of
8329definition of a function, it is undefined behavior if the argument
8330value does not point to storage of adequate size and alignment for a
8331value of type ``T``.
8332
8333Making indirect results explicit in the signature allows C functions to
8334directly construct objects into them without relying on language
8335optimizations like C++'s named return value optimization (NRVO).)reST";
8336
8337static const char AttrDoc_SwiftName[] = R"reST(The ``swift_name`` attribute provides the name of the declaration in Swift. If
8338this attribute is absent, the name is transformed according to the algorithm
8339built into the Swift compiler.
8340
8341The argument is a string literal that contains the Swift name of the function,
8342variable, or type. When renaming a function, the name may be a compound Swift
8343name. For a type, enum constant, property, or variable declaration, the name
8344must be a simple or qualified identifier.
8345
8346 .. code-block:: objc
8347
8348 @interface URL
8349 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
8350 @end
8351
8352 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
8353 })reST";
8354
8355static const char AttrDoc_SwiftNewType[] = R"reST(The ``swift_newtype`` attribute indicates that the typedef to which the
8356attribute appertains is imported as a new Swift type of the typedef's name.
8357Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
8358the attribute is identical with either spelling, ``swift_wrapper`` is
8359deprecated, only exists for compatibility purposes, and should not be used in
8360new code.
8361
8362* ``swift_newtype(struct)`` means that a Swift struct will be created for this
8363 typedef.
8364
8365* ``swift_newtype(enum)`` means that a Swift enum will be created for this
8366 typedef.
8367
8368 .. code-block:: c
8369
8370 // Import UIFontTextStyle as an enum type, with enumerated values being
8371 // constants.
8372 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
8373
8374 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
8375 // values being members of the type structure.
8376 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));)reST";
8377
8378static const char AttrDoc_SwiftNullability[] = R"reST()reST";
8379
8380static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
8381of this class will be implicitly marked with the ``@objcMembers`` Swift
8382attribute, exposing them back to Objective-C.)reST";
8383
8384static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the ``swift_private`` attribute are hidden from the
8385framework client but are still made available for use within the framework or
8386Swift SDK overlay.
8387
8388The purpose of this attribute is to permit a more idomatic implementation of
8389declarations in Swift while hiding the non-idiomatic one.)reST";
8390
8391static const char AttrDoc_SwiftType[] = R"reST()reST";
8392
8393static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
8394
8395static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
8396
8397static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
8398function to match the default convention used on Sys V targets such as Linux,
8399Mac, and BSD. This attribute has no effect on other targets.)reST";
8400
8401static const char AttrDoc_TLSModel[] = R"reST(The ``tls_model`` attribute allows you to specify which thread-local storage
8402model to use. It accepts the following strings:
8403
8404* global-dynamic
8405* local-dynamic
8406* initial-exec
8407* local-exec
8408
8409TLS models are mutually exclusive.)reST";
8410
8411static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
8412This attribute may be attached to a function definition and instructs
8413the backend to use different code generation options than were passed on the
8414command line.
8415
8416The current set of options correspond to the existing "subtarget features" for
8417the target with or without a "-mno-" in front corresponding to the absence
8418of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
8419for the function.
8420
8421For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
8422code for the given CPU without changing the available instructions.
8423
8424For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march
8425command line options. ``cpu="CPU"`` can be used to select a specific cpu,
8426as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the
8427"branch-protection=<args>" option, where the permissible arguments and their
8428effect on code generation are the same as for the command-line option
8429``-mbranch-protection``.
8430
8431Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8432"avx", "xop" and largely correspond to the machine specific options handled by
8433the front end.
8434
8435Note that this attribute does not apply transitively to nested functions such
8436as blocks or C++ lambdas.
8437
8438Additionally, this attribute supports function multiversioning for ELF based
8439x86/x86-64 targets, which can be used to create multiple implementations of the
8440same function that will be resolved at runtime based on the priority of their
8441``target`` attribute strings. A function is considered a multiversioned function
8442if either two declarations of the function have different ``target`` attribute
8443strings, or if it has a ``target`` attribute string of ``default``. For
8444example:
8445
8446 .. code-block:: c++
8447
8448 __attribute__((target("arch=atom")))
8449 void foo() {} // will be called on 'atom' processors.
8450 __attribute__((target("default")))
8451 void foo() {} // will be called on any other processors.
8452
8453All multiversioned functions must contain a ``default`` (fallback)
8454implementation, otherwise usages of the function are considered invalid.
8455Additionally, a function may not become multiversioned after its first use.)reST";
8456
8457static const char AttrDoc_TargetClones[] = R"reST(Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be
8458attached to a function declaration and causes function multiversioning, where
8459multiple versions of the function will be emitted with different code
8460generation options. Additionally, these versions will be resolved at runtime
8461based on the priority of their attribute options. All ``target_clone`` functions
8462are considered multiversioned functions.
8463
8464For AArch64 target:
8465The attribute contains comma-separated strings of target features joined by "+"
8466sign. For example:
8467
8468 .. code-block:: c++
8469
8470 __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
8471 void foo() {}
8472
8473For every multiversioned function a ``default`` (fallback) implementation
8474always generated if not specified directly.
8475
8476For x86/x86-64 targets:
8477All multiversioned functions must contain a ``default`` (fallback)
8478implementation, otherwise usages of the function are considered invalid.
8479Additionally, a function may not become multiversioned after its first use.
8480
8481The options to ``target_clones`` can either be a target-specific architecture
8482(specified as ``arch=CPU``), or one of a list of subtarget features.
8483
8484Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8485"avx", "xop" and largely correspond to the machine specific options handled by
8486the front end.
8487
8488The versions can either be listed as a comma-separated sequence of string
8489literals or as a single string literal containing a comma-separated list of
8490versions. For compatibility with GCC, the two formats can be mixed. For
8491example, the following will emit 4 versions of the function:
8492
8493 .. code-block:: c++
8494
8495 __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
8496 void foo() {}
8497
8498For targets that support the GNU indirect function (IFUNC) feature, dispatch
8499is performed by emitting an indirect function that is resolved to the appropriate
8500target clone at load time. The indirect function is given the name the
8501multiversioned function would have if it had been declared without the attribute.
8502For backward compatibility with earlier Clang releases, a function alias with an
8503``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8504feature and support for it may be removed in the future.)reST";
8505
8506static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
8507``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a
8508function it instructs compiler to emit multiple function versions based on
8509``target_version`` attribute strings, which resolved at runtime depend on their
8510priority and target features availability. One of the versions is always
8511( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can
8512contain dependent features names joined by the "+" sign.
8513
8514For targets that support the GNU indirect function (IFUNC) feature, dispatch
8515is performed by emitting an indirect function that is resolved to the appropriate
8516target clone at load time. The indirect function is given the name the
8517multiversioned function would have if it had been declared without the attribute.
8518For backward compatibility with earlier Clang releases, a function alias with an
8519``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8520feature and support for it may be removed in the future.)reST";
8521
8522static const char AttrDoc_TestTypestate[] = R"reST(Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
8523returns true if the object is in the specified state..)reST";
8524
8525static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8526function to use ECX for the first parameter (typically the implicit ``this``
8527parameter of C++ methods) and clear parameters off of the stack on return. This
8528convention does not support variadic calls or unprototyped functions in C, and
8529has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
8530MSDN.
8531
8532.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
8533
8534static const char AttrDoc_Thread[] = R"reST(The ``__declspec(thread)`` attribute declares a variable with thread local
8535storage. It is available under the ``-fms-extensions`` flag for MSVC
8536compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
8537
8538.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
8539
8540In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
8541GNU ``__thread`` keyword. The variable must not have a destructor and must have
8542a constant initializer, if any. The attribute only applies to variables
8543declared with static storage duration, such as globals, class static data
8544members, and static locals.)reST";
8545
8546static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
8547functions that have an argument with a transparent union type. The compiler
8548behavior is changed in the following manner:
8549
8550- A value whose type is any member of the transparent union can be passed as an
8551 argument without the need to cast that value.
8552
8553- The argument is passed to the function using the calling convention of the
8554 first member of the transparent union. Consequently, all the members of the
8555 transparent union should have the same calling convention as its first member.
8556
8557Transparent unions are not supported in C++.)reST";
8558
8559static const char AttrDoc_TrivialABI[] = R"reST(The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
8560It instructs the compiler to pass and return the type using the C ABI for the
8561underlying type when the type would otherwise be considered non-trivial for the
8562purpose of calls.
8563A class annotated with ``trivial_abi`` can have non-trivial destructors or
8564copy/move constructors without automatically becoming non-trivial for the
8565purposes of calls. For example:
8566
8567 .. code-block:: c++
8568
8569 // A is trivial for the purposes of calls because ``trivial_abi`` makes the
8570 // user-provided special functions trivial.
8571 struct __attribute__((trivial_abi)) A {
8572 ~A();
8573 A(const A &);
8574 A(A &&);
8575 int x;
8576 };
8577
8578 // B's destructor and copy/move constructor are considered trivial for the
8579 // purpose of calls because A is trivial.
8580 struct B {
8581 A a;
8582 };
8583
8584If a type is trivial for the purposes of calls, has a non-trivial destructor,
8585and is passed as an argument by value, the convention is that the callee will
8586destroy the object before returning. The lifetime of the copy of the parameter
8587in the caller ends without a destructor call when the call begins.
8588
8589If a type is trivial for the purpose of calls, it is assumed to be trivially
8590relocatable for the purpose of ``__is_trivially_relocatable`` and
8591``__builtin_is_cpp_trivially_relocatable``.
8592When a type marked with ``[[trivial_abi]]`` is used as a function argument,
8593the compiler may omit the call to the copy constructor.
8594Thus, side effects of the copy constructor are potentially not performed.
8595For example, objects that contain pointers to themselves or otherwise depend
8596on their address (or the address or their subobjects) should not be declared
8597``[[trivial_abi]]``.
8598
8599Attribute ``trivial_abi`` has no effect in the following cases:
8600
8601- The class directly declares a virtual base or virtual methods.
8602- Copy constructors and move constructors of the class are all deleted.
8603- The class has a base class that is non-trivial for the purposes of calls.
8604- The class has a non-static data member whose type is non-trivial for the
8605 purposes of calls, which includes:
8606
8607 - classes that are non-trivial for the purposes of calls
8608 - __weak-qualified types in Objective-C++
8609 - arrays of any of the above)reST";
8610
8611static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
8612actually acquire the capability; they accept a Boolean value determining
8613whether acquiring the capability means success (true), or failing to acquire
8614the capability means success (false).)reST";
8615
8616static const char AttrDoc_TypeNonNull[] = R"reST(The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
8617value for a value of the ``_Nonnull`` pointer type. For example, given a
8618declaration such as:
8619
8620 .. code-block:: c
8621
8622 int fetch(int * _Nonnull ptr);
8623
8624a caller of ``fetch`` should not provide a null value, and the compiler will
8625produce a warning if it sees a literal null value passed to ``fetch``. Note
8626that, unlike the declaration attribute ``nonnull``, the presence of
8627``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
8628is free to consider null undefined behavior or (perhaps for
8629backward-compatibility reasons) defensively handle null.)reST";
8630
8631static const char AttrDoc_TypeNullUnspecified[] = R"reST(The ``_Null_unspecified`` nullability qualifier indicates that neither the
8632``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
8633type. It is used primarily to indicate that the role of null with specific
8634pointers in a nullability-annotated header is unclear, e.g., due to
8635overly-complex implementations or historical factors with a long-lived API.)reST";
8636
8637static const char AttrDoc_TypeNullable[] = R"reST(The ``_Nullable`` nullability qualifier indicates that a value of the
8638``_Nullable`` pointer type can be null. For example, given:
8639
8640 .. code-block:: c
8641
8642 int fetch_or_zero(int * _Nullable ptr);
8643
8644a caller of ``fetch_or_zero`` can provide null.
8645
8646The ``_Nullable`` attribute on classes indicates that the given class can
8647represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
8648make sense for this type. For example:
8649
8650 .. code-block:: c
8651
8652 class _Nullable ArenaPointer { ... };
8653
8654 ArenaPointer _Nonnull x = ...;
8655 ArenaPointer _Nullable y = nullptr;)reST";
8656
8657static const char AttrDoc_TypeNullableResult[] = R"reST(The ``_Nullable_result`` nullability qualifier means that a value of the
8658``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
8659attribute differs from ``_Nullable`` is when it's used on a parameter to a
8660completion handler in a Swift async method. For instance, here:
8661
8662 .. code-block:: objc
8663
8664 -(void)fetchSomeDataWithID:(int)identifier
8665 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
8666
8667This method asynchronously calls ``completionHandler`` when the data is
8668available, or calls it with an error. ``_Nullable_result`` indicates to the
8669Swift importer that this is the uncommon case where ``result`` can get ``nil``
8670even if no error has occurred, and will therefore import it as a Swift optional
8671type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
8672importer will assume that ``result`` will always be non-nil unless an error
8673occurred.)reST";
8674
8675static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
8676``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
8677is tied to the ``type`` argument given to the attribute.
8678
8679In the attribute prototype above:
8680 * ``kind`` is an identifier that should be used when annotating all applicable
8681 type tags.
8682 * ``type`` indicates the name of the type.
8683
8684Clang supports annotating type tags of two forms.
8685
8686 * **Type tag that is a reference to a declared identifier.**
8687 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
8688 identifier:
8689
8690 .. code-block:: c++
8691
8692 typedef int MPI_Datatype;
8693 extern struct mpi_datatype mpi_datatype_int
8694 __attribute__(( type_tag_for_datatype(mpi,int) ));
8695 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
8696 // &mpi_datatype_int is a type tag. It is tied to type "int".
8697
8698 * **Type tag that is an integral literal.**
8699 Declare a ``static const`` variable with an initializer value and attach
8700 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
8701
8702 .. code-block:: c++
8703
8704 typedef int MPI_Datatype;
8705 static const MPI_Datatype mpi_datatype_int
8706 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
8707 #define MPI_INT ((MPI_Datatype) 42)
8708 // The number 42 is a type tag. It is tied to type "int".
8709
8710
8711The ``type_tag_for_datatype`` attribute also accepts an optional third argument
8712that determines how the type of the function argument specified by either
8713``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
8714tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
8715function argument specified by ``arg_idx`` is compared against the type
8716associated with the type tag. Also recall that for the ``pointer_with_type_tag``
8717attribute, the pointee type of the function argument specified by ``ptr_idx`` is
8718compared against the type associated with the type tag.) There are two supported
8719values for this optional third argument:
8720
8721 * ``layout_compatible`` will cause types to be compared according to
8722 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
8723 layout-compatibility rules for two standard-layout struct types and for two
8724 standard-layout union types). This is useful when creating a type tag
8725 associated with a struct or union type. For example:
8726
8727 .. code-block:: c++
8728
8729 /* In mpi.h */
8730 typedef int MPI_Datatype;
8731 struct internal_mpi_double_int { double d; int i; };
8732 extern struct mpi_datatype mpi_datatype_double_int
8733 __attribute__(( type_tag_for_datatype(mpi,
8734 struct internal_mpi_double_int, layout_compatible) ));
8735
8736 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
8737
8738 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
8739 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
8740
8741 /* In user code */
8742 struct my_pair { double a; int b; };
8743 struct my_pair *buffer;
8744 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
8745 // layout of my_pair is
8746 // compatible with that of
8747 // internal_mpi_double_int
8748
8749 struct my_int_pair { int a; int b; }
8750 struct my_int_pair *buffer2;
8751 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
8752 // layout of my_int_pair
8753 // does not match that of
8754 // internal_mpi_double_int
8755
8756 * ``must_be_null`` specifies that the function argument specified by either
8757 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
8758 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
8759 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
8760 example:
8761
8762 .. code-block:: c++
8763
8764 /* In mpi.h */
8765 typedef int MPI_Datatype;
8766 extern struct mpi_datatype mpi_datatype_null
8767 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
8768
8769 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
8770 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
8771 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
8772
8773 /* In user code */
8774 struct my_pair { double a; int b; };
8775 struct my_pair *buffer;
8776 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
8777 // was specified but buffer
8778 // is not a null pointer)reST";
8779
8780static const char AttrDoc_TypeVisibility[] = R"reST(The ``type_visibility`` attribute allows the visibility of a type and its vague
8781linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
8782the visibility of functions and data members of the type.
8783
8784For example, this can be used to give default visibility to the typeinfo and the vtable
8785of a type while still keeping hidden visibility on its member functions and static data
8786members.
8787
8788This attribute can only be applied to types and namespaces.
8789
8790If both ``visibility`` and ``type_visibility`` are applied to a type or a namespace, the
8791visibility specified with the ``type_visibility`` attribute overrides the visibility
8792provided with the regular ``visibility`` attribute.)reST";
8793
8794static const char AttrDoc_UPtr[] = R"reST(The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
8795extended when converted to a 64-bit pointer.)reST";
8796
8797static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
8798
8799static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
8800initialize trivial automatic stack variables. By default, trivial automatic
8801stack variables are uninitialized. This attribute is used to override the
8802command-line parameter, forcing variables to remain uninitialized. It has no
8803semantic meaning in that using uninitialized values is undefined behavior,
8804it rather documents the programmer's intent.)reST";
8805
8806static const char AttrDoc_Unlikely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
8807The attributes are used to aid the compiler to determine which branch is
8808likely or unlikely to be taken. This is done by marking the branch substatement
8809with one of the two attributes.
8810
8811It isn't allowed to annotate a single statement with both ``likely`` and
8812``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
8813statement with the same likelihood attribute will result in a diagnostic and
8814the attributes are ignored on both branches.
8815
8816In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
8817or the ``default`` label with the same likelihood attribute. This makes
8818* all labels without an attribute have a neutral likelihood,
8819* all labels marked ``[[likely]]`` have an equally positive likelihood, and
8820* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
8821The neutral likelihood is the more likely of path execution than the negative
8822likelihood. The positive likelihood is the more likely of path of execution
8823than the neutral likelihood.
8824
8825These attributes have no effect on the generated code when using
8826PGO (Profile-Guided Optimization) or at optimization level 0.
8827
8828In Clang, the attributes will be ignored if they're not placed on
8829* the ``case`` or ``default`` label of a ``switch`` statement,
8830* or on the substatement of an ``if`` or ``else`` statement,
8831* or on the substatement of an ``for`` or ``while`` statement.
8832The C++ Standard recommends to honor them on every statement in the
8833path of execution, but that can be confusing:
8834
8835.. code-block:: c++
8836
8837 if (b) {
8838 [[unlikely]] --b; // Per the standard this is in the path of
8839 // execution, so this branch should be considered
8840 // unlikely. However, Clang ignores the attribute
8841 // here since it is not on the substatement.
8842 }
8843
8844 if (b) {
8845 --b;
8846 if(b)
8847 return;
8848 [[unlikely]] --b; // Not in the path of execution,
8849 } // the branch has no likelihood information.
8850
8851 if (b) {
8852 --b;
8853 foo(b);
8854 // Whether or not the next statement is in the path of execution depends
8855 // on the declaration of foo():
8856 // In the path of execution: void foo(int);
8857 // Not in the path of execution: [[noreturn]] void foo(int);
8858 // This means the likelihood of the branch depends on the declaration
8859 // of foo().
8860 [[unlikely]] --b;
8861 }
8862
8863
8864Below are some example usages of the likelihood attributes and their effects:
8865
8866.. code-block:: c++
8867
8868 if (b) [[likely]] { // Placement on the first statement in the branch.
8869 // The compiler will optimize to execute the code here.
8870 } else {
8871 }
8872
8873 if (b)
8874 [[unlikely]] b++; // Placement on the first statement in the branch.
8875 else {
8876 // The compiler will optimize to execute the code here.
8877 }
8878
8879 if (b) {
8880 [[unlikely]] b++; // Placement on the second statement in the branch.
8881 } // The attribute will be ignored.
8882
8883 if (b) [[likely]] {
8884 [[unlikely]] b++; // No contradiction since the second attribute
8885 } // is ignored.
8886
8887 if (b)
8888 ;
8889 else [[likely]] {
8890 // The compiler will optimize to execute the code here.
8891 }
8892
8893 if (b)
8894 ;
8895 else
8896 // The compiler will optimize to execute the next statement.
8897 [[likely]] b = f();
8898
8899 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
8900 else [[likely]]; // and the attributes are ignored.
8901
8902 if (b)
8903 [[likely]] int i = 5; // Issues a diagnostic since the attribute
8904 // isn't allowed on a declaration.
8905
8906 switch (i) {
8907 [[likely]] case 1: // This value is likely
8908 ...
8909 break;
8910
8911 [[unlikely]] case 2: // This value is unlikely
8912 ...
8913 [[fallthrough]];
8914
8915 case 3: // No likelihood attribute
8916 ...
8917 [[likely]] break; // No effect
8918
8919 case 4: [[likely]] { // attribute on substatement has no effect
8920 ...
8921 break;
8922 }
8923
8924 [[unlikely]] default: // All other values are unlikely
8925 ...
8926 break;
8927 }
8928
8929 switch (i) {
8930 [[likely]] case 0: // This value and code path is likely
8931 ...
8932 [[fallthrough]];
8933
8934 case 1: // No likelihood attribute, code path is neutral
8935 break; // falling through has no effect on the likelihood
8936
8937 case 2: // No likelihood attribute, code path is neutral
8938 [[fallthrough]];
8939
8940 [[unlikely]] default: // This value and code path are both unlikely
8941 break;
8942 }
8943
8944 for(int i = 0; i != size; ++i) [[likely]] {
8945 ... // The loop is the likely path of execution
8946 }
8947
8948 for(const auto &E : Elements) [[likely]] {
8949 ... // The loop is the likely path of execution
8950 }
8951
8952 while(i != size) [[unlikely]] {
8953 ... // The loop is the unlikely path of execution
8954 } // The generated code will optimize to skip the loop body
8955
8956 while(true) [[unlikely]] {
8957 ... // The attribute has no effect
8958 } // Clang elides the comparison and generates an infinite
8959 // loop)reST";
8960
8961static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
8962that need to be avoided as they are prone to buffer overflows or unsafe buffer
8963struct fields. It is designed to work together with the off-by-default compiler
8964warning ``-Wunsafe-buffer-usage`` to help codebases transition away from raw pointer
8965based buffer management, in favor of safer abstractions such as C++20 ``std::span``.
8966The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the function or
8967the field it is attached to, and it may also lead to emission of automatic fix-it
8968hints which would help the user replace the use of unsafe functions(/fields) with safe
8969alternatives, though the attribute can be used even when the fix can't be automated.
8970
8971* Attribute attached to functions: The attribute suppresses all
8972 ``-Wunsafe-buffer-usage`` warnings within the function it is attached to, as the
8973 function is now classified as unsafe. The attribute should be used carefully, as it
8974 will silence all unsafe operation warnings inside the function; including any new
8975 unsafe operations introduced in the future.
8976
8977 The attribute is warranted even if the only way a function can overflow
8978 the buffer is by violating the function's preconditions. For example, it
8979 would make sense to put the attribute on function ``foo()`` below because
8980 passing an incorrect size parameter would cause a buffer overflow:
8981
8982 .. code-block:: c++
8983
8984 [[clang::unsafe_buffer_usage]]
8985 void foo(int *buf, size_t size) {
8986 for (size_t i = 0; i < size; ++i) {
8987 buf[i] = i;
8988 }
8989 }
8990
8991 The attribute is NOT warranted when the function uses safe abstractions,
8992 assuming that these abstractions weren't misused outside the function.
8993 For example, function ``bar()`` below doesn't need the attribute,
8994 because assuming that the container ``buf`` is well-formed (has size that
8995 fits the original buffer it refers to), overflow cannot occur:
8996
8997 .. code-block:: c++
8998
8999 void bar(std::span<int> buf) {
9000 for (size_t i = 0; i < buf.size(); ++i) {
9001 buf[i] = i;
9002 }
9003 }
9004
9005 In this case function ``bar()`` enables the user to keep the buffer
9006 "containerized" in a span for as long as possible. On the other hand,
9007 Function ``foo()`` in the previous example may have internal
9008 consistency, but by accepting a raw buffer it requires the user to unwrap
9009 their span, which is undesirable according to the programming model
9010 behind ``-Wunsafe-buffer-usage``.
9011
9012 The attribute is warranted when a function accepts a raw buffer only to
9013 immediately put it into a span:
9014
9015 .. code-block:: c++
9016
9017 [[clang::unsafe_buffer_usage]]
9018 void baz(int *buf, size_t size) {
9019 std::span<int> sp{ buf, size };
9020 for (size_t i = 0; i < sp.size(); ++i) {
9021 sp[i] = i;
9022 }
9023 }
9024
9025 In this case ``baz()`` does not contain any unsafe operations, but the awkward
9026 parameter type causes the caller to unwrap the span unnecessarily.
9027 Note that regardless of the attribute, code inside ``baz()`` isn't flagged
9028 by ``-Wunsafe-buffer-usage`` as unsafe. It is definitely undesirable,
9029 but if ``baz()`` is on an API surface, there is no way to improve it
9030 to make it as safe as ``bar()`` without breaking the source and binary
9031 compatibility with existing users of the function. In such cases
9032 the proper solution would be to create a different function (possibly
9033 an overload of ``baz()``) that accepts a safe container like ``bar()``,
9034 and then use the attribute on the original ``baz()`` to help the users
9035 update their code to use the new function.
9036
9037* Attribute attached to fields: The attribute should only be attached to
9038 struct fields, if the fields can not be updated to a safe type with bounds
9039 check, such as std::span. In other words, the buffers prone to unsafe accesses
9040 should always be updated to use safe containers/views and attaching the attribute
9041 must be last resort when such an update is infeasible.
9042
9043 The attribute can be placed on individual fields or a set of them as shown below.
9044
9045 .. code-block:: c++
9046
9047 struct A {
9048 [[clang::unsafe_buffer_usage]]
9049 int *ptr1;
9050
9051 [[clang::unsafe_buffer_usage]]
9052 int *ptr2, buf[10];
9053
9054 [[clang::unsafe_buffer_usage]]
9055 size_t sz;
9056 };
9057
9058 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
9059 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
9060
9061static const char AttrDoc_Unused[] = R"reST(When passing the ``-Wunused`` flag to Clang, entities that are unused by the
9062program may be diagnosed. The ``[[maybe_unused]]`` (or
9063``__attribute__((unused))``) attribute can be used to silence such diagnostics
9064when the entity cannot be removed. For instance, a local variable may exist
9065solely for use in an ``assert()`` statement, which makes the local variable
9066unused when ``NDEBUG`` is defined.
9067
9068The attribute may be applied to the declaration of a class, a typedef, a
9069variable, a function or method, a function parameter, an enumeration, an
9070enumerator, a non-static data member, or a label.
9071
9072.. code-block:: c++
9073
9074 #include <cassert>
9075
9076 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
9077 [[maybe_unused]] bool thing2) {
9078 [[maybe_unused]] bool b = thing1 && thing2;
9079 assert(b);
9080 })reST";
9081
9082static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9083parameter is annotated with ``use_handle(tag)`` it is assumed to not to change
9084the state of the handle. It is also assumed to require an open handle to work with.
9085The attribute requires a string literal argument to identify the handle being used.
9086
9087.. code-block:: c++
9088
9089 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
9090 zx_time_t deadline,
9091 zx_port_packet_t* packet);)reST";
9092
9093static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
9094that there may be references to the entity which are not apparent in the source
9095code. For example, it may be referenced from inline ``asm``, or it may be
9096found through a dynamic symbol or section lookup.
9097
9098The compiler must emit the definition even if it appears to be unused, and it
9099must not apply optimizations which depend on fully understanding how the entity
9100is used.
9101
9102Whether this attribute has any effect on the linker depends on the target and
9103the linker. Most linkers support the feature of section garbage collection
9104(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
9105discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
9106targets (Windows and Apple platforms), the `used` attribute prevents symbols
9107from being removed by linker section GC. On ELF targets, it has no effect on its
9108own, and the linker may remove the definition if it is not otherwise referenced.
9109This linker GC can be avoided by also adding the ``retain`` attribute. Note
9110that ``retain`` requires special support from the linker; see that attribute's
9111documentation for further information.)reST";
9112
9113static const char AttrDoc_UsingIfExists[] = R"reST(The ``using_if_exists`` attribute applies to a using-declaration. It allows
9114programmers to import a declaration that potentially does not exist, instead
9115deferring any errors to the point of use. For instance:
9116
9117.. code-block:: c++
9118
9119 namespace empty_namespace {};
9120 __attribute__((using_if_exists))
9121 using empty_namespace::does_not_exist; // no error!
9122
9123 does_not_exist x; // error: use of unresolved 'using_if_exists'
9124
9125The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
9126supported as a clang extension, since ISO C++ doesn't support attributes in this
9127position. If the entity referred to by the using-declaration is found by name
9128lookup, the attribute has no effect. This attribute is useful for libraries
9129(primarily, libc++) that wish to redeclare a set of declarations in another
9130namespace, when the availability of those declarations is difficult or
9131impossible to detect at compile time with the preprocessor.)reST";
9132
9133static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
9134
9135static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
9136
9137static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
9138
9139static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
9140
9141static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
9142convention of a function to pass vector parameters in SSE registers.
9143
9144On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
9145The first two integer parameters are passed in ECX and EDX. Subsequent integer
9146parameters are passed in memory, and callee clears the stack. On x86_64
9147targets, the callee does *not* clear the stack, and integer parameters are
9148passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
9149convention.
9150
9151On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
9152passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
9153passed in sequential SSE registers if enough are available. If AVX is enabled,
9154256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
9155cannot be passed in registers for any reason is passed by reference, which
9156allows the caller to align the parameter memory.
9157
9158See the documentation for `__vectorcall`_ on MSDN for more details.
9159
9160.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
9161
9162static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
9163
9164static const char AttrDoc_WarnUnused[] = R"reST(No documentation.)reST";
9165
9166static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
9167expression are discarded under suspicious circumstances. A diagnostic is
9168generated when a function or its return type is marked with ``[[nodiscard]]``
9169(or ``__attribute__((warn_unused_result))``) and the function call appears as a
9170potentially-evaluated discarded-value expression that is not explicitly cast to
9171``void``.
9172
9173A string literal may optionally be provided to the attribute, which will be
9174reproduced in any resulting diagnostics. Redeclarations using different forms
9175of the attribute (with or without the string literal or with different string
9176literal contents) are allowed. If there are redeclarations of the entity with
9177differing string literals, it is unspecified which one will be used by Clang
9178in any resulting diagnostics.
9179
9180.. code-block:: c++
9181
9182 struct [[nodiscard]] error_info { /*...*/ };
9183 error_info enable_missile_safety_mode();
9184
9185 void launch_missiles();
9186 void test_missiles() {
9187 enable_missile_safety_mode(); // diagnoses
9188 launch_missiles();
9189 }
9190 error_info &foo();
9191 void f() { foo(); } // Does not diagnose, error_info is a reference.
9192
9193Additionally, discarded temporaries resulting from a call to a constructor
9194marked with ``[[nodiscard]]`` or a constructor of a type marked
9195``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
9196use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
9197
9198.. code-block:: c++
9199
9200 struct [[nodiscard]] marked_type {/*..*/ };
9201 struct marked_ctor {
9202 [[nodiscard]] marked_ctor();
9203 marked_ctor(int);
9204 };
9205
9206 struct S {
9207 operator marked_type() const;
9208 [[nodiscard]] operator int() const;
9209 };
9210
9211 void usages() {
9212 marked_type(); // diagnoses.
9213 marked_ctor(); // diagnoses.
9214 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
9215
9216 S s;
9217 static_cast<marked_type>(s); // diagnoses
9218 (int)s; // diagnoses
9219 })reST";
9220
9221static const char AttrDoc_Weak[] = R"reST(In supported output formats the ``weak`` attribute can be used to
9222specify that a variable or function should be emitted as a symbol with
9223``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
9224external symbol) `linkage
9225<https://llvm.org/docs/LangRef.html#linkage-types>`_.
9226
9227If there is a non-weak definition of the symbol the linker will select
9228that over the weak. They must have same type and alignment (variables
9229must also have the same size), but may have a different value.
9230
9231If there are multiple weak definitions of same symbol, but no non-weak
9232definition, they should have same type, size, alignment and value, the
9233linker will select one of them (see also selectany_ attribute).
9234
9235If the ``weak`` attribute is applied to a ``const`` qualified variable
9236definition that variable is no longer consider a compiletime constant
9237as its value can change during linking (or dynamic linking). This
9238means that it can e.g no longer be part of an initializer expression.
9239
9240.. code-block:: c
9241
9242 const int ANSWER __attribute__ ((weak)) = 42;
9243
9244 /* This function may be replaced link-time */
9245 __attribute__ ((weak)) void debug_log(const char *msg)
9246 {
9247 fprintf(stderr, "DEBUG: %s\n", msg);
9248 }
9249
9250 int main(int argc, const char **argv)
9251 {
9252 debug_log ("Starting up...");
9253
9254 /* This may print something else than "6 * 7 = 42",
9255 if there is a non-weak definition of "ANSWER" in
9256 an object linked in */
9257 printf("6 * 7 = %d\n", ANSWER);
9258
9259 return 0;
9260 }
9261
9262If an external declaration is marked weak and that symbol does not
9263exist during linking (possibly dynamic) the address of the symbol will
9264evaluate to NULL.
9265
9266.. code-block:: c
9267
9268 void may_not_exist(void) __attribute__ ((weak));
9269
9270 int main(int argc, const char **argv)
9271 {
9272 if (may_not_exist) {
9273 may_not_exist();
9274 } else {
9275 printf("Function did not exist\n");
9276 }
9277 return 0;
9278 })reST";
9279
9280static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
9281
9282static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
9283
9284static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9285attribute for the WebAssembly target. This attribute may be attached to a
9286function declaration, where it modifies how the symbol is to be exported
9287from the linked WebAssembly.
9288
9289WebAssembly functions are exported via string name. By default when a symbol
9290is exported, the export name for C/C++ symbols are the same as their C/C++
9291symbol names. This attribute can be used to override the default behavior, and
9292request a specific string name be used instead.)reST";
9293
9294static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9295attribute for the WebAssembly target. This attribute may be attached to a
9296function declaration, where it modifies how the symbol is to be exported
9297from the linked WebAssembly.
9298
9299WebAssembly functions are exported via string name. By default when a symbol
9300is exported, the export name for C/C++ symbols are the same as their C/C++
9301symbol names. This attribute can be used to override the default behavior, and
9302request a specific string name be used instead.)reST";
9303
9304static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the ``__attribute__((import_module(<module_name>)))``
9305attribute for the WebAssembly target. This attribute may be attached to a
9306function declaration, where it modifies how the symbol is to be imported
9307within the WebAssembly linking environment.
9308
9309WebAssembly imports use a two-level namespace scheme, consisting of a module
9310name, which typically identifies a module from which to import, and a field
9311name, which typically identifies a field from that module to import. By
9312default, module names for C/C++ symbols are assigned automatically by the
9313linker. This attribute can be used to override the default behavior, and
9314request a specific module name be used instead.)reST";
9315
9316static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the ``__attribute__((import_name(<name>)))``
9317attribute for the WebAssembly target. This attribute may be attached to a
9318function declaration, where it modifies how the symbol is to be imported
9319within the WebAssembly linking environment.
9320
9321WebAssembly imports use a two-level namespace scheme, consisting of a module
9322name, which typically identifies a module from which to import, and a field
9323name, which typically identifies a field from that module to import. By
9324default, field names for C/C++ symbols are the same as their C/C++ symbol
9325names. This attribute can be used to override the default behavior, and
9326request a specific field name be used instead.)reST";
9327
9328static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
9329
9330static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
9331
9332Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
9333(like 'movaps') that work with the stack require operands to be 16-byte aligned.
9334This attribute realigns the stack in the function prologue to make sure the
9335stack can be used with SSE instructions.
9336
9337Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
9338Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
9339rare cases where the caller does not align the stack properly (e.g. flow
9340jumps from i386 arch code).
9341
9342 .. code-block:: c
9343
9344 __attribute__ ((force_align_arg_pointer))
9345 void f () {
9346 ...
9347 })reST";
9348
9349static const char AttrDoc_XRayInstrument[] = R"reST(``__attribute__((xray_always_instrument))`` or
9350``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9351methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9352instrumented with XRay. This will cause the function to always have space at
9353the beginning and exit points to allow for runtime patching.
9354
9355Conversely, ``__attribute__((xray_never_instrument))`` or
9356``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9357instrumentation points.
9358
9359If a function has neither of these attributes, they become subject to the XRay
9360heuristics used to determine whether a function should be instrumented or
9361otherwise.
9362
9363``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9364used to preserve N function arguments for the logging function. Currently,
9365only N==1 is supported.)reST";
9366
9367static const char AttrDoc_XRayLogArgs[] = R"reST(``__attribute__((xray_always_instrument))`` or
9368``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9369methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9370instrumented with XRay. This will cause the function to always have space at
9371the beginning and exit points to allow for runtime patching.
9372
9373Conversely, ``__attribute__((xray_never_instrument))`` or
9374``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9375instrumentation points.
9376
9377If a function has neither of these attributes, they become subject to the XRay
9378heuristics used to determine whether a function should be instrumented or
9379otherwise.
9380
9381``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9382used to preserve N function arguments for the logging function. Currently,
9383only N==1 is supported.)reST";
9384
9385static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
9386subset of all call-used registers before the function returns. It's used to
9387increase program security by either mitigating `Return-Oriented Programming`_
9388(ROP) attacks or preventing information leakage through registers.
9389
9390The term "call-used" means registers which are not guaranteed to be preserved
9391unchanged for the caller by the current calling convention. This could also be
9392described as "caller-saved" or "not callee-saved".
9393
9394The `choice` parameters gives the programmer flexibility to choose the subset
9395of the call-used registers to be zeroed:
9396
9397- ``skip`` doesn't zero any call-used registers. This choice overrides any
9398 command-line arguments.
9399- ``used`` only zeros call-used registers used in the function. By ``used``, we
9400 mean a register whose contents have been set or referenced in the function.
9401- ``used-gpr`` only zeros call-used GPR registers used in the function.
9402- ``used-arg`` only zeros call-used registers used to pass arguments to the
9403 function.
9404- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to
9405 the function.
9406- ``all`` zeros all call-used registers.
9407- ``all-gpr`` zeros all call-used GPR registers.
9408- ``all-arg`` zeros all call-used registers used to pass arguments to the
9409 function.
9410- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to
9411 the function.
9412
9413The default for the attribute is controlled by the ``-fzero-call-used-regs``
9414flag.
9415
9416.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
9417