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(.. warning::
98 These attributes are deprecated. Use the ``amdgpu_waves_per_eu`` attribute to
99 control SGPR and VGPR usage instead.
100
101Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
102``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
103target. These attributes may be attached to a kernel function definition and are
104an optimization hint.
105
106If these attributes are specified, then the AMDGPU target backend will attempt
107to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
108number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
109allocation requirements or constraints of the subtarget. Passing ``0`` as
110``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
111
112These attributes can be used to test the AMDGPU target backend. It is
113recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
114resources such as SGPRs and VGPRs since it is aware of the limits for different
115subtargets.
116
117An error will be given if:
118 - Specified values violate subtarget specifications;
119 - Specified values are not compatible with values provided through other
120 attributes;
121 - The AMDGPU target backend is unable to create machine code that can meet the
122 request.)reST";
123
124static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(.. warning::
125 These attributes are deprecated. Use the ``amdgpu_waves_per_eu`` attribute to
126 control SGPR and VGPR usage instead.
127
128Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
129``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
130target. These attributes may be attached to a kernel function definition and are
131an optimization hint.
132
133If these attributes are specified, then the AMDGPU target backend will attempt
134to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
135number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
136allocation requirements or constraints of the subtarget. Passing ``0`` as
137``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
138
139These attributes can be used to test the AMDGPU target backend. It is
140recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
141resources such as SGPRs and VGPRs since it is aware of the limits for different
142subtargets.
143
144An error will be given if:
145 - Specified values violate subtarget specifications;
146 - Specified values are not compatible with values provided through other
147 attributes;
148 - The AMDGPU target backend is unable to create machine code that can meet the
149 request.)reST";
150
151static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
152It is composed of one or more execution units (EU), which are responsible for
153executing the wavefronts. An EU can have enough resources to maintain the state
154of more than one executing wavefront. This allows an EU to hide latency by
155switching between wavefronts in a similar way to symmetric multithreading on a
156CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
157resources used by a single wavefront have to be limited. For example, the number
158of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
159but can result in having to spill some register state to memory.
160
161Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
162attribute for the AMDGPU target. This attribute may be attached to a kernel
163function definition and is an optimization hint.
164
165``<min>`` parameter specifies the requested minimum number of waves per EU, and
166*optional* ``<max>`` parameter specifies the requested maximum number of waves
167per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
168then there is no restriction on the maximum number of waves per EU other than
169the one dictated by the hardware for which the kernel is compiled. Passing
170``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
171
172If specified, this attribute allows an advanced developer to tune the number of
173wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
174target backend can use this information to limit resources, such as number of
175SGPRs, number of VGPRs, size of available group and private memory segments, in
176such a way that guarantees that at least ``<min>`` wavefronts and at most
177``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
178more wavefronts can hide memory latency but limits available registers which
179can result in spilling. Requesting fewer wavefronts can help reduce cache
180thrashing, but can reduce memory latency hiding.
181
182This attribute controls the machine code generated by the AMDGPU target backend
183to ensure it is capable of meeting the requested values. However, when the
184kernel is executed, there may be other reasons that prevent meeting the request,
185for example, there may be wavefronts from other kernels executing on the EU.
186
187An error will be given if:
188 - Specified values violate subtarget specifications;
189 - Specified values are not compatible with values provided through other
190 attributes;
191
192The AMDGPU target backend will emit a warning whenever it is unable to
193create machine code that meets the request.)reST";
194
195static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
196ARM targets. This attribute may be attached to a function definition and
197instructs the backend to generate appropriate function entry/exit code so that
198it can be used directly as an interrupt service routine.
199
200The parameter passed to the interrupt attribute is optional, but if
201provided it must be a string literal with one of the following values: "IRQ",
202"FIQ", "SWI", "ABORT", "UNDEF".
203
204The semantics are as follows:
205
206- If the function is AAPCS, Clang instructs the backend to realign the stack to
207 8 bytes on entry. This is a general requirement of the AAPCS at public
208 interfaces, but may not hold when an exception is taken. Doing this allows
209 other AAPCS functions to be called.
210- If the CPU is M-class this is all that needs to be done since the architecture
211 itself is designed in such a way that functions obeying the normal AAPCS ABI
212 constraints are valid exception handlers.
213- If the CPU is not M-class, the prologue and epilogue are modified to save all
214 non-banked registers that are used, so that upon return the user-mode state
215 will not be corrupted. Note that to avoid unnecessary overhead, only
216 general-purpose (integer) registers are saved in this way. If VFP operations
217 are needed, that state must be saved manually.
218
219 Specifically, interrupt kinds other than "FIQ" will save all core registers
220 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
221- If the CPU is not M-class, the return instruction is changed to one of the
222 canonical sequences permitted by the architecture for exception return. Where
223 possible the function itself will make the necessary "lr" adjustments so that
224 the "preferred return address" is selected.
225
226 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
227 handler, where the offset from "lr" to the preferred return address depends on
228 the execution state of the code which generated the exception. In this case
229 a sequence equivalent to "movs pc, lr" will be used.)reST";
230
231static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt_save_fp("TYPE")))``
232on ARM targets. This attribute behaves the same way as the ARM interrupt
233attribute, except the general purpose floating point registers are also saved,
234along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
235point context can be automatically saved depending on the FPCCR, the general
236purpose floating point registers will be saved.)reST";
237
238static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
239
240static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
241AVR targets. This attribute may be attached to a function definition and instructs
242the backend to generate appropriate function entry/exit code so that it can be used
243directly as an interrupt service routine.
244
245On the AVR, the hardware globally disables interrupts when an interrupt is executed.
246The first instruction of an interrupt handler declared with this attribute is a SEI
247instruction to re-enable interrupts. See also the signal attribute that
248does not insert a SEI instruction.)reST";
249
250static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style ``__attribute__((signal))`` attribute on
251AVR targets. This attribute may be attached to a function definition and instructs
252the backend to generate appropriate function entry/exit code so that it can be used
253directly as an interrupt service routine.
254
255Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
256
257static const char AttrDoc_AbiTag[] = R"reST(The ``abi_tag`` attribute can be applied to a function, variable, class or
258inline namespace declaration to modify the mangled name of the entity. It gives
259the ability to distinguish between different versions of the same entity but
260with different ABI versions supported. For example, a newer version of a class
261could have a different set of data members and thus have a different size. Using
262the ``abi_tag`` attribute, it is possible to have different mangled names for
263a global variable of the class type. Therefore, the old code could keep using
264the old mangled name and the new code will use the new mangled name with tags.)reST";
265
266static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
267
268static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
269a new handle. In case this annotation is on an output parameter,
270the function is assumed to fill the corresponding argument with a new
271handle. The attribute requires a string literal argument which used to
272identify the handle with later uses of ``use_handle`` or
273``release_handle``.
274
275.. code-block:: c++
276
277 // Output arguments from Zircon.
278 zx_status_t zx_socket_create(uint32_t options,
279 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
280 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
281
282
283 // Returned handle.
284 [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
285 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));)reST";
286
287static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
288
289static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
290
291static const char AttrDoc_AddressSpace[] = R"reST(.. Note:: This attribute is mainly intended to be used by target headers
292 provided by the toolchain. End users should prefer the documented, named
293 address space annotations for their platform, such as the
294 `OpenCL address spaces`_, ``__global__``, ``__local__``, or something else.
295
296The ``address_space`` attribute functions as a type qualifier that allows the
297programmer to specify the address space for a pointer or reference type.
298Qualified pointer types are considered distinct types for the purposes of
299overload resolution. The attribute takes a single, non-negative integer
300constant expression identifying the address space. For example:
301
302.. code-block:: c
303
304 int * __attribute__((address_space(1))) ptr;
305
306 void foo(__attribute__((address_space(2))) float *buf);
307
308
309Only one address space qualifier may be applied to a given pointer or reference
310type. Where address spaces are allowed (e.g., variables, parameters, return
311types) and what values are valid depends on the target and language mode.
312
313The meaning of each value is defined by the target; multiple address spaces are
314used in environments such as OpenCL, CUDA, HIP, and other GPU programming
315models to distinguish global, local, constant, and private memory. See for
316example the address spaces defined in the `NVPTX Usage Guide`_ and the
317`AMDGPU Usage Guide`_.
318
319.. _`NVPTX Usage Guide`: https://llvm.org/docs/NVPTXUsage.html#address-spaces
320.. _`AMDGPU Usage Guide`: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
321
322Address spaces may partially overlap or be entirely distinct. The compiler may
323reject attempts to convert between distinct, incompatible address spaces.
324Pointer width may vary between different address spaces, so some explicit casts
325may truncate.
326
327For more information, refer to `ISO TR18037`_, which covers embedded C language
328extensions. Section 5 covers named address spaces.
329
330.. _`ISO TR18037`: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip)reST";
331
332static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
333
334static const char AttrDoc_AlignMac68k[] = R"reST()reST";
335
336static const char AttrDoc_AlignNatural[] = R"reST()reST";
337
338static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
339declaration of a variable of pointer or reference type. It specifies that the
340pointer will point to, or the reference will bind to, only objects with at
341least the provided alignment. This alignment value must be some positive power
342of 2.
343
344 .. code-block:: c
345
346 typedef double * aligned_double_ptr __attribute__((align_value(64)));
347 void foo(double & x __attribute__((align_value(128))),
348 aligned_double_ptr y) { ... }
349
350If the pointer value does not have the specified alignment at runtime, the
351behavior of the program is undefined.)reST";
352
353static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
354
355static const char AttrDoc_AllocAlign[] = R"reST(Use ``__attribute__((alloc_align(<alignment>))`` on a function
356declaration to specify that the return value of the function (which must be a
357pointer type) is at least as aligned as the value of the indicated parameter. The
358parameter is given by its index in the list of formal parameters; the first
359parameter has index 1 unless the function is a C++ non-static member function,
360in which case the first parameter has index 2 to account for the implicit ``this``
361parameter.
362
363.. code-block:: c++
364
365 // The returned pointer has the alignment specified by the first parameter.
366 void *a(size_t align) __attribute__((alloc_align(1)));
367
368 // The returned pointer has the alignment specified by the second parameter.
369 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
370
371 // The returned pointer has the alignment specified by the second visible
372 // parameter, however it must be adjusted for the implicit 'this' parameter.
373 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
374
375Note that this attribute merely informs the compiler that a function always
376returns a sufficiently aligned pointer. It does not cause the compiler to
377emit code to enforce that alignment. The behavior is undefined if the returned
378pointer is not sufficiently aligned.)reST";
379
380static const char AttrDoc_AllocSize[] = R"reST(The ``alloc_size`` attribute can be placed on functions that return pointers in
381order to hint to the compiler how many bytes of memory will be available at the
382returned pointer. ``alloc_size`` takes one or two arguments.
383
384- ``alloc_size(N)`` implies that argument number N equals the number of
385 available bytes at the returned pointer.
386- ``alloc_size(N, M)`` implies that the product of argument number N and
387 argument number M equals the number of available bytes at the returned
388 pointer.
389
390Argument numbers are 1-based.
391
392An example of how to use ``alloc_size``
393
394.. code-block:: c
395
396 void *my_malloc(int a) __attribute__((alloc_size(1)));
397 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
398
399 int main() {
400 void *const p = my_malloc(100);
401 assert(__builtin_object_size(p, 0) == 100);
402 void *const a = my_calloc(20, 5);
403 assert(__builtin_object_size(a, 0) == 100);
404 }
405
406When ``-Walloc-size`` is enabled, this attribute allows the compiler to
407diagnose cases when the allocated memory is insufficient for the size of the
408type the returned pointer is cast to.
409
410.. code-block:: c
411
412 void *my_malloc(int a) __attribute__((alloc_size(1)));
413 void consumer_func(int *);
414
415 int main() {
416 int *ptr = my_malloc(sizeof(int)); // no warning
417 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
418 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
419 }
420
421.. Note:: This attribute works differently in clang than it does in GCC.
422 Specifically, clang will only trace ``const`` pointers (as above); we give up
423 on pointers that are not marked as ``const``. In the vast majority of cases,
424 this is unimportant, because LLVM has support for the ``alloc_size``
425 attribute. However, this may cause mildly unintuitive behavior when used with
426 other attributes, such as ``enable_if``.)reST";
427
428static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
429of ``nonallocating`` by the compiler.)reST";
430
431static const char AttrDoc_AlwaysDestroy[] = R"reST(The ``always_destroy`` attribute specifies that a variable with static or thread
432storage duration should have its exit-time destructor run. This attribute is the
433default unless clang was invoked with -fno-c++-static-destructors.
434
435If a variable is explicitly declared with this attribute, Clang will silence
436otherwise applicable ``-Wexit-time-destructors`` warnings.)reST";
437
438static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
439optimization level.
440
441``[[clang::always_inline]]`` spelling can be used as a statement attribute; other
442spellings of the attribute are not supported on statements. If a statement is
443marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts
444to inline those calls.
445
446.. code-block:: c
447
448 int example(void) {
449 int i;
450 [[clang::always_inline]] foo(); // attempts to inline foo
451 [[clang::always_inline]] i = bar(); // attempts to inline bar
452 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
453 }
454
455A declaration statement, which is a statement, is not a statement that can have an
456attribute associated with it (the attribute applies to the declaration, not the
457statement in that case). So this use case will not work:
458
459.. code-block:: c
460
461 int example(void) {
462 [[clang::always_inline]] int i = bar();
463 return i;
464 }
465
466This attribute does not guarantee that inline substitution actually occurs.
467
468<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
469has no effect; other optimization levels may only partially inline and result in a
470diagnostic.</ins>
471
472See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
473Attribute docs`_, and `the GCC Inline docs`_.
474
475.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
476.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
477.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html)reST";
478
479static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
480
481static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements,
482typically for use by static analysis tools that are not integrated into the
483core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools).
484It is a counterpart to the `annotate_type` attribute, which serves the same
485purpose, but for types.
486
487The attribute takes a mandatory string literal argument specifying the
488annotation category and an arbitrary number of optional arguments that provide
489additional information specific to the annotation category. The optional
490arguments must be constant expressions of arbitrary type.
491
492For example:
493
494.. code-block:: c++
495
496 [[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) {
497 [[clang::annotate("category3")]] if (val) {
498
499 }
500 })reST";
501
502static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
503analysis tools that are not integrated into the core Clang compiler (e.g.,
504Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
505`annotate` attribute, which serves the same purpose, but for declarations.
506
507The attribute takes a mandatory string literal argument specifying the
508annotation category and an arbitrary number of optional arguments that provide
509additional information specific to the annotation category. The optional
510arguments must be constant expressions of arbitrary type.
511
512For example:
513
514.. code-block:: c++
515
516 int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
517
518The attribute does not have any effect on the semantics of the type system,
519neither type checking rules, nor runtime semantics. In particular:
520
521- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types
522 ``T``.
523
524- It is not permissible for overloaded functions or template specializations
525 to differ merely by an ``annotate_type`` attribute.
526
527- The presence of an ``annotate_type`` attribute will not affect name
528 mangling.)reST";
529
530static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
531targets. This attribute may be attached to a function definition and instructs
532the backend to generate appropriate function entry/exit code so that it can be
533used directly as an interrupt service routine.
534
535Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
536and return using the ``IRET`` instruction. All registers in an interrupt handler are callee-saved.
537Exception handlers also have access to the error code pushed onto the stack by the processor,
538when applicable.
539
540An interrupt handler must take the following arguments:
541
542 .. code-block:: c
543
544 __attribute__ ((interrupt))
545 void f (struct stack_frame *frame) {
546 ...
547 }
548
549 Where ``struct stack_frame`` is a suitable struct matching the stack frame pushed by the
550 processor.
551
552An exception handler must take the following arguments:
553
554 .. code-block:: c
555
556 __attribute__ ((interrupt))
557 void g (struct stack_frame *frame, unsigned long code) {
558 ...
559 }
560
561 On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
562
563Exception handlers should only be used when an error code is pushed by the processor.
564Using the incorrect handler type will crash the system.
565
566Interrupt and exception handlers cannot be called by other functions and must have return type ``void``.
567
568Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
569attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
570non-GPR registers.)reST";
571
572static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
573caller-saved registers. That is, all registers are callee-saved except for
574registers used for passing parameters to the function or returning parameters
575from the function.
576The compiler saves and restores any modified registers that were not used for
577passing or returning arguments to the function.
578
579The user can call functions specified with the 'no_caller_saved_registers'
580attribute from an interrupt handler without saving and restoring all
581call-clobbered registers.
582
583Functions specified with the 'no_caller_saved_registers' attribute should only
584call other functions with the 'no_caller_saved_registers' attribute, or should be
585compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
586
587Note that 'no_caller_saved_registers' attribute is not a calling convention.
588In fact, it only overrides the decision of which registers should be saved by
589the caller, but not how the parameters are passed from the caller to the callee.
590
591For example:
592
593 .. code-block:: c
594
595 __attribute__ ((no_caller_saved_registers, fastcall))
596 void f (int arg1, int arg2) {
597 ...
598 }
599
600 In this case parameters 'arg1' and 'arg2' will be passed in registers.
601 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
602 register parameters. However, it will not assume any scratch registers and
603 should save and restore any modified registers except for ECX and EDX.)reST";
604
605static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
606indirect call / jmp, e.g. redirect control-flow to non-programmer
607intended bytes in the binary.
608X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
609Enforcement Technology (CET). IBT instruments ENDBR instructions used to
610specify valid targets of indirect call / jmp.
611The ``nocf_check`` attribute has two roles:
6121. Appertains to a function - do not add ENDBR instruction at the beginning of
613the function.
6142. Appertains to a function pointer - do not track the target function of this
615pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
616
617static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
618
619static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
620type_tag_idx)))`` on a function declaration to specify that the function
621accepts a type tag that determines the type of some other argument.
622
623This attribute is primarily useful for checking arguments of variadic functions
624(``pointer_with_type_tag`` can be used in most non-variadic cases).
625
626In the attribute prototype above:
627 * ``arg_kind`` is an identifier that should be used when annotating all
628 applicable type tags.
629 * ``arg_idx`` provides the position of a function argument. The expected type of
630 this function argument will be determined by the function argument specified
631 by ``type_tag_idx``. In the code example below, "3" means that the type of the
632 function's third argument will be determined by ``type_tag_idx``.
633 * ``type_tag_idx`` provides the position of a function argument. This function
634 argument will be a type tag. The type tag will determine the expected type of
635 the argument specified by ``arg_idx``. In the code example below, "2" means
636 that the type tag associated with the function's second argument should agree
637 with the type of the argument specified by ``arg_idx``.
638
639For example:
640
641.. code-block:: c++
642
643 int fcntl(int fd, int cmd, ...)
644 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
645 // The function's second argument will be a type tag; this type tag will
646 // determine the expected type of the function's third argument.)reST";
647
648static const char AttrDoc_ArmAgnostic[] = R"reST(The ``__arm_agnostic`` keyword applies to prototyped function types and
649affects the function's calling convention for a given state S. This
650attribute allows the user to describe a function that preserves S, without
651requiring the function to share S with its callers and without making
652the assumption that S exists.
653
654If a function has the ``__arm_agnostic(S)`` attribute and calls a function
655without this attribute, then the function's object code will contain code
656to preserve state S. Otherwise, the function's object code will be the same
657as if it did not have the attribute.
658
659The attribute takes string arguments to describe state S. The supported
660states are:
661
662* ``"sme_za_state"`` for state enabled by PSTATE.ZA, such as ZA and ZT0.
663
664The attribute ``__arm_agnostic("sme_za_state")`` cannot be used in conjunction
665with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
666``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
667such as "za" or "zt0".)reST";
668
669static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
670It allows the intrinsic functions to
671be declared using the names defined in ACLE, and still be recognized
672as clang builtins equivalent to the underlying name. For example,
673``arm_mve.h`` declares the function ``vaddq_u32`` with
674``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
675and similarly, one of the type-overloaded declarations of ``vaddq``
676will have the same attribute. This ensures that both functions are
677recognized as that clang builtin, and in the latter case, the choice
678of which builtin to identify the function as can be deferred until
679after overload resolution.
680
681This attribute can only be used to set up the aliases for certain Arm
682intrinsic functions; it is intended for use only inside ``arm_*.h``
683and is not a general mechanism for declaring arbitrary aliases for
684clang builtin functions.
685
686In order to avoid duplicating the attribute definitions for similar
687purpose for other architecture, there is a general form for the
688attribute `clang_builtin_alias`.)reST";
689
690static const char AttrDoc_ArmIn[] = R"reST(The ``__arm_in`` keyword applies to prototyped function types and specifies
691that the function shares a given state S with its caller. For ``__arm_in``, the
692function takes the state S as input and returns with the state S unchanged.
693
694The attribute takes string arguments to instruct the compiler which state
695is shared. The supported states for S are:
696
697* ``"za"`` for Matrix Storage (requires SME)
698
699The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
700``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
701
702static const char AttrDoc_ArmInOut[] = R"reST(The ``__arm_inout`` keyword applies to prototyped function types and specifies
703that the function shares a given state S with its caller. For ``__arm_inout``,
704the function takes the state S as input and returns new state for S.
705
706The attribute takes string arguments to instruct the compiler which state
707is shared. The supported states for S are:
708
709* ``"za"`` for Matrix Storage (requires SME)
710
711The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
712``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
713
714static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The ``__arm_locally_streaming`` keyword applies to function declarations
715and specifies that all the statements in the function are executed in
716streaming mode. This means that:
717
718* the function requires that the target processor implements the Scalable Matrix
719 Extension (SME).
720
721* the program automatically puts the machine into streaming mode before
722 executing the statements and automatically restores the previous mode
723 afterwards.
724
725Clang manages PSTATE.SM automatically; it is not the source code's
726responsibility to do this. For example, Clang will emit code to enable
727streaming mode at the start of the function, and disable streaming mode
728at the end of the function.)reST";
729
730static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
731MVE instruction set. It is used to define the vector types used by the MVE
732intrinsics.
733
734Its effect is to modify the behavior of a vector type with respect to function
735overloading. If a candidate function for overload resolution has a parameter
736type with this attribute, then the selection of that candidate function will be
737disallowed if the actual argument can only be converted via a lax vector
738conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
739intrinsics.
740
741.. code-block:: c++
742
743 void overloaded(uint16x8_t vector, uint16_t scalar);
744 void overloaded(int32x4_t vector, int32_t scalar);
745 uint16x8_t myVector;
746 uint16_t myScalar;
747
748 // myScalar is promoted to int32_t as a side effect of the addition,
749 // so if lax vector conversions are considered for myVector, then
750 // the two overloads are equally good (one argument conversion
751 // each). But if the vector has the __clang_arm_mve_strict_polymorphism
752 // attribute, only the uint16x8_t,uint16_t overload will match.
753 overloaded(myVector, myScalar + 1);
754
755However, this attribute does not prohibit lax vector conversions in contexts
756other than overloading.
757
758.. code-block:: c++
759
760 uint16x8_t function();
761
762 // This is still permitted with lax vector conversion enabled, even
763 // if the vector types have __clang_arm_mve_strict_polymorphism
764 int32x4_t result = function();)reST";
765
766static const char AttrDoc_ArmNew[] = R"reST(The ``__arm_new`` keyword applies to function declarations and specifies
767that the function will create a new scope for state S.
768
769The attribute takes string arguments to instruct the compiler for which state
770to create new scope. The supported states for S are:
771
772* ``"za"`` for Matrix Storage (requires SME)
773
774For state ``"za"``, this means that:
775
776* the function requires that the target processor implements the Scalable Matrix
777 Extension (SME).
778
779* the function will commit any lazily saved ZA data.
780
781* the function will create a new ZA context and enable PSTATE.ZA.
782
783* the function will disable PSTATE.ZA (by setting it to 0) before returning.
784
785For ``__arm_new("za")`` functions Clang will set up the ZA context automatically
786on entry to the function and disable it before returning. For example, if ZA is
787in a dormant state Clang will generate the code to commit a lazy-save and set up
788a new ZA state before executing user code.)reST";
789
790static const char AttrDoc_ArmOut[] = R"reST(The ``__arm_out`` keyword applies to prototyped function types and specifies
791that the function shares a given state S with its caller. For ``__arm_out``,
792the function ignores the incoming state for S and returns new state for S.
793
794The attribute takes string arguments to instruct the compiler which state
795is shared. The supported states for S are:
796
797* ``"za"`` for Matrix Storage (requires SME)
798
799The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
800``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
801
802static const char AttrDoc_ArmPreserves[] = R"reST(The ``__arm_preserves`` keyword applies to prototyped function types and
803specifies that the function does not read a given state S and returns
804with state S unchanged.
805
806The attribute takes string arguments to instruct the compiler which state
807is shared. The supported states for S are:
808
809* ``"za"`` for Matrix Storage (requires SME)
810
811The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
812``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
813
814static const char AttrDoc_ArmStreaming[] = R"reST(The ``__arm_streaming`` keyword applies to prototyped function types and specifies
815that the function has a "streaming interface". This means that:
816
817* the function requires that the processor implements the Scalable Matrix
818 Extension (SME).
819
820* the function must be entered in streaming mode (that is, with PSTATE.SM
821 set to 1)
822
823* the function must return in streaming mode
824
825Clang manages PSTATE.SM automatically; it is not the source code's
826responsibility to do this. For example, if a non-streaming
827function calls an ``__arm_streaming`` function, Clang generates code
828that switches into streaming mode before calling the function and
829switches back to non-streaming mode on return.)reST";
830
831static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The ``__arm_streaming_compatible`` keyword applies to prototyped function types and
832specifies that the function has a "streaming compatible interface". This
833means that:
834
835* the function may be entered in either non-streaming mode (PSTATE.SM=0) or
836 in streaming mode (PSTATE.SM=1).
837
838* the function must return in the same mode as it was entered.
839
840* the code executed in the function is compatible with either mode.
841
842Clang manages PSTATE.SM automatically; it is not the source code's
843responsibility to do this. Clang will ensure that the generated code in
844streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
845PSTATE.SM=1). For example, if an ``__arm_streaming_compatible`` function calls a
846non-streaming function, Clang generates code to temporarily switch out of streaming
847mode before calling the function and switch back to streaming-mode on return if
848``PSTATE.SM`` is ``1`` on entry of the caller. If ``PSTATE.SM`` is ``0`` on
849entry to the ``__arm_streaming_compatible`` function, the call will be executed
850without changing modes.)reST";
851
852static const char AttrDoc_Artificial[] = R"reST(The ``artificial`` attribute can be applied to an inline function. If such a
853function is inlined, the attribute indicates that debuggers should associate
854the resulting instructions with the call site, rather than with the
855corresponding line within the inlined callee.)reST";
856
857static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
858
859On some targets, all C symbols are prefixed by default with a single character,
860typically ``_``. This was done historically to distinguish them from symbols
861used by other languages. (This prefix is also added to the standard Itanium
862C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
863symbol name for a C++ variable declared as ``int cppvar;`` would be
864``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the
865symbol names specified by the ``__asm`` attribute; programmers wishing to match
866a C symbol name must compensate for this.
867
868For example, consider the following C code:
869
870.. code-block:: c
871
872 int var1 __asm("altvar") = 1; // "altvar" in symbol table.
873 int var2 = 1; // "_var2" in symbol table.
874
875 void func1(void) __asm("altfunc");
876 void func1(void) {} // "altfunc" in symbol table.
877 void func2(void) {} // "_func2" in symbol table.
878
879Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
880
881While it is possible to use this attribute to name a special symbol used
882internally by the compiler, such as an LLVM intrinsic, this is neither
883recommended nor supported and may cause the compiler to crash or miscompile.
884Users who wish to gain access to intrinsic behavior are strongly encouraged to
885request new builtin functions.)reST";
886
887static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
888the program if it is not held.)reST";
889
890static const char AttrDoc_AssumeAligned[] = R"reST(Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
891declaration to specify that the return value of the function (which must be a
892pointer type) has the specified offset, in bytes, from an address with the
893specified alignment. The offset is taken to be zero if omitted.
894
895.. code-block:: c++
896
897 // The returned pointer value has 32-byte alignment.
898 void *a() __attribute__((assume_aligned (32)));
899
900 // The returned pointer value is 4 bytes greater than an address having
901 // 32-byte alignment.
902 void *b() __attribute__((assume_aligned (32, 4)));
903
904Note that this attribute provides information to the compiler regarding a
905condition that the code already ensures is true. It does not cause the compiler
906to enforce the provided alignment assumption.)reST";
907
908static const char AttrDoc_Atomic[] = R"reST(The ``atomic`` attribute can be applied to *compound statements* to override or
909further specify the default atomic code-generation behavior, especially on
910targets such as AMDGPU. You can annotate compound statements with options
911to modify how atomic instructions inside that statement are emitted at the IR
912level.
913
914For details, see the documentation for `@atomic
915<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-controlling-atomic-code-generation>`_)reST";
916
917static const char AttrDoc_Availability[] = R"reST(The ``availability`` attribute can be placed on declarations to describe the
918lifecycle of that declaration relative to operating system versions. Consider
919the function declaration for a hypothetical function ``f``:
920
921.. code-block:: c++
922
923 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
924
925The availability attribute states that ``f`` was introduced in macOS 10.4,
926deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
927is used by Clang to determine when it is safe to use ``f``: for example, if
928Clang is instructed to compile code for macOS 10.5, a call to ``f()``
929succeeds. If Clang is instructed to compile code for macOS 10.6, the call
930succeeds but Clang emits a warning specifying that the function is deprecated.
931Finally, if Clang is instructed to compile code for macOS 10.7, the call
932fails because ``f()`` is no longer available.
933
934Clang is instructed to compile code for a minimum deployment version using
935the ``-target`` or ``-mtargetos`` command line arguments. For example,
936macOS 10.7 would be specified as ``-target x86_64-apple-macos10.7`` or
937``-mtargetos=macos10.7``. Variants like Mac Catalyst are specified as
938``-target arm64-apple-ios15.0-macabi`` or ``-mtargetos=ios15.0-macabi``
939
940The availability attribute is a comma-separated list starting with the
941platform name and then including clauses specifying important milestones in the
942declaration's lifetime (in any order) along with additional information. Those
943clauses can be:
944
945introduced=\ *version*
946 The first version in which this declaration was introduced.
947
948deprecated=\ *version*
949 The first version in which this declaration was deprecated, meaning that
950 users should migrate away from this API.
951
952obsoleted=\ *version*
953 The first version in which this declaration was obsoleted, meaning that it
954 was removed completely and can no longer be used.
955
956unavailable
957 This declaration is never available on this platform.
958
959message=\ *string-literal*
960 Additional message text that Clang will provide when emitting a warning or
961 error about use of a deprecated or obsoleted declaration. Useful to direct
962 users to replacement APIs.
963
964replacement=\ *string-literal*
965 Additional message text that Clang will use to provide Fix-It when emitting
966 a warning about use of a deprecated declaration. The Fix-It will replace
967 the deprecated declaration with the new declaration specified.
968
969environment=\ *identifier*
970 Target environment in which this declaration is available. If present,
971 the availability attribute applies only to targets with the same platform
972 and environment. The parameter is currently supported only in HLSL.
973
974Multiple availability attributes can be placed on a declaration, which may
975correspond to different platforms. For most platforms, the availability
976attribute with the platform corresponding to the target platform will be used;
977any others will be ignored. However, the availability for ``watchOS`` and
978``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
979Any explicit availability attributes for those platforms are still preferred over
980the implicitly inferred availability attributes. If no availability attribute
981specifies availability for the current target platform, the availability
982attributes are ignored. Supported platforms are:
983
984``iOS``
985``macOS``
986``tvOS``
987``watchOS``
988``iOSApplicationExtension``
989``macOSApplicationExtension``
990``tvOSApplicationExtension``
991``watchOSApplicationExtension``
992``macCatalyst``
993``macCatalystApplicationExtension``
994``visionOS``
995``visionOSApplicationExtension``
996``driverkit``
997``anyAppleOS``
998``swift``
999``android``
1000``fuchsia``
1001``ohos``
1002``zos``
1003``ShaderModel``
1004
1005Some platforms have alias names:
1006
1007``ios``
1008``macos``
1009``macosx (deprecated)``
1010``tvos``
1011``watchos``
1012``ios_app_extension``
1013``macos_app_extension``
1014``macosx_app_extension (deprecated)``
1015``tvos_app_extension``
1016``watchos_app_extension``
1017``maccatalyst``
1018``maccatalyst_app_extension``
1019``visionos``
1020``visionos_app_extension``
1021``anyappleos``
1022``shadermodel``
1023
1024Supported environment names for the ShaderModel platform:
1025
1026``pixel``
1027``vertex``
1028``geometry``
1029``hull``
1030``domain``
1031``compute``
1032``raygeneration``
1033``intersection``
1034``anyhit``
1035``closesthit``
1036``miss``
1037``callable``
1038``mesh``
1039``amplification``
1040``library``
1041
1042The special platform ``anyAppleOS`` (alias: ``anyappleos``) is a shorthand that
1043applies the availability attribute to all Apple Darwin platforms. An explicit
1044platform-specific availability attribute takes precedence over an ``anyAppleOS``
1045attribute for that platform. Versions specified with ``anyAppleOS`` must be at
1046least 26.0, which is the first OS release where all supported Apple platforms
1047share a unified version number.
1048
1049A declaration can typically be used even when deploying back to a platform
1050version prior to when the declaration was introduced. When this happens, the
1051declaration is `weakly linked
1052<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1053as if the ``weak_import`` attribute were added to the declaration. A
1054weakly-linked declaration may or may not be present a run-time, and a program
1055can determine whether the declaration is present by checking whether the
1056address of that declaration is non-NULL.
1057
1058The flag ``strict`` disallows using API when deploying back to a
1059platform version prior to when the declaration was introduced. An
1060attempt to use such API before its introduction causes a hard error.
1061Weakly-linking is almost always a better API choice, since it allows
1062users to query availability at runtime.
1063
1064If there are multiple declarations of the same entity, the availability
1065attributes must either match on a per-platform basis or later
1066declarations must not have availability attributes for that
1067platform. For example:
1068
1069.. code-block:: c
1070
1071 void g(void) __attribute__((availability(macos,introduced=10.4)));
1072 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1073 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1074 void g(void); // okay, inherits both macos and ios availability from above.
1075 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1076
1077When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1078
1079.. code-block:: objc
1080
1081 @interface A
1082 - (id)method __attribute__((availability(macos,introduced=10.4)));
1083 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1084 @end
1085
1086 @interface B : A
1087 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1088 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1089 @end
1090
1091Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1092``<os/availability.h>`` can simplify the spelling:
1093
1094.. code-block:: objc
1095
1096 @interface A
1097 - (id)method API_AVAILABLE(macos(10.11)));
1098 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1099 @end
1100
1101Availability attributes can also be applied using a ``#pragma clang attribute``.
1102Any explicit availability attribute whose platform corresponds to the target
1103platform is applied to a declaration regardless of the availability attributes
1104specified in the pragma. For example, in the code below,
1105``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1106attribute that is specified with the declaration, whereas
1107``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1108attribute that is applied by the pragma.
1109
1110.. code-block:: c
1111
1112 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1113 void getsThePragmaAvailabilityAttribute(void);
1114 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1115 #pragma clang attribute pop
1116
1117For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1118be implicitly inferred from an ``iOS`` availability attribute, the logic is
1119slightly more complex. The explicit and the pragma-applied availability
1120attributes whose platform corresponds to the target platform are applied as
1121described in the previous paragraph. However, the implicitly inferred attributes
1122are applied to a declaration only when there is no explicit or pragma-applied
1123availability attribute whose platform corresponds to the target platform. For
1124example, the function below will receive the ``tvOS`` availability from the
1125pragma rather than using the inferred ``iOS`` availability from the declaration:
1126
1127.. code-block:: c
1128
1129 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1130 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1131 #pragma clang attribute pop
1132
1133The compiler is also able to apply implicitly inferred attributes from a pragma
1134as well. For example, when targeting ``tvOS``, the function below will receive
1135a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1136availability attribute applied by the pragma:
1137
1138.. code-block:: c
1139
1140 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1141 void infersTVOSAvailabilityFromPragma(void);
1142 #pragma clang attribute pop
1143
1144The implicit attributes that are inferred from explicitly specified attributes
1145whose platform corresponds to the target platform are applied to the declaration
1146even if there is an availability attribute that can be inferred from a pragma.
1147For example, the function below will receive the ``tvOS, introduced=11.0``
1148availability that is inferred from the attribute on the declaration rather than
1149inferring availability from the pragma:
1150
1151.. code-block:: c
1152
1153 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1154 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1155 __attribute__((availability(iOS,introduced=11.0)));
1156 #pragma clang attribute pop
1157
1158Also see the documentation for `@available
1159<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_)reST";
1160
1161static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1162
1163static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1164It is assumed that inlined implementation uses less caller saved registers,
1165than a regular function.
1166Specifically, the following registers are likely to be preserved:
1167- ``R0`` if function return value is ``void``;
1168- ``R2-R5` if function takes 1 argument;
1169- ``R3-R5` if function takes 2 arguments;
1170- ``R4-R5` if function takes 3 arguments;
1171- ``R5`` if function takes 4 arguments;
1172
1173For such functions Clang generates code pattern that allows BPF JIT
1174to recognize and remove unnecessary spills and fills of the preserved
1175registers.)reST";
1176
1177static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the ``__attribute__((preserve_access_index))``
1178attribute for the BPF target. This attribute may be attached to a
1179struct or union declaration, where if -g is specified, it enables
1180preserving struct or union member access debuginfo indices of this
1181struct or union, similar to clang ``__builtin_preserve_access_index()``.)reST";
1182
1183static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the ``__attribute__((preserve_static_offset))``
1184attribute for the BPF target. This attribute may be attached to a
1185struct or union declaration. Reading or writing fields of types having
1186such annotation is guaranteed to generate LDX/ST/STX instruction with
1187offset corresponding to the field.
1188
1189For example:
1190
1191.. code-block:: c
1192
1193 struct foo {
1194 int a;
1195 int b;
1196 };
1197
1198 struct bar {
1199 int a;
1200 struct foo b;
1201 } __attribute__((preserve_static_offset));
1202
1203 void buz(struct bar *g) {
1204 g->b.a = 42;
1205 }
1206
1207The assignment to ``g``'s field would produce an ST instruction with
1208offset 8: ``*(u32)(r1 + 8) = 42;``.
1209
1210Without this attribute generated instructions might be different,
1211depending on optimizations behavior. E.g. the example above could be
1212rewritten as ``r1 += 8; *(u32)(r1 + 0) = 42;``.)reST";
1213
1214static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
1215all targets. This attribute may be attached to a struct/union, struct/union
1216field, function, function parameter, variable or typedef declaration. If -g is
1217specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
1218dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
1219section too.)reST";
1220
1221static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for
1222all targets. It only has effect when ``-g`` is specified on the command line.
1223
1224The attribute can be applied to a pointer type, in which case the tag is
1225associated with the pointee type, e.g.:
1226
1227.. code-block:: c
1228
1229 int __attribute__((btf_type_tag("tag"))) *p;
1230
1231It can also be applied to the underlying type of a typedef, in which case the
1232tag follows the typedef down to its base type, e.g.:
1233
1234.. code-block:: c
1235
1236 typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1237
1238The following is the corresponding btf:
1239
1240.. code-block::
1241
1242 ...
1243 [2] TYPE_TAG 'tag' type_id=4
1244 [3] TYPEDEF 'foo_t' type_id=2
1245 [4] STRUCT 'foo' size=4 vlen=1
1246 'c' type_id=5 bits_offset=0
1247 [5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
1248 ...
1249
1250The attribute is currently silently ignored in any other position (note: this
1251scenario may be diagnosed in the future).
1252
1253The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the
1254types used in variable declarations, function declarations, or typedef
1255declarations.
1256
1257For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF
1258section.)reST";
1259
1260static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of ``nonblocking``
1261by the compiler.)reST";
1262
1263static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1264
1265static const char AttrDoc_Builtin[] = R"reST()reST";
1266
1267static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1268It allows the C intrinsic functions to be declared using the names defined
1269in target builtins, and still be recognized as clang builtins equivalent to the
1270underlying name. For example, ``riscv_vector.h`` declares the function ``vadd``
1271with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``.
1272This ensures that both functions are recognized as that clang builtin,
1273and in the latter case, the choice of which builtin to identify the
1274function as can be deferred until after overload resolution.
1275
1276This attribute can only be used to set up the aliases for certain ARM/RISC-V
1277C intrinsic functions; it is intended for use only inside ``arm_*.h`` and
1278``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases
1279for clang builtin functions.)reST";
1280
1281static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as ``_Noreturn`` shall not return to its caller. The
1282compiler will generate a diagnostic for a function declared as ``_Noreturn``
1283that appears to be capable of returning to its caller. Despite being a type
1284specifier, the ``_Noreturn`` attribute cannot be specified on a function
1285pointer type.)reST";
1286
1287static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1288
1289static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1290
1291static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1292(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1293convention (e.g. functions starting with "get" are assumed to return at
1294``+0``).
1295
1296It can be overridden using a family of the following attributes. In
1297Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1298a function communicates that the object is returned at ``+1``, and the caller
1299is responsible for freeing it.
1300Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1301specifies that the object is returned at ``+0`` and the ownership remains with
1302the callee.
1303The annotation ``__attribute__((ns_consumes_self))`` specifies that
1304the Objective-C method call consumes the reference to ``self``, e.g. by
1305attaching it to a supplied parameter.
1306Additionally, parameters can have an annotation
1307``__attribute__((ns_consumed))``, which specifies that passing an owned object
1308as that parameter effectively transfers the ownership, and the caller is no
1309longer responsible for it.
1310These attributes affect code generation when interacting with ARC code, and
1311they are used by the Clang Static Analyzer.
1312
1313In C programs using CoreFoundation, a similar set of attributes:
1314``__attribute__((cf_returns_not_retained))``,
1315``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1316have the same respective semantics when applied to CoreFoundation objects.
1317These attributes affect code generation when interacting with ARC code, and
1318they are used by the Clang Static Analyzer.
1319
1320Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1321the same attribute family is present:
1322``__attribute__((os_returns_not_retained))``,
1323``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1324with the same respective semantics.
1325Similar to ``__attribute__((ns_consumes_self))``,
1326``__attribute__((os_consumes_this))`` specifies that the method call consumes
1327the reference to "this" (e.g., when attaching it to a different object supplied
1328as a parameter).
1329Out parameters (parameters the function is meant to write into,
1330either via pointers-to-pointers or references-to-pointers)
1331may be annotated with ``__attribute__((os_returns_retained))``
1332or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1333written into the out parameter should (or respectively should not) be released
1334after use.
1335Since often out parameters may or may not be written depending on the exit
1336code of the function,
1337annotations ``__attribute__((os_returns_retained_on_zero))``
1338and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1339an out parameter at ``+1`` is written if and only if the function returns a zero
1340(respectively non-zero) error code.
1341Observe that return-code-dependent out parameter annotations are only
1342available for retained out parameters, as non-retained object do not have to be
1343released by the callee.
1344These attributes are only used by the Clang Static Analyzer.
1345
1346The family of attributes ``X_returns_X_retained`` can be added to functions,
1347C++ methods, and Objective-C methods and properties.
1348Attributes ``X_consumed`` can be added to parameters of methods, functions,
1349and Objective-C methods.)reST";
1350
1351static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
1352attribute. This directs the compiler to not insert any CFG checks for the entire
1353function. This approach is typically used only sparingly in specific situations
1354where the programmer has manually inserted "CFG-equivalent" protection. The
1355programmer knows that they are calling through some read-only function table
1356whose address is obtained through read-only memory references and for which the
1357index is masked to the function table limit. This approach may also be applied
1358to small wrapper functions that are not inlined and that do nothing more than
1359make a call through a function pointer. Since incorrect usage of this directive
1360can compromise the security of CFG, the programmer must be very careful using
1361the directive. Typically, this usage is limited to very small functions that
1362only call one function.
1363
1364`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1365
1366static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
1367make the function's CFI jump table canonical. See :ref:`the CFI documentation
1368<cfi-canonical-jump-tables>` for more details.)reST";
1369
1370static const char AttrDoc_CFISalt[] = R"reST(The ``cfi_salt`` attribute specifies a string literal that is used as a salt
1371for Control-Flow Integrity (CFI) checks to distinguish between functions with
1372the same type signature. This attribute can be applied to function declarations,
1373function definitions, and function pointer typedefs.
1374
1375The attribute prevents function pointers from being replaced with pointers to
1376functions that have a compatible type, which can be a CFI bypass vector.
1377
1378**Syntax:**
1379
1380* GNU-style: ``__attribute__((cfi_salt("<salt_string>")))``
1381* C++11-style: ``[[clang::cfi_salt("<salt_string>")]]``
1382
1383**Usage:**
1384
1385The attribute takes a single string literal argument that serves as the salt.
1386Functions or function types with different salt values will have different CFI
1387hashes, even if they have identical type signatures.
1388
1389**Motivation:**
1390
1391In large codebases like the Linux kernel, there are often hundreds of functions
1392with identical type signatures that are called indirectly:
1393
1394.. code-block::
1395
1396 1662 functions with void (*)(void)
1397 1179 functions with int (*)(void)
1398 ...
1399
1400By salting the CFI hashes, you can make CFI more robust by ensuring that
1401functions intended for different purposes have distinct CFI identities.
1402
1403**Type Compatibility:**
1404
1405* Functions with different salt values are considered to have incompatible types
1406* Function pointers with different salt values cannot be assigned to each other
1407* All declarations of the same function must use the same salt value
1408
1409**Example:**
1410
1411.. code-block:: c
1412
1413 // Header file - define convenience macros
1414 #define __cfi_salt(s) __attribute__((cfi_salt(s)))
1415
1416 // Typedef for regular function pointers
1417 typedef int (*fptr_t)(void);
1418
1419 // Typedef for salted function pointers
1420 typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1421
1422 struct widget_ops {
1423 fptr_t init; // Regular CFI
1424 fptr_salted_t exec; // Salted CFI
1425 fptr_t cleanup; // Regular CFI
1426 };
1427
1428 // Function implementations
1429 static int widget_init(void) { return 0; }
1430 static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1431 static int widget_cleanup(void) { return 0; }
1432
1433 static struct widget_ops ops = {
1434 .init = widget_init, // OK - compatible types
1435 .exec = widget_exec, // OK - both use "pepper" salt
1436 .cleanup = widget_cleanup // OK - compatible types
1437 };
1438
1439 // Using C++11 attribute syntax
1440 void secure_callback(void) [[clang::cfi_salt("secure")]];
1441
1442 // This would cause a compilation error:
1443 // fptr_t bad_ptr = widget_exec; // Error: incompatible types
1444
1445**Notes:**
1446
1447* The salt string can contain non-NULL ASCII characters, including spaces and
1448 quotes
1449* This attribute only applies to function types; using it on non-function
1450 types will generate a warning
1451* All declarations and definitions of the same function must use identical
1452 salt values
1453* The attribute affects type compatibility during compilation and CFI hash
1454 generation during code generation)reST";
1455
1456static const char AttrDoc_CFIUncheckedCallee[] = R"reST(``cfi_unchecked_callee`` is a function type attribute which prevents the compiler from instrumenting
1457`Control Flow Integrity <https://clang.llvm.org/docs/ControlFlowIntegrity.html>`_ checks on indirect
1458function calls. This also includes control flow checks added by
1459`-fsanitize=function <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks>`.
1460Specifically, the attribute has the following semantics:
1461
14621. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1463 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1464 on pointers to function types having this attribute. It does not prevent all indirect function calls
1465 for a given type from being checked.
14662. All direct references to a function whose type has this attribute will always reference the
1467 function definition rather than an entry in the CFI jump table.
14683. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1469 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1470 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1471 direct references to a function with a ``cfi_unchecked_callee`` attribute will still reference the
1472 function definition rather than the CFI jump table.
1473
1474.. code-block:: c
1475
1476 #define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1477
1478 void no_cfi() CFI_UNCHECKED_CALLEE {}
1479
1480 void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1481 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1482 // its jump table entry.
1483
1484 void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1485 func(); // CFI will not instrument this indirect call.
1486
1487 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1488
1489 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1490 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1491 // fail because the reference will be to the function definition rather than the CFI jump
1492 // table entry.
1493 }
1494
1495This attribute can only be applied on functions or member functions. This attribute can be a good
1496alternative to ``no_sanitize("cfi")`` if you only want to disable innstrumentation for specific indirect
1497calls rather than applying ``no_sanitize("cfi")`` on the whole function containing indirect call. Note
1498that ``cfi_unchecked_attribute`` is a type attribute doesn't disable CFI instrumentation on a function
1499body.)reST";
1500
1501static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1502(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1503convention (e.g. functions starting with "get" are assumed to return at
1504``+0``).
1505
1506It can be overridden using a family of the following attributes. In
1507Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1508a function communicates that the object is returned at ``+1``, and the caller
1509is responsible for freeing it.
1510Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1511specifies that the object is returned at ``+0`` and the ownership remains with
1512the callee.
1513The annotation ``__attribute__((ns_consumes_self))`` specifies that
1514the Objective-C method call consumes the reference to ``self``, e.g. by
1515attaching it to a supplied parameter.
1516Additionally, parameters can have an annotation
1517``__attribute__((ns_consumed))``, which specifies that passing an owned object
1518as that parameter effectively transfers the ownership, and the caller is no
1519longer responsible for it.
1520These attributes affect code generation when interacting with ARC code, and
1521they are used by the Clang Static Analyzer.
1522
1523In C programs using CoreFoundation, a similar set of attributes:
1524``__attribute__((cf_returns_not_retained))``,
1525``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1526have the same respective semantics when applied to CoreFoundation objects.
1527These attributes affect code generation when interacting with ARC code, and
1528they are used by the Clang Static Analyzer.
1529
1530Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1531the same attribute family is present:
1532``__attribute__((os_returns_not_retained))``,
1533``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1534with the same respective semantics.
1535Similar to ``__attribute__((ns_consumes_self))``,
1536``__attribute__((os_consumes_this))`` specifies that the method call consumes
1537the reference to "this" (e.g., when attaching it to a different object supplied
1538as a parameter).
1539Out parameters (parameters the function is meant to write into,
1540either via pointers-to-pointers or references-to-pointers)
1541may be annotated with ``__attribute__((os_returns_retained))``
1542or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1543written into the out parameter should (or respectively should not) be released
1544after use.
1545Since often out parameters may or may not be written depending on the exit
1546code of the function,
1547annotations ``__attribute__((os_returns_retained_on_zero))``
1548and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1549an out parameter at ``+1`` is written if and only if the function returns a zero
1550(respectively non-zero) error code.
1551Observe that return-code-dependent out parameter annotations are only
1552available for retained out parameters, as non-retained object do not have to be
1553released by the callee.
1554These attributes are only used by the Clang Static Analyzer.
1555
1556The family of attributes ``X_returns_X_retained`` can be added to functions,
1557C++ methods, and Objective-C methods and properties.
1558Attributes ``X_consumed`` can be added to parameters of methods, functions,
1559and Objective-C methods.)reST";
1560
1561static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1562(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1563convention (e.g. functions starting with "get" are assumed to return at
1564``+0``).
1565
1566It can be overridden using a family of the following attributes. In
1567Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1568a function communicates that the object is returned at ``+1``, and the caller
1569is responsible for freeing it.
1570Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1571specifies that the object is returned at ``+0`` and the ownership remains with
1572the callee.
1573The annotation ``__attribute__((ns_consumes_self))`` specifies that
1574the Objective-C method call consumes the reference to ``self``, e.g. by
1575attaching it to a supplied parameter.
1576Additionally, parameters can have an annotation
1577``__attribute__((ns_consumed))``, which specifies that passing an owned object
1578as that parameter effectively transfers the ownership, and the caller is no
1579longer responsible for it.
1580These attributes affect code generation when interacting with ARC code, and
1581they are used by the Clang Static Analyzer.
1582
1583In C programs using CoreFoundation, a similar set of attributes:
1584``__attribute__((cf_returns_not_retained))``,
1585``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1586have the same respective semantics when applied to CoreFoundation objects.
1587These attributes affect code generation when interacting with ARC code, and
1588they are used by the Clang Static Analyzer.
1589
1590Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1591the same attribute family is present:
1592``__attribute__((os_returns_not_retained))``,
1593``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1594with the same respective semantics.
1595Similar to ``__attribute__((ns_consumes_self))``,
1596``__attribute__((os_consumes_this))`` specifies that the method call consumes
1597the reference to "this" (e.g., when attaching it to a different object supplied
1598as a parameter).
1599Out parameters (parameters the function is meant to write into,
1600either via pointers-to-pointers or references-to-pointers)
1601may be annotated with ``__attribute__((os_returns_retained))``
1602or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1603written into the out parameter should (or respectively should not) be released
1604after use.
1605Since often out parameters may or may not be written depending on the exit
1606code of the function,
1607annotations ``__attribute__((os_returns_retained_on_zero))``
1608and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1609an out parameter at ``+1`` is written if and only if the function returns a zero
1610(respectively non-zero) error code.
1611Observe that return-code-dependent out parameter annotations are only
1612available for retained out parameters, as non-retained object do not have to be
1613released by the callee.
1614These attributes are only used by the Clang Static Analyzer.
1615
1616The family of attributes ``X_returns_X_retained`` can be added to functions,
1617C++ methods, and Objective-C methods and properties.
1618Attributes ``X_consumed`` can be added to parameters of methods, functions,
1619and Objective-C methods.)reST";
1620
1621static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1622
1623static const char AttrDoc_CPUDispatch[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1624resolve multiversioned functions. This form of multiversioning provides a
1625mechanism for declaring versions across translation units and manually
1626specifying the resolved function list. A specified CPU defines a set of minimum
1627features that are required for the function to be called. The result of this is
1628that future processors execute the most restrictive version of the function the
1629new processor can execute.
1630
1631In addition, unlike the ICC implementation of this feature, the selection of the
1632version does not consider the manufacturer or microarchitecture of the processor.
1633It tests solely the list of features that are both supported by the specified
1634processor and present in the compiler-rt library. This can be surprising at times,
1635as the runtime processor may be from a completely different manufacturer, as long
1636as it supports the same feature set.
1637
1638This can additionally be surprising, as some processors are indistringuishable from
1639others based on the list of testable features. When this happens, the variant
1640is selected in an unspecified manner.
1641
1642Function versions are defined with ``cpu_specific``, which takes one or more CPU
1643names as a parameter. For example:
1644
1645.. code-block:: c
1646
1647 // Declares and defines the ivybridge version of single_cpu.
1648 __attribute__((cpu_specific(ivybridge)))
1649 void single_cpu(void){}
1650
1651 // Declares and defines the atom version of single_cpu.
1652 __attribute__((cpu_specific(atom)))
1653 void single_cpu(void){}
1654
1655 // Declares and defines both the ivybridge and atom version of multi_cpu.
1656 __attribute__((cpu_specific(ivybridge, atom)))
1657 void multi_cpu(void){}
1658
1659A dispatching (or resolving) function can be declared anywhere in a project's
1660source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1661as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1662are not expected to be defined, only declared. If such a marked function has a
1663definition, any side effects of the function are ignored; trivial function
1664bodies are permissible for ICC compatibility.
1665
1666.. code-block:: c
1667
1668 // Creates a resolver for single_cpu above.
1669 __attribute__((cpu_dispatch(ivybridge, atom)))
1670 void single_cpu(void){}
1671
1672 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1673 // translation unit.
1674 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1675 void multi_cpu(void){}
1676
1677Note that it is possible to have a resolving function that dispatches based on
1678more or fewer options than are present in the program. Specifying fewer will
1679result in the omitted options not being considered during resolution. Specifying
1680a version for resolution that isn't defined in the program will result in a
1681linking failure.
1682
1683It is also possible to specify a CPU name of ``generic`` which will be resolved
1684if the executing processor doesn't satisfy the features required in the CPU
1685name. The behavior of a program executing on a processor that doesn't satisfy
1686any option of a multiversioned function is undefined.)reST";
1687
1688static const char AttrDoc_CPUSpecific[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1689resolve multiversioned functions. This form of multiversioning provides a
1690mechanism for declaring versions across translation units and manually
1691specifying the resolved function list. A specified CPU defines a set of minimum
1692features that are required for the function to be called. The result of this is
1693that future processors execute the most restrictive version of the function the
1694new processor can execute.
1695
1696In addition, unlike the ICC implementation of this feature, the selection of the
1697version does not consider the manufacturer or microarchitecture of the processor.
1698It tests solely the list of features that are both supported by the specified
1699processor and present in the compiler-rt library. This can be surprising at times,
1700as the runtime processor may be from a completely different manufacturer, as long
1701as it supports the same feature set.
1702
1703This can additionally be surprising, as some processors are indistringuishable from
1704others based on the list of testable features. When this happens, the variant
1705is selected in an unspecified manner.
1706
1707Function versions are defined with ``cpu_specific``, which takes one or more CPU
1708names as a parameter. For example:
1709
1710.. code-block:: c
1711
1712 // Declares and defines the ivybridge version of single_cpu.
1713 __attribute__((cpu_specific(ivybridge)))
1714 void single_cpu(void){}
1715
1716 // Declares and defines the atom version of single_cpu.
1717 __attribute__((cpu_specific(atom)))
1718 void single_cpu(void){}
1719
1720 // Declares and defines both the ivybridge and atom version of multi_cpu.
1721 __attribute__((cpu_specific(ivybridge, atom)))
1722 void multi_cpu(void){}
1723
1724A dispatching (or resolving) function can be declared anywhere in a project's
1725source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1726as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1727are not expected to be defined, only declared. If such a marked function has a
1728definition, any side effects of the function are ignored; trivial function
1729bodies are permissible for ICC compatibility.
1730
1731.. code-block:: c
1732
1733 // Creates a resolver for single_cpu above.
1734 __attribute__((cpu_dispatch(ivybridge, atom)))
1735 void single_cpu(void){}
1736
1737 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1738 // translation unit.
1739 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1740 void multi_cpu(void){}
1741
1742Note that it is possible to have a resolving function that dispatches based on
1743more or fewer options than are present in the program. Specifying fewer will
1744result in the omitted options not being considered during resolution. Specifying
1745a version for resolution that isn't defined in the program will result in a
1746linking failure.
1747
1748It is also possible to specify a CPU name of ``generic`` which will be resolved
1749if the executing processor doesn't satisfy the features required in the CPU
1750name. The behavior of a program executing on a processor that doesn't satisfy
1751any option of a multiversioned function is undefined.)reST";
1752
1753static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the ``cluster_dims`` attribute, conventionally exposed as the
1754``__cluster_dims__`` macro, can be applied to a kernel function to set the dimensions of a
1755thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1756``__cluster_dims__`` defines the cluster size as ``(X, Y, Z)``, where each value is the number
1757of thread blocks in that dimension. The ``cluster_dims`` and `no_cluster`` attributes are
1758mutually exclusive.
1759
1760.. code::
1761
1762 __global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1763 ...
1764 })reST";
1765
1766static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1767
1768static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1769
1770static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The ``device_builtin_surface_type`` attribute can be applied to a class
1771template when declaring the surface reference. A surface reference variable
1772could be accessed on the host side and, on the device side, might be translated
1773into an internal surface object, which is established through surface bind and
1774unbind runtime APIs.)reST";
1775
1776static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The ``device_builtin_texture_type`` attribute can be applied to a class
1777template when declaring the texture reference. A texture reference variable
1778could be accessed on the host side and, on the device side, might be translated
1779into an internal texture object, which is established through texture bind and
1780unbind runtime APIs.)reST";
1781
1782static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1783
1784static const char AttrDoc_CUDAGridConstant[] = R"reST(The ``__grid_constant__`` attribute can be applied to a ``const``-qualified kernel
1785function argument and allows compiler to take the address of that argument without
1786making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1787with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1788
1789static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1790
1791static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1792
1793static const char AttrDoc_CUDALaunchBounds[] = R"reST(No documentation.)reST";
1794
1795static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1796at runtime, even without being annotated with ``__cluster_dims__``. The LLVM/Clang-exclusive
1797``no_cluster`` attribute, conventionally exposed as the ``__no_cluster__`` macro, can be applied to
1798a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1799compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1800without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1801kernel annotated with ``__no_cluster__`` if the cluster feature is enabled at runtime.
1802The ``cluster_dims`` and ``no_cluster`` attributes are mutually exclusive.
1803
1804.. code::
1805
1806 __global__ __no_cluster__ void kernel(...) {
1807 ...
1808 })reST";
1809
1810static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1811
1812static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as ``[[noreturn]]`` shall not return to its caller. The
1813compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
1814that appears to be capable of returning to its caller.
1815
1816The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code
1817migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``.)reST";
1818
1819static const char AttrDoc_CXXAssume[] = R"reST(The ``assume`` attribute is used to indicate to the optimizer that a
1820certain condition is assumed to be true at a certain point in the
1821program. If this condition is violated at runtime, the behavior is
1822undefined. ``assume`` can only be applied to a null statement.
1823
1824Different optimisers are likely to react differently to the presence of
1825this attribute; in some cases, adding ``assume`` may affect performance
1826negatively. It should be used with parsimony and care.
1827
1828Example:
1829
1830.. code-block:: c++
1831
1832 int f(int x, int y) {
1833 [[assume(x == 27)]];
1834 [[assume(x == y)]];
1835 return y + 1; // May be optimised to `return 28`.
1836 })reST";
1837
1838static const char AttrDoc_CallableWhen[] = R"reST(Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1839may be called in. Valid states are unconsumed, consumed, or unknown. Each
1840argument to this attribute must be a quoted string. E.g.:
1841
1842``__attribute__((callable_when("unconsumed", "unknown")))``)reST";
1843
1844static const char AttrDoc_Callback[] = R"reST(The ``callback`` attribute specifies that the annotated function may invoke the
1845specified callback zero or more times. The callback, as well as the passed
1846arguments, are identified by their parameter name or position (starting with
18471!) in the annotated function. The first position in the attribute identifies
1848the callback callee, the following positions declare describe its arguments.
1849The callback callee is required to be callable with the number, and order, of
1850the specified arguments. The index ``0``, or the identifier ``this``, is used to
1851represent an implicit "this" pointer in class methods. If there is no implicit
1852"this" pointer it shall not be referenced. The index '-1', or the name "__",
1853represents an unknown callback callee argument. This can be a value which is
1854not present in the declared parameter list, or one that is, but is potentially
1855inspected, captured, or modified. Parameter names and indices can be mixed in
1856the callback attribute.
1857
1858The ``callback`` attribute, which is directly translated to ``callback``
1859metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
1860connection between the call to the annotated function and the callback callee.
1861This can enable interprocedural optimizations which were otherwise impossible.
1862If a function parameter is mentioned in the ``callback`` attribute, through its
1863position, it is undefined if that parameter is used for anything other than the
1864actual callback. Inspected, captured, or modified parameters shall not be
1865listed in the ``callback`` metadata.
1866
1867Example encodings for the callback performed by ``pthread_create`` are shown
1868below. The explicit attribute annotation indicates that the third parameter
1869(``start_routine``) is called zero or more times by the ``pthread_create`` function,
1870and that the fourth parameter (``arg``) is passed along. Note that the callback
1871behavior of ``pthread_create`` is automatically recognized by Clang. In addition,
1872the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for
1873``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also
1874automatically recognized as broker functions. Further functions might be added
1875in the future.
1876
1877 .. code-block:: c
1878
1879 __attribute__((callback (start_routine, arg)))
1880 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1881 void *(*start_routine) (void *), void *arg);
1882
1883 __attribute__((callback (3, 4)))
1884 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1885 void *(*start_routine) (void *), void *arg);)reST";
1886
1887static const char AttrDoc_CalledOnce[] = R"reST(The ``called_once`` attribute specifies that the annotated function or method
1888parameter is invoked exactly once on all execution paths. It only applies
1889to parameters with function-like types, i.e. function pointers or blocks. This
1890concept is particularly useful for asynchronous programs.
1891
1892Clang implements a check for ``called_once`` parameters,
1893``-Wcalled-once-parameter``. It is on by default and finds the following
1894violations:
1895
1896* Parameter is not called at all.
1897
1898* Parameter is called more than once.
1899
1900* Parameter is not called on one of the execution paths.
1901
1902In the latter case, Clang pinpoints the path where parameter is not invoked
1903by showing the control-flow statement where the path diverges.
1904
1905.. code-block:: objc
1906
1907 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1908 if (somePredicate()) {
1909 ...
1910 callback();
1911 } else {
1912 callback(); // OK: callback is called on every path
1913 }
1914 }
1915
1916 void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1917 if (somePredicate()) {
1918 ...
1919 callback(); // note: previous call is here
1920 }
1921 callback(); // warning: callback is called twice
1922 }
1923
1924 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1925 if (somePredicate()) { // warning: callback is not called when condition is false
1926 ...
1927 callback();
1928 }
1929 }
1930
1931This attribute is useful for API developers who want to double-check if they
1932implemented their method correctly.)reST";
1933
1934static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
1935
1936static const char AttrDoc_CapturedRecord[] = R"reST()reST";
1937
1938static const char AttrDoc_CarriesDependency[] = R"reST(The ``carries_dependency`` attribute specifies dependency propagation into and
1939out of functions.
1940
1941When specified on a function or Objective-C method, the ``carries_dependency``
1942attribute means that the return value carries a dependency out of the function,
1943so that the implementation need not constrain ordering upon return from that
1944function. Implementations of the function and its caller may choose to preserve
1945dependencies instead of emitting memory ordering instructions such as fences.
1946
1947Note, this attribute does not change the meaning of the program, but may result
1948in generation of more efficient code.)reST";
1949
1950static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
1951scope. The attribute takes the identifier of a function with a parameter type
1952that is a pointer to the type with the attribute.
1953
1954.. code-block:: c
1955
1956 static void foo (int *) { ... }
1957 static void bar (int *) { ... }
1958 void baz (void) {
1959 int x __attribute__((cleanup(foo)));
1960 {
1961 int y __attribute__((cleanup(bar)));
1962 }
1963 }
1964
1965The above example will result in a call to ``bar`` being passed the address of
1966``y`` when ``y`` goes out of scope, then a call to ``foo`` being passed the
1967address of ``x`` when ``x`` goes out of scope. If two or more variables share
1968the same scope, their ``cleanup`` callbacks are invoked in the reverse order
1969the variables were declared in. It is not possible to check the return value
1970(if any) of these ``cleanup`` callback functions.)reST";
1971
1972static 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).
1973
1974.. code-block:: c
1975
1976 void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
1977
1978.. _`clspv`: https://github.com/google/clspv
1979.. _`libclc`: https://libclc.llvm.org)reST";
1980
1981static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
1982state, a call to such a function would switch from secure to non-secure state.
1983All non-secure function calls must happen only through a function pointer, and
1984a non-secure function type should only be used as a base type of a pointer.
1985See `ARMv8-M Security Extensions: Requirements on Development
1986Tools - Engineering Specification Documentation
1987<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1988
1989static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
1990from secure state. Entering from and returning to non-secure state would switch
1991to and from secure state, respectively, and prevent flow of information
1992to non-secure state, except via return values. See `ARMv8-M Security Extensions:
1993Requirements on Development Tools - Engineering Specification Documentation
1994<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1995
1996static const char AttrDoc_CodeAlign[] = R"reST(The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
1997alignment for a loop. The attribute accepts a positive integer constant
1998initialization expression indicating the number of bytes for the minimum
1999alignment boundary. Its value must be a power of 2, between 1 and 4096
2000(inclusive).
2001
2002.. code-block:: c++
2003
2004 void foo() {
2005 int var = 0;
2006 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
2007 }
2008
2009 void Array(int *array, size_t n) {
2010 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
2011 }
2012
2013 void count () {
2014 int a1[10], int i = 0;
2015 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
2016 }
2017
2018 void check() {
2019 int a = 10;
2020 [[clang::code_align(8)]] do {
2021 a = a + 1;
2022 } while (a < 20);
2023 }
2024
2025 template<int A>
2026 void func() {
2027 [[clang::code_align(A)]] for(;;) { }
2028 })reST";
2029
2030static const char AttrDoc_CodeModel[] = R"reST(The ``model`` attribute allows overriding the translation unit's
2031code model (specified by ``-mcmodel``) for a specific global variable.
2032
2033On LoongArch, allowed values are "normal", "medium", "extreme".
2034
2035On x86-64, allowed values are ``"small"`` and ``"large"``. ``"small"`` is
2036roughly equivalent to ``-mcmodel=small``, meaning the global is considered
2037"small" placed closer to the ``.text`` section relative to "large" globals, and
2038to prefer using 32-bit relocations to access the global. ``"large"`` is roughly
2039equivalent to ``-mcmodel=large``, meaning the global is considered "large" and
2040placed further from the ``.text`` section relative to "small" globals, and
204164-bit relocations must be used to access the global.)reST";
2042
2043static const char AttrDoc_CodeSeg[] = R"reST(The ``__declspec(code_seg)`` attribute enables the placement of code into separate
2044named segments that can be paged or locked in memory individually. This attribute
2045is used to control the placement of instantiated templates and compiler-generated
2046code. See the documentation for `__declspec(code_seg)`_ on MSDN.
2047
2048.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
2049
2050static const char AttrDoc_Cold[] = R"reST(``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data.
2051If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).)reST";
2052
2053static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
2054
2055static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
2056
2057static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
2058to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
2059according to the rules of [basic.start.static]. The variable is required to
2060have static or thread storage duration. If the initialization of the variable
2061is not a constant initializer an error will be produced. This attribute may
2062only be used in C++; the ``constinit`` spelling is only accepted in C++20
2063onwards.
2064
2065Note that in C++03 strict constant expression checking is not done. Instead
2066the attribute reports if Clang can emit the variable as a constant, even if it's
2067not technically a 'constant initializer'. This behavior is non-portable.
2068
2069Static storage duration variables with constant initializers avoid hard-to-find
2070bugs caused by the indeterminate order of dynamic initialization. They can also
2071be safely used during dynamic initialization across translation units.
2072
2073This attribute acts as a compile time assertion that the requirements
2074for constant initialization have been met. Since these requirements change
2075between dialects and have subtle pitfalls it's important to fail fast instead
2076of silently falling back on dynamic initialization.
2077
2078The first use of the attribute on a variable must be part of, or precede, the
2079initializing declaration of the variable. C++20 requires the ``constinit``
2080spelling of the attribute to be present on the initializing declaration if it
2081is used anywhere. The other spellings can be specified on a forward declaration
2082and omitted on a later initializing declaration.
2083
2084.. code-block:: c++
2085
2086 // -std=c++14
2087 #define SAFE_STATIC [[clang::require_constant_initialization]]
2088 struct T {
2089 constexpr T(int) {}
2090 ~T(); // non-trivial
2091 };
2092 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2093 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2094 // copy initialization is not a constant expression on a non-literal type.)reST";
2095
2096static const char AttrDoc_Constructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2097``main()``, and the ``destructor`` attribute causes the function to be called
2098after returning from ``main()`` or when the ``exit()`` function has been
2099called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2100marked ``destructor`` from being called.
2101
2102The constructor or destructor function should not accept any arguments and its
2103return type should be ``void``.
2104
2105The attributes accept an optional argument used to specify the priority order
2106in which to execute constructor and destructor functions. The priority is
2107given as an integer constant expression between 101 and 65535 (inclusive).
2108Priorities outside of that range are reserved for use by the implementation. A
2109lower value indicates a higher priority of initialization. Note that only the
2110relative ordering of values is important. For example:
2111
2112.. code-block:: c++
2113
2114 __attribute__((constructor(200))) void foo(void);
2115 __attribute__((constructor(101))) void bar(void);
2116
2117``bar()`` will be called before ``foo()``, and both will be called before
2118``main()``. If no argument is given to the ``constructor`` or ``destructor``
2119attribute, they default to the value ``65535``.)reST";
2120
2121static const char AttrDoc_Consumable[] = R"reST(Each ``class`` that uses any of the typestate annotations must first be marked
2122using the ``consumable`` attribute. Failure to do so will result in a warning.
2123
2124This attribute accepts a single parameter that must be one of the following:
2125``unknown``, ``consumed``, or ``unconsumed``.)reST";
2126
2127static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2128
2129static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2130
2131static const char AttrDoc_Convergent[] = R"reST(The ``convergent`` attribute can be placed on a function declaration. It is
2132translated into the LLVM ``convergent`` attribute, which indicates that the call
2133instructions of a function with this attribute cannot be made control-dependent
2134on any additional values.
2135
2136This attribute is different from ``noduplicate`` because it allows duplicating
2137function calls if it can be proved that the duplicated function calls are
2138not made control-dependent on any additional values, e.g., unrolling a loop
2139executed by all work items.
2140
2141Sample usage:
2142
2143.. code-block:: c
2144
2145 void convfunc(void) __attribute__((convergent));
2146 // Setting it as a C++11 attribute is also valid in a C++ program.
2147 // void convfunc(void) [[clang::convergent]];)reST";
2148
2149static const char AttrDoc_CoroAwaitElidable[] = R"reST(The ``[[clang::coro_await_elidable]]`` is a class attribute which can be
2150applied to a coroutine return type. It provides a hint to the compiler to apply
2151Heap Allocation Elision more aggressively.
2152
2153When a coroutine function returns such a type, a direct call expression therein
2154that returns a prvalue of a type attributed ``[[clang::coro_await_elidable]]``
2155is said to be under a safe elide context if one of the following is true:
2156- it is the immediate right-hand side operand to a co_await expression.
2157- it is an argument to a ``[[clang::coro_await_elidable_argument]]`` parameter
2158or parameter pack of another direct call expression under a safe elide context.
2159
2160Do note that the safe elide context applies only to the call expression itself,
2161and the context does not transitively include any of its subexpressions unless
2162exceptional rules of ``[[clang::coro_await_elidable_argument]]`` apply.
2163
2164The compiler performs heap allocation elision on call expressions under a safe
2165elide context, if the callee is a coroutine.
2166
2167Example:
2168
2169.. code-block:: c++
2170
2171 class [[clang::coro_await_elidable]] Task { ... };
2172
2173 Task foo();
2174 Task bar() {
2175 co_await foo(); // foo()'s coroutine frame on this line is elidable
2176 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2177 co_await t;
2178 }
2179
2180Such elision replaces the heap allocated activation frame of the callee coroutine
2181with a local variable within the enclosing braces in the caller's stack frame.
2182The local variable, like other variables in coroutines, may be collected into the
2183coroutine frame, which may be allocated on the heap. The behavior is undefined
2184if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2185
2186static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The ``[[clang::coro_await_elidable_argument]]`` is a function parameter attribute.
2187It works in conjunction with ``[[clang::coro_await_elidable]]`` to propagate a
2188safe elide context to a parameter or parameter pack if the function is called
2189under a safe elide context.
2190
2191This is sometimes necessary on utility functions used to compose or modify the
2192behavior of a callee coroutine.
2193
2194Example:
2195
2196.. code-block:: c++
2197
2198 template <typename T>
2199 class [[clang::coro_await_elidable]] Task { ... };
2200
2201 template <typename... T>
2202 class [[clang::coro_await_elidable]] WhenAll { ... };
2203
2204 // `when_all` is a utility function that composes coroutines. It does not
2205 // need to be a coroutine to propagate.
2206 template <typename... T>
2207 WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2208
2209 Task<int> foo();
2210 Task<int> bar();
2211 Task<void> example1() {
2212 // `when_all``, `foo``, and `bar` are all elide safe because `when_all` is
2213 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2214 // attribute, such context is propagated to foo and bar.
2215 co_await when_all(foo(), bar());
2216 }
2217
2218 Task<void> example2() {
2219 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2220 auto f = foo();
2221 co_await when_all(f, bar());
2222 }
2223
2224
2225 Task<void> example3() {
2226 // None of the calls are elide safe.
2227 auto t = when_all(foo(), bar());
2228 co_await t;
2229 })reST";
2230
2231static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2232to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2233it should also be annotated with ``[[clang::coro_return_type]]``).
2234
2235All parameters of a function are considered to be lifetime bound if the function returns a
2236coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2237This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2238with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2239See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2240
2241
2242Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2243
2244For example,
2245
2246.. code-block:: c++
2247
2248 task<int> coro(const int& a) { co_return a + 1; }
2249 task<int> dangling_refs(int a) {
2250 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2251 auto foo = coro(1);
2252 // `coro` captures reference to local variable `a` which is destroyed after the return.
2253 return coro(a);
2254 }
2255
2256Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2257which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2258``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2259temporaries or return address of a local variable.
2260
2261Both coroutines and coroutine wrappers are part of this analysis.
2262
2263.. code-block:: c++
2264
2265 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2266 using promise_type = some_promise_type;
2267 };
2268
2269 Task<int> coro(const int& a) { co_return a + 1; }
2270 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2271 return a > b ? coro(a) : coro(b);
2272 }
2273 Task<int> temporary_reference() {
2274 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2275
2276 int a = 1;
2277 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2278
2279 co_return co_await coro(1); // fine.
2280 }
2281 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2282 return coro(a); // warning: returning address of stack variable `a`.
2283 }
2284
2285This analysis can be disabled for all calls to a particular function by annotating the function
2286with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2287For example, this could be useful for coroutine wrappers which accept reference parameters
2288but do not pass them to the underlying coroutine or pass them by value.
2289
2290.. code-block:: c++
2291
2292 Task<int> coro(int a) { co_return a + 1; }
2293 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2294 return coro(a + 1);
2295 }
2296 void use() {
2297 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2298 })reST";
2299
2300static const char AttrDoc_CoroLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2301to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2302it should also be annotated with ``[[clang::coro_return_type]]``).
2303
2304All parameters of a function are considered to be lifetime bound if the function returns a
2305coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2306This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2307with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2308See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2309
2310
2311Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2312
2313For example,
2314
2315.. code-block:: c++
2316
2317 task<int> coro(const int& a) { co_return a + 1; }
2318 task<int> dangling_refs(int a) {
2319 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2320 auto foo = coro(1);
2321 // `coro` captures reference to local variable `a` which is destroyed after the return.
2322 return coro(a);
2323 }
2324
2325Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2326which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2327``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2328temporaries or return address of a local variable.
2329
2330Both coroutines and coroutine wrappers are part of this analysis.
2331
2332.. code-block:: c++
2333
2334 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2335 using promise_type = some_promise_type;
2336 };
2337
2338 Task<int> coro(const int& a) { co_return a + 1; }
2339 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2340 return a > b ? coro(a) : coro(b);
2341 }
2342 Task<int> temporary_reference() {
2343 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2344
2345 int a = 1;
2346 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2347
2348 co_return co_await coro(1); // fine.
2349 }
2350 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2351 return coro(a); // warning: returning address of stack variable `a`.
2352 }
2353
2354This analysis can be disabled for all calls to a particular function by annotating the function
2355with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2356For example, this could be useful for coroutine wrappers which accept reference parameters
2357but do not pass them to the underlying coroutine or pass them by value.
2358
2359.. code-block:: c++
2360
2361 Task<int> coro(int a) { co_return a + 1; }
2362 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2363 return coro(a + 1);
2364 }
2365 void use() {
2366 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2367 })reST";
2368
2369static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2370whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2371reached the final suspend point.
2372
2373This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2374
2375For example,
2376
2377.. code-block:: c++
2378
2379 A foo() {
2380 dtor d;
2381 co_await something();
2382 dtor d1;
2383 co_await something();
2384 dtor d2;
2385 co_return 43;
2386 }
2387
2388The compiler may generate the following pseudocode:
2389
2390.. code-block:: c++
2391
2392 void foo.destroy(foo.Frame *frame) {
2393 switch(frame->suspend_index()) {
2394 case 1:
2395 frame->d.~dtor();
2396 break;
2397 case 2:
2398 frame->d.~dtor();
2399 frame->d1.~dtor();
2400 break;
2401 case 3:
2402 frame->d.~dtor();
2403 frame->d1.~dtor();
2404 frame->d2.~dtor();
2405 break;
2406 default: // coroutine completed or haven't started
2407 break;
2408 }
2409
2410 frame->promise.~promise_type();
2411 delete frame;
2412 }
2413
2414The `foo.destroy()` function's purpose is to release all of the resources
2415initialized for the coroutine when it is destroyed in a suspended state.
2416However, if the coroutine is only ever destroyed at the final suspend state,
2417the rest of the conditions are superfluous.
2418
2419The user can use the `coro_only_destroy_when_complete` attributo suppress
2420generation of the other destruction cases, optimizing the above `foo.destroy` to:
2421
2422.. code-block:: c++
2423
2424 void foo.destroy(foo.Frame *frame) {
2425 frame->promise.~promise_type();
2426 delete frame;
2427 })reST";
2428
2429static const char AttrDoc_CoroReturnType[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2430coroutines from the function signatures.
2431
2432The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2433a **coroutine return type (CRT)**.
2434
2435A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2436is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2437(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2438
2439If the return type of a function is a ``CRT`` then the function must be a coroutine.
2440Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2441if the function is marked with ``[[clang::coro_wrapper]]``.
2442
2443The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2444a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2445is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2446
2447Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2448with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2449
2450From a language perspective, it is not possible to differentiate between a coroutine and a
2451function returning a CRT by merely looking at the function signature.
2452
2453Coroutine wrappers, in particular, are susceptible to capturing
2454references to temporaries and other lifetime issues. This allows to avoid such lifetime
2455issues with coroutine wrappers.
2456
2457For example,
2458
2459.. code-block:: c++
2460
2461 // This is a CRT.
2462 template <typename T> struct [[clang::coro_return_type]] Task {
2463 using promise_type = some_promise_type;
2464 };
2465
2466 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2467 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2468
2469 // Fine for a coroutine wrapper to return a CRT.
2470 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2471
2472 void bar() {
2473 // Invalid. This intantiates a function which returns a CRT but is not marked as
2474 // a coroutine wrapper.
2475 std::function<Task<int>(int)> f = increment;
2476 }
2477
2478Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2479implementation detail of any coroutine library.)reST";
2480
2481static const char AttrDoc_CoroWrapper[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2482coroutines from the function signatures.
2483
2484The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2485a **coroutine return type (CRT)**.
2486
2487A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2488is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2489(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2490
2491If the return type of a function is a ``CRT`` then the function must be a coroutine.
2492Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2493if the function is marked with ``[[clang::coro_wrapper]]``.
2494
2495The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2496a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2497is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2498
2499Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2500with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2501
2502From a language perspective, it is not possible to differentiate between a coroutine and a
2503function returning a CRT by merely looking at the function signature.
2504
2505Coroutine wrappers, in particular, are susceptible to capturing
2506references to temporaries and other lifetime issues. This allows to avoid such lifetime
2507issues with coroutine wrappers.
2508
2509For example,
2510
2511.. code-block:: c++
2512
2513 // This is a CRT.
2514 template <typename T> struct [[clang::coro_return_type]] Task {
2515 using promise_type = some_promise_type;
2516 };
2517
2518 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2519 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2520
2521 // Fine for a coroutine wrapper to return a CRT.
2522 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2523
2524 void bar() {
2525 // Invalid. This intantiates a function which returns a CRT but is not marked as
2526 // a coroutine wrapper.
2527 std::function<Task<int>(int)> f = increment;
2528 }
2529
2530Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2531implementation detail of any coroutine library.)reST";
2532
2533static const char AttrDoc_CountedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2534structure in C. The argument for the attribute is the name of a field member
2535holding the count of elements in the flexible array. This information can be
2536used to improve the results of the array bound sanitizer and the
2537``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2538within the same non-anonymous, enclosing struct as the flexible array member.
2539
2540This example specifies that the flexible array member ``array`` has the number
2541of elements allocated for it in ``count``:
2542
2543.. code-block:: c
2544
2545 struct bar;
2546
2547 struct foo {
2548 size_t count;
2549 char other;
2550 struct bar *array[] __attribute__((counted_by(count)));
2551 };
2552
2553This establishes a relationship between ``array`` and ``count``. Specifically,
2554``array`` must have at least ``count`` number of elements available. It's the
2555user's responsibility to ensure that this relationship is maintained through
2556changes to the structure.
2557
2558In the following example, the allocated array erroneously has fewer elements
2559than what's specified by ``p->count``. This would result in an out-of-bounds
2560access not being detected.
2561
2562.. code-block:: c
2563
2564 #define SIZE_INCR 42
2565
2566 struct foo *p;
2567
2568 void foo_alloc(size_t count) {
2569 p = malloc(MAX(sizeof(struct foo),
2570 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2571 p->count = count + SIZE_INCR;
2572 }
2573
2574The next example updates ``p->count``, but breaks the relationship requirement
2575that ``p->array`` must have at least ``p->count`` number of elements available:
2576
2577.. code-block:: c
2578
2579 #define SIZE_INCR 42
2580
2581 struct foo *p;
2582
2583 void foo_alloc(size_t count) {
2584 p = malloc(MAX(sizeof(struct foo),
2585 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2586 p->count = count;
2587 }
2588
2589 void use_foo(int index, int val) {
2590 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2591 p->array[index] = val; /* The sanitizer can't properly check this access. */
2592 }
2593
2594In this example, an update to ``p->count`` maintains the relationship
2595requirement:
2596
2597.. code-block:: c
2598
2599 void use_foo(int index, int val) {
2600 if (p->count == 0)
2601 return;
2602 --p->count;
2603 p->array[index] = val;
2604 })reST";
2605
2606static const char AttrDoc_CountedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2607structure in C. The argument for the attribute is the name of a field member
2608holding the count of elements in the flexible array. This information can be
2609used to improve the results of the array bound sanitizer and the
2610``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2611within the same non-anonymous, enclosing struct as the flexible array member.
2612
2613This example specifies that the flexible array member ``array`` has the number
2614of elements allocated for it in ``count``:
2615
2616.. code-block:: c
2617
2618 struct bar;
2619
2620 struct foo {
2621 size_t count;
2622 char other;
2623 struct bar *array[] __attribute__((counted_by(count)));
2624 };
2625
2626This establishes a relationship between ``array`` and ``count``. Specifically,
2627``array`` must have at least ``count`` number of elements available. It's the
2628user's responsibility to ensure that this relationship is maintained through
2629changes to the structure.
2630
2631In the following example, the allocated array erroneously has fewer elements
2632than what's specified by ``p->count``. This would result in an out-of-bounds
2633access not being detected.
2634
2635.. code-block:: c
2636
2637 #define SIZE_INCR 42
2638
2639 struct foo *p;
2640
2641 void foo_alloc(size_t count) {
2642 p = malloc(MAX(sizeof(struct foo),
2643 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2644 p->count = count + SIZE_INCR;
2645 }
2646
2647The next example updates ``p->count``, but breaks the relationship requirement
2648that ``p->array`` must have at least ``p->count`` number of elements available:
2649
2650.. code-block:: c
2651
2652 #define SIZE_INCR 42
2653
2654 struct foo *p;
2655
2656 void foo_alloc(size_t count) {
2657 p = malloc(MAX(sizeof(struct foo),
2658 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2659 p->count = count;
2660 }
2661
2662 void use_foo(int index, int val) {
2663 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2664 p->array[index] = val; /* The sanitizer can't properly check this access. */
2665 }
2666
2667In this example, an update to ``p->count`` maintains the relationship
2668requirement:
2669
2670.. code-block:: c
2671
2672 void use_foo(int index, int val) {
2673 if (p->count == 0)
2674 return;
2675 --p->count;
2676 p->array[index] = val;
2677 })reST";
2678
2679static const char AttrDoc_DLLExport[] = R"reST(The ``__declspec(dllexport)`` attribute declares a variable, function, or
2680Objective-C interface to be exported from the module. It is available under the
2681``-fdeclspec`` flag for compatibility with various compilers. The primary use
2682is for COFF object files which explicitly specify what interfaces are available
2683for external use. See the dllexport_ documentation on MSDN for more
2684information.
2685
2686.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2687
2688static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2689
2690static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2691
2692static const char AttrDoc_DLLImport[] = R"reST(The ``__declspec(dllimport)`` attribute declares a variable, function, or
2693Objective-C interface to be imported from an external module. It is available
2694under the ``-fdeclspec`` flag for compatibility with various compilers. The
2695primary use is for COFF object files which explicitly specify what interfaces
2696are imported from external modules. See the dllimport_ documentation on MSDN
2697for more information.
2698
2699Note that a dllimport function may still be inlined, if its definition is
2700available and it doesn't reference any non-dllimport functions or global
2701variables.
2702
2703.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2704
2705static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2706
2707static const char AttrDoc_Deprecated[] = R"reST(The ``deprecated`` attribute can be applied to a function, a variable, or a
2708type. This is useful when identifying functions, variables, or types that are
2709expected to be removed in a future version of a program.
2710
2711Consider the function declaration for a hypothetical function ``f``:
2712
2713.. code-block:: c++
2714
2715 void f(void) __attribute__((deprecated("message", "replacement")));
2716
2717When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have
2718two optional string arguments. The first one is the message to display when
2719emitting the warning; the second one enables the compiler to provide a Fix-It
2720to replace the deprecated name with a new name. Otherwise, when spelled as
2721``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional
2722string argument which is the message to display when emitting the warning.)reST";
2723
2724static const char AttrDoc_Destructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2725``main()``, and the ``destructor`` attribute causes the function to be called
2726after returning from ``main()`` or when the ``exit()`` function has been
2727called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2728marked ``destructor`` from being called.
2729
2730The constructor or destructor function should not accept any arguments and its
2731return type should be ``void``.
2732
2733The attributes accept an optional argument used to specify the priority order
2734in which to execute constructor and destructor functions. The priority is
2735given as an integer constant expression between 101 and 65535 (inclusive).
2736Priorities outside of that range are reserved for use by the implementation. A
2737lower value indicates a higher priority of initialization. Note that only the
2738relative ordering of values is important. For example:
2739
2740.. code-block:: c++
2741
2742 __attribute__((constructor(200))) void foo(void);
2743 __attribute__((constructor(101))) void bar(void);
2744
2745``bar()`` will be called before ``foo()``, and both will be called before
2746``main()``. If no argument is given to the ``constructor`` or ``destructor``
2747attribute, they default to the value ``65535``.)reST";
2748
2749static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2750The specific semantics depend on the offloading language, target, and attribute spelling.
2751Here is a code example using the attribute to mark a function as a kernel:
2752
2753.. code-block:: c++
2754
2755 [[clang::device_kernel]] int foo(int x) { return ++x; })reST";
2756
2757static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
2758be applied to the declared function as if it were the function specified by the
2759attribute. The builtin function whose diagnostics are to be mimicked should be
2760given. In addition, the order in which arguments should be applied must also
2761be given.
2762
2763For example, the attribute can be used as follows.
2764
2765.. code-block:: c
2766
2767 __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2768 void *mymemset(int n, int c, void *s) {
2769 // ...
2770 }
2771
2772This indicates that calls to ``mymemset`` should be diagnosed as if they were
2773calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
2774order in which arguments of ``mymemset`` should be applied to
2775``__builtin_memset``. The third argument should be applied first, then the
2776second, and then the first. Thus (when Fortify warnings are enabled) the call
2777``mymemset(n, c, s)`` will diagnose overflows as if it were the call
2778``__builtin_memset(s, c, n)``.
2779
2780For variadic functions, the variadic arguments must come in the same order as
2781they would to the builtin function, after all normal arguments. For instance,
2782to diagnose a new function as if it were `sscanf`, we can use the attribute as
2783follows.
2784
2785.. code-block:: c
2786
2787 __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2788 int mysscanf(const char *str, const char *format, ...) {
2789 // ...
2790 }
2791
2792Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2793if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2794
2795This attribute cannot be applied to non-static member functions.)reST";
2796
2797static const char AttrDoc_DiagnoseIf[] = R"reST(The ``diagnose_if`` attribute can be placed on function declarations to emit
2798warnings or errors at compile-time if calls to the attributed function meet
2799certain user-defined criteria. For example:
2800
2801.. code-block:: c
2802
2803 int abs(int a)
2804 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2805 int must_abs(int a)
2806 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2807
2808 int val = abs(1); // warning: Redundant abs call
2809 int val2 = must_abs(1); // error: Redundant abs call
2810 int val3 = abs(val);
2811 int val4 = must_abs(val); // Because run-time checks are not emitted for
2812 // diagnose_if attributes, this executes without
2813 // issue.
2814
2815
2816``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
2817
2818* Overload resolution is not aware of ``diagnose_if`` attributes: they're
2819 considered only after we select the best candidate from a given candidate set.
2820* Function declarations that differ only in their ``diagnose_if`` attributes are
2821 considered to be redeclarations of the same function (not overloads).
2822* If the condition provided to ``diagnose_if`` cannot be evaluated, no
2823 diagnostic will be emitted.
2824
2825Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
2826
2827As a result of bullet number two, ``diagnose_if`` attributes will stack on the
2828same function. For example:
2829
2830.. code-block:: c
2831
2832 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2833 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2834
2835 int bar = foo(); // warning: diag1
2836 // warning: diag2
2837 int (*fooptr)(void) = foo; // warning: diag1
2838 // warning: diag2
2839
2840 constexpr int supportsAPILevel(int N) { return N < 5; }
2841 int baz(int a)
2842 __attribute__((diagnose_if(!supportsAPILevel(10),
2843 "Upgrade to API level 10 to use baz", "error")));
2844 int baz(int a)
2845 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2846
2847 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2848 int v = baz(0); // error: Upgrade to API level 10 to use baz
2849
2850Query for this feature with ``__has_attribute(diagnose_if)``.)reST";
2851
2852static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the ``disable_sanitizer_instrumentation`` attribute on a function,
2853Objective-C method, or global variable, to specify that no sanitizer
2854instrumentation should be applied.
2855
2856This is not the same as ``__attribute__((no_sanitize(...)))``, which depending
2857on the tool may still insert instrumentation to prevent false positive reports.)reST";
2858
2859static const char AttrDoc_DisableTailCalls[] = R"reST(The ``disable_tail_calls`` attribute instructs the backend to not perform tail
2860call optimization inside the marked function.
2861
2862For example:
2863
2864 .. code-block:: c
2865
2866 int callee(int);
2867
2868 int foo(int a) __attribute__((disable_tail_calls)) {
2869 return callee(a); // This call is not tail-call optimized.
2870 }
2871
2872Marking virtual functions as ``disable_tail_calls`` is legal.
2873
2874 .. code-block:: c++
2875
2876 int callee(int);
2877
2878 class Base {
2879 public:
2880 [[clang::disable_tail_calls]] virtual int foo1() {
2881 return callee(); // This call is not tail-call optimized.
2882 }
2883 };
2884
2885 class Derived1 : public Base {
2886 public:
2887 int foo1() override {
2888 return callee(); // This call is tail-call optimized.
2889 }
2890 };)reST";
2891
2892static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2893empty-base-optimization more frequently.
2894This attribute only applies to struct, class, and union types.
2895It is only supported when using the Microsoft C++ ABI.)reST";
2896
2897static const char AttrDoc_EnableIf[] = R"reST(.. Note:: Some features of this attribute are experimental. The meaning of
2898 multiple enable_if attributes on a single declaration is subject to change in
2899 a future version of clang. Also, the ABI is not standardized and the name
2900 mangling may change in future versions. To avoid that, use asm labels.
2901
2902The ``enable_if`` attribute can be placed on function declarations to control
2903which overload is selected based on the values of the function's arguments.
2904When combined with the ``overloadable`` attribute, this feature is also
2905available in C.
2906
2907.. code-block:: c++
2908
2909 int isdigit(int c);
2910 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")));
2911
2912 void foo(char c) {
2913 isdigit(c);
2914 isdigit(10);
2915 isdigit(-10); // results in a compile-time error.
2916 }
2917
2918The enable_if attribute takes two arguments, the first is an expression written
2919in terms of the function parameters, the second is a string explaining why this
2920overload candidate could not be selected to be displayed in diagnostics. The
2921expression is part of the function signature for the purposes of determining
2922whether it is a redeclaration (following the rules used when determining
2923whether a C++ template specialization is ODR-equivalent), but is not part of
2924the type.
2925
2926The enable_if expression is evaluated as if it were the body of a
2927bool-returning constexpr function declared with the arguments of the function
2928it is being applied to, then called with the parameters at the call site. If the
2929result is false or could not be determined through constant expression
2930evaluation, then this overload will not be chosen and the provided string may
2931be used in a diagnostic if the compile fails as a result.
2932
2933Because the enable_if expression is an unevaluated context, there are no global
2934state changes, nor the ability to pass information from the enable_if
2935expression to the function body. For example, suppose we want calls to
2936strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
2937strbuf) only if the size of strbuf can be determined:
2938
2939.. code-block:: c++
2940
2941 __attribute__((always_inline))
2942 static inline size_t strnlen(const char *s, size_t maxlen)
2943 __attribute__((overloadable))
2944 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
2945 "chosen when the buffer size is known but 'maxlen' is not")))
2946 {
2947 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
2948 }
2949
2950Multiple enable_if attributes may be applied to a single declaration. In this
2951case, the enable_if expressions are evaluated from left to right in the
2952following manner. First, the candidates whose enable_if expressions evaluate to
2953false or cannot be evaluated are discarded. If the remaining candidates do not
2954share ODR-equivalent enable_if expressions, the overload resolution is
2955ambiguous. Otherwise, enable_if overload resolution continues with the next
2956enable_if attribute on the candidates that have not been discarded and have
2957remaining enable_if attributes. In this way, we pick the most specific
2958overload out of a number of viable overloads using enable_if.
2959
2960.. code-block:: c++
2961
2962 void f() __attribute__((enable_if(true, ""))); // #1
2963 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
2964
2965 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
2966 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
2967
2968In this example, a call to f() is always resolved to #2, as the first enable_if
2969expression is ODR-equivalent for both declarations, but #1 does not have another
2970enable_if expression to continue evaluating, so the next round of evaluation has
2971only a single candidate. In a call to g(1, 1), the call is ambiguous even though
2972#2 has more enable_if attributes, because the first enable_if expressions are
2973not ODR-equivalent.
2974
2975Query for this feature with ``__has_attribute(enable_if)``.
2976
2977Note that functions with one or more ``enable_if`` attributes may not have
2978their address taken, unless all of the conditions specified by said
2979``enable_if`` are constants that evaluate to ``true``. For example:
2980
2981.. code-block:: c
2982
2983 const int TrueConstant = 1;
2984 const int FalseConstant = 0;
2985 int f(int a) __attribute__((enable_if(a > 0, "")));
2986 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
2987 int h(int a) __attribute__((enable_if(1, "")));
2988 int i(int a) __attribute__((enable_if(TrueConstant, "")));
2989 int j(int a) __attribute__((enable_if(FalseConstant, "")));
2990
2991 void fn() {
2992 int (*ptr)(int);
2993 ptr = &f; // error: 'a > 0' is not always true
2994 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
2995 ptr = &h; // OK: 1 is a truthy constant
2996 ptr = &i; // OK: 'TrueConstant' is a truthy constant
2997 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
2998 }
2999
3000Because ``enable_if`` evaluation happens during overload resolution,
3001``enable_if`` may give unintuitive results when used with templates, depending
3002on when overloads are resolved. In the example below, clang will emit a
3003diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
3004
3005.. code-block:: c++
3006
3007 double foo(int i) __attribute__((enable_if(i > 0, "")));
3008 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
3009 template <int I>
3010 auto bar() { return foo(I); }
3011
3012 template <typename T>
3013 auto baz() { return foo(T::number); }
3014
3015 struct WithNumber { constexpr static int number = 1; };
3016 void callThem() {
3017 bar<sizeof(WithNumber)>();
3018 baz<WithNumber>();
3019 }
3020
3021This is because, in ``bar``, ``foo`` is resolved prior to template
3022instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
3023conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
3024template instantiation, so the value for ``T::number`` is known.)reST";
3025
3026static const char AttrDoc_EnforceTCB[] = R"reST(The ``enforce_tcb`` attribute can be placed on functions to enforce that a
3027 trusted compute base (TCB) does not call out of the TCB. This generates a
3028 warning every time a function not marked with an ``enforce_tcb`` attribute is
3029 called from a function with the ``enforce_tcb`` attribute. A function may be a
3030 part of multiple TCBs. Invocations through function pointers are currently
3031 not checked. Builtins are considered to a part of every TCB.
3032
3033 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
3034
3035static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
3036 ``enforce_tcb`` for the marked function to be in the named TCB but does not
3037 continue to check the functions called from within the leaf function.
3038
3039 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
3040
3041static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute ``enum_extensibility`` is used to distinguish between enum definitions
3042that are extensible and those that are not. The attribute can take either
3043``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
3044enum type takes a value that corresponds to one of the enumerators listed in the
3045enum definition or, when the enum is annotated with ``flag_enum``, a value that
3046can be constructed using values corresponding to the enumerators. ``open``
3047indicates a variable of the enum type can take any values allowed by the
3048standard and instructs clang to be more lenient when issuing warnings.
3049
3050.. code-block:: c
3051
3052 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3053 A0, A1
3054 };
3055
3056 enum __attribute__((enum_extensibility(open))) OpenEnum {
3057 B0, B1
3058 };
3059
3060 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3061 C0 = 1 << 0, C1 = 1 << 1
3062 };
3063
3064 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3065 D0 = 1 << 0, D1 = 1 << 1
3066 };
3067
3068 void foo1() {
3069 enum ClosedEnum ce;
3070 enum OpenEnum oe;
3071 enum ClosedFlagEnum cfe;
3072 enum OpenFlagEnum ofe;
3073
3074 ce = A1; // no warnings
3075 ce = 100; // warning issued
3076 oe = B1; // no warnings
3077 oe = 100; // no warnings
3078 cfe = C0 | C1; // no warnings
3079 cfe = C0 | C1 | 4; // warning issued
3080 ofe = D0 | D1; // no warnings
3081 ofe = D0 | D1 | 4; // no warnings
3082 })reST";
3083
3084static const char AttrDoc_Error[] = R"reST(The ``error`` and ``warning`` function attributes can be used to specify a
3085custom diagnostic to be emitted when a call to such a function is not
3086eliminated via optimizations. This can be used to create compile time
3087assertions that depend on optimizations, while providing diagnostics
3088pointing to precise locations of the call site in the source.
3089
3090.. code-block:: c++
3091
3092 __attribute__((warning("oh no"))) void dontcall();
3093 void foo() {
3094 if (someCompileTimeAssertionThatsTrue)
3095 dontcall(); // Warning
3096
3097 dontcall(); // Warning
3098
3099 if (someCompileTimeAssertionThatsFalse)
3100 dontcall(); // No Warning
3101 sizeof(dontcall()); // No Warning
3102 }
3103
3104When the call occurs through inlined functions, the
3105``-fdiagnostics-show-inlining-chain`` option can be used to show the
3106inlining chain that led to the call. This helps identify which call site
3107triggered the diagnostic when the attributed function is called from
3108multiple locations through inline functions.
3109
3110When enabled, this option automatically uses debug info for accurate source
3111locations if available (``-gline-directives-only`` (implicitly enabled at
3112``-g1``) or higher), or falls back to a heuristic based on metadata tracking.
3113When falling back, a note is emitted suggesting ``-gline-directives-only`` for
3114more accurate locations.)reST";
3115
3116static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
3117class template from being part of explicit template instantiations of that
3118class template. This means that an explicit instantiation will not instantiate
3119members of the class template marked with the attribute, but also that code
3120where an extern template declaration of the enclosing class template is visible
3121will not take for granted that an external instantiation of the class template
3122would provide those members (which would otherwise be a link error, since the
3123explicit instantiation won't provide those members). For example, let's say we
3124don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
3125is not exported from the dylib, we give it hidden visibility:
3126
3127 .. code-block:: c++
3128
3129 // in <string>
3130 template <class CharT>
3131 class basic_string {
3132 public:
3133 __attribute__((__visibility__("hidden")))
3134 const value_type* data() const noexcept { ... }
3135 };
3136
3137 template class basic_string<char>;
3138
3139Since an explicit template instantiation declaration for ``basic_string<char>``
3140is provided, the compiler is free to assume that ``basic_string<char>::data()``
3141will be provided by another translation unit, and it is free to produce an
3142external call to this function. However, since ``data()`` has hidden visibility
3143and the explicit template instantiation is provided in a shared library (as
3144opposed to simply another translation unit), ``basic_string<char>::data()``
3145won't be found and a link error will ensue. This happens because the compiler
3146assumes that ``basic_string<char>::data()`` is part of the explicit template
3147instantiation declaration, when it really isn't. To tell the compiler that
3148``data()`` is not part of the explicit template instantiation declaration, the
3149``exclude_from_explicit_instantiation`` attribute can be used:
3150
3151 .. code-block:: c++
3152
3153 // in <string>
3154 template <class CharT>
3155 class basic_string {
3156 public:
3157 __attribute__((__visibility__("hidden")))
3158 __attribute__((exclude_from_explicit_instantiation))
3159 const value_type* data() const noexcept { ... }
3160 };
3161
3162 template class basic_string<char>;
3163
3164Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
3165externally despite there being an explicit template instantiation declaration:
3166the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
3167TUs where it is used.
3168
3169This attribute can be used on static and non-static member functions of class
3170templates, static data members of class templates and member classes of class
3171templates.
3172
3173**Interaction with __declspec(dllexport/dllimport)**
3174
3175For a DLL platform (i.e., Windows), this attribute also means "this member will
3176never be exported or imported". Despite its name, this semantics applies to
3177implicit instantiations and non-template entities as well.
3178
3179 .. code-block:: c++
3180
3181 // in <exception>
3182 class __declspec(dllimport) nested_exception {
3183 ...
3184 public:
3185 __attribute__((exclude_from_explicit_instantiation))
3186 exception_ptr nested_ptr() const noexcept { ... }
3187 };
3188
3189In this case, ``nested_exception::nested_ptr`` will never be attempted to be
3190imported.)reST";
3191
3192static const char AttrDoc_ExplicitInit[] = R"reST(The ``clang::require_explicit_initialization`` attribute indicates that a
3193field of an aggregate must be initialized explicitly by the user when an object
3194of the aggregate type is constructed. The attribute supports both C and C++,
3195but its usage is invalid on non-aggregates.
3196
3197Note that this attribute is *not* a memory safety feature, and is *not* intended
3198to guard against use of uninitialized memory.
3199
3200Rather, it is intended for use in "parameter-objects", used to simulate,
3201for example, the passing of named parameters.
3202Except inside unevaluated contexts, the attribute generates a warning when
3203explicit initializers for such variables are not provided (this occurs
3204regardless of whether any in-class field initializers exist):
3205
3206.. code-block:: c++
3207
3208 struct Buffer {
3209 void *address [[clang::require_explicit_initialization]];
3210 size_t length [[clang::require_explicit_initialization]] = 0;
3211 };
3212
3213 struct ArrayIOParams {
3214 size_t count [[clang::require_explicit_initialization]];
3215 size_t element_size [[clang::require_explicit_initialization]];
3216 int flags = 0;
3217 };
3218
3219 size_t ReadArray(FILE *file, struct Buffer buffer,
3220 struct ArrayIOParams params);
3221
3222 int main() {
3223 unsigned int buf[512];
3224 ReadArray(stdin, {
3225 buf
3226 // warning: field 'length' is not explicitly initialized
3227 }, {
3228 .count = sizeof(buf) / sizeof(*buf),
3229 // warning: field 'element_size' is not explicitly initialized
3230 // (Note that a missing initializer for 'flags' is not diagnosed, because
3231 // the field is not marked as requiring explicit initialization.)
3232 });
3233 })reST";
3234
3235static const char AttrDoc_ExtVectorType[] = R"reST(The ``ext_vector_type(N)`` attribute specifies that a type is a vector with N
3236elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3237allows element access the array subscript operator ``[]``, ``sN`` where N is
3238a hexadecimal value, or ``x, y, z, w`` for graphics-style indexing.
3239This attribute enables efficient SIMD operations and is usable in
3240general-purpose code.
3241
3242.. code-block:: c++
3243
3244 template <typename T, uint32_t N>
3245 constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3246 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3247 if constexpr (N == 1)
3248 return v[0];
3249 else
3250 return simd_reduce<T, N / 2>(v.hi + v.lo);
3251 }
3252
3253The vector type also supports swizzling up to sixteen elements. This can be done
3254using the object accessors. The OpenCL documentation lists all of the accepted
3255values.
3256
3257.. code-block:: c++
3258
3259 using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3260
3261 f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3262
3263See the OpenCL documentation for some more complete examples.)reST";
3264
3265static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The ``external_source_symbol`` attribute specifies that a declaration originates
3266from an external source and describes the nature of that source.
3267
3268The fact that Clang is capable of recognizing declarations that were defined
3269externally can be used to provide better tooling support for mixed-language
3270projects or projects that rely on auto-generated code. For instance, an IDE that
3271uses Clang and that supports mixed-language projects can use this attribute to
3272provide a correct 'jump-to-definition' feature. For a concrete example,
3273consider a protocol that's defined in a Swift file:
3274
3275.. code-block:: swift
3276
3277 @objc public protocol SwiftProtocol {
3278 func method()
3279 }
3280
3281This protocol can be used from Objective-C code by including a header file that
3282was generated by the Swift compiler. The declarations in that header can use
3283the ``external_source_symbol`` attribute to make Clang aware of the fact
3284that ``SwiftProtocol`` actually originates from a Swift module:
3285
3286.. code-block:: objc
3287
3288 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
3289 @protocol SwiftProtocol
3290 @required
3291 - (void) method;
3292 @end
3293
3294Consequently, when 'jump-to-definition' is performed at a location that
3295references ``SwiftProtocol``, the IDE can jump to the original definition in
3296the Swift source file rather than jumping to the Objective-C declaration in the
3297auto-generated header file.
3298
3299The ``external_source_symbol`` attribute is a comma-separated list that includes
3300clauses that describe the origin and the nature of the particular declaration.
3301Those clauses can be:
3302
3303language=\ *string-literal*
3304 The name of the source language in which this declaration was defined.
3305
3306defined_in=\ *string-literal*
3307 The name of the source container in which the declaration was defined. The
3308 exact definition of source container is language-specific, e.g. Swift's
3309 source containers are modules, so ``defined_in`` should specify the Swift
3310 module name.
3311
3312USR=\ *string-literal*
3313 String that specifies a unified symbol resolution (USR) value for this
3314 declaration. USR string uniquely identifies this particular declaration, and
3315 is typically used when constructing an index of a codebase.
3316 The USR value in this attribute is expected to be generated by an external
3317 compiler that compiled the native declaration using its original source
3318 language. The exact format of the USR string and its other attributes
3319 are determined by the specification of this declaration's source language.
3320 When not specified, Clang's indexer will use the Clang USR for this symbol.
3321 User can query to see if Clang supports the use of the ``USR`` clause in
3322 the ``external_source_symbol`` attribute with
3323 ``__has_attribute(external_source_symbol) >= 20230206``.
3324
3325generated_declaration
3326 This declaration was automatically generated by some tool.
3327
3328The clauses can be specified in any order. The clauses that are listed above are
3329all optional, but the attribute has to have at least one clause.)reST";
3330
3331static const char AttrDoc_FallThrough[] = R"reST(The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
3332to annotate intentional fall-through
3333between switch labels. It can only be applied to a null statement placed at a
3334point of execution between any statement and the next switch label. It is
3335common to mark these places with a specific comment, but this attribute is
3336meant to replace comments with a more strict annotation, which can be checked
3337by the compiler. This attribute doesn't change semantics of the code and can
3338be used wherever an intended fall-through occurs. It is designed to mimic
3339control-flow statements like ``break;``, so it can be placed in most places
3340where ``break;`` can, but only if there are no statements on the execution path
3341between it and the next switch label.
3342
3343By default, Clang does not warn on unannotated fallthrough from one ``switch``
3344case to another. Diagnostics on fallthrough without a corresponding annotation
3345can be enabled with the ``-Wimplicit-fallthrough`` argument.
3346
3347Here is an example:
3348
3349.. code-block:: c++
3350
3351 // compile with -Wimplicit-fallthrough
3352 switch (n) {
3353 case 22:
3354 case 33: // no warning: no statements between case labels
3355 f();
3356 case 44: // warning: unannotated fall-through
3357 g();
3358 [[clang::fallthrough]];
3359 case 55: // no warning
3360 if (x) {
3361 h();
3362 break;
3363 }
3364 else {
3365 i();
3366 [[clang::fallthrough]];
3367 }
3368 case 66: // no warning
3369 p();
3370 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3371 // directly precede case label
3372 q();
3373 case 77: // warning: unannotated fall-through
3374 r();
3375 })reST";
3376
3377static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3378function to use ECX and EDX as register parameters and clear parameters off of
3379the stack on return. This convention does not support variadic calls or
3380unprototyped functions in C, and has no effect on x86_64 targets. This calling
3381convention is supported primarily for compatibility with existing code. Users
3382seeking register parameters should use the ``regparm`` attribute, which does
3383not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
3384
3385.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3386
3387static const char AttrDoc_Final[] = R"reST()reST";
3388
3389static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3390is intended to be used as a flag type. This will cause the compiler to assume
3391that the range of the type includes all of the values that you can get by
3392manipulating bits of the enumerator when issuing warnings.)reST";
3393
3394static const char AttrDoc_Flatten[] = R"reST(The ``flatten`` attribute causes calls within the attributed function to
3395be inlined unless it is impossible to do so, for example if the body of the
3396callee is unavailable or if the callee has the ``noinline`` attribute.)reST";
3397
3398static const char AttrDoc_Format[] = R"reST(Clang supports the ``format`` attribute, which indicates that the function
3399accepts (among other possibilities) a ``printf`` or ``scanf``-like format string
3400and corresponding arguments or a ``va_list`` that contains these arguments.
3401
3402Please see `GCC documentation about format attribute
3403<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
3404about attribute syntax.
3405
3406Clang implements two kinds of checks with this attribute.
3407
3408#. Clang checks that the function with the ``format`` attribute is called with
3409 a format string that uses format specifiers that are allowed, and that
3410 arguments match the format string. This is the ``-Wformat`` warning, it is
3411 on by default.
3412
3413#. Clang checks that the format string argument is a literal string. This is
3414 the ``-Wformat-nonliteral`` warning, it is off by default.
3415
3416 Clang implements this mostly the same way as GCC, but there is a difference
3417 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
3418 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
3419 functions. Clang does not warn if the format string comes from a function
3420 parameter, where the function is annotated with a compatible attribute,
3421 otherwise it warns. For example:
3422
3423 .. code-block:: c
3424
3425 __attribute__((__format__ (__scanf__, 1, 3)))
3426 void foo(const char* s, char *buf, ...) {
3427 va_list ap;
3428 va_start(ap, buf);
3429
3430 vprintf(s, ap); // warning: format string is not a string literal
3431 }
3432
3433 In this case we warn because ``s`` contains a format string for a
3434 ``scanf``-like function, but it is passed to a ``printf``-like function.
3435
3436 If the attribute is removed, clang still warns, because the format string is
3437 not a string literal.
3438
3439 Another example:
3440
3441 .. code-block:: c
3442
3443 __attribute__((__format__ (__printf__, 1, 3)))
3444 void foo(const char* s, char *buf, ...) {
3445 va_list ap;
3446 va_start(ap, buf);
3447
3448 vprintf(s, ap); // warning
3449 }
3450
3451 In this case Clang does not warn because the format string ``s`` and
3452 the corresponding arguments are annotated. If the arguments are
3453 incorrect, the caller of ``foo`` will receive a warning.
3454
3455As an extension to GCC's behavior, Clang accepts the ``format`` attribute on
3456non-variadic functions. Clang checks non-variadic format functions for the same
3457classes of issues that can be found on variadic functions, as controlled by the
3458same warning flags, except that the types of formatted arguments is forced by
3459the function signature. For example:
3460
3461.. code-block:: c
3462
3463 __attribute__((__format__(__printf__, 1, 2)))
3464 void fmt(const char *s, const char *a, int b);
3465
3466 void bar(void) {
3467 fmt("%s %i", "hello", 123); // OK
3468 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3469 extern const char *fmt;
3470 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3471 }
3472
3473When using the format attribute on a variadic function, the first data parameter
3474_must_ be the index of the ellipsis in the parameter list. Clang will generate
3475a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3476to `printf`-family functions. For instance, this is an error:
3477
3478.. code-block:: c
3479
3480 __attribute__((__format__(__printf__, 1, 2)))
3481 void fmt(const char *s, int b, ...);
3482 // ^ error: format attribute parameter 3 is out of bounds
3483 // (must be __printf__, 1, 3)
3484
3485Using the ``format`` attribute on a non-variadic function emits a GCC
3486compatibility diagnostic.)reST";
3487
3488static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3489
3490static const char AttrDoc_FormatMatches[] = R"reST(The ``format`` attribute is the basis for the enforcement of diagnostics in the
3491``-Wformat`` family, but it only handles the case where the format string is
3492passed along with the arguments it is going to format. It cannot handle the case
3493where the format string and the format arguments are passed separately from each
3494other. For instance:
3495
3496.. code-block:: c
3497
3498 static const char *first_name;
3499 static double todays_temperature;
3500 static int wind_speed;
3501
3502 void say_hi(const char *fmt) {
3503 printf(fmt, first_name, todays_temperature);
3504 // ^ warning: format string is not a string literal
3505 printf(fmt, first_name, wind_speed);
3506 // ^ warning: format string is not a string literal
3507 }
3508
3509 int main() {
3510 say_hi("hello %s, it is %g degrees outside");
3511 say_hi("hello %s, it is %d degrees outside!");
3512 // ^ no diagnostic, but %d cannot format doubles
3513 }
3514
3515In this example, ``fmt`` is expected to format a ``const char *`` and a
3516``double``, but these values are not passed to ``say_hi``. Without the
3517``format`` attribute (which cannot apply in this case), the -Wformat-nonliteral
3518diagnostic unnecessarily triggers in the body of ``say_hi``, and incorrect
3519``say_hi`` call sites do not trigger a diagnostic.
3520
3521To complement the ``format`` attribute, Clang also defines the
3522``format_matches`` attribute. Its syntax is similar to the ``format``
3523attribute's, but instead of taking the index of the first formatted value
3524argument, it takes a C string literal with the expected specifiers:
3525
3526.. code-block:: c
3527
3528 static const char *first_name;
3529 static double todays_temperature;
3530 static int wind_speed;
3531
3532 __attribute__((__format_matches__(printf, 1, "%s %g")))
3533 void say_hi(const char *fmt) {
3534 printf(fmt, first_name, todays_temperature); // no dignostic
3535 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3536 }
3537
3538 int main() {
3539 say_hi("hello %s, it is %g degrees outside");
3540 say_hi("it is %g degrees outside, have a good day %s!");
3541 // warning: format specifies 'double' where 'const char *' is required
3542 // warning: format specifies 'const char *' where 'double' is required
3543 }
3544
3545The third argument to ``format_matches`` is expected to evaluate to a **C string
3546literal** even when the format string would normally be a different type for the
3547given flavor, like a ``CFStringRef`` or a ``NSString *``.
3548
3549The only requirement on the format string literal is that it has specifiers
3550that are compatible with the arguments that will be used. It can contain
3551arbitrary non-format characters. For instance, for the purposes of compile-time
3552validation, ``"%s scored %g%% on her test"`` and ``"%s%g"`` are interchangeable
3553as the format string argument. As a means of self-documentation, users may
3554prefer the former when it provides a useful example of an expected format
3555string.
3556
3557In the implementation of a function with the ``format_matches`` attribute,
3558format verification works as if the format string was identical to the one
3559specified in the attribute.
3560
3561.. code-block:: c
3562
3563 __attribute__((__format_matches__(printf, 1, "%s %g")))
3564 void say_hi(const char *fmt) {
3565 printf(fmt, "person", 546);
3566 // ^ warning: format specifies type 'double' but the
3567 // argument has type 'int'
3568 // note: format string is defined here:
3569 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3570 // ^~
3571 }
3572
3573
3574At the call sites of functions with the ``format_matches`` attribute, format
3575verification instead compares the two format strings to evaluate their
3576equivalence. Each format flavor defines equivalence between format specifiers.
3577Generally speaking, two specifiers are equivalent if they format the same type.
3578For instance, in the ``printf`` flavor, ``%2i`` and ``%-0.5d`` are compatible.
3579When ``-Wformat-signedness`` is disabled, ``%d`` and ``%u`` are compatible. For
3580a negative example, ``%ld`` is incompatible with ``%d``.
3581
3582Do note the following un-obvious cases:
3583
3584* Passing ``NULL`` as the format string does not trigger format diagnostics.
3585* When the format string is not NULL, it cannot _miss_ specifiers, even in
3586 trailing positions. For instance, ``%d`` is not accepted when the required
3587 format is ``%d %d %d``.
3588* While checks for the ``format`` attribute tolerate sone size mismatches
3589 that standard argument promotion renders immaterial (such as formatting an
3590 ``int`` with ``%hhd``, which specifies a ``char``-sized integer), checks for
3591 ``format_matches`` require specified argument sizes to match exactly.
3592* Format strings expecting a variable modifier (such as ``%*s``) are
3593 incompatible with format strings that would itemize the variable modifiers
3594 (such as ``%i %s``), even if the two specify ABI-compatible argument lists.
3595* All pointer specifiers, modifiers aside, are mutually incompatible. For
3596 instance, ``%s`` is not compatible with ``%p``, and ``%p`` is not compatible
3597 with ``%n``, and ``%hhn`` is incompatible with ``%s``, even if the pointers
3598 are ABI-compatible or identical on the selected platform. However, ``%0.5s``
3599 is compatible with ``%s``, since the difference only exists in modifier flags.
3600 This is not overridable with ``-Wformat-pedantic`` or its inverse, which
3601 control similar behavior in ``-Wformat``.
3602
3603At this time, clang implements ``format_matches`` only for format types in the
3604``printf`` family. This includes variants such as Apple's NSString format and
3605the FreeBSD ``kprintf``, but excludes ``scanf``. Using a known but unsupported
3606format silently fails in order to be compatible with other implementations that
3607would support these formats.)reST";
3608
3609static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute ``function_return`` can replace return instructions with jumps to
3610target-specific symbols. This attribute supports 2 possible values,
3611corresponding to the values supported by the ``-mfunction-return=`` command
3612line flag:
3613
3614* ``__attribute__((function_return("keep")))`` to disable related transforms.
3615 This is useful for undoing global setting from ``-mfunction-return=`` locally
3616 for individual functions.
3617* ``__attribute__((function_return("thunk-extern")))`` to replace returns with
3618 jumps, while NOT emitting the thunk.
3619
3620The values ``thunk`` and ``thunk-inline`` from GCC are not supported.
3621
3622The symbol used for ``thunk-extern`` is target specific:
3623* X86: ``__x86_return_thunk``
3624
3625As such, this function attribute is currently only supported on X86 targets.)reST";
3626
3627static const char AttrDoc_GCCStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
3628special record layout compatibility mode which mimics the layout of Microsoft or
3629Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3630requested ABI, the attribute does nothing. However, if it does not, annotated
3631structure or class is laid out in a special compatibility mode, which slightly
3632changes offsets for fields and bit-fields. The intention is to match the layout
3633of the requested ABI for structures which only use C features.
3634
3635Note that the default behavior can be controlled by ``-mms-bitfields`` and
3636``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
3637
3638The primary difference is for bitfields, where the MS variant only packs
3639adjacent fields into the same allocation unit if they have integral types
3640of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3641tightly.)reST";
3642
3643static const char AttrDoc_GNUInline[] = R"reST(The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
3644semantics, meaning:
3645
3646* If any declaration that is declared ``inline`` is not declared ``extern``,
3647 then the ``inline`` keyword is just a hint. In particular, an out-of-line
3648 definition is still emitted for a function with external linkage, even if all
3649 call sites are inlined, unlike in C99 and C++ inline semantics.
3650
3651* If all declarations that are declared ``inline`` are also declared
3652 ``extern``, then the function body is present only for inlining and no
3653 out-of-line version is emitted.
3654
3655Some important consequences: ``static inline`` emits an out-of-line
3656version if needed, a plain ``inline`` definition emits an out-of-line version
3657always, and an ``extern inline`` definition (in a header) followed by a
3658(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
3659version of the function in that source file but provides the function body for
3660inlining to all includers of the header.
3661
3662Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
3663``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
3664exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
3665function attribute can be used to get GNU inline semantics on a per function
3666basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
3667already being compiled with GNU inline semantics as the implied default. It is
3668unspecified which macro is defined in a C++ compilation.
3669
3670GNU inline semantics are the default behavior with ``-std=gnu89``,
3671``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.)reST";
3672
3673static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3674
3675static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3676
3677static const char AttrDoc_HIPManaged[] = R"reST(The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
3678A managed variable is emitted as an undefined global symbol in the device binary and is
3679registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
3680managed memory and uses it to define the symbol when loading the device binary.
3681A managed variable can be accessed in both device and host code.)reST";
3682
3683static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3684
3685static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3686
3687static const char AttrDoc_HLSLColumnMajor[] = R"reST(The ``row_major`` and ``column_major`` keywords specify the memory layout
3688of an HLSL matrix type.
3689
3690* ``row_major``: Matrices are stored in memory row-by-row.
3691* ``column_major``: Matrices are stored in memory column-by-column (default).
3692
3693Example:
3694.. code-block:: hlsl
3695
3696 row_major float2x2 myMatrix;)reST";
3697
3698static const char AttrDoc_HLSLContainedType[] = R"reST()reST";
3699
3700static const char AttrDoc_HLSLControlFlowHint[] = R"reST()reST";
3701
3702static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3703HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3704and so on to ensure the correct ordering of reads and writes to shared memory
3705in the shader and to avoid data races.
3706Here's an example to declare a groupshared variable.
3707.. code-block:: c++
3708
3709 groupshared GSData data[5*5*1];
3710
3711The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared)reST";
3712
3713static const char AttrDoc_HLSLIsArray[] = R"reST()reST";
3714
3715static const char AttrDoc_HLSLIsCounter[] = R"reST()reST";
3716
3717static const char AttrDoc_HLSLLoopHint[] = R"reST(The ``[loop]`` directive allows loop optimization hints to be
3718specified for the subsequent loop. The directive allows unrolling to
3719be disabled and is not compatible with [unroll(x)].
3720
3721Specifying the parameter, ``[loop]``, directs the
3722unroller to not unroll the loop.
3723
3724.. code-block:: hlsl
3725
3726 [loop]
3727 for (...) {
3728 ...
3729 }
3730
3731.. code-block:: hlsl
3732
3733 [loop]
3734 while (...) {
3735 ...
3736 }
3737
3738.. code-block:: hlsl
3739
3740 [loop]
3741 do {
3742 ...
3743 } while (...)
3744
3745See `hlsl loop extensions <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for>`_
3746for details.)reST";
3747
3748static const char AttrDoc_HLSLNumThreads[] = R"reST(The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts
3749are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute
3750dictate the thread id. Total number of threads executed is ``X * Y * Z``.
3751
3752The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)reST";
3753
3754static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3755Attribute spelling in HLSL is: ``packoffset( c[Subcomponent][.component] )``.
3756A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3757
3758Examples:
3759
3760.. code-block:: hlsl
3761
3762 cbuffer A {
3763 float3 a : packoffset(c0.y);
3764 float4 b : packoffset(c4);
3765 }
3766
3767The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset)reST";
3768
3769static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3770three qualifiers to denote parameter passing behavior. The three qualifiers are
3771`in`, `out` and `inout`.
3772
3773Parameters annotated with `in` or with no annotation are passed by value from
3774the caller to the callee.
3775
3776Parameters annotated with `out` are written to the argument after the callee
3777returns (Note: arguments values passed into `out` parameters *are not* copied
3778into the callee).
3779
3780Parameters annotated with `inout` are copied into the callee via a temporary,
3781and copied back to the argument after the callee returns.)reST";
3782
3783static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3784
3785static const char AttrDoc_HLSLROV[] = R"reST()reST";
3786
3787static const char AttrDoc_HLSLRawBuffer[] = R"reST()reST";
3788
3789static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3790Attribute spelling in HLSL is: ``register(slot [, space])``.
3791``slot`` takes the format ``[type][number]``,
3792where ``type`` is a single character specifying the resource type and ``number`` is the virtual register number.
3793
3794Register types are:
3795t for shader resource views (SRV),
3796s for samplers,
3797u for unordered access views (UAV),
3798b for constant buffer views (CBV).
3799
3800Register space is specified in the format ``space[number]`` and defaults to ``space0`` if omitted.
3801Here're resource binding examples with and without space:
3802
3803.. code-block:: hlsl
3804
3805 RWBuffer<float> Uav : register(u3, space1);
3806 Buffer<float> Buf : register(t1);
3807
3808The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl)reST";
3809
3810static const char AttrDoc_HLSLResourceClass[] = R"reST()reST";
3811
3812static const char AttrDoc_HLSLResourceDimension[] = R"reST()reST";
3813
3814static const char AttrDoc_HLSLRowMajor[] = R"reST(The ``row_major`` and ``column_major`` keywords specify the memory layout
3815of an HLSL matrix type.
3816
3817* ``row_major``: Matrices are stored in memory row-by-row.
3818* ``column_major``: Matrices are stored in memory column-by-column (default).
3819
3820Example:
3821.. code-block:: hlsl
3822
3823 row_major float2x2 myMatrix;)reST";
3824
3825static const char AttrDoc_HLSLShader[] = R"reST(The ``shader`` type attribute applies to HLSL shader entry functions to
3826identify the shader type for the entry function.
3827The syntax is:
3828
3829.. code-block:: text
3830
3831 ``[shader(string-literal)]``
3832
3833where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3834"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3835"miss", "callable", "mesh", "amplification". Normally the shader type is set
3836by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
3837library target like ``lib_6_3``, the shader type attribute can help the
3838compiler to identify the shader type. It is mostly used by Raytracing shaders
3839where shaders must be compiled into a library and linked at runtime.)reST";
3840
3841static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
3842
3843static const char AttrDoc_HLSLVkBinding[] = R"reST(The ``[[vk::binding]]`` attribute allows you to explicitly specify the descriptor
3844set and binding for a resource when targeting SPIR-V. This is particularly
3845useful when you need different bindings for SPIR-V and DXIL, as the ``register``
3846attribute can be used for DXIL-specific bindings.
3847
3848The attribute takes two integer arguments: the binding and the descriptor set.
3849The descriptor set is optional and defaults to 0 if not provided.
3850
3851.. code-block:: c++
3852
3853 // A structured buffer with binding 23 in descriptor set 102.
3854 [[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
3855
3856 // A structured buffer with binding 14 in descriptor set 0.
3857 [[vk::binding(14)]] StructuredBuffer<float> Buf2;
3858
3859 // A cbuffer with binding 1 in descriptor set 2.
3860 [[vk::binding(1, 2)]] cbuffer MyCBuffer {
3861 float4x4 worldViewProj;
3862 };)reST";
3863
3864static const char AttrDoc_HLSLVkConstantId[] = R"reST(The ``vk::constant_id`` attribute specifies the id for a SPIR-V specialization
3865constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
3866In SPIR-V, the
3867variable will be replaced with an `OpSpecConstant` with the given id.
3868The syntax is:
3869
3870.. code-block:: text
3871
3872 ``[[vk::constant_id(<Id>)]] const T Name = <Init>``)reST";
3873
3874static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
3875initialized by the driver/pipeline, but each copy is private to the current
3876lane.
3877
3878Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
3879like follows:
3880
3881.. code-block:: c++
3882
3883 [[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
3884 static const uint3 groupid;
3885
3886This variable will be lowered into a module-level variable, with the `Input`
3887storage class, and the `BuiltIn 26` decoration.
3888
3889The full documentation for this inline SPIR-V attribute can be found here:
3890https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3891
3892static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
3893visible to the driver/pipeline, but each copy is private to the current
3894lane.
3895
3896Those builtins can be declared using the `[[vk::ext_builtin_output]]`
3897attribute like follows:
3898
3899.. code-block:: c++
3900
3901 [[vk::ext_builtin_output(/* Position */ 0)]]
3902 static float4 position;
3903
3904This variable will be lowered into a module-level variable, with the `Output`
3905storage class, and the `BuiltIn 0` decoration.
3906
3907The full documentation for this inline SPIR-V attribute can be found here:
3908https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3909
3910static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
3911variables. Allowed on function parameters, function returns, and struct
3912fields. This parameter has no effect when used outside of an entrypoint
3913parameter/parameter field/return value.
3914
3915This attribute maps to the 'Location' SPIR-V decoration.)reST";
3916
3917static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
3918
3919The ``[[vk::push_constant]]`` attribute allows you to declare this
3920global variable as a push constant when targeting Vulkan.
3921This attribute is ignored otherwise.
3922
3923This attribute must be applied to the variable, not underlying type.
3924The variable type must be a struct, per the requirements of Vulkan, "there
3925must be no more than one push constant block statically used per shader entry
3926point.")reST";
3927
3928static const char AttrDoc_HLSLWaveSize[] = R"reST(The ``WaveSize`` attribute specify a wave size on a shader entry point in order
3929to indicate either that a shader depends on or strongly prefers a specific wave
3930size.
3931There're 2 versions of the attribute: ``WaveSize`` and ``RangedWaveSize``.
3932The syntax for ``WaveSize`` is:
3933
3934.. code-block:: text
3935
3936 ``[WaveSize(<numLanes>)]``
3937
3938The allowed wave sizes that an HLSL shader may specify are the powers of 2
3939between 4 and 128, inclusive.
3940In other words, the set: [4, 8, 16, 32, 64, 128].
3941
3942The syntax for ``RangedWaveSize`` is:
3943
3944.. code-block:: text
3945
3946 ``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
3947
3948Where minWaveSize is the minimum wave size supported by the shader representing
3949the beginning of the allowed range, maxWaveSize is the maximum wave size
3950supported by the shader representing the end of the allowed range, and
3951prefWaveSize is the optional preferred wave size representing the size expected
3952to be the most optimal for this shader.
3953
3954``WaveSize`` is available for HLSL shader model 6.6 and later.
3955``RangedWaveSize`` available for HLSL shader model 6.8 and later.
3956
3957The full documentation is available here: https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html
3958and https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html)reST";
3959
3960static const char AttrDoc_Hot[] = R"reST(``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data.
3961If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``).)reST";
3962
3963static const char AttrDoc_HybridPatchable[] = R"reST(The ``hybrid_patchable`` attribute declares an ARM64EC function with an additional
3964x86-64 thunk, which may be patched at runtime.
3965
3966For more information see
3967`ARM64EC ABI documentation <https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi>`_.)reST";
3968
3969static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
3970
3971static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
3972
3973static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
3974
3975static const char AttrDoc_IFunc[] = R"reST(``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
3976declaration should be resolved at runtime by calling a resolver function.
3977
3978The symbol name of the resolver function is given in quotes. A function with
3979this name (after mangling) must be defined in the current translation unit; it
3980may be ``static``. The resolver function should return a pointer.
3981
3982The ``ifunc`` attribute may only be used on a function declaration. A function
3983declaration with an ``ifunc`` attribute is considered to be a definition of the
3984declared entity. The entity must not have weak linkage; for example, in C++,
3985it cannot be applied to a declaration if a definition at that location would be
3986considered inline.
3987
3988Not all targets support this attribute:
3989
3990- ELF target support depends on both the linker and runtime linker, and is
3991 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
3992 v2.11.1 and later, and FreeBSD 9.1 and later.
3993- Mach-O targets support it, but with slightly different semantics: the resolver
3994 is run at first call, instead of at load time by the runtime linker.
3995- Windows target supports it on AArch64, but with different semantics: the
3996 ``ifunc`` is replaced with a global function pointer, and the call is replaced
3997 with an indirect call. The function pointer is initialized by a constructor
3998 that calls the resolver.
3999- Baremetal target supports it on AVR.
4000- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
4001 regular function (has an entry point ``.foo[PR]`` and a function descriptor
4002 ``foo[DS]``). The entry point is a stub that branches to the function address
4003 in the descriptor, and the descriptor is initialized via a constructor
4004 function (``__init_ifuncs``) that is linked into every shared object and
4005 executable. ``__init_ifuncs`` calls the resolver of each ifunc and stores the
4006 result in the corresponding descriptor.
4007- Other targets currently do not support this attribute.)reST";
4008
4009static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
4010
4011static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
4012units is unspecified, unlike the ordering within a single translation unit. The
4013``init_priority`` attribute allows you to specify a relative ordering for the
4014initialization of objects declared at namespace scope in C++ within a single
4015linked image on supported platforms. The priority is given as an integer constant
4016expression between 101 and 65535 (inclusive). Priorities outside of that range are
4017reserved for use by the implementation. A lower value indicates a higher priority
4018of initialization. Note that only the relative ordering of values is important.
4019For example:
4020
4021.. code-block:: c++
4022
4023 struct SomeType { SomeType(); };
4024 __attribute__((init_priority(200))) SomeType Obj1;
4025 __attribute__((init_priority(101))) SomeType Obj2;
4026
4027``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
4028initialization being the opposite.
4029
4030Note that this attribute does not control the initialization order of objects
4031across final linked image boundaries like shared objects and executables.
4032
4033On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and
4034``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)``
4035uses the default 65535 priority.
4036
4037On MachO platforms, this attribute also does not control the order of initialization
4038across translation units, where it only affects the order within a single TU.
4039
4040This attribute is only supported for C++ and Objective-C++ and is ignored in
4041other language modes.)reST";
4042
4043static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by ``pragma init_seg()`` controls the section into
4044which global initialization function pointers are emitted. It is only
4045available with ``-fms-extensions``. Typically, this function pointer is
4046emitted into ``.CRT$XCU`` on Windows. The user can change the order of
4047initialization by using a different section name with the same
4048``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
4049after the standard ``.CRT$XCU`` sections. See the init_seg_
4050documentation on MSDN for more information.
4051
4052.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
4053
4054static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
4055
4056static const char AttrDoc_InternalLinkage[] = R"reST(The ``internal_linkage`` attribute changes the linkage type of the declaration
4057to internal. This is similar to C-style ``static``, but can be used on classes
4058and class methods. When applied to a class definition, this attribute affects
4059all methods and static data members of that class. This can be used to contain
4060the ABI of a C++ library by excluding unwanted class methods from the export
4061tables.)reST";
4062
4063static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See :doc:`LTOVisibility`.)reST";
4064
4065static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
4066layout rules of a particular compiler version.
4067This attribute only applies to struct, class, and union types.
4068It is only supported when using the Microsoft C++ ABI.)reST";
4069
4070static const char AttrDoc_Leaf[] = R"reST(The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
4071in library functions. Functions marked with the ``leaf`` attribute are not allowed
4072to jump back into the caller's translation unit, whether through invoking a
4073callback function, an external function call, use of ``longjmp``, or other means.
4074Therefore, they cannot use or modify any data that does not escape the caller function's
4075compilation unit.
4076
4077For more information see
4078`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
4079
4080static const char AttrDoc_LifetimeBound[] = R"reST(The ``lifetimebound`` attribute on a function parameter or implicit object
4081parameter indicates that objects that are referred to by that parameter may
4082also be referred to by the return value of the annotated function (or, for a
4083parameter of a constructor, by the value of the constructed object).
4084
4085By default, a reference is considered to refer to its referenced object, a
4086pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
4087is considered to refer to its underlying array, and aggregates (arrays and
4088simple ``struct``\s) are considered to refer to all objects that their
4089transitive subobjects refer to.
4090
4091Clang warns if it is able to detect that an object or reference refers to
4092another object with a shorter lifetime. For example, Clang will warn if a
4093function returns a reference to a local variable, or if a reference is bound to
4094a temporary object whose lifetime is not extended. By using the
4095``lifetimebound`` attribute, this determination can be extended to look through
4096user-declared functions. For example:
4097
4098.. code-block:: c++
4099
4100 #include <map>
4101 #include <string>
4102
4103 using namespace std::literals;
4104
4105 // Returns m[key] if key is present, or default_value if not.
4106 template<typename T, typename U>
4107 const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4108 const T &key, /* note, not lifetimebound */
4109 const U &default_value [[clang::lifetimebound]]) {
4110 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4111 else return default_value;
4112 }
4113
4114 int main() {
4115 std::map<std::string, std::string> m;
4116 // warning: temporary bound to local reference 'val1' will be destroyed
4117 // at the end of the full-expression
4118 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4119
4120 // No warning in this case.
4121 std::string def_val = "bar"s;
4122 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4123
4124 return 0;
4125 }
4126
4127The attribute can be applied to the implicit ``this`` parameter of a member
4128function by writing the attribute after the function type:
4129
4130.. code-block:: c++
4131
4132 struct string {
4133 // The returned pointer should not outlive ``*this``.
4134 const char *data() const [[clang::lifetimebound]];
4135 };
4136
4137This attribute is inspired by the C++ committee paper `P0936R0
4138<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects
4139have their lifetimes extended.)reST";
4140
4141static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to `lifetimebound`_, the ``lifetime_capture_by(X)`` attribute on a
4142function parameter or implicit object parameter indicates that the capturing
4143entity ``X`` may refer to the object referred by that parameter.
4144
4145Below is a list of types of the parameters and what they're considered to refer to:
4146
4147- A reference param (of non-view type) is considered to refer to its referenced object.
4148- A pointer param (of non-view type) is considered to refer to its pointee.
4149- View type param (type annotated with ``[[gsl::Pointer()]]``) is considered to refer
4150 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4151 in the parameter. For example, both ``std::string_view`` and
4152 ``const std::string_view &`` are considered to refer to a ``std::string``.
4153- A ``std::initializer_list<T>`` is considered to refer to its underlying array.
4154- Aggregates (arrays and simple ``struct``\s) are considered to refer to all
4155 objects that their transitive subobjects refer to.
4156
4157Clang would diagnose when a temporary object is used as an argument to such an
4158annotated parameter.
4159In this case, the capturing entity ``X`` could capture a dangling reference to this
4160temporary object.
4161
4162.. code-block:: c++
4163
4164 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4165 s.insert(a);
4166 }
4167 void use() {
4168 std::set<std::string_view> s;
4169 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4170 // ^^^^^^^^^^^^^
4171 std::string local;
4172 addToSet(local, s); // Ok.
4173 }
4174
4175The capturing entity ``X`` can be one of the following:
4176
4177- Another (named) function parameter.
4178
4179 .. code-block:: c++
4180
4181 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4182 s.insert(a);
4183 }
4184
4185- ``this`` (in case of member functions).
4186
4187 .. code-block:: c++
4188
4189 class S {
4190 void addToSet(std::string_view a [[clang::lifetime_capture_by(this)]]) {
4191 s.insert(a);
4192 }
4193 std::set<std::string_view> s;
4194 };
4195
4196 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by(this)]]` is just an alias of `[[clang::lifetimebound]]`.
4197
4198- `global`, `unknown`.
4199
4200 .. code-block:: c++
4201
4202 std::set<std::string_view> s;
4203 void addToSet(std::string_view a [[clang::lifetime_capture_by(global)]]) {
4204 s.insert(a);
4205 }
4206 void addSomewhere(std::string_view a [[clang::lifetime_capture_by(unknown)]]);
4207
4208The attribute can be applied to the implicit ``this`` parameter of a member
4209function by writing the attribute after the function type:
4210
4211.. code-block:: c++
4212
4213 struct S {
4214 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4215 s.insert(this);
4216 }
4217 };
4218
4219The attribute supports specifying more than one capturing entities:
4220
4221.. code-block:: c++
4222
4223 void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4224 std::set<std::string_view>& s1,
4225 std::set<std::string_view>& s2) {
4226 s1.insert(a);
4227 s2.insert(a);
4228 }
4229
4230Limitation: The capturing entity ``X`` is not used by the analysis and is
4231used for documentation purposes only. This is because the analysis is
4232statement-local and only detects use of a temporary as an argument to the
4233annotated parameter.
4234
4235.. code-block:: c++
4236
4237 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4238 void use() {
4239 std::set<std::string_view> s;
4240 if (foo()) {
4241 std::string str;
4242 addToSet(str, s); // Not detected.
4243 }
4244 })reST";
4245
4246static const char AttrDoc_Likely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
4247The attributes are used to aid the compiler to determine which branch is
4248likely or unlikely to be taken. This is done by marking the branch substatement
4249with one of the two attributes.
4250
4251It isn't allowed to annotate a single statement with both ``likely`` and
4252``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
4253statement with the same likelihood attribute will result in a diagnostic and
4254the attributes are ignored on both branches.
4255
4256In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
4257or the ``default`` label with the same likelihood attribute. This makes
4258* all labels without an attribute have a neutral likelihood,
4259* all labels marked ``[[likely]]`` have an equally positive likelihood, and
4260* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
4261The neutral likelihood is the more likely of path execution than the negative
4262likelihood. The positive likelihood is the more likely of path of execution
4263than the neutral likelihood.
4264
4265These attributes have no effect on the generated code when using
4266PGO (Profile-Guided Optimization) or at optimization level 0.
4267
4268In Clang, the attributes will be ignored if they're not placed on
4269* the ``case`` or ``default`` label of a ``switch`` statement,
4270* or on the substatement of an ``if`` or ``else`` statement,
4271* or on the substatement of an ``for`` or ``while`` statement.
4272The C++ Standard recommends to honor them on every statement in the
4273path of execution, but that can be confusing:
4274
4275.. code-block:: c++
4276
4277 if (b) {
4278 [[unlikely]] --b; // Per the standard this is in the path of
4279 // execution, so this branch should be considered
4280 // unlikely. However, Clang ignores the attribute
4281 // here since it is not on the substatement.
4282 }
4283
4284 if (b) {
4285 --b;
4286 if(b)
4287 return;
4288 [[unlikely]] --b; // Not in the path of execution,
4289 } // the branch has no likelihood information.
4290
4291 if (b) {
4292 --b;
4293 foo(b);
4294 // Whether or not the next statement is in the path of execution depends
4295 // on the declaration of foo():
4296 // In the path of execution: void foo(int);
4297 // Not in the path of execution: [[noreturn]] void foo(int);
4298 // This means the likelihood of the branch depends on the declaration
4299 // of foo().
4300 [[unlikely]] --b;
4301 }
4302
4303
4304Below are some example usages of the likelihood attributes and their effects:
4305
4306.. code-block:: c++
4307
4308 if (b) [[likely]] { // Placement on the first statement in the branch.
4309 // The compiler will optimize to execute the code here.
4310 } else {
4311 }
4312
4313 if (b)
4314 [[unlikely]] b++; // Placement on the first statement in the branch.
4315 else {
4316 // The compiler will optimize to execute the code here.
4317 }
4318
4319 if (b) {
4320 [[unlikely]] b++; // Placement on the second statement in the branch.
4321 } // The attribute will be ignored.
4322
4323 if (b) [[likely]] {
4324 [[unlikely]] b++; // No contradiction since the second attribute
4325 } // is ignored.
4326
4327 if (b)
4328 ;
4329 else [[likely]] {
4330 // The compiler will optimize to execute the code here.
4331 }
4332
4333 if (b)
4334 ;
4335 else
4336 // The compiler will optimize to execute the next statement.
4337 [[likely]] b = f();
4338
4339 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4340 else [[likely]]; // and the attributes are ignored.
4341
4342 if (b)
4343 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4344 // isn't allowed on a declaration.
4345
4346 switch (i) {
4347 [[likely]] case 1: // This value is likely
4348 ...
4349 break;
4350
4351 [[unlikely]] case 2: // This value is unlikely
4352 ...
4353 [[fallthrough]];
4354
4355 case 3: // No likelihood attribute
4356 ...
4357 [[likely]] break; // No effect
4358
4359 case 4: [[likely]] { // attribute on substatement has no effect
4360 ...
4361 break;
4362 }
4363
4364 [[unlikely]] default: // All other values are unlikely
4365 ...
4366 break;
4367 }
4368
4369 switch (i) {
4370 [[likely]] case 0: // This value and code path is likely
4371 ...
4372 [[fallthrough]];
4373
4374 case 1: // No likelihood attribute, code path is neutral
4375 break; // falling through has no effect on the likelihood
4376
4377 case 2: // No likelihood attribute, code path is neutral
4378 [[fallthrough]];
4379
4380 [[unlikely]] default: // This value and code path are both unlikely
4381 break;
4382 }
4383
4384 for(int i = 0; i != size; ++i) [[likely]] {
4385 ... // The loop is the likely path of execution
4386 }
4387
4388 for(const auto &E : Elements) [[likely]] {
4389 ... // The loop is the likely path of execution
4390 }
4391
4392 while(i != size) [[unlikely]] {
4393 ... // The loop is the unlikely path of execution
4394 } // The generated code will optimize to skip the loop body
4395
4396 while(true) [[unlikely]] {
4397 ... // The attribute has no effect
4398 } // Clang elides the comparison and generates an infinite
4399 // loop)reST";
4400
4401static const char AttrDoc_LoaderUninitialized[] = R"reST(The ``loader_uninitialized`` attribute can be placed on global variables to
4402indicate that the variable does not need to be zero initialized by the loader.
4403On most targets, zero-initialization does not incur any additional cost.
4404For example, most general purpose operating systems deliberately ensure
4405that all memory is properly initialized in order to avoid leaking privileged
4406information from the kernel or other programs. However, some targets
4407do not make this guarantee, and on these targets, avoiding an unnecessary
4408zero-initialization can have a significant impact on load times and/or code
4409size.
4410
4411A declaration with this attribute is a non-tentative definition just as if it
4412provided an initializer. Variables with this attribute are considered to be
4413uninitialized in the same sense as a local variable, and the programs must
4414write to them before reading from them. If the variable's type is a C++ class
4415type with a non-trivial default constructor, or an array thereof, this attribute
4416only suppresses the static zero-initialization of the variable, not the dynamic
4417initialization provided by executing the default constructor.)reST";
4418
4419static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4420
4421static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4422
4423static const char AttrDoc_LoopHint[] = R"reST(The ``#pragma clang loop`` directive allows loop optimization hints to be
4424specified for the subsequent loop. The directive allows pipelining to be
4425disabled, or vectorization, vector predication, interleaving, and unrolling to
4426be enabled or disabled. Vector width, vector predication, interleave count,
4427unrolling count, and the initiation interval for pipelining can be explicitly
4428specified. See `language extensions
4429<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
4430for details.)reST";
4431
4432static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4433
4434static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4435to clear parameters off the stack on return. In other words, callee is
4436responsible for cleaning out the stack space allocated for incoming paramters.
4437This convention does not support variadic calls or unprototyped functions in C.
4438When targeting M68010 or newer CPUs, this calling convention is implemented
4439using the `rtd` instruction.)reST";
4440
4441static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4442functions that follow it to only release arguments passed to them when they
4443return "success" (a ``kern_return_t`` error code that indicates that
4444no errors have occurred). Otherwise the release is performed by the MIG client
4445that called the function. The annotation ``__attribute__((mig_server_routine))``
4446is applied in order to specify which functions are expected to follow the
4447convention. This allows the Static Analyzer to find bugs caused by violations of
4448that convention. The attribute would normally appear on the forward declaration
4449of the actual server routine in the MIG server header, but it may also be
4450added to arbitrary functions that need to follow the same convention - for
4451example, a user can add them to auxiliary functions called by the server routine
4452that have their return value of type ``kern_return_t`` unconditionally returned
4453from the routine. The attribute can be applied to C++ methods, and in this case
4454it will be automatically applied to overrides if the method is virtual. The
4455attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.)reST";
4456
4457static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4458a function to match the default convention used on Windows. This
4459attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4460
4461static const char AttrDoc_MSAllocator[] = R"reST(The ``__declspec(allocator)`` attribute is applied to functions that allocate
4462memory, such as operator new in C++. When CodeView debug information is emitted
4463(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4464record the code offset of heap allocation call sites in the debug info. It will
4465also record the type being allocated using some local heuristics. The Visual
4466Studio debugger uses this information to `profile memory usage`_.
4467
4468.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4469
4470This attribute does not affect optimizations in any way, unlike GCC's
4471``__attribute__((malloc))``.)reST";
4472
4473static const char AttrDoc_MSConstexpr[] = R"reST(The ``[[msvc::constexpr]]`` attribute can be applied only to a function
4474definition or a ``return`` statement. It does not impact function declarations.
4475A ``[[msvc::constexpr]]`` function cannot be ``constexpr`` or ``consteval``.
4476A ``[[msvc::constexpr]]`` function is treated as if it were a ``constexpr`` function
4477when it is evaluated in a constant context of ``[[msvc::constexpr]] return`` statement.
4478Otherwise, it is treated as a regular function.
4479
4480Semantics of this attribute are enabled only under MSVC compatibility
4481(``-fms-compatibility-version``) 19.33 and later.)reST";
4482
4483static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under ``-fms-extensions`` and controls
4484the pointer-to-member representation used on ``*-*-win32`` targets.
4485
4486The ``*-*-win32`` targets utilize a pointer-to-member representation which
4487varies in size and alignment depending on the definition of the underlying
4488class.
4489
4490However, this is problematic when a forward declaration is only available and
4491no definition has been made yet. In such cases, Clang is forced to utilize the
4492most general representation that is available to it.
4493
4494These keywords make it possible to use a pointer-to-member representation other
4495than the most general one regardless of whether or not the definition will ever
4496be present in the current translation unit.
4497
4498This family of keywords belong between the ``class-key`` and ``class-name``:
4499
4500.. code-block:: c++
4501
4502 struct __single_inheritance S;
4503 int S::*i;
4504 struct S {};
4505
4506This keyword can be applied to class templates but only has an effect when used
4507on full specializations:
4508
4509.. code-block:: c++
4510
4511 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4512 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4513 template <> struct __single_inheritance A<int, float>;
4514
4515Note that choosing an inheritance model less general than strictly necessary is
4516an error:
4517
4518.. code-block:: c++
4519
4520 struct __multiple_inheritance S; // error: inheritance model does not match definition
4521 int S::*i;
4522 struct S {};)reST";
4523
4524static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4525the compiler that constructors and destructors will not reference the virtual
4526function table. It is only supported when using the Microsoft C++ ABI.)reST";
4527
4528static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4529
4530static const char AttrDoc_MSStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
4531special record layout compatibility mode which mimics the layout of Microsoft or
4532Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4533requested ABI, the attribute does nothing. However, if it does not, annotated
4534structure or class is laid out in a special compatibility mode, which slightly
4535changes offsets for fields and bit-fields. The intention is to match the layout
4536of the requested ABI for structures which only use C features.
4537
4538Note that the default behavior can be controlled by ``-mms-bitfields`` and
4539``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
4540
4541The primary difference is for bitfields, where the MS variant only packs
4542adjacent fields into the same allocation unit if they have integral types
4543of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4544tightly.)reST";
4545
4546static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4547
4548static const char AttrDoc_MallocSpan[] = R"reST(The ``malloc_span`` attribute can be used to mark that a function which acts
4549like a system memory allocation function and returns a span-like structure,
4550where the returned memory range does not alias storage from any other object
4551accessible to the caller.
4552
4553In this context, a span-like structure is assumed to have two non-static data
4554members, one of which is a pointer to the start of the allocated memory and
4555the other one is either an integer type containing the size of the actually
4556allocated memory or a pointer to the end of the allocated region. Note, static
4557data members do not impact whether a type is span-like or not.)reST";
4558
4559static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4560
4561static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4562
4563static const char AttrDoc_MaybeUndef[] = R"reST(The ``maybe_undef`` attribute can be placed on a function parameter. It indicates
4564that the parameter is allowed to use undef values. It informs the compiler
4565to insert a freeze LLVM IR instruction on the function parameter.
4566Please note that this is an attribute that is used as an internal
4567implementation detail and not intended to be used by external users.
4568
4569In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4570it is enough for only one or some threads to provide defined arguments.
4571Depending on semantics, undef arguments in some threads don't produce
4572undefined results in the function call. Since, these functions accept undefined
4573arguments, ``maybe_undef`` attribute can be placed.
4574
4575Sample usage:
4576.. code-block:: c
4577
4578 void maybeundeffunc(int __attribute__((maybe_undef))param);)reST";
4579
4580static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
4581``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
4582may be attached to a function definition and instructs the backend to generate
4583or not to generate microMIPS code for that function.
4584
4585These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
4586on the command line.)reST";
4587
4588static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4589make choices that keep the function code size as small as possible. Optimizations may
4590also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4591
4592static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
4593attribute may be attached to a function and informs the backend that this
4594function desires vectors of at least this width to be generated. Target-specific
4595maximum vector widths still apply. This means even if you ask for something
4596larger than the target supports, you will only get what the target supports.
4597This attribute is meant to be a hint to control target heuristics that may
4598generate narrower vectors than what the target hardware supports.
4599
4600This is currently used by the X86 target to allow some CPUs that support 512-bit
4601vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4602This is currently enabled with the ``-prefer-vector-width=256`` command line
4603option. The ``min_vector_width`` attribute can be used to prevent the backend
4604from trying to split vector operations to match the ``prefer-vector-width``. All
4605X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4606use of any of the X86-specific vector builtins will implicitly set this
4607attribute on the calling function. The intent is that explicitly writing vector
4608code using the X86 intrinsics will prevent ``prefer-vector-width`` from
4609affecting the code.)reST";
4610
4611static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4612
4613static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
4614MIPS targets. This attribute may be attached to a function definition and instructs
4615the backend to generate appropriate function entry/exit code so that it can be used
4616directly as an interrupt service routine.
4617
4618By default, the compiler will produce a function prologue and epilogue suitable for
4619an interrupt service routine that handles an External Interrupt Controller (eic)
4620generated interrupt. This behavior can be explicitly requested with the "eic"
4621argument.
4622
4623Otherwise, for use with vectored interrupt mode, the argument passed should be
4624of the form "vector=LEVEL" where LEVEL is one of the following values:
4625"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4626then set the interrupt mask to the corresponding level which will mask all
4627interrupts up to and including the argument.
4628
4629The semantics are as follows:
4630
4631- The prologue is modified so that the Exception Program Counter (EPC) and
4632 Status coprocessor registers are saved to the stack. The interrupt mask is
4633 set so that the function can only be interrupted by a higher priority
4634 interrupt. The epilogue will restore the previous values of EPC and Status.
4635
4636- The prologue and epilogue are modified to save and restore all non-kernel
4637 registers as necessary.
4638
4639- The FPU is disabled in the prologue, as the floating pointer registers are not
4640 spilled to the stack.
4641
4642- The function return sequence is changed to use an exception return instruction.
4643
4644- The parameter sets the interrupt mask for the function corresponding to the
4645 interrupt level specified. If no mask is specified the interrupt mask
4646 defaults to "eic".)reST";
4647
4648static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4649and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
4650only be added to function declarations and change the code generated
4651by the compiler when directly calling the function. The ``near`` attribute
4652allows calls to the function to be made using the ``jal`` instruction, which
4653requires the function to be located in the same naturally aligned 256MB
4654segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
4655and require the use of a different call sequence that works regardless
4656of the distance between the functions.
4657
4658These attributes have no effect for position-independent code.
4659
4660These attributes take priority over command line switches such
4661as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4662
4663static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4664``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
4665on MIPS targets. These attributes may only be added to function declarations
4666and change the code generated by the compiler when directly calling
4667the function. The ``short_call`` and ``near`` attributes are synonyms and
4668allow calls to the function to be made using the ``jal`` instruction, which
4669requires the function to be located in the same naturally aligned 256MB segment
4670as the caller. The ``long_call`` and ``far`` attributes are synonyms and
4671require the use of a different call sequence that works regardless
4672of the distance between the functions.
4673
4674These attributes have no effect for position-independent code.
4675
4676These attributes take priority over command line switches such
4677as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4678
4679static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4680
4681static const char AttrDoc_ModularFormat[] = R"reST(The ``modular_format`` attribute can be applied to a function that bears the
4682``format`` attribute (or standard library functions) to indicate that the
4683implementation is "modular", that is, that the implementation is logically
4684divided into a number of named aspects. When the compiler can determine that
4685not all aspects of the implementation are needed for a given call, the compiler
4686may redirect the call to the identifier given as the first argument to the
4687attribute (the modular implementation function).
4688
4689The second argument is an implementation name, and the remaining arguments are
4690aspects of the format string for the compiler to report. The implementation
4691name is an unevaluated identifier in the C namespace.
4692
4693The compiler reports that a call requires an aspect by issuing a relocation for
4694the symbol ``<impl_name>_<aspect>`` at the point of the call. This arranges for
4695code and data needed to support the aspect of the implementation to be brought
4696into the link to satisfy weak references in the modular implemenation function.
4697If the compiler does not understand an aspect, it must summarily consider any
4698call to require that aspect.
4699
4700For example, say ``printf`` is annotated with
4701``modular_format(__modular_printf, "__printf", "float")``. Then, a call to
4702``printf(var, 42)`` would be untouched. A call to ``printf("%d", 42)`` would
4703become a call to ``__modular_printf`` with the same arguments, as would
4704``printf("%f", 42.0)``. The latter would be accompanied with a strong
4705relocation against the symbol ``__printf_float``, which would bring floating
4706point support for ``printf`` into the link.
4707
4708If the attribute appears more than once on a declaration, or across a chain of
4709redeclarations, it is an error for the attributes to have different arguments,
4710excepting that the aspects may be in any order.
4711
4712The following aspects are currently supported:
4713
4714- ``fixed``: The call has a C ISO 18037 fixed-point argument.
4715- ``float``: The call has a floating-point argument.)reST";
4716
4717static const char AttrDoc_MustTail[] = R"reST(If a ``return`` statement is marked ``musttail``, this indicates that the
4718compiler must generate a tail call for the program to be correct, even when
4719optimizations are disabled. This guarantees that the call will not cause
4720unbounded stack growth if it is part of a recursive cycle in the call graph.
4721
4722If the callee is a virtual function that is implemented by a thunk, there is
4723no guarantee in general that the thunk tail-calls the implementation of the
4724virtual function, so such a call in a recursive cycle can still result in
4725unbounded stack growth.
4726
4727``clang::musttail`` can only be applied to a ``return`` statement whose value
4728is the result of a function call (even functions returning void must use
4729``return``, although no value is returned). The target function must have the
4730same number of arguments as the caller. The types of the return value and all
4731arguments must be similar according to C++ rules (differing only in cv
4732qualifiers or array size), including the implicit "this" argument, if any.
4733Any variables in scope, including all arguments to the function and the
4734return value must be trivially destructible. The calling convention of the
4735caller and callee must match, and they must not be variadic functions or have
4736old style K&R C function declarations.
4737
4738The lifetimes of all local variables and function parameters end immediately
4739before the call to the function. This means that it is undefined behaviour to
4740pass a pointer or reference to a local variable to the called function, which
4741is not the case without the attribute. Clang will emit a warning in common
4742cases where this happens.
4743
4744``clang::musttail`` provides assurances that the tail call can be optimized on
4745all targets, not just one.)reST";
4746
4747static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4748(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4749convention (e.g. functions starting with "get" are assumed to return at
4750``+0``).
4751
4752It can be overridden using a family of the following attributes. In
4753Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4754a function communicates that the object is returned at ``+1``, and the caller
4755is responsible for freeing it.
4756Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4757specifies that the object is returned at ``+0`` and the ownership remains with
4758the callee.
4759The annotation ``__attribute__((ns_consumes_self))`` specifies that
4760the Objective-C method call consumes the reference to ``self``, e.g. by
4761attaching it to a supplied parameter.
4762Additionally, parameters can have an annotation
4763``__attribute__((ns_consumed))``, which specifies that passing an owned object
4764as that parameter effectively transfers the ownership, and the caller is no
4765longer responsible for it.
4766These attributes affect code generation when interacting with ARC code, and
4767they are used by the Clang Static Analyzer.
4768
4769In C programs using CoreFoundation, a similar set of attributes:
4770``__attribute__((cf_returns_not_retained))``,
4771``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4772have the same respective semantics when applied to CoreFoundation objects.
4773These attributes affect code generation when interacting with ARC code, and
4774they are used by the Clang Static Analyzer.
4775
4776Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4777the same attribute family is present:
4778``__attribute__((os_returns_not_retained))``,
4779``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4780with the same respective semantics.
4781Similar to ``__attribute__((ns_consumes_self))``,
4782``__attribute__((os_consumes_this))`` specifies that the method call consumes
4783the reference to "this" (e.g., when attaching it to a different object supplied
4784as a parameter).
4785Out parameters (parameters the function is meant to write into,
4786either via pointers-to-pointers or references-to-pointers)
4787may be annotated with ``__attribute__((os_returns_retained))``
4788or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4789written into the out parameter should (or respectively should not) be released
4790after use.
4791Since often out parameters may or may not be written depending on the exit
4792code of the function,
4793annotations ``__attribute__((os_returns_retained_on_zero))``
4794and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4795an out parameter at ``+1`` is written if and only if the function returns a zero
4796(respectively non-zero) error code.
4797Observe that return-code-dependent out parameter annotations are only
4798available for retained out parameters, as non-retained object do not have to be
4799released by the callee.
4800These attributes are only used by the Clang Static Analyzer.
4801
4802The family of attributes ``X_returns_X_retained`` can be added to functions,
4803C++ methods, and Objective-C methods and properties.
4804Attributes ``X_consumed`` can be added to parameters of methods, functions,
4805and Objective-C methods.)reST";
4806
4807static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4808(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4809convention (e.g. functions starting with "get" are assumed to return at
4810``+0``).
4811
4812It can be overridden using a family of the following attributes. In
4813Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4814a function communicates that the object is returned at ``+1``, and the caller
4815is responsible for freeing it.
4816Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4817specifies that the object is returned at ``+0`` and the ownership remains with
4818the callee.
4819The annotation ``__attribute__((ns_consumes_self))`` specifies that
4820the Objective-C method call consumes the reference to ``self``, e.g. by
4821attaching it to a supplied parameter.
4822Additionally, parameters can have an annotation
4823``__attribute__((ns_consumed))``, which specifies that passing an owned object
4824as that parameter effectively transfers the ownership, and the caller is no
4825longer responsible for it.
4826These attributes affect code generation when interacting with ARC code, and
4827they are used by the Clang Static Analyzer.
4828
4829In C programs using CoreFoundation, a similar set of attributes:
4830``__attribute__((cf_returns_not_retained))``,
4831``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4832have the same respective semantics when applied to CoreFoundation objects.
4833These attributes affect code generation when interacting with ARC code, and
4834they are used by the Clang Static Analyzer.
4835
4836Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4837the same attribute family is present:
4838``__attribute__((os_returns_not_retained))``,
4839``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4840with the same respective semantics.
4841Similar to ``__attribute__((ns_consumes_self))``,
4842``__attribute__((os_consumes_this))`` specifies that the method call consumes
4843the reference to "this" (e.g., when attaching it to a different object supplied
4844as a parameter).
4845Out parameters (parameters the function is meant to write into,
4846either via pointers-to-pointers or references-to-pointers)
4847may be annotated with ``__attribute__((os_returns_retained))``
4848or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4849written into the out parameter should (or respectively should not) be released
4850after use.
4851Since often out parameters may or may not be written depending on the exit
4852code of the function,
4853annotations ``__attribute__((os_returns_retained_on_zero))``
4854and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4855an out parameter at ``+1`` is written if and only if the function returns a zero
4856(respectively non-zero) error code.
4857Observe that return-code-dependent out parameter annotations are only
4858available for retained out parameters, as non-retained object do not have to be
4859released by the callee.
4860These attributes are only used by the Clang Static Analyzer.
4861
4862The family of attributes ``X_returns_X_retained`` can be added to functions,
4863C++ methods, and Objective-C methods and properties.
4864Attributes ``X_consumed`` can be added to parameters of methods, functions,
4865and Objective-C methods.)reST";
4866
4867static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
4868and categorize these enums with error domains.
4869
4870The ``ns_error_domain`` attribute indicates a global ``NSString`` or
4871``CFString`` constant representing the error domain that an error code belongs
4872to. For pointer uniqueness and code size this is a constant symbol, not a
4873literal.
4874
4875The domain and error code need to be used together. The ``ns_error_domain``
4876attribute links error codes to their domain at the source level.
4877
4878This metadata is useful for documentation purposes, for static analysis, and for
4879improving interoperability between Objective-C and Swift. It is not used for
4880code generation in Objective-C.
4881
4882For example:
4883
4884 .. code-block:: objc
4885
4886 #define NS_ERROR_ENUM(_type, _name, _domain) \
4887 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
4888
4889 extern NSString *const MyErrorDomain;
4890 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
4891 MyErrFirst,
4892 MyErrSecond,
4893 };)reST";
4894
4895static const char AttrDoc_NSReturnsAutoreleased[] = 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_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4956(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4957convention (e.g. functions starting with "get" are assumed to return at
4958``+0``).
4959
4960It can be overridden using a family of the following attributes. In
4961Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4962a function communicates that the object is returned at ``+1``, and the caller
4963is responsible for freeing it.
4964Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4965specifies that the object is returned at ``+0`` and the ownership remains with
4966the callee.
4967The annotation ``__attribute__((ns_consumes_self))`` specifies that
4968the Objective-C method call consumes the reference to ``self``, e.g. by
4969attaching it to a supplied parameter.
4970Additionally, parameters can have an annotation
4971``__attribute__((ns_consumed))``, which specifies that passing an owned object
4972as that parameter effectively transfers the ownership, and the caller is no
4973longer responsible for it.
4974These attributes affect code generation when interacting with ARC code, and
4975they are used by the Clang Static Analyzer.
4976
4977In C programs using CoreFoundation, a similar set of attributes:
4978``__attribute__((cf_returns_not_retained))``,
4979``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4980have the same respective semantics when applied to CoreFoundation objects.
4981These attributes affect code generation when interacting with ARC code, and
4982they are used by the Clang Static Analyzer.
4983
4984Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4985the same attribute family is present:
4986``__attribute__((os_returns_not_retained))``,
4987``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4988with the same respective semantics.
4989Similar to ``__attribute__((ns_consumes_self))``,
4990``__attribute__((os_consumes_this))`` specifies that the method call consumes
4991the reference to "this" (e.g., when attaching it to a different object supplied
4992as a parameter).
4993Out parameters (parameters the function is meant to write into,
4994either via pointers-to-pointers or references-to-pointers)
4995may be annotated with ``__attribute__((os_returns_retained))``
4996or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4997written into the out parameter should (or respectively should not) be released
4998after use.
4999Since often out parameters may or may not be written depending on the exit
5000code of the function,
5001annotations ``__attribute__((os_returns_retained_on_zero))``
5002and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5003an out parameter at ``+1`` is written if and only if the function returns a zero
5004(respectively non-zero) error code.
5005Observe that return-code-dependent out parameter annotations are only
5006available for retained out parameters, as non-retained object do not have to be
5007released by the callee.
5008These attributes are only used by the Clang Static Analyzer.
5009
5010The family of attributes ``X_returns_X_retained`` can be added to functions,
5011C++ methods, and Objective-C methods and properties.
5012Attributes ``X_consumed`` can be added to parameters of methods, functions,
5013and Objective-C methods.)reST";
5014
5015static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5016(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5017convention (e.g. functions starting with "get" are assumed to return at
5018``+0``).
5019
5020It can be overridden using a family of the following attributes. In
5021Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5022a function communicates that the object is returned at ``+1``, and the caller
5023is responsible for freeing it.
5024Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5025specifies that the object is returned at ``+0`` and the ownership remains with
5026the callee.
5027The annotation ``__attribute__((ns_consumes_self))`` specifies that
5028the Objective-C method call consumes the reference to ``self``, e.g. by
5029attaching it to a supplied parameter.
5030Additionally, parameters can have an annotation
5031``__attribute__((ns_consumed))``, which specifies that passing an owned object
5032as that parameter effectively transfers the ownership, and the caller is no
5033longer responsible for it.
5034These attributes affect code generation when interacting with ARC code, and
5035they are used by the Clang Static Analyzer.
5036
5037In C programs using CoreFoundation, a similar set of attributes:
5038``__attribute__((cf_returns_not_retained))``,
5039``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5040have the same respective semantics when applied to CoreFoundation objects.
5041These attributes affect code generation when interacting with ARC code, and
5042they are used by the Clang Static Analyzer.
5043
5044Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5045the same attribute family is present:
5046``__attribute__((os_returns_not_retained))``,
5047``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5048with the same respective semantics.
5049Similar to ``__attribute__((ns_consumes_self))``,
5050``__attribute__((os_consumes_this))`` specifies that the method call consumes
5051the reference to "this" (e.g., when attaching it to a different object supplied
5052as a parameter).
5053Out parameters (parameters the function is meant to write into,
5054either via pointers-to-pointers or references-to-pointers)
5055may be annotated with ``__attribute__((os_returns_retained))``
5056or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5057written into the out parameter should (or respectively should not) be released
5058after use.
5059Since often out parameters may or may not be written depending on the exit
5060code of the function,
5061annotations ``__attribute__((os_returns_retained_on_zero))``
5062and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5063an out parameter at ``+1`` is written if and only if the function returns a zero
5064(respectively non-zero) error code.
5065Observe that return-code-dependent out parameter annotations are only
5066available for retained out parameters, as non-retained object do not have to be
5067released by the callee.
5068These attributes are only used by the Clang Static Analyzer.
5069
5070The family of attributes ``X_returns_X_retained`` can be added to functions,
5071C++ methods, and Objective-C methods and properties.
5072Attributes ``X_consumed`` can be added to parameters of methods, functions,
5073and Objective-C methods.)reST";
5074
5075static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
5076
5077static const char AttrDoc_NoAlias[] = R"reST(The ``noalias`` attribute indicates that the only memory accesses inside
5078function are loads and stores from objects pointed to by its pointer-typed
5079arguments, with arbitrary offsets.)reST";
5080
5081static const char AttrDoc_NoBuiltin[] = R"reST(The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
5082except it is specific to the body of a function. The attribute may also be
5083applied to a virtual function but has no effect on the behavior of overriding
5084functions in a derived class.
5085
5086It accepts one or more strings corresponding to the specific names of the
5087builtins to disable (e.g. "memcpy", "memset").
5088If the attribute is used without parameters it will disable all buitins at
5089once.
5090
5091.. code-block:: c++
5092
5093 // The compiler is not allowed to add any builtin to foo's body.
5094 void foo(char* data, size_t count) __attribute__((no_builtin)) {
5095 // The compiler is not allowed to convert the loop into
5096 // `__builtin_memset(data, 0xFE, count);`.
5097 for (size_t i = 0; i < count; ++i)
5098 data[i] = 0xFE;
5099 }
5100
5101 // The compiler is not allowed to add the `memcpy` builtin to bar's body.
5102 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5103 // The compiler is allowed to convert the loop into
5104 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5105 // `__builtin_memcpy`
5106 for (size_t i = 0; i < count; ++i)
5107 data[i] = 0xFE;
5108 })reST";
5109
5110static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5111
5112static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5113function is marked ``noconvergent``, calls to that function are not
5114automatically assumed to be convergent, unless such calls are explicitly marked
5115as ``convergent``. If a statement is marked as ``noconvergent``, any calls to
5116inline ``asm`` in that statement are no longer treated as convergent.
5117
5118In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5119declarations and inline asm calls are treated as convergent by default for
5120correctness. This ``noconvergent`` attribute is helpful for developers to
5121prevent them from being treated as convergent when it's safe.
5122
5123.. code-block:: c
5124
5125 __device__ float bar(float);
5126 __device__ float foo(float) __attribute__((noconvergent)) {}
5127
5128 __device__ int example(void) {
5129 float x;
5130 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5131 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5132 })reST";
5133
5134static const char AttrDoc_NoDebug[] = R"reST(The ``nodebug`` attribute allows you to suppress debugging information for a
5135function or method, for a variable that is not a parameter or a non-static
5136data member, or for a typedef or using declaration.)reST";
5137
5138static const char AttrDoc_NoDeref[] = R"reST(The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
5139This is ideally used with pointers that point to special memory which cannot be read
5140from or written to, but allowing for the pointer to be used in pointer arithmetic.
5141The following are examples of valid expressions where dereferences are diagnosed:
5142
5143.. code-block:: c
5144
5145 int __attribute__((noderef)) *p;
5146 int x = *p; // warning
5147
5148 int __attribute__((noderef)) **p2;
5149 x = **p2; // warning
5150
5151 int * __attribute__((noderef)) *p3;
5152 p = *p3; // warning
5153
5154 struct S {
5155 int a;
5156 };
5157 struct S __attribute__((noderef)) *s;
5158 x = s->a; // warning
5159 x = (*s).a; // warning
5160
5161Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5162accessed. The following are examples of valid expressions where may not be diagnosed:
5163
5164.. code-block:: c
5165
5166 int *q;
5167 int __attribute__((noderef)) *p;
5168 q = &*p;
5169 q = *&p;
5170
5171 struct S {
5172 int a;
5173 };
5174 struct S __attribute__((noderef)) *s;
5175 p = &s->a;
5176 p = &(*s).a;
5177
5178``noderef`` is currently only supported for pointers and arrays and not usable
5179for references or Objective-C object pointers.
5180
5181.. code-block:: c++
5182
5183 int x = 2;
5184 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5185
5186.. code-block:: objc
5187
5188 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type)reST";
5189
5190static const char AttrDoc_NoDestroy[] = R"reST(The ``no_destroy`` attribute specifies that a variable with static or thread
5191storage duration shouldn't have its exit-time destructor run. Annotating every
5192static and thread duration variable with this attribute is equivalent to
5193invoking clang with -fno-c++-static-destructors.
5194
5195If a variable is declared with this attribute, clang doesn't access check or
5196generate the type's destructor. If you have a type that you only want to be
5197annotated with ``no_destroy``, you can therefore declare the destructor private:
5198
5199.. code-block:: c++
5200
5201 struct only_no_destroy {
5202 only_no_destroy();
5203 private:
5204 ~only_no_destroy();
5205 };
5206
5207 [[clang::no_destroy]] only_no_destroy global; // fine!
5208
5209Note that destructors are still required for subobjects of aggregates annotated
5210with this attribute. This is because previously constructed subobjects need to
5211be destroyed if an exception gets thrown before the initialization of the
5212complete object is complete. For instance:
5213
5214.. code-block:: c++
5215
5216 void f() {
5217 try {
5218 [[clang::no_destroy]]
5219 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5220 } catch (...) {
5221 // Handle the error
5222 }
5223 }
5224
5225Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]``
5226will be destroyed, so the element's destructor needs to be accessible.)reST";
5227
5228static const char AttrDoc_NoDuplicate[] = R"reST(The ``noduplicate`` attribute can be placed on function declarations to control
5229whether function calls to this function can be duplicated or not as a result of
5230optimizations. This is required for the implementation of functions with
5231certain special requirements, like the OpenCL "barrier" function, that might
5232need to be run concurrently by all the threads that are executing in lockstep
5233on the hardware. For example this attribute applied on the function
5234"nodupfunc" in the code below avoids that:
5235
5236.. code-block:: c
5237
5238 void nodupfunc() __attribute__((noduplicate));
5239 // Setting it as a C++11 attribute is also valid
5240 // void nodupfunc() [[clang::noduplicate]];
5241 void foo();
5242 void bar();
5243
5244 nodupfunc();
5245 if (a > n) {
5246 foo();
5247 } else {
5248 bar();
5249 }
5250
5251gets possibly modified by some optimizations into code similar to this:
5252
5253.. code-block:: c
5254
5255 if (a > n) {
5256 nodupfunc();
5257 foo();
5258 } else {
5259 nodupfunc();
5260 bar();
5261 }
5262
5263where the call to "nodupfunc" is duplicated and sunk into the two branches
5264of the condition.)reST";
5265
5266static const char AttrDoc_NoEscape[] = R"reST(``noescape`` placed on a function parameter of a pointer type is used to inform
5267the compiler that the pointer cannot escape: that is, no reference to the object
5268the pointer points to that is derived from the parameter value will survive
5269after the function returns. Users are responsible for making sure parameters
5270annotated with ``noescape`` do not actually escape. The optimizer may make
5271assumptions based on the fact that it knows that a call to the function does
5272not escape a certain parameter, so incorrectly annotating a parameter with
5273``noescape`` leads to undefined behavior. The callee is also not allowed to
5274deallocate memory through a ``noescape`` parameter: the optimizer does not make
5275assumptions based on this information at the moment, but may do so in the
5276future. Some cases of invalid uses of ``noescape`` can be found with
5277:ref:`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`.
5278
5279For example:
5280
5281.. code-block:: c
5282
5283 int *gp;
5284
5285 void nonescapingFunc(__attribute__((noescape)) int *p) {
5286 *p += 100; // OK.
5287 }
5288
5289 void escapingFunc(__attribute__((noescape)) int *p) {
5290 gp = p; // Not OK.
5291 }
5292
5293 void freeingFunc(__attribute__((noescape)) int *p) {
5294 free(p); // Not OK.
5295 }
5296
5297Since ``noescape`` is a parameter attribute and not a type attribute, it only
5298applies to the outermost pointer level, regardless of where in the parameter
5299declaration you place it:
5300
5301.. code-block:: c
5302
5303 int **gp;
5304
5305 void nestingEscapes(__attribute__((noescape)) int **p) {
5306 gp = p; // Not OK.
5307 *gp = *p; // OK, p does not escape.
5308 }
5309
5310Additionally, when the parameter is a `block pointer
5311<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
5312applies to copies of the block. For example:
5313
5314.. code-block:: c
5315
5316 typedef void (^BlockTy)();
5317 BlockTy g0, g1;
5318
5319 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5320 block(); // OK.
5321 }
5322
5323 void escapingFunc(__attribute__((noescape)) BlockTy block) {
5324 g0 = block; // Not OK.
5325 g1 = Block_copy(block); // Not OK either.
5326 }
5327
5328The function *is* allowed to leak information about the memory address of the
5329pointer, but not any provenance of the allocation:
5330
5331.. code-block:: c
5332
5333 bool isNull(__attribute__((noescape)) void *p) {
5334 return !p; // OK.
5335 }
5336
5337 uintptr_t gi;
5338
5339 void escapingAddress(__attribute__((noescape)) int *p) {
5340 // OK *if and only if* gi is never casted back to a pointer.
5341 gi = (uintptr_t)p;
5342 }
5343
5344 bool usingEscapedAddress(int *p) {
5345 return (uintptr_t)p > gi; // OK.
5346 }
5347
5348 bool usingEscapedPointer(int *p) {
5349 return p > (int*)gi; // Not OK.
5350 }
5351
5352 int *gp;
5353
5354 void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) {
5355 gp = p + len; // Not OK.
5356 })reST";
5357
5358static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5359
5360static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5361of the function.
5362
5363``[[clang::noinline]]`` spelling can be used as a statement attribute; other
5364spellings of the attribute are not supported on statements. If a statement is
5365marked ``[[clang::noinline]]`` and contains calls, those calls inside the
5366statement will not be inlined by the compiler.
5367
5368``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to
5369avoid diagnostics due to usage of ``__attribute__((__noinline__))``
5370with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``.
5371
5372.. code-block:: c
5373
5374 int example(void) {
5375 int r;
5376 [[clang::noinline]] foo();
5377 [[clang::noinline]] r = bar();
5378 return r;
5379 })reST";
5380
5381static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5382
5383static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked ``nomerge`` and contains call expressions, those call
5384expressions inside the statement will not be merged during optimization. This
5385attribute can be used to prevent the optimizer from obscuring the source
5386location of certain calls. For example, it will prevent tail merging otherwise
5387identical code sequences that raise an exception or terminate the program. Tail
5388merging normally reduces the precision of source location information, making
5389stack traces less useful for debugging. This attribute gives the user control
5390over the tradeoff between code size and debug information precision.
5391
5392``nomerge`` attribute can also be used as function attribute to prevent all
5393calls to the specified function from merging. It has no effect on indirect
5394calls to such functions. For example:
5395
5396.. code-block:: c++
5397
5398 [[clang::nomerge]] void foo(int) {}
5399
5400 void bar(int x) {
5401 auto *ptr = foo;
5402 if (x) foo(1); else foo(2); // will not be merged
5403 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5404 }
5405
5406``nomerge`` attribute can also be used for pointers to functions to
5407prevent calls through such pointer from merging. In such case the
5408effect applies only to a specific function pointer. For example:
5409
5410.. code-block:: c++
5411
5412 [[clang::nomerge]] void (*foo)(int);
5413
5414 void bar(int x) {
5415 auto *ptr = foo;
5416 if (x) foo(1); else foo(2); // will not be merged
5417 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5418 })reST";
5419
5420static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
5421``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
5422may be attached to a function definition and instructs the backend to generate
5423or not to generate microMIPS code for that function.
5424
5425These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
5426on the command line.)reST";
5427
5428static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5429
5430static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5431
5432Outlining is the process where common parts of separate functions are extracted
5433into a separate function (or assembly snippet), and calls to that function or
5434snippet are inserted in the original functions. In this way, it can be seen as
5435the opposite of inlining. It can help to reduce code size.)reST";
5436
5437static const char AttrDoc_NoProfileFunction[] = R"reST(Use the ``no_profile_instrument_function`` attribute on a function declaration
5438to denote that the compiler should not instrument the function with
5439profile-related instrumentation, such as via the
5440``-fprofile-generate`` / ``-fprofile-instr-generate`` /
5441``-fcs-profile-generate`` / ``-fprofile-arcs`` flags.)reST";
5442
5443static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
5444for structure layout field randomization; a compile-time hardening technique. A
5445"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
5446For example:
5447
5448.. code-block:: bash
5449
5450 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5451 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5452
5453You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
5454For example:
5455
5456.. code-block:: bash
5457
5458 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5459 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5460
5461The randomization is deterministic based for a given seed, so the entire
5462program should be compiled with the same seed, but keep the seed safe
5463otherwise.
5464
5465The attribute ``no_randomize_layout``, when attached to a C structure,
5466instructs the compiler that this structure should not have its field layout
5467randomized.)reST";
5468
5469static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5470
5471static const char AttrDoc_NoSanitize[] = R"reST(Use the ``no_sanitize`` attribute on a function or a global variable
5472declaration to specify that a particular instrumentation or set of
5473instrumentations should not be applied.
5474
5475The attribute takes a list of string literals with the following accepted
5476values:
5477
5478* all values accepted by ``-fno-sanitize=``;
5479* ``coverage``, to disable SanitizerCoverage instrumentation.
5480
5481For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies
5482that AddressSanitizer and ThreadSanitizer should not be applied to the function
5483or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that
5484SanitizerCoverage should not be applied to the function.
5485
5486See :ref:`Controlling Code Generation <controlling-code-generation>` for a
5487full list of supported sanitizer flags.)reST";
5488
5489static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5490templates which should not be explicitly specialized by users. This is primarily
5491used to diagnose user specializations of standard library type traits.)reST";
5492
5493static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5494 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5495 is *not* needed for the function body. This can also be applied to a method
5496 in Objective C. This attribute will take precedence over the command line flag in
5497 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5498
5499 Warning: This attribute may not prevent Speculative Load Hardening from being
5500 enabled for a function which inlines a function that has the
5501 'speculative_load_hardening' attribute. This is intended to provide a
5502 maximally conservative model where the code that is marked with the
5503 'speculative_load_hardening' attribute will always (even when inlined)
5504 be hardened. A user of this attribute may want to mark functions called by
5505 a function they do not want to be hardened with the 'noinline' attribute.
5506
5507 For example:
5508
5509 .. code-block:: c
5510
5511 __attribute__((speculative_load_hardening))
5512 int foo(int i) {
5513 return i;
5514 }
5515
5516 // Note: bar() may still have speculative load hardening enabled if
5517 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5518 // to avoid this situation.
5519 __attribute__((no_speculative_load_hardening))
5520 int bar(int i) {
5521 return foo(i);
5522 })reST";
5523
5524static const char AttrDoc_NoSplitStack[] = R"reST(The ``no_split_stack`` attribute disables the emission of the split stack
5525preamble for a particular function. It has no effect if ``-fsplit-stack``
5526is not specified.)reST";
5527
5528static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style ``__attribute__((no_stack_protector))`` and Microsoft
5529style ``__declspec(safebuffers)`` attribute which disables
5530the stack protector on the specified function. This attribute is useful for
5531selectively disabling the stack protector on some functions when building with
5532``-fstack-protector`` compiler option.
5533
5534For example, it disables the stack protector for the function ``foo`` but function
5535``bar`` will still be built with the stack protector with the ``-fstack-protector``
5536option.
5537
5538.. code-block:: c
5539
5540 int __attribute__((no_stack_protector))
5541 foo (int x); // stack protection will be disabled for foo.
5542
5543 int bar(int y); // bar can be built with the stack protector.)reST";
5544
5545static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5546
5547static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
5548``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function
5549declarations. This attribute informs the compiler that the annotated function
5550does not throw an exception. This prevents exception-unwinding. This attribute
5551is particularly useful on functions in the C Standard Library that are
5552guaranteed to not throw an exception.)reST";
5553
5554static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The ``__declspec(no_init_all)`` attribute disables the automatic initialization that the
5555`-ftrivial-auto-var-init`_ flag would have applied to locals in a marked function, or instances of
5556a marked type. Note that this attribute has no effect for locals that are automatically initialized
5557without the `-ftrivial-auto-var-init`_ flag.
5558
5559.. _`-ftrivial-auto-var-init`: ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init)reST";
5560
5561static const char AttrDoc_NoUniqueAddress[] = R"reST(The ``no_unique_address`` attribute allows tail padding in a non-static data
5562member to overlap other members of the enclosing class (and in the special
5563case when the type is empty, permits it to fully overlap other members).
5564The field is laid out as if a base class were encountered at the corresponding
5565point within the class (except that it does not share a vptr with the enclosing
5566object).
5567
5568Example usage:
5569
5570.. code-block:: c++
5571
5572 template<typename T, typename Alloc> struct my_vector {
5573 T *p;
5574 [[no_unique_address]] Alloc alloc;
5575 // ...
5576 };
5577 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5578
5579``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
5580in C++11 onwards.
5581
5582On MSVC targets, ``[[no_unique_address]]`` is ignored; use
5583``[[msvc::no_unique_address]]`` instead. Currently there is no guarantee of ABI
5584compatibility or stability with MSVC.)reST";
5585
5586static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the ``nouwtable`` attribute which skips emitting
5587the unwind table entry for the specified function. This attribute is useful for
5588selectively emitting the unwind table entry on some functions when building with
5589``-funwind-tables`` compiler option.)reST";
5590
5591static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5592to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5593is false, the attribute is equivalent to ``allocating``.)reST";
5594
5595static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5596to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5597is false, the attribute is equivalent to ``blocking``.
5598
5599For the purposes of diagnostics, ``nonblocking`` is considered to include the
5600``nonallocating`` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5601
5602static const char AttrDoc_NonNull[] = R"reST(The ``nonnull`` attribute indicates that some function parameters must not be
5603null, and can be used in several different ways. It's original usage
5604(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
5605is as a function (or Objective-C method) attribute that specifies which
5606parameters of the function are nonnull in a comma-separated list. For example:
5607
5608 .. code-block:: c
5609
5610 extern void * my_memcpy (void *dest, const void *src, size_t len)
5611 __attribute__((nonnull (1, 2)));
5612
5613Here, the ``nonnull`` attribute indicates that parameters 1 and 2
5614cannot have a null value. Omitting the parenthesized list of parameter indices
5615means that all parameters of pointer type cannot be null:
5616
5617 .. code-block:: c
5618
5619 extern void * my_memcpy (void *dest, const void *src, size_t len)
5620 __attribute__((nonnull));
5621
5622Clang also allows the ``nonnull`` attribute to be placed directly on a function
5623(or Objective-C method) parameter, eliminating the need to specify the
5624parameter index ahead of type. For example:
5625
5626 .. code-block:: c
5627
5628 extern void * my_memcpy (void *dest __attribute__((nonnull)),
5629 const void *src __attribute__((nonnull)), size_t len);
5630
5631Note that the ``nonnull`` attribute indicates that passing null to a non-null
5632parameter is undefined behavior, which the optimizer may take advantage of to,
5633e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
5634pointer cannot be null in a more general manner (because it is part of the type
5635system) and does not imply undefined behavior, making it more widely applicable.)reST";
5636
5637static const char AttrDoc_NonString[] = R"reST(The ``nonstring`` attribute can be applied to the declaration of a variable or
5638a field whose type is a character pointer or character array to specify that
5639the buffer is not intended to behave like a null-terminated string. This will
5640silence diagnostics with code like:
5641
5642.. code-block:: c
5643
5644 char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5645 __attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed)reST";
5646
5647static const char AttrDoc_NotTailCalled[] = R"reST(The ``not_tail_called`` attribute prevents tail-call optimization on statically
5648bound calls. Objective-c methods, and functions marked as ``always_inline``
5649cannot be marked as ``not_tail_called``.
5650
5651For example, it prevents tail-call optimization in the following case:
5652
5653 .. code-block:: c
5654
5655 int __attribute__((not_tail_called)) foo1(int);
5656
5657 int foo2(int a) {
5658 return foo1(a); // No tail-call optimization on direct calls.
5659 }
5660
5661However, it doesn't prevent tail-call optimization in this case:
5662
5663 .. code-block:: c
5664
5665 int __attribute__((not_tail_called)) foo1(int);
5666
5667 int foo2(int a) {
5668 int (*fn)(int) = &foo1;
5669
5670 // not_tail_called has no effect on an indirect call even if the call can
5671 // be resolved at compile time.
5672 return (*fn)(a);
5673 }
5674
5675Generally, marking an overriding virtual function as ``not_tail_called`` is
5676not useful, because this attribute is a property of the static type. Calls
5677made through a pointer or reference to the base class type will respect
5678the ``not_tail_called`` attribute of the base class's member function,
5679regardless of the runtime destination of the call:
5680
5681 .. code-block:: c++
5682
5683 struct Foo { virtual void f(); };
5684 struct Bar : Foo {
5685 [[clang::not_tail_called]] void f() override;
5686 };
5687 void callera(Bar& bar) {
5688 Foo& foo = bar;
5689 // not_tail_called has no effect on here, even though the
5690 // underlying method is f from Bar.
5691 foo.f();
5692 bar.f(); // No tail-call optimization on here.
5693 })reST";
5694
5695static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5696
5697static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the ``[[omp::assume("assumption")]]`` attribute to
5698provide additional information to the optimizer. The string-literal, here
5699"assumption", will be attached to the function declaration such that later
5700analysis and optimization passes can assume the "assumption" to hold.
5701This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
5702instead of an expression that can be assumed to be non-zero, the assumption is
5703expressed as a string and it holds for the entire function.
5704
5705A function can have multiple assume attributes and they propagate from prior
5706declarations to later definitions. Multiple assumptions are aggregated into a
5707single comma separated string. Thus, one can provide multiple assumptions via
5708a comma separated string, i.a.,
5709``[[omp::assume("assumption1,assumption2")]]``.
5710
5711While LLVM plugins might provide more assumption strings, the default LLVM
5712optimization passes are aware of the following assumptions:
5713
5714 .. code-block:: none
5715
5716 "omp_no_openmp"
5717 "omp_no_openmp_routines"
5718 "omp_no_parallelism"
5719 "omp_no_openmp_constructs"
5720
5721The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5722spelled "XYZ" in the `OpenMP 5.1 Standard`_).
5723
5724.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5725
5726static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5727
5728static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5729
5730static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The ``declare simd`` construct can be applied to a function to enable the creation
5731of one or more versions that can process multiple arguments using SIMD
5732instructions from a single invocation in a SIMD loop. The ``declare simd``
5733directive is a declarative directive. There may be multiple ``declare simd``
5734directives for a function. The use of a ``declare simd`` construct on a function
5735enables the creation of SIMD versions of the associated function that can be
5736used to process multiple arguments from a single invocation from a SIMD loop
5737concurrently.
5738The syntax of the ``declare simd`` construct is as follows:
5739
5740 .. code-block:: none
5741
5742 #pragma omp declare simd [clause[[,] clause] ...] new-line
5743 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
5744 [...]
5745 function definition or declaration
5746
5747where clause is one of the following:
5748
5749 .. code-block:: none
5750
5751 simdlen(length)
5752 linear(argument-list[:constant-linear-step])
5753 aligned(argument-list[:alignment])
5754 uniform(argument-list)
5755 inbranch
5756 notinbranch)reST";
5757
5758static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The ``declare target`` directive specifies that variables and functions are mapped
5759to a device for OpenMP offload mechanism.
5760
5761The syntax of the declare target directive is as follows:
5762
5763 .. code-block:: c
5764
5765 #pragma omp declare target new-line
5766 declarations-definition-seq
5767 #pragma omp end declare target new-line
5768
5769or
5770
5771 .. code-block:: c
5772
5773 #pragma omp declare target (extended-list) new-line
5774
5775or
5776
5777 .. code-block:: c
5778
5779 #pragma omp declare target clause[ [,] clause ... ] new-line
5780
5781where clause is one of the following:
5782
5783
5784 .. code-block:: c
5785
5786 to(extended-list)
5787 link(list)
5788 device_type(host | nohost | any))reST";
5789
5790static const char AttrDoc_OMPDeclareVariant[] = R"reST(The ``declare variant`` directive declares a specialized variant of a base
5791function and specifies the context in which that specialized variant is used.
5792The declare variant directive is a declarative directive.
5793The syntax of the ``declare variant`` construct is as follows:
5794
5795 .. code-block:: none
5796
5797 #pragma omp declare variant(variant-func-id) clause new-line
5798 [#pragma omp declare variant(variant-func-id) clause new-line]
5799 [...]
5800 function definition or declaration
5801
5802where clause is one of the following:
5803
5804 .. code-block:: none
5805
5806 match(context-selector-specification)
5807
5808and where ``variant-func-id`` is the name of a function variant that is either a
5809base language identifier or, for C++, a template-id.
5810
5811Clang provides the following context selector extensions, used via
5812``implementation={extension(EXTENSION)}``:
5813
5814 .. code-block:: none
5815
5816 match_all
5817 match_any
5818 match_none
5819 disable_implicit_base
5820 allow_templates
5821 bind_to_declaration
5822
5823The match extensions change when the *entire* context selector is considered a
5824match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
5825selector is allowed to be in the OpenMP context, with ``any`` a single trait in
5826both the selector and OpenMP context is sufficient. Only a single match
5827extension trait is allowed per context selector.
5828The disable extensions remove default effects of the ``begin declare variant``
5829applied to a definition. If ``disable_implicit_base`` is given, we will not
5830introduce an implicit base function for a variant if no base function was
5831found. The variant is still generated but will never be called, due to the
5832absence of a base function and consequently calls to a base function.
5833The allow extensions change when the ``begin declare variant`` effect is
5834applied to a definition. If ``allow_templates`` is given, template function
5835definitions are considered as specializations of existing or assumed template
5836declarations with the same name. The template parameters for the base functions
5837are used to instantiate the specialization. If ``bind_to_declaration`` is given,
5838apply the same variant rules to function declarations. This allows the user to
5839override declarations with only a function declaration.)reST";
5840
5841static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
5842
5843static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
5844
5845static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
5846
5847static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
5848
5849static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5850(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5851convention (e.g. functions starting with "get" are assumed to return at
5852``+0``).
5853
5854It can be overridden using a family of the following attributes. In
5855Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5856a function communicates that the object is returned at ``+1``, and the caller
5857is responsible for freeing it.
5858Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5859specifies that the object is returned at ``+0`` and the ownership remains with
5860the callee.
5861The annotation ``__attribute__((ns_consumes_self))`` specifies that
5862the Objective-C method call consumes the reference to ``self``, e.g. by
5863attaching it to a supplied parameter.
5864Additionally, parameters can have an annotation
5865``__attribute__((ns_consumed))``, which specifies that passing an owned object
5866as that parameter effectively transfers the ownership, and the caller is no
5867longer responsible for it.
5868These attributes affect code generation when interacting with ARC code, and
5869they are used by the Clang Static Analyzer.
5870
5871In C programs using CoreFoundation, a similar set of attributes:
5872``__attribute__((cf_returns_not_retained))``,
5873``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5874have the same respective semantics when applied to CoreFoundation objects.
5875These attributes affect code generation when interacting with ARC code, and
5876they are used by the Clang Static Analyzer.
5877
5878Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5879the same attribute family is present:
5880``__attribute__((os_returns_not_retained))``,
5881``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5882with the same respective semantics.
5883Similar to ``__attribute__((ns_consumes_self))``,
5884``__attribute__((os_consumes_this))`` specifies that the method call consumes
5885the reference to "this" (e.g., when attaching it to a different object supplied
5886as a parameter).
5887Out parameters (parameters the function is meant to write into,
5888either via pointers-to-pointers or references-to-pointers)
5889may be annotated with ``__attribute__((os_returns_retained))``
5890or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5891written into the out parameter should (or respectively should not) be released
5892after use.
5893Since often out parameters may or may not be written depending on the exit
5894code of the function,
5895annotations ``__attribute__((os_returns_retained_on_zero))``
5896and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5897an out parameter at ``+1`` is written if and only if the function returns a zero
5898(respectively non-zero) error code.
5899Observe that return-code-dependent out parameter annotations are only
5900available for retained out parameters, as non-retained object do not have to be
5901released by the callee.
5902These attributes are only used by the Clang Static Analyzer.
5903
5904The family of attributes ``X_returns_X_retained`` can be added to functions,
5905C++ methods, and Objective-C methods and properties.
5906Attributes ``X_consumed`` can be added to parameters of methods, functions,
5907and Objective-C methods.)reST";
5908
5909static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5910(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5911convention (e.g. functions starting with "get" are assumed to return at
5912``+0``).
5913
5914It can be overridden using a family of the following attributes. In
5915Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5916a function communicates that the object is returned at ``+1``, and the caller
5917is responsible for freeing it.
5918Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5919specifies that the object is returned at ``+0`` and the ownership remains with
5920the callee.
5921The annotation ``__attribute__((ns_consumes_self))`` specifies that
5922the Objective-C method call consumes the reference to ``self``, e.g. by
5923attaching it to a supplied parameter.
5924Additionally, parameters can have an annotation
5925``__attribute__((ns_consumed))``, which specifies that passing an owned object
5926as that parameter effectively transfers the ownership, and the caller is no
5927longer responsible for it.
5928These attributes affect code generation when interacting with ARC code, and
5929they are used by the Clang Static Analyzer.
5930
5931In C programs using CoreFoundation, a similar set of attributes:
5932``__attribute__((cf_returns_not_retained))``,
5933``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5934have the same respective semantics when applied to CoreFoundation objects.
5935These attributes affect code generation when interacting with ARC code, and
5936they are used by the Clang Static Analyzer.
5937
5938Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5939the same attribute family is present:
5940``__attribute__((os_returns_not_retained))``,
5941``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5942with the same respective semantics.
5943Similar to ``__attribute__((ns_consumes_self))``,
5944``__attribute__((os_consumes_this))`` specifies that the method call consumes
5945the reference to "this" (e.g., when attaching it to a different object supplied
5946as a parameter).
5947Out parameters (parameters the function is meant to write into,
5948either via pointers-to-pointers or references-to-pointers)
5949may be annotated with ``__attribute__((os_returns_retained))``
5950or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5951written into the out parameter should (or respectively should not) be released
5952after use.
5953Since often out parameters may or may not be written depending on the exit
5954code of the function,
5955annotations ``__attribute__((os_returns_retained_on_zero))``
5956and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5957an out parameter at ``+1`` is written if and only if the function returns a zero
5958(respectively non-zero) error code.
5959Observe that return-code-dependent out parameter annotations are only
5960available for retained out parameters, as non-retained object do not have to be
5961released by the callee.
5962These attributes are only used by the Clang Static Analyzer.
5963
5964The family of attributes ``X_returns_X_retained`` can be added to functions,
5965C++ methods, and Objective-C methods and properties.
5966Attributes ``X_consumed`` can be added to parameters of methods, functions,
5967and Objective-C methods.)reST";
5968
5969static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5970(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5971convention (e.g. functions starting with "get" are assumed to return at
5972``+0``).
5973
5974It can be overridden using a family of the following attributes. In
5975Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5976a function communicates that the object is returned at ``+1``, and the caller
5977is responsible for freeing it.
5978Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5979specifies that the object is returned at ``+0`` and the ownership remains with
5980the callee.
5981The annotation ``__attribute__((ns_consumes_self))`` specifies that
5982the Objective-C method call consumes the reference to ``self``, e.g. by
5983attaching it to a supplied parameter.
5984Additionally, parameters can have an annotation
5985``__attribute__((ns_consumed))``, which specifies that passing an owned object
5986as that parameter effectively transfers the ownership, and the caller is no
5987longer responsible for it.
5988These attributes affect code generation when interacting with ARC code, and
5989they are used by the Clang Static Analyzer.
5990
5991In C programs using CoreFoundation, a similar set of attributes:
5992``__attribute__((cf_returns_not_retained))``,
5993``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5994have the same respective semantics when applied to CoreFoundation objects.
5995These attributes affect code generation when interacting with ARC code, and
5996they are used by the Clang Static Analyzer.
5997
5998Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5999the same attribute family is present:
6000``__attribute__((os_returns_not_retained))``,
6001``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6002with the same respective semantics.
6003Similar to ``__attribute__((ns_consumes_self))``,
6004``__attribute__((os_consumes_this))`` specifies that the method call consumes
6005the reference to "this" (e.g., when attaching it to a different object supplied
6006as a parameter).
6007Out parameters (parameters the function is meant to write into,
6008either via pointers-to-pointers or references-to-pointers)
6009may be annotated with ``__attribute__((os_returns_retained))``
6010or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6011written into the out parameter should (or respectively should not) be released
6012after use.
6013Since often out parameters may or may not be written depending on the exit
6014code of the function,
6015annotations ``__attribute__((os_returns_retained_on_zero))``
6016and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6017an out parameter at ``+1`` is written if and only if the function returns a zero
6018(respectively non-zero) error code.
6019Observe that return-code-dependent out parameter annotations are only
6020available for retained out parameters, as non-retained object do not have to be
6021released by the callee.
6022These attributes are only used by the Clang Static Analyzer.
6023
6024The family of attributes ``X_returns_X_retained`` can be added to functions,
6025C++ methods, and Objective-C methods and properties.
6026Attributes ``X_consumed`` can be added to parameters of methods, functions,
6027and Objective-C methods.)reST";
6028
6029static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6030(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6031convention (e.g. functions starting with "get" are assumed to return at
6032``+0``).
6033
6034It can be overridden using a family of the following attributes. In
6035Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6036a function communicates that the object is returned at ``+1``, and the caller
6037is responsible for freeing it.
6038Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6039specifies that the object is returned at ``+0`` and the ownership remains with
6040the callee.
6041The annotation ``__attribute__((ns_consumes_self))`` specifies that
6042the Objective-C method call consumes the reference to ``self``, e.g. by
6043attaching it to a supplied parameter.
6044Additionally, parameters can have an annotation
6045``__attribute__((ns_consumed))``, which specifies that passing an owned object
6046as that parameter effectively transfers the ownership, and the caller is no
6047longer responsible for it.
6048These attributes affect code generation when interacting with ARC code, and
6049they are used by the Clang Static Analyzer.
6050
6051In C programs using CoreFoundation, a similar set of attributes:
6052``__attribute__((cf_returns_not_retained))``,
6053``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6054have the same respective semantics when applied to CoreFoundation objects.
6055These attributes affect code generation when interacting with ARC code, and
6056they are used by the Clang Static Analyzer.
6057
6058Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6059the same attribute family is present:
6060``__attribute__((os_returns_not_retained))``,
6061``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6062with the same respective semantics.
6063Similar to ``__attribute__((ns_consumes_self))``,
6064``__attribute__((os_consumes_this))`` specifies that the method call consumes
6065the reference to "this" (e.g., when attaching it to a different object supplied
6066as a parameter).
6067Out parameters (parameters the function is meant to write into,
6068either via pointers-to-pointers or references-to-pointers)
6069may be annotated with ``__attribute__((os_returns_retained))``
6070or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6071written into the out parameter should (or respectively should not) be released
6072after use.
6073Since often out parameters may or may not be written depending on the exit
6074code of the function,
6075annotations ``__attribute__((os_returns_retained_on_zero))``
6076and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6077an out parameter at ``+1`` is written if and only if the function returns a zero
6078(respectively non-zero) error code.
6079Observe that return-code-dependent out parameter annotations are only
6080available for retained out parameters, as non-retained object do not have to be
6081released by the callee.
6082These attributes are only used by the Clang Static Analyzer.
6083
6084The family of attributes ``X_returns_X_retained`` can be added to functions,
6085C++ methods, and Objective-C methods and properties.
6086Attributes ``X_consumed`` can be added to parameters of methods, functions,
6087and Objective-C methods.)reST";
6088
6089static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6090(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6091convention (e.g. functions starting with "get" are assumed to return at
6092``+0``).
6093
6094It can be overridden using a family of the following attributes. In
6095Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6096a function communicates that the object is returned at ``+1``, and the caller
6097is responsible for freeing it.
6098Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6099specifies that the object is returned at ``+0`` and the ownership remains with
6100the callee.
6101The annotation ``__attribute__((ns_consumes_self))`` specifies that
6102the Objective-C method call consumes the reference to ``self``, e.g. by
6103attaching it to a supplied parameter.
6104Additionally, parameters can have an annotation
6105``__attribute__((ns_consumed))``, which specifies that passing an owned object
6106as that parameter effectively transfers the ownership, and the caller is no
6107longer responsible for it.
6108These attributes affect code generation when interacting with ARC code, and
6109they are used by the Clang Static Analyzer.
6110
6111In C programs using CoreFoundation, a similar set of attributes:
6112``__attribute__((cf_returns_not_retained))``,
6113``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6114have the same respective semantics when applied to CoreFoundation objects.
6115These attributes affect code generation when interacting with ARC code, and
6116they are used by the Clang Static Analyzer.
6117
6118Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6119the same attribute family is present:
6120``__attribute__((os_returns_not_retained))``,
6121``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6122with the same respective semantics.
6123Similar to ``__attribute__((ns_consumes_self))``,
6124``__attribute__((os_consumes_this))`` specifies that the method call consumes
6125the reference to "this" (e.g., when attaching it to a different object supplied
6126as a parameter).
6127Out parameters (parameters the function is meant to write into,
6128either via pointers-to-pointers or references-to-pointers)
6129may be annotated with ``__attribute__((os_returns_retained))``
6130or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6131written into the out parameter should (or respectively should not) be released
6132after use.
6133Since often out parameters may or may not be written depending on the exit
6134code of the function,
6135annotations ``__attribute__((os_returns_retained_on_zero))``
6136and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6137an out parameter at ``+1`` is written if and only if the function returns a zero
6138(respectively non-zero) error code.
6139Observe that return-code-dependent out parameter annotations are only
6140available for retained out parameters, as non-retained object do not have to be
6141released by the callee.
6142These attributes are only used by the Clang Static Analyzer.
6143
6144The family of attributes ``X_returns_X_retained`` can be added to functions,
6145C++ methods, and Objective-C methods and properties.
6146Attributes ``X_consumed`` can be added to parameters of methods, functions,
6147and Objective-C methods.)reST";
6148
6149static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6150(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6151convention (e.g. functions starting with "get" are assumed to return at
6152``+0``).
6153
6154It can be overridden using a family of the following attributes. In
6155Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6156a function communicates that the object is returned at ``+1``, and the caller
6157is responsible for freeing it.
6158Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6159specifies that the object is returned at ``+0`` and the ownership remains with
6160the callee.
6161The annotation ``__attribute__((ns_consumes_self))`` specifies that
6162the Objective-C method call consumes the reference to ``self``, e.g. by
6163attaching it to a supplied parameter.
6164Additionally, parameters can have an annotation
6165``__attribute__((ns_consumed))``, which specifies that passing an owned object
6166as that parameter effectively transfers the ownership, and the caller is no
6167longer responsible for it.
6168These attributes affect code generation when interacting with ARC code, and
6169they are used by the Clang Static Analyzer.
6170
6171In C programs using CoreFoundation, a similar set of attributes:
6172``__attribute__((cf_returns_not_retained))``,
6173``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6174have the same respective semantics when applied to CoreFoundation objects.
6175These attributes affect code generation when interacting with ARC code, and
6176they are used by the Clang Static Analyzer.
6177
6178Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6179the same attribute family is present:
6180``__attribute__((os_returns_not_retained))``,
6181``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6182with the same respective semantics.
6183Similar to ``__attribute__((ns_consumes_self))``,
6184``__attribute__((os_consumes_this))`` specifies that the method call consumes
6185the reference to "this" (e.g., when attaching it to a different object supplied
6186as a parameter).
6187Out parameters (parameters the function is meant to write into,
6188either via pointers-to-pointers or references-to-pointers)
6189may be annotated with ``__attribute__((os_returns_retained))``
6190or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6191written into the out parameter should (or respectively should not) be released
6192after use.
6193Since often out parameters may or may not be written depending on the exit
6194code of the function,
6195annotations ``__attribute__((os_returns_retained_on_zero))``
6196and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6197an out parameter at ``+1`` is written if and only if the function returns a zero
6198(respectively non-zero) error code.
6199Observe that return-code-dependent out parameter annotations are only
6200available for retained out parameters, as non-retained object do not have to be
6201released by the callee.
6202These attributes are only used by the Clang Static Analyzer.
6203
6204The family of attributes ``X_returns_X_retained`` can be added to functions,
6205C++ methods, and Objective-C methods and properties.
6206Attributes ``X_consumed`` can be added to parameters of methods, functions,
6207and Objective-C methods.)reST";
6208
6209static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the ``objc_boxable`` attribute can be used
6210with the Objective-C boxed expression syntax, ``@(...)``.
6211
6212**Usage**: ``__attribute__((objc_boxable))``. This attribute
6213can only be placed on a declaration of a trivially-copyable struct or union:
6214
6215.. code-block:: objc
6216
6217 struct __attribute__((objc_boxable)) some_struct {
6218 int i;
6219 };
6220 union __attribute__((objc_boxable)) some_union {
6221 int i;
6222 float f;
6223 };
6224 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6225
6226 // ...
6227
6228 some_struct ss;
6229 NSValue *boxed = @(ss);)reST";
6230
6231static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6232
6233static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6234
6235static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6236
6237static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6238instantiated at runtime.
6239
6240Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
6241still has a "class stub" that is visible to the linker. This allows categories
6242to be defined. Static message sends with the class as a receiver use a special
6243access pattern to ensure the class is lazily instantiated from the class stub.
6244
6245Classes annotated with this attribute cannot be subclassed and cannot have
6246implementations defined for them. This attribute is intended for use in
6247Swift-generated headers for classes defined in Swift.
6248
6249Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6250
6251static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6252
6253static const char AttrDoc_ObjCDirect[] = R"reST(The ``objc_direct`` attribute can be used to mark an Objective-C method as
6254being *direct*. A direct method is treated statically like an ordinary method,
6255but dynamically it behaves more like a C function. This lowers some of the costs
6256associated with the method but also sacrifices some of the ordinary capabilities
6257of Objective-C methods.
6258
6259A message send of a direct method calls the implementation directly, as if it
6260were a C function, rather than using ordinary Objective-C method dispatch. This
6261is substantially faster and potentially allows the implementation to be inlined,
6262but it also means the method cannot be overridden in subclasses or replaced
6263dynamically, as ordinary Objective-C methods can.
6264
6265Furthermore, a direct method is not listed in the class's method lists. This
6266substantially reduces the code-size overhead of the method but also means it
6267cannot be called dynamically using ordinary Objective-C method dispatch at all;
6268in particular, this means that it cannot override a superclass method or satisfy
6269a protocol requirement.
6270
6271Because a direct method cannot be overridden, it is an error to perform
6272a ``super`` message send of one.
6273
6274Although a message send of a direct method causes the method to be called
6275directly as if it were a C function, it still obeys Objective-C semantics in other
6276ways:
6277
6278- If the receiver is ``nil``, the message send does nothing and returns the zero value
6279 for the return type.
6280
6281- A message send of a direct class method will cause the class to be initialized,
6282 including calling the ``+initialize`` method if present.
6283
6284- The implicit ``_cmd`` parameter containing the method's selector is still defined.
6285 In order to minimize code-size costs, the implementation will not emit a reference
6286 to the selector if the parameter is unused within the method.
6287
6288Symbols for direct method implementations are implicitly given hidden
6289visibility, meaning that they can only be called within the same linkage unit.
6290
6291It is an error to do any of the following:
6292
6293- declare a direct method in a protocol,
6294- declare an override of a direct method with a method in a subclass,
6295- declare an override of a non-direct method with a direct method in a subclass,
6296- declare a method with different directness in different class interfaces, or
6297- implement a non-direct method (as declared in any class interface) with a direct method.
6298
6299If any of these rules would be violated if every method defined in an
6300``@implementation`` within a single linkage unit were declared in an
6301appropriate class interface, the program is ill-formed with no diagnostic
6302required. If a violation of this rule is not diagnosed, behavior remains
6303well-defined; this paragraph is simply reserving the right to diagnose such
6304conflicts in the future, not to treat them as undefined behavior.
6305
6306Additionally, Clang will warn about any ``@selector`` expression that
6307names a selector that is only known to be used for direct methods.
6308
6309For the purpose of these rules, a "class interface" includes a class's primary
6310``@interface`` block, its class extensions, its categories, its declared protocols,
6311and all the class interfaces of its superclasses.
6312
6313An Objective-C property can be declared with the ``direct`` property
6314attribute. If a direct property declaration causes an implicit declaration of
6315a getter or setter method (that is, if the given method is not explicitly
6316declared elsewhere), the method is declared to be direct.
6317
6318Some programmers may wish to make many methods direct at once. In order
6319to simplify this, the ``objc_direct_members`` attribute is provided; see its
6320documentation for more information.)reST";
6321
6322static const char AttrDoc_ObjCDirectMembers[] = R"reST(The ``objc_direct_members`` attribute can be placed on an Objective-C
6323``@interface`` or ``@implementation`` to mark that methods declared
6324therein should be considered direct by default. See the documentation
6325for ``objc_direct`` for more information about direct methods.
6326
6327When ``objc_direct_members`` is placed on an ``@interface`` block, every
6328method in the block is considered to be declared as direct. This includes any
6329implicit method declarations introduced by property declarations. If the method
6330redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6331method was annotated with the ``objc_direct`` attribute.
6332
6333When ``objc_direct_members`` is placed on an ``@implementation`` block,
6334methods defined in the block are considered to be declared as direct unless
6335they have been previously declared as non-direct in any interface of the class.
6336This includes the implicit method definitions introduced by synthesized
6337properties, including auto-synthesized properties.)reST";
6338
6339static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6340
6341static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6342
6343static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The ``objc_externally_retained`` attribute can be applied to strong local
6344variables, functions, methods, or blocks to opt into
6345`externally-retained semantics
6346<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
6347
6348When applied to the definition of a function, method, or block, every parameter
6349of the function with implicit strong retainable object pointer type is
6350considered externally-retained, and becomes ``const``. By explicitly annotating
6351a parameter with ``__strong``, you can opt back into the default
6352non-externally-retained behavior for that parameter. For instance,
6353``first_param`` is externally-retained below, but not ``second_param``:
6354
6355.. code-block:: objc
6356
6357 __attribute__((objc_externally_retained))
6358 void f(NSArray *first_param, __strong NSArray *second_param) {
6359 // ...
6360 }
6361
6362Likewise, when applied to a strong local variable, that variable becomes
6363``const`` and is considered externally-retained.
6364
6365When compiled without ``-fobjc-arc``, this attribute is ignored.)reST";
6366
6367static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6368
6369static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6370
6371static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6372
6373static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6374
6375static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6376selectors. It is sometimes useful to be able to mark a method as having a
6377particular conventional meaning despite not having the right selector, or as
6378not having the conventional meaning that its selector would suggest. For these
6379use cases, we provide an attribute to specifically describe the "method family"
6380that a method belongs to.
6381
6382**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
6383``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
6384attribute can only be placed at the end of a method declaration:
6385
6386.. code-block:: objc
6387
6388 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6389
6390Users who do not wish to change the conventional meaning of a method, and who
6391merely want to document its non-standard retain and release semantics, should
6392use the retaining behavior attributes (``ns_returns_retained``,
6393``ns_returns_not_retained``, etc).
6394
6395Query for this feature with ``__has_attribute(objc_method_family)``.)reST";
6396
6397static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6398
6399static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C ``@interface`` or
6400``@implementation`` declaration to add the class to the list of non-lazily
6401initialized classes. A non-lazy class will be initialized eagerly when the
6402Objective-C runtime is loaded. This is required for certain system classes which
6403have instances allocated in non-standard ways, such as the classes for blocks
6404and constant strings. Adding this attribute is essentially equivalent to
6405providing a trivial ``+load`` method but avoids the (fairly small) load-time
6406overheads associated with defining and calling such a method.)reST";
6407
6408static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The ``objc_non_runtime_protocol`` attribute can be used to mark that an
6409Objective-C protocol is only used during static type-checking and doesn't need
6410to be represented dynamically. This avoids several small code-size and run-time
6411overheads associated with handling the protocol's metadata. A non-runtime
6412protocol cannot be used as the operand of a ``@protocol`` expression, and
6413dynamic attempts to find it with ``objc_getProtocol`` will fail.
6414
6415If a non-runtime protocol inherits from any ordinary protocols, classes and
6416derived protocols that declare conformance to the non-runtime protocol will
6417dynamically list their conformance to those bare protocols.)reST";
6418
6419static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6420
6421static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6422
6423static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6424
6425static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6426parent class but expect that the overriding method also calls the overridden
6427method in the parent class. For these cases, we provide an attribute to
6428designate that a method requires a "call to ``super``" in the overriding
6429method in the subclass.
6430
6431**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
6432be placed at the end of a method declaration:
6433
6434.. code-block:: objc
6435
6436 - (void)foo __attribute__((objc_requires_super));
6437
6438This attribute can only be applied the method declarations within a class, and
6439not a protocol. Currently this attribute does not enforce any placement of
6440where the call occurs in the overriding method (such as in the case of
6441``-dealloc`` where the call must appear at the end). It checks only that it
6442exists.
6443
6444Note that on both OS X and iOS that the Foundation framework provides a
6445convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
6446attribute:
6447
6448.. code-block:: objc
6449
6450 - (void)foo NS_REQUIRES_SUPER;
6451
6452This macro is conditionally defined depending on the compiler's support for
6453this attribute. If the compiler does not support the attribute the macro
6454expands to nothing.
6455
6456Operationally, when a method has this annotation the compiler will warn if the
6457implementation of an override in a subclass does not call super. For example:
6458
6459.. code-block:: objc
6460
6461 warning: method possibly missing a [super AnnotMeth] call
6462 - (void) AnnotMeth{};
6463 ^)reST";
6464
6465static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6466
6467static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6468
6469static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6470in the metadata name for that object. The ``objc_runtime_name``
6471attribute allows annotated interfaces or protocols to use the
6472specified string argument in the object's metadata name instead of the
6473default name.
6474
6475**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
6476can only be placed before an @protocol or @interface declaration:
6477
6478.. code-block:: objc
6479
6480 __attribute__((objc_runtime_name("MyLocalName")))
6481 @interface Message
6482 @end)reST";
6483
6484static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6485visible to the Objective-C runtime but not to the linker. Classes annotated
6486with this attribute cannot be subclassed and cannot have categories defined for
6487them.)reST";
6488
6489static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C ``@interface`` declaration to
6490ensure that this class cannot be subclassed.)reST";
6491
6492static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6493
6494static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6495
6496static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6497to declare if they are being read or written by a kernel or function.
6498
6499The read_only/__read_only, write_only/__write_only and read_write/__read_write
6500names are reserved for use as access qualifiers and shall not be used otherwise.
6501
6502.. code-block:: c
6503
6504 kernel void
6505 foo (read_only image2d_t imageA,
6506 write_only image2d_t imageB) {
6507 ...
6508 }
6509
6510In the above example imageA is a read-only 2D image object, and imageB is a
6511write-only 2D image object.
6512
6513The read_write (or __read_write) qualifier can not be used with pipe.
6514
6515More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6516
6517static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6518a constant (non-modifiable) memory region. It is available to all work items.
6519Any type can be annotated with the constant address space attribute. Objects
6520with the constant address space qualifier can be declared in any scope and must
6521have an initializer.)reST";
6522
6523static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6524It can be used with pointer types. Variables in global and local scope and
6525function parameters in non-kernel functions can have the generic address space
6526type attribute. It is intended to be a placeholder for any other address space
6527except for '__constant' in OpenCL code which can be used with multiple address
6528spaces.)reST";
6529
6530static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6531global memory, which is accessible by all work items. The content stored in this
6532memory area persists between kernel executions. Pointer types to the global
6533address space are allowed as function parameters or local variables. Starting
6534with OpenCL v2.0, the global address space can be used with global (program
6535scope) variables and static local variable as well.)reST";
6536
6537static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6538an object is allocated in global memory on the device/host. It helps to
6539distinguish USM (Unified Shared Memory) pointers that access global device
6540memory from those that access global host memory. These new address spaces are
6541a subset of the ``__global/opencl_global`` address space, the full address space
6542set model for OpenCL 2.0 with the extension looks as follows:
6543
6544 | generic->global->host
6545 | ->device
6546 | ->private
6547 | ->local
6548 | constant
6549
6550As ``global_device`` and ``global_host`` are a subset of
6551``__global/opencl_global`` address spaces it is allowed to convert
6552``global_device`` and ``global_host`` address spaces to
6553``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6554"Address space nesting and rules for pointers").
6555
6556These attributes are deprecated and may be removed in a future version of Clang.)reST";
6557
6558static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6559an object is allocated in global memory on the device/host. It helps to
6560distinguish USM (Unified Shared Memory) pointers that access global device
6561memory from those that access global host memory. These new address spaces are
6562a subset of the ``__global/opencl_global`` address space, the full address space
6563set model for OpenCL 2.0 with the extension looks as follows:
6564
6565 | generic->global->host
6566 | ->device
6567 | ->private
6568 | ->local
6569 | constant
6570
6571As ``global_device`` and ``global_host`` are a subset of
6572``__global/opencl_global`` address spaces it is allowed to convert
6573``global_device`` and ``global_host`` address spaces to
6574``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6575"Address space nesting and rules for pointers").
6576
6577These attributes are deprecated and may be removed in a future version of Clang.)reST";
6578
6579static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6580the kernel must be compiled and executed with the specified subgroup size. When
6581this attribute is present, get_max_sub_group_size() is guaranteed to return the
6582specified integer value. This is important for the correctness of many subgroup
6583algorithms, and in some cases may be used by the compiler to generate more optimal
6584code. See `cl_intel_required_subgroup_size
6585<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6586for details.)reST";
6587
6588static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6589group) memory area, which is accessible to all work items in the same work
6590group. The content stored in this memory region is not accessible after
6591the kernel execution ends. In a kernel function scope, any variable can be in
6592the local address space. In other scopes, only pointer types to the local address
6593space are allowed. Local address space variables cannot have an initializer.)reST";
6594
6595static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6596(work item) memory. Other work items cannot access the same memory area and its
6597content is destroyed after work item execution ends. Local variables can be
6598declared in the private address space. Function arguments are always in the
6599private address space. Kernel function arguments of a pointer or an array type
6600cannot point to the private address space.)reST";
6601
6602static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6603(for, while and do loops) can be unrolled. This attribute qualifier can be
6604used to specify full unrolling or partial unrolling by a specified amount.
6605This is a compiler hint and the compiler may ignore this directive. See
6606`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
6607s6.11.5 for details.)reST";
6608
6609static const char AttrDoc_OptimizeNone[] = R"reST(The ``optnone`` attribute suppresses essentially all optimizations
6610on a function or method, regardless of the optimization level applied to
6611the compilation unit as a whole. This is particularly useful when you
6612need to debug a particular function, but it is infeasible to build the
6613entire application without optimization. Avoiding optimization on the
6614specified function can improve the quality of the debugging information
6615for that function.
6616
6617This attribute is incompatible with the ``always_inline`` and ``minsize``
6618attributes.
6619
6620Note that this attribute does not apply recursively to nested functions such as
6621lambdas or blocks when using declaration-specific attribute syntaxes such as double
6622square brackets (``[[]]``) or ``__attribute__``. The ``#pragma`` syntax can be
6623used to apply the attribute to all functions, including nested functions, in a
6624range of source code.)reST";
6625
6626static const char AttrDoc_OverflowBehavior[] = R"reST(The ``overflow_behavior`` attribute provides fine-grained, type-level control
6627over how arithmetic operations on an integer type behave on overflow. It may be
6628applied to a ``typedef``, to a variable or data member, or to an integer type
6629directly, and accepts one of two behaviors as its argument:
6630
6631* ``wrap``: arithmetic on the attributed type wraps on overflow, using two's
6632 complement semantics. This is equivalent to ``-fwrapv`` but scoped to the
6633 attributed type, and works for both signed and unsigned types. UBSan's
6634 ``signed-integer-overflow``, ``unsigned-integer-overflow``,
6635 ``implicit-signed-integer-truncation``, and
6636 ``implicit-unsigned-integer-truncation`` checks are suppressed for the type.
6637
6638* ``trap``: arithmetic on the attributed type is checked for overflow, enabling
6639 overflow checks for the type even when ``-fwrapv`` is in effect globally.
6640
6641.. code-block:: c++
6642
6643 typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint;
6644
6645 non_wrapping_uint add_one(non_wrapping_uint a) {
6646 return a + 1; // Overflow is checked for this operation.
6647 }
6648
6649 int mul_alot(int n) {
6650 int __attribute__((overflow_behavior(wrap))) a = n;
6651 return a * 1337; // Overflow is not checked and is well-defined.
6652 }
6653
6654The keyword spellings ``__ob_wrap`` and ``__ob_trap`` are equivalent to
6655``overflow_behavior(wrap)`` and ``overflow_behavior(trap)`` respectively.
6656
6657The attribute wholly overrides global flags (``-ftrapv``, ``-fwrapv``,
6658sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can
6659only be applied to integer types.
6660
6661This feature is experimental and must be enabled with the ``-cc1`` option
6662``-fexperimental-overflow-behavior-types``. For full details on promotion and
6663conversion rules, pointer semantics, diagnostics, and interaction with
6664sanitizers, see :doc:`OverflowBehaviorTypes`.)reST";
6665
6666static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6667in C is introduced using the ``overloadable`` attribute. For example, one
6668might provide several overloaded versions of a ``tgsin`` function that invokes
6669the appropriate standard function computing the sine of a value with ``float``,
6670``double``, or ``long double`` precision:
6671
6672.. code-block:: c
6673
6674 #include <math.h>
6675 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6676 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6677 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6678
6679Given these declarations, one can call ``tgsin`` with a ``float`` value to
6680receive a ``float`` result, with a ``double`` to receive a ``double`` result,
6681etc. Function overloading in C follows the rules of C++ function overloading
6682to pick the best overload given the call arguments, with a few C-specific
6683semantics:
6684
6685* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
6686 floating-point promotion (per C99) rather than as a floating-point conversion
6687 (as in C++).
6688
6689* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
6690 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
6691 compatible types.
6692
6693* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
6694 and ``U`` are compatible types. This conversion is given "conversion" rank.
6695
6696* If no viable candidates are otherwise available, we allow a conversion from a
6697 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
6698 incompatible. This conversion is ranked below all other types of conversions.
6699 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
6700 for ``T`` and ``U`` to be incompatible.
6701
6702The declaration of ``overloadable`` functions is restricted to function
6703declarations and definitions. If a function is marked with the ``overloadable``
6704attribute, then all declarations and definitions of functions with that name,
6705except for at most one (see the note below about unmarked overloads), must have
6706the ``overloadable`` attribute. In addition, redeclarations of a function with
6707the ``overloadable`` attribute must have the ``overloadable`` attribute, and
6708redeclarations of a function without the ``overloadable`` attribute must *not*
6709have the ``overloadable`` attribute. e.g.,
6710
6711.. code-block:: c
6712
6713 int f(int) __attribute__((overloadable));
6714 float f(float); // error: declaration of "f" must have the "overloadable" attribute
6715 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6716
6717 int g(int) __attribute__((overloadable));
6718 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6719
6720 int h(int);
6721 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6722 // have the "overloadable" attribute
6723
6724Functions marked ``overloadable`` must have prototypes. Therefore, the
6725following code is ill-formed:
6726
6727.. code-block:: c
6728
6729 int h() __attribute__((overloadable)); // error: h does not have a prototype
6730
6731However, ``overloadable`` functions are allowed to use a ellipsis even if there
6732are no named parameters (as is permitted in C++). This feature is particularly
6733useful when combined with the ``unavailable`` attribute:
6734
6735.. code-block:: c++
6736
6737 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6738
6739Functions declared with the ``overloadable`` attribute have their names mangled
6740according to the same rules as C++ function names. For example, the three
6741``tgsin`` functions in our motivating example get the mangled names
6742``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
6743caveats to this use of name mangling:
6744
6745* Future versions of Clang may change the name mangling of functions overloaded
6746 in C, so you should not depend on an specific mangling. To be completely
6747 safe, we strongly urge the use of ``static inline`` with ``overloadable``
6748 functions.
6749
6750* The ``overloadable`` attribute has almost no meaning when used in C++,
6751 because names will already be mangled and functions are already overloadable.
6752 However, when an ``overloadable`` function occurs within an ``extern "C"``
6753 linkage specification, its name *will* be mangled in the same way as it
6754 would in C.
6755
6756For the purpose of backwards compatibility, at most one function with the same
6757name as other ``overloadable`` functions may omit the ``overloadable``
6758attribute. In this case, the function without the ``overloadable`` attribute
6759will not have its name mangled.
6760
6761For example:
6762
6763.. code-block:: c
6764
6765 // Notes with mangled names assume Itanium mangling.
6766 int f(int);
6767 int f(double) __attribute__((overloadable));
6768 void foo() {
6769 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6770 // was marked with overloadable).
6771 f(1.0); // Emits a call to _Z1fd.
6772 }
6773
6774Support for unmarked overloads is not present in some versions of clang. You may
6775query for it using ``__has_extension(overloadable_unmarked)``.
6776
6777Query for this attribute with ``__has_attribute(overloadable)``.)reST";
6778
6779static const char AttrDoc_Override[] = R"reST()reST";
6780
6781static const char AttrDoc_Owner[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6782 a future version of clang.
6783
6784The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
6785object of type ``T``:
6786
6787.. code::
6788
6789 class [[gsl::Owner(int)]] IntOwner {
6790 private:
6791 int value;
6792 public:
6793 int *getInt() { return &value; }
6794 };
6795
6796The argument ``T`` is optional and is ignored.
6797This attribute may be used by analysis tools and has no effect on code
6798generation. A ``void`` argument means that the class can own any type.
6799
6800See Pointer_ for an example.)reST";
6801
6802static const char AttrDoc_Ownership[] = R"reST(.. note::
6803
6804 In order for the Clang Static Analyzer to acknowledge these attributes, the
6805 ``Optimistic`` config needs to be set to true for the checker
6806 ``unix.DynamicMemoryModeling``:
6807
6808 ``-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true``
6809
6810These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6811facilities to mark custom allocating/deallocating functions.
6812
6813All 3 attributes' first parameter of type string is the type of the allocation:
6814``malloc``, ``new``, etc. to allow for catching :ref:`mismatched deallocation
6815<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6816a function annotated with
6817returning a piece of memory of type ``lasagna`` but freed with a function
6818annotated to release ``cheese`` typed memory will result in mismatched
6819deallocation warning.
6820
6821The (currently) only allocation type having special meaning is ``malloc`` --
6822the Clang Static Analyzer makes sure that allocating functions annotated with
6823``malloc`` are treated like they used the standard ``malloc()``, and can be
6824safely deallocated with the standard ``free()``.
6825
6826* Use ``ownership_returns`` to mark a function as an allocating function.
6827 It takes 1 or 2 arguments.
6828 The first argument is a user-provided identifier representing the "kind" of the allocation.
6829 This is basically what is enforced when checking the deallocation. This is mandatory.
6830 The second argument is optional.
6831 It represents the index of the parameter that represents the allocation size in bytes (counting from 1).
6832 The referenced parameter must have some integral type.
6833 This attribute may appear at most once per declaration.
6834 If this argument is not set, then tooling, such as the Clang Static Analyzer,
6835 won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses.
6836 However, such tooling could still warn if the wrong deallocation function
6837 was used for the ``ownership_returns`` attributed resource.
6838 If forward declarations have this attribute, those must have the same arguments.
6839* Use ``ownership_takes`` to mark a function as a deallocating function. Takes 2
6840 arguments: the allocation type, and the index of the parameter that is being
6841 deallocated (counting from 1).
6842* Use ``ownership_holds`` to mark that a function takes over the ownership of a
6843 piece of memory and will free it at some unspecified point in the future. Like
6844 ``ownership_takes``, this takes 2 arguments: the allocation type, and the
6845 index of the parameter whose ownership will be taken over (counting from 1).
6846
6847The annotations ``ownership_takes`` and ``ownership_holds`` both prevent memory
6848leak reports (concerning the specified parameter); the difference between them
6849is that using taken memory is a use-after-free error, while using held memory
6850is assumed to be legitimate. However, releasing the held memory or passing it
6851to another holding call is reported by the analyzer as an "attempt to release
6852non-owned memory".
6853
6854Example:
6855
6856.. code-block:: c
6857
6858 // Denotes that my_malloc will return with a dynamically allocated piece of
6859 // memory using malloc().
6860 void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz);
6861
6862 // 'sz' (parameter 1) is the allocation size.
6863 void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz);
6864
6865 // Denotes that my_free will deallocate its argument using free().
6866 void __attribute((ownership_takes(malloc, 1))) my_free(void *);
6867
6868 // Denotes that my_hold will take over the ownership of its argument that was
6869 // allocated via malloc().
6870 void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
6871
6872Further reading about dynamic memory modeling in the Clang Static Analyzer is
6873found in these checker docs:
6874:ref:`unix.Malloc <unix-Malloc>`, :ref:`unix.MallocSizeof <unix-MallocSizeof>`,
6875:ref:`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
6876:ref:`cplusplus.NewDelete <cplusplus-NewDelete>`,
6877:ref:`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
6878:ref:`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
6879Mind that many more checkers are affected by dynamic memory modeling changes to
6880some extent.
6881
6882Further reading for other annotations:
6883`Source Annotations in the Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/user-docs/Annotations.html>`_.)reST";
6884
6885static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
6886
6887static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
6888function with annotated parameters will issue a warning if the corresponding
6889argument isn't in the expected state. The attribute is also used to set the
6890initial state of the parameter when analyzing the function's body.)reST";
6891
6892static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
6893
6894static const char AttrDoc_PassObjectSize[] = R"reST(.. Note:: The mangling of functions with parameters that are annotated with
6895 ``pass_object_size`` is subject to change. You can get around this by
6896 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
6897 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
6898 not mangled.
6899
6900The ``pass_object_size(Type)`` attribute can be placed on function parameters to
6901instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
6902of said function, and implicitly pass the result of this call in as an invisible
6903argument of type ``size_t`` directly after the parameter annotated with
6904``pass_object_size``. Clang will also replace any calls to
6905``__builtin_object_size(param, Type)`` in the function by said implicit
6906parameter.
6907
6908Example usage:
6909
6910.. code-block:: c
6911
6912 int bzero1(char *const p __attribute__((pass_object_size(0))))
6913 __attribute__((noinline)) {
6914 int i = 0;
6915 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
6916 p[i] = 0;
6917 }
6918 return i;
6919 }
6920
6921 int main() {
6922 char chars[100];
6923 int n = bzero1(&chars[0]);
6924 assert(n == sizeof(chars));
6925 return 0;
6926 }
6927
6928If successfully evaluating ``__builtin_object_size(param, Type)`` at the
6929callsite is not possible, then the "failed" value is passed in. So, using the
6930definition of ``bzero1`` from above, the following code would exit cleanly:
6931
6932.. code-block:: c
6933
6934 int main2(int argc, char *argv[]) {
6935 int n = bzero1(argv);
6936 assert(n == -1);
6937 return 0;
6938 }
6939
6940``pass_object_size`` plays a part in overload resolution. If two overload
6941candidates are otherwise equally good, then the overload with one or more
6942parameters with ``pass_object_size`` is preferred. This implies that the choice
6943between two identical overloads both with ``pass_object_size`` on one or more
6944parameters will always be ambiguous; for this reason, having two such overloads
6945is illegal. For example:
6946
6947.. code-block:: c++
6948
6949 #define PS(N) __attribute__((pass_object_size(N)))
6950 // OK
6951 void Foo(char *a, char *b); // Overload A
6952 // OK -- overload A has no parameters with pass_object_size.
6953 void Foo(char *a PS(0), char *b PS(0)); // Overload B
6954 // Error -- Same signature (sans pass_object_size) as overload B, and both
6955 // overloads have one or more parameters with the pass_object_size attribute.
6956 void Foo(void *a PS(0), void *b);
6957
6958 // OK
6959 void Bar(void *a PS(0)); // Overload C
6960 // OK
6961 void Bar(char *c PS(1)); // Overload D
6962
6963 void main() {
6964 char known[10], *unknown;
6965 Foo(unknown, unknown); // Calls overload B
6966 Foo(known, unknown); // Calls overload B
6967 Foo(unknown, known); // Calls overload B
6968 Foo(known, known); // Calls overload B
6969
6970 Bar(known); // Calls overload D
6971 Bar(unknown); // Calls overload D
6972 }
6973
6974Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
6975
6976* Only one use of ``pass_object_size`` is allowed per parameter.
6977
6978* It is an error to take the address of a function with ``pass_object_size`` on
6979 any of its parameters. If you wish to do this, you can create an overload
6980 without ``pass_object_size`` on any parameters.
6981
6982* It is an error to apply the ``pass_object_size`` attribute to parameters that
6983 are not pointers. Additionally, any parameter that ``pass_object_size`` is
6984 applied to must be marked ``const`` at its function's definition.
6985
6986Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
6987identically to ``pass_object_size``, but evaluates a call to
6988``__builtin_dynamic_object_size`` at the callee instead of
6989``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
6990runtime checks when the object size can't be determined at compile-time. You can
6991read more about ``__builtin_dynamic_object_size`` `here
6992<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.)reST";
6993
6994static const char AttrDoc_PatchableFunctionEntry[] = R"reST(``__attribute__((patchable_function_entry(N,M,Section)))`` is used to generate M
6995NOPs before the function entry and N-M NOPs after the function entry, with a record of
6996the entry stored in section ``Section``. This attribute takes precedence over the
6997command line option ``-fpatchable-function-entry=N,M,Section``. ``M`` defaults to 0
6998if omitted.``Section`` defaults to the ``-fpatchable-function-entry`` section name if
6999set, or to ``__patchable_function_entries`` otherwise.
7000
7001This attribute is only supported on
7002aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
7003For ppc/ppc64 targets, AIX is still not supported.)reST";
7004
7005static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
7006similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
7007"aapcs-vfp".)reST";
7008
7009static const char AttrDoc_Personality[] = R"reST(``__attribute__((personality(<routine>)))`` is used to specify a personality
7010routine that is different from the language that is being used to implement the
7011function. This is a targeted, low-level feature aimed at language runtime
7012implementors who write runtime support code in C/C++ but need that code to
7013participate in a foreign language's exception-handling or unwinding model.
7014
7015A personality routine is a language-specific callback attached to each stack
7016frame that the unwinder invokes to determine whether that frame handles a given
7017exception and what cleanup actions to perform. It effectively colors the
7018language-agnostic unwinding mechanism with language-specific semantics, enabling
7019different languages to coexist on the same call stack while each interpreting
7020exceptions according to their own rules.)reST";
7021
7022static const char AttrDoc_Pointer[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
7023 a future version of clang.
7024
7025The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
7026like pointers to an object of type ``T``:
7027
7028.. code::
7029
7030 class [[gsl::Pointer(int)]] IntPointer {
7031 private:
7032 int *valuePointer;
7033 public:
7034 IntPointer(const IntOwner&);
7035 int *getInt() { return valuePointer; }
7036 };
7037
7038The argument ``T`` is optional and is ignored.
7039This attribute may be used by analysis tools and has no effect on code
7040generation. A ``void`` argument means that the pointer can point to any type.
7041
7042Example:
7043When constructing an instance of a class annotated like this (a Pointer) from
7044an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
7045then the analysis will consider the Pointer to point inside the Owner.
7046When the Owner's lifetime ends, it will consider the Pointer to be dangling.
7047
7048.. code-block:: c++
7049
7050 int f() {
7051 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
7052 P.getInt(); // P is dangling
7053 }
7054
7055**Transparent Member Functions**
7056
7057The analysis automatically tracks certain member functions of ``[[gsl::Pointer]]`` types
7058that provide transparent access to the pointed-to object. These include:
7059
7060* Dereference operators: ``operator*``, ``operator->``
7061* Data access methods: ``data()``, ``c_str()``, ``get()``
7062* Iterator operations: ``begin()``, ``end()``, ``rbegin()``, ``rend()``, ``cbegin()``, ``cend()``, ``crbegin()``, ``crend()``, ``operator+``, ``operator-``, ``operator++``, ``operator--``
7063
7064When these methods return pointers, view types, or references, the analysis treats them as
7065transparently borrowing from the same object that the pointer itself borrows from,
7066enabling detection of use-after-free through these access patterns:
7067
7068.. code-block:: c++
7069
7070 // For example, .data() here returns a borrow to 's' instead of 'v'.
7071 const char* f() {
7072 std::string s = "hello";
7073 std::string_view v = s; // warning: address of stack memory returned
7074 return v.data(); // note: returned here
7075 }
7076
7077 const MyObj& g(MyObj obj) {
7078 View v = obj; // warning: address of stack memory returned
7079 return *v; // note: returned here
7080 }
7081
7082This tracking also applies to range-based for loops, where the ``begin()`` and ``end()``
7083iterators are used to access elements:
7084
7085.. code-block:: c++
7086
7087 std::string_view f(std::vector<std::string> vec) {
7088 for (const std::string& s : vec) { // warning: address of stack memory returned
7089 return s; // note: returned here
7090 }
7091 }
7092
7093**Container Template Specialization**
7094
7095If a template class is annotated with ``[[gsl::Owner]]``, and the first
7096instantiated template argument is a pointer type (raw pointer, or ``[[gsl::Pointer]]``),
7097the analysis will consider the instantiated class as a container of the pointer.
7098When constructing such an object from a GSL owner object, the analysis will
7099assume that the container holds a pointer to the owner object. Consequently,
7100when the owner object is destroyed, the pointer will be considered dangling.
7101
7102.. code-block:: c++
7103
7104 int f() {
7105 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
7106 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
7107 })reST";
7108
7109static const char AttrDoc_PointerAuth[] = R"reST(The ``__ptrauth`` qualifier allows the programmer to directly control
7110how pointers are signed when they are stored in a particular variable.
7111This can be used to strengthen the default protections of pointer
7112authentication and make it more difficult for an attacker to escalate
7113an ability to alter memory into full control of a process.
7114
7115.. code-block:: c
7116
7117 #include <ptrauth.h>
7118
7119 typedef void (*my_callback)(const void*);
7120 my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
7121
7122The first argument to ``__ptrauth`` is the name of the signing key.
7123Valid key names for the target are defined in ``<ptrauth.h>``.
7124
7125The second argument to ``__ptrauth`` is a flag (0 or 1) specifying whether
7126the object should use address discrimination.
7127
7128The third argument to ``__ptrauth`` is a 16-bit non-negative integer which
7129allows additional discrimination between objects.)reST";
7130
7131static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
7132
7133static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
7134
7135static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
7136
7137static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
7138
7139static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
7140
7141static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
7142
7143static const char AttrDoc_PreferredName[] = R"reST(The ``preferred_name`` attribute can be applied to a class template, and
7144specifies a preferred way of naming a specialization of the template. The
7145preferred name will be used whenever the corresponding template specialization
7146would otherwise be printed in a diagnostic or similar context.
7147
7148The preferred name must be a typedef or type alias declaration that refers to a
7149specialization of the class template (not including any type qualifiers). In
7150general this requires the template to be declared at least twice. For example:
7151
7152.. code-block:: c++
7153
7154 template<typename T> struct basic_string;
7155 using string = basic_string<char>;
7156 using wstring = basic_string<wchar_t>;
7157 template<typename T> struct [[clang::preferred_name(string),
7158 clang::preferred_name(wstring)]] basic_string {
7159 // ...
7160 };
7161
7162
7163Note that the ``preferred_name`` attribute will be ignored when the compiler
7164writes a C++20 Module interface now. This is due to a compiler issue
7165(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize
7166declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
7167
7168static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
7169This can be helpful when a bit-field is intended to store an enumeration value,
7170but has to be specified as having the enumeration's underlying type in order to
7171facilitate compiler optimizations or bit-field packing behavior. Normally, the
7172underlying type is what is emitted in debug information, which can make it hard
7173for debuggers to know to map a bit-field's value back to a particular enumeration.
7174
7175.. code-block:: c++
7176
7177 enum Colors { Red, Green, Blue };
7178
7179 struct S {
7180 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
7181 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
7182 } s = { Green, false };
7183
7184Without the attribute, a debugger is likely to display the value ``1`` for ``ColorVal``
7185and ``0`` for ``UseAlternateColorSpace``. With the attribute, the debugger may now
7186display ``Green`` and ``false`` instead.
7187
7188This can be used to map a bit-field to an arbitrary type that isn't integral
7189or an enumeration type. For example:
7190
7191.. code-block:: c++
7192
7193 struct A {
7194 short a1;
7195 short a2;
7196 };
7197
7198 struct B {
7199 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7200 };
7201
7202will associate the type ``A`` with the ``b1`` bit-field and is intended to display
7203something like this in the debugger:
7204
7205.. code-block:: text
7206
7207 Process 2755547 stopped
7208 * thread #1, name = 'test-preferred-', stop reason = step in
7209 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7210 10 int main()
7211 11 {
7212 12 B b;
7213 -> 13 return b.b1;
7214 14 }
7215 (lldb) v -T
7216 (B) b = {
7217 (A:32) b1 = {
7218 (short) a1 = 12
7219 (short) a2 = 15
7220 }
7221 }
7222
7223Note that debuggers may not be able to handle more complex mappings, and so
7224this usage is debugger-dependent.)reST";
7225
7226static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7227a function. The ``preserve_all`` calling convention attempts to make the code
7228in the caller even less intrusive than the ``preserve_most`` calling convention.
7229This calling convention also behaves identical to the ``C`` calling convention
7230on how arguments and return values are passed, but it uses a different set of
7231caller/callee-saved registers. This removes the burden of saving and
7232recovering a large register set before and after the call in the caller. If
7233the arguments are passed in callee-saved registers, then they will be
7234preserved by the callee across the call. This doesn't apply for values
7235returned in callee-saved registers.
7236
7237- On X86-64 the callee preserves all general purpose registers, except for
7238 R11. R11 can be used as a scratch register. Furthermore it also preserves
7239 all floating-point registers (XMMs/YMMs).
7240
7241- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7242 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7243 point registers.
7244
7245The idea behind this convention is to support calls to runtime functions
7246that don't need to call out to any other functions.
7247
7248This calling convention, like the ``preserve_most`` calling convention, will be
7249used by a future version of the Objective-C runtime and should be considered
7250experimental at this time.)reST";
7251
7252static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7253a function. The ``preserve_most`` calling convention attempts to make the code
7254in the caller as unintrusive as possible. This convention behaves identically
7255to the ``C`` calling convention on how arguments and return values are passed,
7256but it uses a different set of caller/callee-saved registers. This alleviates
7257the burden of saving and recovering a large register set before and after the
7258call in the caller. If the arguments are passed in callee-saved registers,
7259then they will be preserved by the callee across the call. This doesn't
7260apply for values returned in callee-saved registers.
7261
7262- On X86-64 the callee preserves all general purpose registers, except for
7263 R11. R11 can be used as a scratch register. Floating-point registers
7264 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7265
7266- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7267 X16-X18.
7268
7269The idea behind this convention is to support calls to runtime functions
7270that have a hot path and a cold path. The hot path is usually a small piece
7271of code that doesn't use many registers. The cold path might need to call out to
7272another function and therefore only needs to preserve the caller-saved
7273registers, which haven't already been saved by the caller. The
7274``preserve_most`` calling convention is very similar to the ``cold`` calling
7275convention in terms of caller/callee-saved registers, but they are used for
7276different types of function calls. ``coldcc`` is for function calls that are
7277rarely executed, whereas ``preserve_most`` function calls are intended to be
7278on the hot path and definitely executed a lot. Furthermore ``preserve_most``
7279doesn't prevent the inliner from inlining the function call.
7280
7281This calling convention will be used by a future version of the Objective-C
7282runtime and should therefore still be considered experimental at this time.
7283Although this convention was created to optimize certain runtime calls to
7284the Objective-C runtime, it is not limited to this runtime and might be used
7285by other runtimes in the future too. The current implementation only
7286supports X86-64 and AArch64, but the intention is to support more architectures
7287in the future.)reST";
7288
7289static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7290The ``preserve_none`` calling convention tries to preserve as few general
7291registers as possible. So all general registers are caller saved registers. It
7292also uses more general registers to pass arguments. This attribute doesn't
7293impact floating-point registers. ``preserve_none``'s ABI is still unstable, and
7294may be changed in the future.
7295
7296- On X86-64, only RSP and RBP are preserved by the callee.
7297 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7298 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7299 follow the C calling convention.
7300- On AArch64, only LR and FP are preserved by the callee.
7301 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7302 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7303 convention. X15 is not available for argument passing on Windows, but is
7304 used to pass arguments on other platforms.)reST";
7305
7306static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7307
7308static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7309
7310static const char AttrDoc_Ptr32[] = R"reST(The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
731164-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
7312``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
7313is sign extended or zero extended. This qualifier is enabled under
7314``-fms-extensions``.)reST";
7315
7316static const char AttrDoc_Ptr64[] = R"reST(The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
731732-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
7318qualifier is enabled under ``-fms-extensions``.)reST";
7319
7320static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7321
7322static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
7323targets. This attribute may be attached to a function definition and instructs
7324the backend to generate appropriate function entry/exit code so that it can be
7325used directly as an interrupt service routine.
7326
7327Permissible values for this parameter are ``machine``, ``supervisor``,
7328``rnmi``, ``qci-nest``, ``qci-nonest``, ``SiFive-CLIC-preemptible``, and
7329``SiFive-CLIC-stack-swap``. If there is no parameter, then it defaults to
7330``machine``.
7331
7332The ``rnmi`` value is used for resumable non-maskable interrupts. It requires the
7333standard Smrnmi extension.
7334
7335The ``qci-nest`` and ``qci-nonest`` values require Qualcomm's Xqciint extension
7336and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7337interrupts. These use the following instructions from Xqciint to save and
7338restore interrupt state to the stack -- the ``qci-nest`` value will use
7339``qc.c.mienter.nest`` and the ``qci-nonest`` value will use ``qc.c.mienter`` to
7340begin the interrupt handler. Both of these will use ``qc.c.mileaveret`` to
7341restore the state and return to the previous context.
7342
7343The ``SiFive-CLIC-preemptible`` and ``SiFive-CLIC-stack-swap`` values are used
7344for machine-mode interrupts. For ``SiFive-CLIC-preemptible`` interrupts, the
7345values of ``mcause`` and ``mepc`` are saved onto the stack, and interrupts are
7346re-enabled. For ``SiFive-CLIC-stack-swap`` interrupts, the stack pointer is
7347swapped with ``mscratch`` before its first use and after its last use.
7348
7349The SiFive CLIC values may be combined with each other and with the ``machine``
7350attribute value. Any other combination of different values is not allowed.
7351
7352Repeated interrupt attribute on the same declaration will cause a warning
7353to be emitted. In case of repeated declarations, the last one prevails.
7354
7355Refer to:
7356https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
7357https://riscv.org/specifications/privileged-isa/
7358The RISC-V Instruction Set Manual Volume II: Privileged Architecture
7359Version 1.10.
7360https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0
7361https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf)reST";
7362
7363static const char AttrDoc_RISCVVLSCC[] = R"reST(The ``riscv_vls_cc`` attribute can be applied to a function. Functions
7364declared with this attribute will utilize the standard fixed-length vector
7365calling convention variant instead of the default calling convention defined by
7366the ABI. This variant aims to pass fixed-length vectors via vector registers,
7367if possible, rather than through general-purpose registers.)reST";
7368
7369static const char AttrDoc_RISCVVectorCC[] = R"reST(The ``riscv_vector_cc`` attribute can be applied to a function. It preserves 15
7370registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7371to save these registers before function calls, and callees only need to save
7372them if they use them.)reST";
7373
7374static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
7375for structure layout field randomization; a compile-time hardening technique. A
7376"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
7377For example:
7378
7379.. code-block:: bash
7380
7381 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7382 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7383
7384You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
7385For example:
7386
7387.. code-block:: bash
7388
7389 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7390 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7391
7392The randomization is deterministic based for a given seed, so the entire
7393program should be compiled with the same seed, but keep the seed safe
7394otherwise.
7395
7396The attribute ``no_randomize_layout``, when attached to a C structure,
7397instructs the compiler that this structure should not have its field layout
7398randomized.)reST";
7399
7400static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7401 When attached to a record declaration/definition, it checks if all instances
7402 of this type can be placed in the read-only data segment of the program. If it
7403 finds an instance that can not be placed in a read-only segment, the compiler
7404 emits a warning at the source location where the type was used.
7405
7406 Examples:
7407 * ``struct __attribute__((enforce_read_only_placement)) Foo;``
7408 * ``struct __attribute__((enforce_read_only_placement)) Bar { ... };``
7409
7410 Both ``Foo`` and ``Bar`` types have the ``enforce_read_only_placement`` attribute.
7411
7412 The goal of introducing this attribute is to assist developers with writing secure
7413 code. A ``const``-qualified global is generally placed in the read-only section
7414 of the memory that has additional run time protection from malicious writes. By
7415 attaching this attribute to a declaration, the developer can express the intent
7416 to place all instances of the annotated type in the read-only program memory.
7417
7418 Note 1: The attribute doesn't guarantee that the object will be placed in the
7419 read-only data segment as it does not instruct the compiler to ensure such
7420 a placement. It emits a warning if something in the code can be proven to prevent
7421 an instance from being placed in the read-only data segment.
7422
7423 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
7424 are ``const``-qualified. The following conditions would also prevent the data to be
7425 put into read only segment, but the corresponding warnings are not yet implemented.
7426
7427 1. An instance of type ``T`` is allocated on the heap/stack.
7428 2. Type ``T`` defines/inherits a mutable field.
7429 3. Type ``T`` defines/inherits non-constexpr constructor(s) for initialization.
7430 4. A field of type ``T`` is defined by type ``Q``, which does not bear the
7431 ``enforce_read_only_placement`` attribute.
7432 5. A type ``Q`` inherits from type ``T`` and it does not have the
7433 ``enforce_read_only_placement`` attribute.)reST";
7434
7435static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7436
7437static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7438`__regcall`_ convention. This convention aims to pass as many arguments
7439as possible in registers. It also tries to utilize registers for the
7440return value whenever it is possible.
7441
7442.. _`__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";
7443
7444static const char AttrDoc_Reinitializes[] = R"reST(The ``reinitializes`` attribute can be applied to a non-static, non-const C++
7445member function to indicate that this member function reinitializes the entire
7446object to a known state, independent of the previous state of the object.
7447
7448This attribute can be interpreted by static analyzers that warn about uses of an
7449object that has been left in an indeterminate state by a move operation. If a
7450member function marked with the ``reinitializes`` attribute is called on a
7451moved-from object, the analyzer can conclude that the object is no longer in an
7452indeterminate state.
7453
7454A typical example where this attribute would be used is on functions that clear
7455a container class:
7456
7457.. code-block:: c++
7458
7459 template <class T>
7460 class Container {
7461 public:
7462 ...
7463 [[clang::reinitializes]] void Clear();
7464 ...
7465 };)reST";
7466
7467static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7468
7469static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with ``release_handle(tag)`` it is assumed to
7470close the handle. It is also assumed to require an open handle to work with. The
7471attribute requires a string literal argument to identify the handle being released.
7472
7473.. code-block:: c++
7474
7475 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);)reST";
7476
7477static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7478
7479static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7480
7481static const char AttrDoc_Restrict[] = R"reST(The ``malloc`` attribute has two forms with different functionality. The first
7482is when it is used without arguments, where it marks that a function acts like
7483a system memory allocation function, returning a pointer to allocated storage
7484that does not alias storage from any other object accessible to the caller.
7485
7486The second form is when ``malloc`` takes one or two arguments. The first
7487argument names a function that should be associated with this function as its
7488deallocation function. When this form is used, it enables the compiler to
7489diagnose when the incorrect deallocation function is used with this variable.
7490However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7491yet implemented in clang.)reST";
7492
7493static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7494section garbage collection in the linker. It does not prevent other discard
7495mechanisms, such as archive member selection, and COMDAT group resolution.
7496
7497If the compiler does not emit the definition, e.g. because it was not used in
7498the translation unit or the compiler was able to eliminate all of the uses,
7499this attribute has no effect. This attribute is typically combined with the
7500``used`` attribute to force the definition to be emitted and preserved into the
7501final linked image.
7502
7503This attribute is only necessary on ELF targets; other targets prevent section
7504garbage collection by the linker when using the ``used`` attribute alone.
7505Using the attributes together should result in consistent behavior across
7506targets.
7507
7508This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
7509This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as
7510well as in ``ld.lld`` 13.)reST";
7511
7512static const char AttrDoc_ReturnTypestate[] = R"reST(The ``return_typestate`` attribute can be applied to functions or parameters.
7513When applied to a function the attribute specifies the state of the returned
7514value. The function's body is checked to ensure that it always returns a value
7515in the specified state. On the caller side, values returned by the annotated
7516function are initialized to the given state.
7517
7518When applied to a function parameter it modifies the state of an argument after
7519a call to the function returns. The function's body is checked to ensure that
7520the parameter is in the expected state before returning.)reST";
7521
7522static const char AttrDoc_ReturnsNonNull[] = R"reST(The ``returns_nonnull`` attribute indicates that a particular function (or
7523Objective-C method) always returns a non-null pointer. For example, a
7524particular system ``malloc`` might be defined to terminate a process when
7525memory is not available rather than returning a null pointer:
7526
7527 .. code-block:: c
7528
7529 extern void * malloc (size_t size) __attribute__((returns_nonnull));
7530
7531The ``returns_nonnull`` attribute implies that returning a null pointer is
7532undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
7533type qualifier indicates that a pointer cannot be null in a more general manner
7534(because it is part of the type system) and does not imply undefined behavior,
7535making it more widely applicable)reST";
7536
7537static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7538
7539static const char AttrDoc_RootSignature[] = R"reST(The ``RootSignature`` attribute applies to HLSL entry functions to define what
7540types of resources are bound to the graphics pipeline.
7541
7542For details about the use and specification of Root Signatures please see here:
7543https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures)reST";
7544
7545static const char AttrDoc_SPtr[] = R"reST(The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
7546extended when converted to a 64-bit pointer.)reST";
7547
7548static const char AttrDoc_SYCLExternal[] = R"reST(The ``sycl_external`` attribute indicates that a function defined in another
7549translation unit may be called by a device function defined in the current
7550translation unit or, if defined in the current translation unit, the function
7551may be called by device functions defined in other translation units.
7552The attribute is intended for use in the implementation of the ``SYCL_EXTERNAL``
7553macro as specified in section 5.10.1, "SYCL functions and member functions
7554linkage", of the SYCL 2020 specification.
7555
7556The attribute only appertains to functions and only those that meet the
7557following requirements:
7558
7559* Has external linkage
7560* Is not explicitly defined as deleted (the function may be an explicitly
7561 defaulted function that is defined as deleted)
7562
7563The attribute shall be present on the first declaration of a function and
7564may optionally be present on subsequent declarations.
7565
7566When compiling for a SYCL device target that does not support the generic
7567address space, the function shall not specify a raw pointer or reference type
7568as the return type or as a parameter type.
7569See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7570The following examples demonstrate the use of this attribute:
7571
7572.. code-block:: c++
7573
7574 [[clang::sycl_external]] void Foo(); // Ok.
7575
7576 [[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7577
7578 [[clang::sycl_external]] extern void Baz(); // Ok.
7579
7580 [[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.)reST";
7581
7582static const char AttrDoc_SYCLKernel[] = R"reST(The ``sycl_kernel`` attribute specifies that a function template will be used
7583to outline device code and to generate an OpenCL kernel.
7584Here is a code example of the SYCL program, which demonstrates the compiler's
7585outlining job:
7586
7587.. code-block:: c++
7588
7589 int foo(int x) { return ++x; }
7590
7591 using namespace cl::sycl;
7592 queue Q;
7593 buffer<int, 1> a(range<1>{1024});
7594 Q.submit([&](handler& cgh) {
7595 auto A = a.get_access<access::mode::write>(cgh);
7596 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
7597 A[index] = index[0] + foo(42);
7598 });
7599 }
7600
7601A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
7602A SYCL kernel defines the entry point to the "device part" of the code. The
7603compiler will emit all symbols accessible from a "kernel". In this code
7604example, the compiler will emit "foo" function. More details about the
7605compilation of functions for the device part can be found in the SYCL 1.2.1
7606specification Section 6.4.
7607To show to the compiler entry point to the "device part" of the code, the SYCL
7608runtime can use the ``sycl_kernel`` attribute in the following way:
7609
7610.. code-block:: c++
7611
7612 namespace cl {
7613 namespace sycl {
7614 class handler {
7615 template <typename KernelName, typename KernelType/*, ...*/>
7616 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
7617 // ...
7618 KernelFuncObj();
7619 }
7620
7621 template <typename KernelName, typename KernelType, int Dims>
7622 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
7623 #ifdef __SYCL_DEVICE_ONLY__
7624 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
7625 #else
7626 // Host implementation
7627 #endif
7628 }
7629 };
7630 } // namespace sycl
7631 } // namespace cl
7632
7633The compiler will also generate an OpenCL kernel using the function marked with
7634the ``sycl_kernel`` attribute.
7635Here is the list of SYCL device compiler expectations with regard to the
7636function marked with the ``sycl_kernel`` attribute:
7637
7638- The function must be a template with at least two type template parameters.
7639 The compiler generates an OpenCL kernel and uses the first template parameter
7640 as a unique name for the generated OpenCL kernel. The host application uses
7641 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
7642 specialized by this name and second template parameter ``KernelType`` (which
7643 might be an unnamed function object type).
7644- The function must have at least one parameter. The first parameter is
7645 required to be a function object type (named or unnamed i.e. lambda). The
7646 compiler uses function object type fields to generate OpenCL kernel
7647 parameters.
7648- The function must return void. The compiler reuses the body of marked functions to
7649 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``.
7650
7651The SYCL kernel in the previous code sample meets these expectations.)reST";
7652
7653static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The ``sycl_kernel_entry_point`` attribute facilitates the launch of a SYCL
7654kernel and the generation of an offload kernel entry point, sometimes called
7655a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
7656offload device. The attribute is intended for use in the implementation of
7657SYCL kernel invocation functions like the ``single_task`` and ``parallel_for``
7658member functions of the ``sycl::handler`` class specified in section 4.9.4,
7659"Command group ``handler`` class", of the SYCL 2020 specification.
7660
7661The attribute requires a single type argument that meets the requirements for
7662a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
7663SYCL 2020 specification. A unique kernel name type is required for each
7664function declared with the attribute. The attribute may not first appear on a
7665declaration that follows a definition of the function.
7666
7667The attribute only appertains to functions and only those that meet the
7668following requirements.
7669
7670* Has a non-deduced ``void`` return type.
7671* Is not a constructor or destructor.
7672* Is not a non-static member function with an explicit object parameter.
7673* Is not a C variadic function.
7674* Is not a coroutine.
7675* Is not defined as deleted or as defaulted.
7676* Is not defined with a function try block.
7677* Is not declared with the ``constexpr`` or ``consteval`` specifiers.
7678* Is not declared with the ``[[noreturn]]`` attribute.
7679
7680Use in the implementation of a SYCL kernel invocation function might look as
7681follows.
7682
7683.. code-block:: c++
7684
7685 namespace sycl {
7686 class handler {
7687 template<typename KernelName, typename... Ts>
7688 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
7689 // This code will run on the host and is responsible for calling functions
7690 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
7691 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
7692 // to a device and to schedule an invocation of the offload kernel entry
7693 // point denoted by kernelSymbol with the copied arguments.
7694 }
7695
7696 template<typename KernelName, typename KernelType>
7697 [[ clang::sycl_kernel_entry_point(KernelName) ]]
7698 void kernel_entry_point(KernelType kernelFunc) {
7699 // This code will run on the device. The call to kernelFunc() invokes
7700 // the SYCL kernel.
7701 kernelFunc();
7702 }
7703
7704 public:
7705 template<typename KernelName, typename KernelType>
7706 void single_task(const KernelType& kernelFunc) {
7707 // This code will run on the host. kernel_entry_point() is called to
7708 // trigger generation of an offload kernel entry point and to schedule
7709 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
7710 // passed as a kernel argument. This call will result in an implicit call
7711 // to sycl_kernel_launch() with the symbol name for the generated offload
7712 // kernel entry point passed as the first function argument followed by
7713 // kernelFunc.
7714 kernel_entry_point<KernelName>(kernelFunc);
7715 }
7716 };
7717 } // namespace sycl
7718
7719A SYCL kernel object is a callable object of class type that is constructed on
7720a host, often via a lambda expression, and then passed to a SYCL kernel
7721invocation function to be executed on an offload device. The ``kernelFunc``
7722parameters in the example code above correspond to SYCL kernel objects.
7723
7724A SYCL kernel object type is required to satisfy the device copyability
7725requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
7726specification. Additionally, any data members of the kernel object type are
7727required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
7728For most types, these rules require that the type is trivially copyable.
7729However, the SYCL specification mandates that certain special SYCL types, such
7730as ``sycl::accessor`` and ``sycl::stream``, be device copyable even if they are
7731not trivially copyable. These types require special handling because they cannot
7732necessarily be copied to device memory as if by ``memcpy()``.
7733
7734The SYCL kernel object and its data members constitute the parameters of an
7735offload kernel. An offload kernel consists of an offload entry point function
7736and the set of all functions and variables that are directly or indirectly used
7737by the entry point function.
7738
7739A SYCL kernel invocation function is responsible for performing the following
7740tasks (likely with the help of an offload backend like OpenCL):
7741
7742#. Identifying the offload kernel entry point to be used for the SYCL kernel.
7743
7744#. Validating that the SYCL kernel object type and its data members meet the
7745 SYCL device copyability and kernel parameter requirements noted above.
7746
7747#. Copying the SYCL kernel object and any other kernel arguments to device
7748 memory including any special handling required for SYCL special types.
7749
7750#. Initiating execution of the offload kernel entry point.
7751
7752The offload kernel entry point for a SYCL kernel performs the following tasks:
7753
7754#. Calling the ``operator()`` member function of the SYCL kernel object.
7755
7756The ``sycl_kernel_entry_point`` attribute facilitates or automates these tasks
7757by providing generation of an offload kernel entry point with a unique symbol
7758name, type checking of kernel argument requirements, and initiation of kernel
7759execution via synthesized calls to a ``sycl_kernel_launch`` template.
7760
7761A function declared with the ``sycl_kernel_entry_point`` attribute specifies
7762the parameters and body of an offload entry point function. Consider the
7763following call to the ``single_task()`` SYCL kernel invocation function assuming
7764an implementation similar to the one shown above.
7765
7766.. code-block:: c++
7767
7768 struct S { int i; };
7769 void f(sycl::handler &handler, sycl::stream &sout, S s) {
7770 handler.single_task<struct KN>([=] {
7771 sout << "The value of s.i is " << s.i << "\n";
7772 });
7773 }
7774
7775The SYCL kernel object is the result of the lambda expression. The call to
7776``kernel_entry_point()`` via the call to ``single_task()`` triggers the
7777generation of an offload kernel entry point function that looks approximately
7778as follows.
7779
7780.. code-block:: c++
7781
7782 void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
7783 kernelFunc();
7784 }
7785
7786There are a few items worthy of note:
7787
7788#. ``sycl-kernel-caller-for-KN`` is an exposition only name; the actual name
7789 generated for an entry point is an implementation detail and subject to
7790 change. However, the name will incorporate the SYCL kernel name, ``KN``,
7791 that was passed as the ``KernelName`` template parameter to
7792 ``single_task()`` and eventually provided as the argument to the
7793 ``sycl_kernel_entry_point`` attribute in order to ensure that a unique
7794 name is generated for each entry point. There is a one-to-one correspondence
7795 between SYCL kernel names and offload kernel entry points.
7796
7797#. The SYCL kernel is a lambda closure type and therefore has no name;
7798 ``kernel-type`` is substituted above and corresponds to the ``KernelType``
7799 template parameter deduced in the call to ``single_task()``.
7800
7801#. The parameter and the call to ``kernelFunc()`` in the function body
7802 correspond to the definition of ``kernel_entry_point()`` as called by
7803 ``single_task()``.
7804
7805#. The parameter is type checked for conformance with the SYCL device
7806 copyability and kernel parameter requirements.
7807
7808Within ``single_task()``, the call to ``kernel_entry_point()`` is effectively
7809replaced with a synthesized call to a ''sycl_kernel_launch`` template that
7810looks approximately as follows.
7811
7812.. code-block:: c++
7813
7814 sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
7815
7816There are a few items worthy of note:
7817
7818#. Lookup for the ``sycl_kernel_launch`` template is performed as if from the
7819 body of the (possibly instantiated) definition of ``kernel_entry_point()``.
7820 If name lookup or overload resolution fails, the program is ill-formed.
7821 If the selected overload is a non-static member function, then ``this`` is
7822 passed as the implicit object parameter.
7823
7824#. Function arguments passed to ``sycl_kernel_launch()`` are passed
7825 as if by ``std::move(x)``.
7826
7827#. The ``sycl_kernel_launch`` template is expected to be provided by the SYCL
7828 library implementation. It is responsible for copying the kernel arguments
7829 to device memory and for scheduling execution of the generated offload
7830 kernel entry point identified by the symbol name passed as the first
7831 function argument. ``sycl-kernel-caller-for-KN`` is substituted above for
7832 the actual symbol name that would be generated for the offload kernel entry
7833 point.
7834
7835It is not necessary for a function declared with the ``sycl_kernel_entry_point``
7836attribute to be called for the offload kernel entry point to be emitted. For
7837inline functions and function templates, any ODR-use will suffice. For other
7838functions, an ODR-use is not required; the offload kernel entry point will be
7839emitted if the function is defined. In any case, a call to the function is
7840required for the synthesized call to ``sycl_kernel_launch()`` to occur.
7841
7842A function declared with the ``sycl_kernel_entry_point`` attribute may include
7843an exception specification. If a non-throwing exception specification is
7844present, an exception propagating from the implicit call to the
7845``sycl_kernel_launch`` template will result in a call to ``std::terminate()``.
7846Otherwise, such an exception will propagate normally.
7847
7848Functions declared with the ``sycl_kernel_entry_point`` attribute are not
7849limited to the simple example shown above. They may have additional template
7850parameters, declare additional function parameters, and have complex control
7851flow in the function body. The function must abide by the language feature
7852restrictions described in section 5.4, "Language restrictions for device
7853functions" in the SYCL 2020 specification. If the function is a non-static
7854member function, ``this`` shall not be used in a potentially evaluated
7855expression.)reST";
7856
7857static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
7858specific handling during the generation of the SPIR entry point.
7859The ``__attribute__((sycl_special_class))`` attribute is used in SYCL
7860headers to indicate that a class or a struct needs a specific handling when
7861it is passed from host to device.
7862Special classes will have a mandatory ``__init`` method and an optional
7863``__finalize`` method (the ``__finalize`` method is used only with the
7864``stream`` type). Kernel parameters types are extract from the ``__init`` method
7865parameters. The kernel function arguments list is derived from the
7866arguments of the ``__init`` method. The arguments of the ``__init`` method are
7867copied into the kernel function argument list and the ``__init`` and
7868``__finalize`` methods are called at the beginning and the end of the kernel,
7869respectively.
7870The ``__init`` and ``__finalize`` methods must be defined inside the
7871special class.
7872Please note that this is an attribute that is used as an internal
7873implementation detail and not intended to be used by external users.
7874
7875The syntax of the attribute is as follows:
7876
7877.. code-block:: text
7878
7879 class __attribute__((sycl_special_class)) accessor {};
7880 class [[clang::sycl_special_class]] accessor {};
7881
7882This is a code example that illustrates the use of the attribute:
7883
7884.. code-block:: c++
7885
7886 class __attribute__((sycl_special_class)) SpecialType {
7887 int F1;
7888 int F2;
7889 void __init(int f1) {
7890 F1 = f1;
7891 F2 = f1;
7892 }
7893 void __finalize() {}
7894 public:
7895 SpecialType() = default;
7896 int getF2() const { return F2; }
7897 };
7898
7899 int main () {
7900 SpecialType T;
7901 cgh.single_task([=] {
7902 T.getF2();
7903 });
7904 }
7905
7906This would trigger the following kernel entry point in the AST:
7907
7908.. code-block:: c++
7909
7910 void __sycl_kernel(int f1) {
7911 SpecialType T;
7912 T.__init(f1);
7913 ...
7914 T.__finalize()
7915 })reST";
7916
7917static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
7918
7919static const char AttrDoc_Section[] = R"reST(The ``section`` attribute allows you to specify a specific section a
7920global variable or function should be in after translation.)reST";
7921
7922static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
7923definition (
7924`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
7925), allowing the linker to select any definition.
7926
7927For more information see
7928`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
7929or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.)reST";
7930
7931static const char AttrDoc_Sentinel[] = R"reST(The ``sentinel`` attribute can be applied to variadic functions and pointers to
7932variadic functions, to diagnose each function call that does not pass a
7933sentinel value (a null pointer constant) as the last argument to the function
7934call. The attribute accepts two optional arguments: the first argument is the
7935position of the expected sentinel value, starting from the last parameter. The
7936second argument describes whether the last fixed parameter is treated as a
7937valid sentinel value when set to '1'.
7938All arguments described above default to '0' when elided.
7939The attribute is also supported with blocks and in Objective-C.
7940
7941.. code-block:: c
7942
7943 void foo(const char*, ...) __attribute__((sentinel));
7944 void bar(int, ...) __attribute__((sentinel(1)));
7945 void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1)));
7946
7947 void example() {
7948 foo("Example", (void*)0);
7949 foo("Another", "example", NULL);
7950 foo("Missing", "sentinel"); // Not OK
7951
7952 bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position
7953 bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23
7954 bar(1, 2, 3, 4, NULL); // Not OK
7955
7956 baz("Test", "with", "multiple", "args", NULL);
7957 baz("One", NULL); // OK: last fixed parameter is a valid sentinel
7958
7959 void (*ptr) (int arg, ...) __attribute__ ((__sentinel__));
7960 ptr(1, 2, 3, NULL);
7961 }
7962
7963.. code-block:: c++
7964
7965 struct Ty {
7966 int value;
7967
7968 template<typename T>
7969 auto&& foo(T&& val, ...) __attribute__((sentinel(1))) {
7970 return std::forward<T>(val);
7971 }
7972
7973 template<class Self>
7974 auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) {
7975 return std::forward<Self>(self).value;
7976 }
7977 };
7978
7979 void example2() {
7980 auto sty = Ty{};
7981 sty.foo(1, nullptr, 3);
7982 sty.bar(1, nullptr, 3);
7983
7984 auto lmbd = [](int a, ...) __attribute__((sentinel)) {};
7985 lmbd(1, 2, nullptr);
7986 })reST";
7987
7988static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
7989``__attribute__((set_typestate(new_state)))``. The new state must be
7990unconsumed, consumed, or unknown.)reST";
7991
7992static const char AttrDoc_SizedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7993structure in C. The argument for the attribute is the name of a field member
7994holding the count of elements in the flexible array. This information can be
7995used to improve the results of the array bound sanitizer and the
7996``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7997within the same non-anonymous, enclosing struct as the flexible array member.
7998
7999This example specifies that the flexible array member ``array`` has the number
8000of elements allocated for it in ``count``:
8001
8002.. code-block:: c
8003
8004 struct bar;
8005
8006 struct foo {
8007 size_t count;
8008 char other;
8009 struct bar *array[] __attribute__((counted_by(count)));
8010 };
8011
8012This establishes a relationship between ``array`` and ``count``. Specifically,
8013``array`` must have at least ``count`` number of elements available. It's the
8014user's responsibility to ensure that this relationship is maintained through
8015changes to the structure.
8016
8017In the following example, the allocated array erroneously has fewer elements
8018than what's specified by ``p->count``. This would result in an out-of-bounds
8019access not being detected.
8020
8021.. code-block:: c
8022
8023 #define SIZE_INCR 42
8024
8025 struct foo *p;
8026
8027 void foo_alloc(size_t count) {
8028 p = malloc(MAX(sizeof(struct foo),
8029 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8030 p->count = count + SIZE_INCR;
8031 }
8032
8033The next example updates ``p->count``, but breaks the relationship requirement
8034that ``p->array`` must have at least ``p->count`` number of elements available:
8035
8036.. code-block:: c
8037
8038 #define SIZE_INCR 42
8039
8040 struct foo *p;
8041
8042 void foo_alloc(size_t count) {
8043 p = malloc(MAX(sizeof(struct foo),
8044 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8045 p->count = count;
8046 }
8047
8048 void use_foo(int index, int val) {
8049 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
8050 p->array[index] = val; /* The sanitizer can't properly check this access. */
8051 }
8052
8053In this example, an update to ``p->count`` maintains the relationship
8054requirement:
8055
8056.. code-block:: c
8057
8058 void use_foo(int index, int val) {
8059 if (p->count == 0)
8060 return;
8061 --p->count;
8062 p->array[index] = val;
8063 })reST";
8064
8065static const char AttrDoc_SizedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
8066structure in C. The argument for the attribute is the name of a field member
8067holding the count of elements in the flexible array. This information can be
8068used to improve the results of the array bound sanitizer and the
8069``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
8070within the same non-anonymous, enclosing struct as the flexible array member.
8071
8072This example specifies that the flexible array member ``array`` has the number
8073of elements allocated for it in ``count``:
8074
8075.. code-block:: c
8076
8077 struct bar;
8078
8079 struct foo {
8080 size_t count;
8081 char other;
8082 struct bar *array[] __attribute__((counted_by(count)));
8083 };
8084
8085This establishes a relationship between ``array`` and ``count``. Specifically,
8086``array`` must have at least ``count`` number of elements available. It's the
8087user's responsibility to ensure that this relationship is maintained through
8088changes to the structure.
8089
8090In the following example, the allocated array erroneously has fewer elements
8091than what's specified by ``p->count``. This would result in an out-of-bounds
8092access not being detected.
8093
8094.. code-block:: c
8095
8096 #define SIZE_INCR 42
8097
8098 struct foo *p;
8099
8100 void foo_alloc(size_t count) {
8101 p = malloc(MAX(sizeof(struct foo),
8102 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8103 p->count = count + SIZE_INCR;
8104 }
8105
8106The next example updates ``p->count``, but breaks the relationship requirement
8107that ``p->array`` must have at least ``p->count`` number of elements available:
8108
8109.. code-block:: c
8110
8111 #define SIZE_INCR 42
8112
8113 struct foo *p;
8114
8115 void foo_alloc(size_t count) {
8116 p = malloc(MAX(sizeof(struct foo),
8117 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8118 p->count = count;
8119 }
8120
8121 void use_foo(int index, int val) {
8122 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
8123 p->array[index] = val; /* The sanitizer can't properly check this access. */
8124 }
8125
8126In this example, an update to ``p->count`` maintains the relationship
8127requirement:
8128
8129.. code-block:: c
8130
8131 void use_foo(int index, int val) {
8132 if (p->count == 0)
8133 return;
8134 --p->count;
8135 p->array[index] = val;
8136 })reST";
8137
8138static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
8139 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
8140 should be enabled for the function body. This can also be applied to a method
8141 in Objective C. This attribute will take precedence over the command line flag in
8142 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
8143
8144 Speculative Load Hardening is a best-effort mitigation against
8145 information leak attacks that make use of control flow
8146 miss-speculation - specifically miss-speculation of whether a branch
8147 is taken or not. Typically vulnerabilities enabling such attacks are
8148 classified as "Spectre variant #1". Notably, this does not attempt to
8149 mitigate against miss-speculation of branch target, classified as
8150 "Spectre variant #2" vulnerabilities.
8151
8152 When inlining, the attribute is sticky. Inlining a function that
8153 carries this attribute will cause the caller to gain the
8154 attribute. This is intended to provide a maximally conservative model
8155 where the code in a function annotated with this attribute will always
8156 (even after inlining) end up hardened.)reST";
8157
8158static const char AttrDoc_StackProtectorIgnore[] = R"reST(The ``stack_protector_ignore`` attribute skips analysis of the given local
8159variable when determining if a function should use a stack protector.
8160
8161The ``-fstack-protector`` option uses a heuristic to only add stack protectors
8162to functions which contain variables or buffers over some size threshold. This
8163attribute overrides that heuristic for the attached variable, opting
8164them out. If this results in no variables or buffers remaining over the stack
8165protector threshold, then the function will no longer use a stack protector.)reST";
8166
8167static const char AttrDoc_StandaloneDebug[] = R"reST(The ``standalone_debug`` attribute causes debug info to be emitted for a record
8168type regardless of the debug info optimizations that are enabled with
8169-fno-standalone-debug. This attribute only has an effect when debug info
8170optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
8171
8172static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8173function to clear parameters off of the stack on return. This convention does
8174not support variadic calls or unprototyped functions in C, and has no effect on
8175x86_64 targets. This calling convention is used widely by the Windows API and
8176COM applications. See the documentation for `__stdcall`_ on MSDN.
8177
8178.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
8179
8180static const char AttrDoc_StrictFP[] = R"reST()reST";
8181
8182static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style ``__declspec((strict_gs_check))`` attribute
8183which upgrades the stack protector check from ``-fstack-protector`` to
8184``-fstack-protector-strong``.
8185
8186For example, it upgrades the stack protector for the function ``foo`` to
8187``-fstack-protector-strong`` but function ``bar`` will still be built with the
8188stack protector with the ``-fstack-protector`` option.
8189
8190.. code-block:: c
8191
8192 __declspec((strict_gs_check))
8193 int foo(int x); // stack protection will be upgraded for foo.
8194
8195 int bar(int y); // bar can be built with the standard stack protector checks.)reST";
8196
8197static const char AttrDoc_Suppress[] = R"reST(The ``suppress`` attribute suppresses unwanted warnings coming from static
8198analysis tools such as the Clang Static Analyzer. The tool will not report
8199any issues in source code annotated with the attribute.
8200
8201The attribute cannot be used to suppress traditional Clang warnings, because
8202many such warnings are emitted before the attribute is fully parsed.
8203Consider using ``#pragma clang diagnostic`` to control such diagnostics,
8204as described in `Controlling Diagnostics via Pragmas
8205<https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas>`_.
8206
8207The ``suppress`` attribute can be placed on an individual statement in order to
8208suppress warnings about undesirable behavior occurring at that statement:
8209
8210.. code-block:: c++
8211
8212 int foo() {
8213 int *x = nullptr;
8214 ...
8215 [[clang::suppress]]
8216 return *x; // null pointer dereference warning suppressed here
8217 }
8218
8219Putting the attribute on a compound statement suppresses all warnings in scope:
8220
8221.. code-block:: c++
8222
8223 int foo() {
8224 [[clang::suppress]] {
8225 int *x = nullptr;
8226 ...
8227 return *x; // warnings suppressed in the entire scope
8228 }
8229 }
8230
8231The attribute can also be placed on entire declarations of functions, classes,
8232variables, member variables, and so on, to suppress warnings related
8233to the declarations themselves. When used this way, the attribute additionally
8234suppresses all warnings in the lexical scope of the declaration:
8235
8236.. code-block:: c++
8237
8238 class [[clang::suppress]] C {
8239 int foo() {
8240 int *x = nullptr;
8241 ...
8242 return *x; // warnings suppressed in the entire class scope
8243 }
8244
8245 int bar();
8246 };
8247
8248 int C::bar() {
8249 int *x = nullptr;
8250 ...
8251 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
8252 }
8253
8254Some static analysis warnings are accompanied by one or more notes, and the
8255line of code against which the warning is emitted isn't necessarily the best
8256for suppression purposes. In such cases the tools are allowed to implement
8257additional ways to suppress specific warnings based on the attribute attached
8258to a note location.
8259
8260For example, the Clang Static Analyzer suppresses memory leak warnings when
8261the suppression attribute is placed at the allocation site (highlited by
8262a "note: memory is allocated"), which may be different from the line of code
8263at which the program "loses track" of the pointer (where the warning
8264is ultimately emitted):
8265
8266.. code-block:: c
8267
8268 int bar1(bool coin_flip) {
8269 __attribute__((suppress))
8270 int *result = (int *)malloc(sizeof(int));
8271 if (coin_flip)
8272 return 1; // warning about this leak path is suppressed
8273
8274 return *result; // warning about this leak path is also suppressed
8275 }
8276
8277 int bar2(bool coin_flip) {
8278 int *result = (int *)malloc(sizeof(int));
8279 if (coin_flip)
8280 return 1; // leak warning on this path NOT suppressed
8281
8282 __attribute__((suppress))
8283 return *result; // leak warning is suppressed only on this path
8284 }
8285
8286
8287When written as ``[[gsl::suppress]]``, this attribute suppresses specific
8288clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
8289way. The attribute can be attached to declarations, statements, and at
8290namespace scope.
8291
8292.. code-block:: c++
8293
8294 [[gsl::suppress("Rh-public")]]
8295 void f_() {
8296 int *p;
8297 [[gsl::suppress("type")]] {
8298 p = reinterpret_cast<int*>(7);
8299 }
8300 }
8301 namespace N {
8302 [[clang::suppress("type", "bounds")]];
8303 ...
8304 }
8305
8306.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8307
8308static const char AttrDoc_SwiftAsync[] = R"reST(The ``swift_async`` attribute specifies if and how a particular function or
8309Objective-C method is imported into a swift async method. For instance:
8310
8311.. code-block:: objc
8312
8313 @interface MyClass : NSObject
8314 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8315 __attribute__((swift_async(none)));
8316
8317 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8318 __attribute__((swift_async(swift_private, 1)));
8319 @end
8320
8321Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
8322``async`` (because it's last parameter's selector piece is
8323``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
8324Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
8325``async`` if not for the ``swift_async`` attribute because it doesn't match the
8326naming convention.
8327
8328When using ``swift_async`` to enable importing, the first argument to the
8329attribute is either ``swift_private`` or ``not_swift_private`` to indicate
8330whether the function/method is private to the current framework, and the second
8331argument is the index of the completion handler parameter.)reST";
8332
8333static const char AttrDoc_SwiftAsyncCall[] = R"reST(The ``swiftasynccall`` attribute indicates that a function is
8334compatible with the low-level conventions of Swift async functions,
8335provided it declares the right formal arguments.
8336
8337In most respects, this is similar to the ``swiftcall`` attribute, except for
8338the following:
8339
8340- A parameter may be marked ``swift_async_context``, ``swift_context``
8341 or ``swift_indirect_result`` (with the same restrictions on parameter
8342 ordering as ``swiftcall``) but the parameter attribute
8343 ``swift_error_result`` is not permitted.
8344
8345- A ``swiftasynccall`` function must have return type ``void``.
8346
8347- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall``
8348 function that is the immediate operand of a ``return`` statement is
8349 guaranteed to be performed as a tail call. This syntax is allowed even
8350 in C as an extension (a call to a void-returning function cannot be a
8351 return operand in standard C). If something in the calling function would
8352 semantically be performed after a guaranteed tail call, such as the
8353 non-trivial destruction of a local variable or temporary,
8354 then the program is ill-formed.
8355
8356Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
8357the target supports the calling convention with
8358``__has_extension(swiftasynccc)``.)reST";
8359
8360static const char AttrDoc_SwiftAsyncContext[] = R"reST(The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall``
8361function as having the special asynchronous context-parameter ABI treatment.
8362
8363If the function is not ``swiftasynccall``, this attribute only generates
8364extended frame information.
8365
8366A context parameter must have pointer or reference type.)reST";
8367
8368static const char AttrDoc_SwiftAsyncError[] = R"reST(The ``swift_async_error`` attribute specifies how an error state will be
8369represented in a swift async method. It's a bit analogous to the ``swift_error``
8370attribute for the generated async method. The ``swift_async_error`` attribute
8371can indicate a variety of different ways of representing an error.
8372
8373- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the
8374 async method is considered to have failed if the Nth argument to the
8375 completion handler is zero.
8376
8377- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that
8378 the async method is considered to have failed if the Nth argument to the
8379 completion handler is non-zero.
8380
8381- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the
8382 async method is considered to have failed if the ``NSError *`` argument to the
8383 completion handler is non-null.
8384
8385- ``__attribute__((swift_async_error(none)))``, specifies that the async method
8386 cannot fail.
8387
8388
8389For instance:
8390
8391.. code-block:: objc
8392
8393 @interface MyClass : NSObject
8394 -(void)asyncMethod:(void (^)(char, int, float))handler
8395 __attribute__((swift_async(swift_private, 1)))
8396 __attribute__((swift_async_error(zero_argument, 2)));
8397 @end
8398
8399Here, the ``swift_async`` attribute specifies that ``handler`` is the completion
8400handler for this method, and the ``swift_async_error`` attribute specifies that
8401the ``int`` parameter is the one that represents the error.)reST";
8402
8403static const char AttrDoc_SwiftAsyncName[] = R"reST(The ``swift_async_name`` attribute provides the name of the ``async`` overload for
8404the given declaration in Swift. If this attribute is absent, the name is
8405transformed according to the algorithm built into the Swift compiler.
8406
8407The argument is a string literal that contains the Swift name of the function or
8408method. The name may be a compound Swift name. The function or method with such
8409an attribute must have more than zero parameters, as its last parameter is
8410assumed to be a callback that's eliminated in the Swift ``async`` name.
8411
8412 .. code-block:: objc
8413
8414 @interface URL
8415 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8416 @end)reST";
8417
8418static const char AttrDoc_SwiftAttr[] = R"reST(The ``swift_attr`` provides a Swift-specific annotation for the declaration
8419or type to which the attribute appertains to. It can be used on any declaration
8420or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
8421semantic meaning in languages supported by Clang. The Swift compiler can
8422interpret these annotations according to its own rules when importing C or
8423Objective-C declarations.)reST";
8424
8425static const char AttrDoc_SwiftBridge[] = R"reST(The ``swift_bridge`` attribute indicates that the declaration to which the
8426attribute appertains is bridged to the named Swift type.
8427
8428 .. code-block:: objc
8429
8430 __attribute__((__objc_root__))
8431 @interface Base
8432 - (instancetype)init;
8433 @end
8434
8435 __attribute__((__swift_bridge__("BridgedI")))
8436 @interface I : Base
8437 @end
8438
8439In this example, the Objective-C interface ``I`` will be made available to Swift
8440with the name ``BridgedI``. It would be possible for the compiler to refer to
8441``I`` still in order to bridge the type back to Objective-C.)reST";
8442
8443static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
8444the attribute appertains is imported into Swift, it should refer to the bridged
8445Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
8446(e.g. ``NSString``).
8447
8448 .. code-block:: objc
8449
8450 @interface NSString;
8451 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
8452
8453 extern void acceptsAliasedString(AliasedString _Nonnull parameter);
8454
8455In this case, the function ``acceptsAliasedString`` will be imported into Swift
8456as a function which accepts a ``String`` type parameter.)reST";
8457
8458static const char AttrDoc_SwiftCall[] = R"reST(The ``swiftcall`` attribute indicates that a function should be called
8459using the Swift calling convention for a function or function pointer.
8460
8461The lowering for the Swift calling convention, as described by the Swift
8462ABI documentation, occurs in multiple phases. The first, "high-level"
8463phase breaks down the formal parameters and results into innately direct
8464and indirect components, adds implicit parameters for the generic
8465signature, and assigns the context and error ABI treatments to parameters
8466where applicable. The second phase breaks down the direct parameters
8467and results from the first phase and assigns them to registers or the
8468stack. The ``swiftcall`` convention only handles this second phase of
8469lowering; the C function type must accurately reflect the results
8470of the first phase, as follows:
8471
8472- Results classified as indirect by high-level lowering should be
8473 represented as parameters with the ``swift_indirect_result`` attribute.
8474
8475- Results classified as direct by high-level lowering should be represented
8476 as follows:
8477
8478 - First, remove any empty direct results.
8479
8480 - If there are no direct results, the C result type should be ``void``.
8481
8482 - If there is one direct result, the C result type should be a type with
8483 the exact layout of that result type.
8484
8485 - If there are a multiple direct results, the C result type should be
8486 a struct type with the exact layout of a tuple of those results.
8487
8488- Parameters classified as indirect by high-level lowering should be
8489 represented as parameters of pointer type.
8490
8491- Parameters classified as direct by high-level lowering should be
8492 omitted if they are empty types; otherwise, they should be represented
8493 as a parameter type with a layout exactly matching the layout of the
8494 Swift parameter type.
8495
8496- The context parameter, if present, should be represented as a trailing
8497 parameter with the ``swift_context`` attribute.
8498
8499- The error result parameter, if present, should be represented as a
8500 trailing parameter (always following a context parameter) with the
8501 ``swift_error_result`` attribute.
8502
8503``swiftcall`` does not support variadic arguments or unprototyped functions.
8504
8505The parameter ABI treatment attributes are aspects of the function type.
8506A function type which applies an ABI treatment attribute to a
8507parameter is a different type from an otherwise-identical function type
8508that does not. A single parameter may not have multiple ABI treatment
8509attributes.
8510
8511Support for this feature is target-dependent, although it should be
8512supported on every target that Swift supports. Query for this attribute
8513with ``__has_attribute(swiftcall)``. Query if the target supports the
8514calling convention with ``__has_extension(swiftcc)``. This implies
8515support for the ``swift_context``, ``swift_error_result``, and
8516``swift_indirect_result`` attributes.)reST";
8517
8518static const char AttrDoc_SwiftContext[] = R"reST(The ``swift_context`` attribute marks a parameter of a ``swiftcall``
8519or ``swiftasynccall`` function as having the special context-parameter
8520ABI treatment.
8521
8522This treatment generally passes the context value in a special register
8523which is normally callee-preserved.
8524
8525A ``swift_context`` parameter must either be the last parameter or must be
8526followed by a ``swift_error_result`` parameter (which itself must always be
8527the last parameter).
8528
8529A context parameter must have pointer or reference type.)reST";
8530
8531static const char AttrDoc_SwiftError[] = R"reST(The ``swift_error`` attribute controls whether a particular function (or
8532Objective-C method) is imported into Swift as a throwing function, and if so,
8533which dynamic convention it uses.
8534
8535All of these conventions except ``none`` require the function to have an error
8536parameter. Currently, the error parameter is always the last parameter of type
8537``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
8538the imported API. When calling the API, Swift will always pass a valid address
8539initialized to a null pointer.
8540
8541* ``swift_error(none)`` means that the function should not be imported as
8542 throwing. The error parameter and result type will be imported normally.
8543
8544* ``swift_error(null_result)`` means that calls to the function should be
8545 considered to have thrown if they return a null value. The return type must be
8546 a pointer type, and it will be imported into Swift with a non-optional type.
8547 This is the default error convention for Objective-C methods that return
8548 pointers.
8549
8550* ``swift_error(zero_result)`` means that calls to the function should be
8551 considered to have thrown if they return a zero result. The return type must be
8552 an integral type. If the return type would have been imported as ``Bool``, it
8553 is instead imported as ``Void``. This is the default error convention for
8554 Objective-C methods that return a type that would be imported as ``Bool``.
8555
8556* ``swift_error(nonzero_result)`` means that calls to the function should be
8557 considered to have thrown if they return a non-zero result. The return type must
8558 be an integral type. If the return type would have been imported as ``Bool``,
8559 it is instead imported as ``Void``.
8560
8561* ``swift_error(nonnull_error)`` means that calls to the function should be
8562 considered to have thrown if they leave a non-null error in the error parameter.
8563 The return type is left unmodified.)reST";
8564
8565static const char AttrDoc_SwiftErrorResult[] = R"reST(The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
8566function as having the special error-result ABI treatment.
8567
8568This treatment generally passes the underlying error value in and out of
8569the function through a special register which is normally callee-preserved.
8570This is modeled in C by pretending that the register is addressable memory:
8571
8572- The caller appears to pass the address of a variable of pointer type.
8573 The current value of this variable is copied into the register before
8574 the call; if the call returns normally, the value is copied back into the
8575 variable.
8576
8577- The callee appears to receive the address of a variable. This address
8578 is actually a hidden location in its own stack, initialized with the
8579 value of the register upon entry. When the function returns normally,
8580 the value in that hidden location is written back to the register.
8581
8582A ``swift_error_result`` parameter must be the last parameter, and it must be
8583preceded by a ``swift_context`` parameter.
8584
8585A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
8586type T. Note that no qualifiers are permitted on the intermediate level.
8587
8588It is undefined behavior if the caller does not pass a pointer or
8589reference to a valid object.
8590
8591The standard convention is that the error value itself (that is, the
8592value stored in the apparent argument) will be null upon function entry,
8593but this is not enforced by the ABI.)reST";
8594
8595static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
8596
8597static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
8598
8599static const char AttrDoc_SwiftIndirectResult[] = R"reST(The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
8600or ``swiftasynccall`` function as having the special indirect-result ABI
8601treatment.
8602
8603This treatment gives the parameter the target's normal indirect-result
8604ABI treatment, which may involve passing it differently from an ordinary
8605parameter. However, only the first indirect result will receive this
8606treatment. Furthermore, low-level lowering may decide that a direct result
8607must be returned indirectly; if so, this will take priority over the
8608``swift_indirect_result`` parameters.
8609
8610A ``swift_indirect_result`` parameter must either be the first parameter or
8611follow another ``swift_indirect_result`` parameter.
8612
8613A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
8614some object type ``T``. If ``T`` is a complete type at the point of
8615definition of a function, it is undefined behavior if the argument
8616value does not point to storage of adequate size and alignment for a
8617value of type ``T``.
8618
8619Making indirect results explicit in the signature allows C functions to
8620directly construct objects into them without relying on language
8621optimizations like C++'s named return value optimization (NRVO).)reST";
8622
8623static const char AttrDoc_SwiftName[] = R"reST(The ``swift_name`` attribute provides the name of the declaration in Swift. If
8624this attribute is absent, the name is transformed according to the algorithm
8625built into the Swift compiler.
8626
8627The argument is a string literal that contains the Swift name of the function,
8628variable, or type. When renaming a function, the name may be a compound Swift
8629name. For a type, enum constant, property, or variable declaration, the name
8630must be a simple or qualified identifier.
8631
8632 .. code-block:: objc
8633
8634 @interface URL
8635 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
8636 @end
8637
8638 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
8639 })reST";
8640
8641static const char AttrDoc_SwiftNewType[] = R"reST(The ``swift_newtype`` attribute indicates that the typedef to which the
8642attribute appertains is imported as a new Swift type of the typedef's name.
8643Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
8644the attribute is identical with either spelling, ``swift_wrapper`` is
8645deprecated, only exists for compatibility purposes, and should not be used in
8646new code.
8647
8648* ``swift_newtype(struct)`` means that a Swift struct will be created for this
8649 typedef.
8650
8651* ``swift_newtype(enum)`` means that a Swift enum will be created for this
8652 typedef.
8653
8654 .. code-block:: c
8655
8656 // Import UIFontTextStyle as an enum type, with enumerated values being
8657 // constants.
8658 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
8659
8660 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
8661 // values being members of the type structure.
8662 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));)reST";
8663
8664static const char AttrDoc_SwiftNullability[] = R"reST()reST";
8665
8666static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
8667of this class will be implicitly marked with the ``@objcMembers`` Swift
8668attribute, exposing them back to Objective-C.)reST";
8669
8670static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the ``swift_private`` attribute are hidden from the
8671framework client but are still made available for use within the framework or
8672Swift SDK overlay.
8673
8674The purpose of this attribute is to permit a more idomatic implementation of
8675declarations in Swift while hiding the non-idiomatic one.)reST";
8676
8677static const char AttrDoc_SwiftType[] = R"reST()reST";
8678
8679static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
8680
8681static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
8682
8683static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
8684function to match the default convention used on Sys V targets such as Linux,
8685Mac, and BSD. This attribute has no effect on other targets.)reST";
8686
8687static const char AttrDoc_TLSModel[] = R"reST(The ``tls_model`` attribute allows you to specify which thread-local storage
8688model to use. It accepts the following strings:
8689
8690* global-dynamic
8691* local-dynamic
8692* initial-exec
8693* local-exec
8694
8695TLS models are mutually exclusive.)reST";
8696
8697static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
8698This attribute may be attached to a function definition and instructs
8699the backend to use different code generation options than were passed on the
8700command line.
8701
8702The current set of options correspond to the existing "subtarget features" for
8703the target with or without a "-mno-" in front corresponding to the absence
8704of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
8705for the function.
8706
8707For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
8708code for the given CPU without changing the available instructions.
8709
8710For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march
8711command line options. ``cpu="CPU"`` can be used to select a specific cpu,
8712as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the
8713"branch-protection=<args>" option, where the permissible arguments and their
8714effect on code generation are the same as for the command-line option
8715``-mbranch-protection``.
8716
8717Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8718"avx", "xop" and largely correspond to the machine specific options handled by
8719the front end.
8720
8721Note that this attribute does not apply transitively to nested functions such
8722as blocks or C++ lambdas.
8723
8724Additionally, this attribute supports function multiversioning for ELF based
8725x86/x86-64 targets, which can be used to create multiple implementations of the
8726same function that will be resolved at runtime based on the priority of their
8727``target`` attribute strings. A function is considered a multiversioned function
8728if either two declarations of the function have different ``target`` attribute
8729strings, or if it has a ``target`` attribute string of ``default``. For
8730example:
8731
8732 .. code-block:: c++
8733
8734 __attribute__((target("arch=atom")))
8735 void foo() {} // will be called on 'atom' processors.
8736 __attribute__((target("default")))
8737 void foo() {} // will be called on any other processors.
8738
8739All multiversioned functions must contain a ``default`` (fallback)
8740implementation, otherwise usages of the function are considered invalid.
8741Additionally, a function may not become multiversioned after its first use.)reST";
8742
8743static const char AttrDoc_TargetClones[] = R"reST(Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be
8744attached to a function declaration and causes function multiversioning, where
8745multiple versions of the function will be emitted with different code
8746generation options. Additionally, these versions will be resolved at runtime
8747based on the priority of their attribute options. All ``target_clone`` functions
8748are considered multiversioned functions.
8749
8750For AArch64 target:
8751The attribute contains comma-separated strings of target features joined by "+"
8752sign. For example:
8753
8754 .. code-block:: c++
8755
8756 __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
8757 void foo() {}
8758
8759For every multiversioned function a ``default`` (fallback) implementation
8760always generated if not specified directly.
8761
8762For x86/x86-64 targets:
8763All multiversioned functions must contain a ``default`` (fallback)
8764implementation, otherwise usages of the function are considered invalid.
8765Additionally, a function may not become multiversioned after its first use.
8766
8767The options to ``target_clones`` can either be a target-specific architecture
8768(specified as ``arch=CPU``), or one of a list of subtarget features.
8769
8770Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8771"avx", "xop" and largely correspond to the machine specific options handled by
8772the front end.
8773
8774The versions can either be listed as a comma-separated sequence of string
8775literals or as a single string literal containing a comma-separated list of
8776versions. For compatibility with GCC, the two formats can be mixed. For
8777example, the following will emit 4 versions of the function:
8778
8779 .. code-block:: c++
8780
8781 __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
8782 void foo() {}
8783
8784For targets that support the GNU indirect function (IFUNC) feature, dispatch
8785is performed by emitting an indirect function that is resolved to the appropriate
8786target clone at load time. The indirect function is given the name the
8787multiversioned function would have if it had been declared without the attribute.
8788For backward compatibility with earlier Clang releases, a function alias with an
8789``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8790feature and support for it may be removed in the future.
8791
8792For PowerPC targets, ``target_clones`` is supported on AIX only. Only CPU
8793(specified as ``cpu=CPU``) and ``default`` options are allowed. IFUNC is supported
8794on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
8795An FMV function that is only declared in a translation unit is treated as a
8796non-FMV. The resolver and the function clones are given internal linkage.)reST";
8797
8798static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
8799``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a
8800function it instructs compiler to emit multiple function versions based on
8801``target_version`` attribute strings, which resolved at runtime depend on their
8802priority and target features availability. One of the versions is always
8803( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can
8804contain dependent features names joined by the "+" sign.
8805
8806For targets that support the GNU indirect function (IFUNC) feature, dispatch
8807is performed by emitting an indirect function that is resolved to the appropriate
8808target clone at load time. The indirect function is given the name the
8809multiversioned function would have if it had been declared without the attribute.
8810For backward compatibility with earlier Clang releases, a function alias with an
8811``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8812feature and support for it may be removed in the future.)reST";
8813
8814static const char AttrDoc_TestTypestate[] = R"reST(Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
8815returns true if the object is in the specified state..)reST";
8816
8817static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8818function to use ECX for the first parameter (typically the implicit ``this``
8819parameter of C++ methods) and clear parameters off of the stack on return. This
8820convention does not support variadic calls or unprototyped functions in C, and
8821has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
8822MSDN.
8823
8824.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
8825
8826static const char AttrDoc_Thread[] = R"reST(The ``__declspec(thread)`` attribute declares a variable with thread local
8827storage. It is available under the ``-fms-extensions`` flag for MSVC
8828compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
8829
8830.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
8831
8832In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
8833GNU ``__thread`` keyword. The variable must not have a destructor and must have
8834a constant initializer, if any. The attribute only applies to variables
8835declared with static storage duration, such as globals, class static data
8836members, and static locals.)reST";
8837
8838static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
8839functions that have an argument with a transparent union type. The compiler
8840behavior is changed in the following manner:
8841
8842- A value whose type is any member of the transparent union can be passed as an
8843 argument without the need to cast that value.
8844
8845- The argument is passed to the function using the calling convention of the
8846 first member of the transparent union. Consequently, all the members of the
8847 transparent union should have the same calling convention as its first member.
8848
8849Transparent unions are not supported in C++.)reST";
8850
8851static const char AttrDoc_TrivialABI[] = R"reST(The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
8852It instructs the compiler to pass and return the type using the C ABI for the
8853underlying type when the type would otherwise be considered non-trivial for the
8854purpose of calls.
8855A class annotated with ``trivial_abi`` can have non-trivial destructors or
8856copy/move constructors without automatically becoming non-trivial for the
8857purposes of calls. For example:
8858
8859 .. code-block:: c++
8860
8861 // A is trivial for the purposes of calls because ``trivial_abi`` makes the
8862 // user-provided special functions trivial.
8863 struct __attribute__((trivial_abi)) A {
8864 ~A();
8865 A(const A &);
8866 A(A &&);
8867 int x;
8868 };
8869
8870 // B's destructor and copy/move constructor are considered trivial for the
8871 // purpose of calls because A is trivial.
8872 struct B {
8873 A a;
8874 };
8875
8876If a type is trivial for the purposes of calls, has a non-trivial destructor,
8877and is passed as an argument by value, the convention is that the callee will
8878destroy the object before returning. The lifetime of the copy of the parameter
8879in the caller ends without a destructor call when the call begins.
8880
8881If a type is trivial for the purpose of calls, it is assumed to be trivially
8882relocatable for the purpose of ``__is_trivially_relocatable`` and
8883``__builtin_is_cpp_trivially_relocatable``.
8884When a type marked with ``[[trivial_abi]]`` is used as a function argument,
8885the compiler may omit the call to the copy constructor.
8886Thus, side effects of the copy constructor are potentially not performed.
8887For example, objects that contain pointers to themselves or otherwise depend
8888on their address (or the address or their subobjects) should not be declared
8889``[[trivial_abi]]``.
8890
8891Attribute ``trivial_abi`` has no effect in the following cases:
8892
8893- The class directly declares a virtual base or virtual methods.
8894- Copy constructors and move constructors of the class are all deleted.
8895- The class has a base class that is non-trivial for the purposes of calls.
8896- The class has a non-static data member whose type is non-trivial for the
8897 purposes of calls, which includes:
8898
8899 - classes that are non-trivial for the purposes of calls
8900 - __weak-qualified types in Objective-C++
8901 - arrays of any of the above)reST";
8902
8903static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
8904actually acquire the capability; they accept a Boolean value determining
8905whether acquiring the capability means success (true), or failing to acquire
8906the capability means success (false).)reST";
8907
8908static const char AttrDoc_TypeNonNull[] = R"reST(The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
8909value for a value of the ``_Nonnull`` pointer type. For example, given a
8910declaration such as:
8911
8912 .. code-block:: c
8913
8914 int fetch(int * _Nonnull ptr);
8915
8916a caller of ``fetch`` should not provide a null value, and the compiler will
8917produce a warning if it sees a literal null value passed to ``fetch``. Note
8918that, unlike the declaration attribute ``nonnull``, the presence of
8919``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
8920is free to consider null undefined behavior or (perhaps for
8921backward-compatibility reasons) defensively handle null.)reST";
8922
8923static const char AttrDoc_TypeNullUnspecified[] = R"reST(The ``_Null_unspecified`` nullability qualifier indicates that neither the
8924``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
8925type. It is used primarily to indicate that the role of null with specific
8926pointers in a nullability-annotated header is unclear, e.g., due to
8927overly-complex implementations or historical factors with a long-lived API.)reST";
8928
8929static const char AttrDoc_TypeNullable[] = R"reST(The ``_Nullable`` nullability qualifier indicates that a value of the
8930``_Nullable`` pointer type can be null. For example, given:
8931
8932 .. code-block:: c
8933
8934 int fetch_or_zero(int * _Nullable ptr);
8935
8936a caller of ``fetch_or_zero`` can provide null.
8937
8938The ``_Nullable`` attribute on classes indicates that the given class can
8939represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
8940make sense for this type. For example:
8941
8942 .. code-block:: c
8943
8944 class _Nullable ArenaPointer { ... };
8945
8946 ArenaPointer _Nonnull x = ...;
8947 ArenaPointer _Nullable y = nullptr;)reST";
8948
8949static const char AttrDoc_TypeNullableResult[] = R"reST(The ``_Nullable_result`` nullability qualifier means that a value of the
8950``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
8951attribute differs from ``_Nullable`` is when it's used on a parameter to a
8952completion handler in a Swift async method. For instance, here:
8953
8954 .. code-block:: objc
8955
8956 -(void)fetchSomeDataWithID:(int)identifier
8957 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
8958
8959This method asynchronously calls ``completionHandler`` when the data is
8960available, or calls it with an error. ``_Nullable_result`` indicates to the
8961Swift importer that this is the uncommon case where ``result`` can get ``nil``
8962even if no error has occurred, and will therefore import it as a Swift optional
8963type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
8964importer will assume that ``result`` will always be non-nil unless an error
8965occurred.)reST";
8966
8967static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
8968``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
8969is tied to the ``type`` argument given to the attribute.
8970
8971In the attribute prototype above:
8972 * ``kind`` is an identifier that should be used when annotating all applicable
8973 type tags.
8974 * ``type`` indicates the name of the type.
8975
8976Clang supports annotating type tags of two forms.
8977
8978 * **Type tag that is a reference to a declared identifier.**
8979 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
8980 identifier:
8981
8982 .. code-block:: c++
8983
8984 typedef int MPI_Datatype;
8985 extern struct mpi_datatype mpi_datatype_int
8986 __attribute__(( type_tag_for_datatype(mpi,int) ));
8987 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
8988 // &mpi_datatype_int is a type tag. It is tied to type "int".
8989
8990 * **Type tag that is an integral literal.**
8991 Declare a ``static const`` variable with an initializer value and attach
8992 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
8993
8994 .. code-block:: c++
8995
8996 typedef int MPI_Datatype;
8997 static const MPI_Datatype mpi_datatype_int
8998 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
8999 #define MPI_INT ((MPI_Datatype) 42)
9000 // The number 42 is a type tag. It is tied to type "int".
9001
9002
9003The ``type_tag_for_datatype`` attribute also accepts an optional third argument
9004that determines how the type of the function argument specified by either
9005``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
9006tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
9007function argument specified by ``arg_idx`` is compared against the type
9008associated with the type tag. Also recall that for the ``pointer_with_type_tag``
9009attribute, the pointee type of the function argument specified by ``ptr_idx`` is
9010compared against the type associated with the type tag.) There are two supported
9011values for this optional third argument:
9012
9013 * ``layout_compatible`` will cause types to be compared according to
9014 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
9015 layout-compatibility rules for two standard-layout struct types and for two
9016 standard-layout union types). This is useful when creating a type tag
9017 associated with a struct or union type. For example:
9018
9019 .. code-block:: c++
9020
9021 /* In mpi.h */
9022 typedef int MPI_Datatype;
9023 struct internal_mpi_double_int { double d; int i; };
9024 extern struct mpi_datatype mpi_datatype_double_int
9025 __attribute__(( type_tag_for_datatype(mpi,
9026 struct internal_mpi_double_int, layout_compatible) ));
9027
9028 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
9029
9030 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9031 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9032
9033 /* In user code */
9034 struct my_pair { double a; int b; };
9035 struct my_pair *buffer;
9036 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
9037 // layout of my_pair is
9038 // compatible with that of
9039 // internal_mpi_double_int
9040
9041 struct my_int_pair { int a; int b; }
9042 struct my_int_pair *buffer2;
9043 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
9044 // layout of my_int_pair
9045 // does not match that of
9046 // internal_mpi_double_int
9047
9048 * ``must_be_null`` specifies that the function argument specified by either
9049 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
9050 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
9051 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
9052 example:
9053
9054 .. code-block:: c++
9055
9056 /* In mpi.h */
9057 typedef int MPI_Datatype;
9058 extern struct mpi_datatype mpi_datatype_null
9059 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
9060
9061 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
9062 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9063 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9064
9065 /* In user code */
9066 struct my_pair { double a; int b; };
9067 struct my_pair *buffer;
9068 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
9069 // was specified but buffer
9070 // is not a null pointer)reST";
9071
9072static const char AttrDoc_TypeVisibility[] = R"reST(The ``type_visibility`` attribute allows the visibility of a type and its vague
9073linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
9074the visibility of functions and data members of the type.
9075
9076For example, this can be used to give default visibility to the typeinfo and the vtable
9077of a type while still keeping hidden visibility on its member functions and static data
9078members.
9079
9080This attribute can only be applied to types and namespaces.
9081
9082If both ``visibility`` and ``type_visibility`` are applied to a type or a namespace, the
9083visibility specified with the ``type_visibility`` attribute overrides the visibility
9084provided with the regular ``visibility`` attribute.)reST";
9085
9086static const char AttrDoc_UPtr[] = R"reST(The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
9087extended when converted to a 64-bit pointer.)reST";
9088
9089static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
9090
9091static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
9092initialize trivial automatic stack variables. By default, trivial automatic
9093stack variables are uninitialized. This attribute is used to override the
9094command-line parameter, forcing variables to remain uninitialized. It has no
9095semantic meaning in that using uninitialized values is undefined behavior,
9096it rather documents the programmer's intent.)reST";
9097
9098static const char AttrDoc_Unlikely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
9099The attributes are used to aid the compiler to determine which branch is
9100likely or unlikely to be taken. This is done by marking the branch substatement
9101with one of the two attributes.
9102
9103It isn't allowed to annotate a single statement with both ``likely`` and
9104``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
9105statement with the same likelihood attribute will result in a diagnostic and
9106the attributes are ignored on both branches.
9107
9108In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
9109or the ``default`` label with the same likelihood attribute. This makes
9110* all labels without an attribute have a neutral likelihood,
9111* all labels marked ``[[likely]]`` have an equally positive likelihood, and
9112* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
9113The neutral likelihood is the more likely of path execution than the negative
9114likelihood. The positive likelihood is the more likely of path of execution
9115than the neutral likelihood.
9116
9117These attributes have no effect on the generated code when using
9118PGO (Profile-Guided Optimization) or at optimization level 0.
9119
9120In Clang, the attributes will be ignored if they're not placed on
9121* the ``case`` or ``default`` label of a ``switch`` statement,
9122* or on the substatement of an ``if`` or ``else`` statement,
9123* or on the substatement of an ``for`` or ``while`` statement.
9124The C++ Standard recommends to honor them on every statement in the
9125path of execution, but that can be confusing:
9126
9127.. code-block:: c++
9128
9129 if (b) {
9130 [[unlikely]] --b; // Per the standard this is in the path of
9131 // execution, so this branch should be considered
9132 // unlikely. However, Clang ignores the attribute
9133 // here since it is not on the substatement.
9134 }
9135
9136 if (b) {
9137 --b;
9138 if(b)
9139 return;
9140 [[unlikely]] --b; // Not in the path of execution,
9141 } // the branch has no likelihood information.
9142
9143 if (b) {
9144 --b;
9145 foo(b);
9146 // Whether or not the next statement is in the path of execution depends
9147 // on the declaration of foo():
9148 // In the path of execution: void foo(int);
9149 // Not in the path of execution: [[noreturn]] void foo(int);
9150 // This means the likelihood of the branch depends on the declaration
9151 // of foo().
9152 [[unlikely]] --b;
9153 }
9154
9155
9156Below are some example usages of the likelihood attributes and their effects:
9157
9158.. code-block:: c++
9159
9160 if (b) [[likely]] { // Placement on the first statement in the branch.
9161 // The compiler will optimize to execute the code here.
9162 } else {
9163 }
9164
9165 if (b)
9166 [[unlikely]] b++; // Placement on the first statement in the branch.
9167 else {
9168 // The compiler will optimize to execute the code here.
9169 }
9170
9171 if (b) {
9172 [[unlikely]] b++; // Placement on the second statement in the branch.
9173 } // The attribute will be ignored.
9174
9175 if (b) [[likely]] {
9176 [[unlikely]] b++; // No contradiction since the second attribute
9177 } // is ignored.
9178
9179 if (b)
9180 ;
9181 else [[likely]] {
9182 // The compiler will optimize to execute the code here.
9183 }
9184
9185 if (b)
9186 ;
9187 else
9188 // The compiler will optimize to execute the next statement.
9189 [[likely]] b = f();
9190
9191 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
9192 else [[likely]]; // and the attributes are ignored.
9193
9194 if (b)
9195 [[likely]] int i = 5; // Issues a diagnostic since the attribute
9196 // isn't allowed on a declaration.
9197
9198 switch (i) {
9199 [[likely]] case 1: // This value is likely
9200 ...
9201 break;
9202
9203 [[unlikely]] case 2: // This value is unlikely
9204 ...
9205 [[fallthrough]];
9206
9207 case 3: // No likelihood attribute
9208 ...
9209 [[likely]] break; // No effect
9210
9211 case 4: [[likely]] { // attribute on substatement has no effect
9212 ...
9213 break;
9214 }
9215
9216 [[unlikely]] default: // All other values are unlikely
9217 ...
9218 break;
9219 }
9220
9221 switch (i) {
9222 [[likely]] case 0: // This value and code path is likely
9223 ...
9224 [[fallthrough]];
9225
9226 case 1: // No likelihood attribute, code path is neutral
9227 break; // falling through has no effect on the likelihood
9228
9229 case 2: // No likelihood attribute, code path is neutral
9230 [[fallthrough]];
9231
9232 [[unlikely]] default: // This value and code path are both unlikely
9233 break;
9234 }
9235
9236 for(int i = 0; i != size; ++i) [[likely]] {
9237 ... // The loop is the likely path of execution
9238 }
9239
9240 for(const auto &E : Elements) [[likely]] {
9241 ... // The loop is the likely path of execution
9242 }
9243
9244 while(i != size) [[unlikely]] {
9245 ... // The loop is the unlikely path of execution
9246 } // The generated code will optimize to skip the loop body
9247
9248 while(true) [[unlikely]] {
9249 ... // The attribute has no effect
9250 } // Clang elides the comparison and generates an infinite
9251 // loop)reST";
9252
9253static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
9254that need to be avoided as they are prone to buffer overflows or unsafe buffer
9255struct fields. It is designed to work together with the off-by-default compiler
9256warning ``-Wunsafe-buffer-usage`` to help codebases transition away from raw pointer
9257based buffer management, in favor of safer abstractions such as C++20 ``std::span``.
9258The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the function or
9259the field it is attached to, and it may also lead to emission of automatic fix-it
9260hints which would help the user replace the use of unsafe functions(/fields) with safe
9261alternatives, though the attribute can be used even when the fix can't be automated.
9262
9263* Attribute attached to functions: The attribute suppresses all
9264 ``-Wunsafe-buffer-usage`` warnings within the function it is attached to, as the
9265 function is now classified as unsafe. The attribute should be used carefully, as it
9266 will silence all unsafe operation warnings inside the function; including any new
9267 unsafe operations introduced in the future.
9268
9269 The attribute is warranted even if the only way a function can overflow
9270 the buffer is by violating the function's preconditions. For example, it
9271 would make sense to put the attribute on function ``foo()`` below because
9272 passing an incorrect size parameter would cause a buffer overflow:
9273
9274 .. code-block:: c++
9275
9276 [[clang::unsafe_buffer_usage]]
9277 void foo(int *buf, size_t size) {
9278 for (size_t i = 0; i < size; ++i) {
9279 buf[i] = i;
9280 }
9281 }
9282
9283 The attribute is NOT warranted when the function uses safe abstractions,
9284 assuming that these abstractions weren't misused outside the function.
9285 For example, function ``bar()`` below doesn't need the attribute,
9286 because assuming that the container ``buf`` is well-formed (has size that
9287 fits the original buffer it refers to), overflow cannot occur:
9288
9289 .. code-block:: c++
9290
9291 void bar(std::span<int> buf) {
9292 for (size_t i = 0; i < buf.size(); ++i) {
9293 buf[i] = i;
9294 }
9295 }
9296
9297 In this case function ``bar()`` enables the user to keep the buffer
9298 "containerized" in a span for as long as possible. On the other hand,
9299 Function ``foo()`` in the previous example may have internal
9300 consistency, but by accepting a raw buffer it requires the user to unwrap
9301 their span, which is undesirable according to the programming model
9302 behind ``-Wunsafe-buffer-usage``.
9303
9304 The attribute is warranted when a function accepts a raw buffer only to
9305 immediately put it into a span:
9306
9307 .. code-block:: c++
9308
9309 [[clang::unsafe_buffer_usage]]
9310 void baz(int *buf, size_t size) {
9311 std::span<int> sp{ buf, size };
9312 for (size_t i = 0; i < sp.size(); ++i) {
9313 sp[i] = i;
9314 }
9315 }
9316
9317 In this case ``baz()`` does not contain any unsafe operations, but the awkward
9318 parameter type causes the caller to unwrap the span unnecessarily.
9319 Note that regardless of the attribute, code inside ``baz()`` isn't flagged
9320 by ``-Wunsafe-buffer-usage`` as unsafe. It is definitely undesirable,
9321 but if ``baz()`` is on an API surface, there is no way to improve it
9322 to make it as safe as ``bar()`` without breaking the source and binary
9323 compatibility with existing users of the function. In such cases
9324 the proper solution would be to create a different function (possibly
9325 an overload of ``baz()``) that accepts a safe container like ``bar()``,
9326 and then use the attribute on the original ``baz()`` to help the users
9327 update their code to use the new function.
9328
9329* Attribute attached to fields: The attribute should only be attached to
9330 struct fields, if the fields can not be updated to a safe type with bounds
9331 check, such as std::span. In other words, the buffers prone to unsafe accesses
9332 should always be updated to use safe containers/views and attaching the attribute
9333 must be last resort when such an update is infeasible.
9334
9335 The attribute can be placed on individual fields or a set of them as shown below.
9336
9337 .. code-block:: c++
9338
9339 struct A {
9340 [[clang::unsafe_buffer_usage]]
9341 int *ptr1;
9342
9343 [[clang::unsafe_buffer_usage]]
9344 int *ptr2, buf[10];
9345
9346 [[clang::unsafe_buffer_usage]]
9347 size_t sz;
9348 };
9349
9350 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
9351 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
9352
9353static const char AttrDoc_Unused[] = R"reST(When passing the ``-Wunused`` flag to Clang, entities that are unused by the
9354program may be diagnosed. The ``[[maybe_unused]]`` (or
9355``__attribute__((unused))``) attribute can be used to silence such diagnostics
9356when the entity cannot be removed. For instance, a local variable may exist
9357solely for use in an ``assert()`` statement, which makes the local variable
9358unused when ``NDEBUG`` is defined.
9359
9360The attribute may be applied to the declaration of a class, a typedef, a
9361variable, a function or method, a function parameter, an enumeration, an
9362enumerator, a non-static data member, or a label.
9363
9364.. code-block:: c++
9365
9366 #include <cassert>
9367
9368 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
9369 [[maybe_unused]] bool thing2) {
9370 [[maybe_unused]] bool b = thing1 && thing2;
9371 assert(b);
9372 })reST";
9373
9374static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9375parameter is annotated with ``use_handle(tag)`` it is assumed to not to change
9376the state of the handle. It is also assumed to require an open handle to work with.
9377The attribute requires a string literal argument to identify the handle being used.
9378
9379.. code-block:: c++
9380
9381 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
9382 zx_time_t deadline,
9383 zx_port_packet_t* packet);)reST";
9384
9385static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
9386that there may be references to the entity which are not apparent in the source
9387code. For example, it may be referenced from inline ``asm``, or it may be
9388found through a dynamic symbol or section lookup.
9389
9390The compiler must emit the definition even if it appears to be unused, and it
9391must not apply optimizations which depend on fully understanding how the entity
9392is used.
9393
9394Whether this attribute has any effect on the linker depends on the target and
9395the linker. Most linkers support the feature of section garbage collection
9396(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
9397discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
9398targets (Windows and Apple platforms), the `used` attribute prevents symbols
9399from being removed by linker section GC. On ELF targets, it has no effect on its
9400own, and the linker may remove the definition if it is not otherwise referenced.
9401This linker GC can be avoided by also adding the ``retain`` attribute. Note
9402that ``retain`` requires special support from the linker; see that attribute's
9403documentation for further information.)reST";
9404
9405static const char AttrDoc_UsingIfExists[] = R"reST(The ``using_if_exists`` attribute applies to a using-declaration. It allows
9406programmers to import a declaration that potentially does not exist, instead
9407deferring any errors to the point of use. For instance:
9408
9409.. code-block:: c++
9410
9411 namespace empty_namespace {};
9412 __attribute__((using_if_exists))
9413 using empty_namespace::does_not_exist; // no error!
9414
9415 does_not_exist x; // error: use of unresolved 'using_if_exists'
9416
9417The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
9418supported as a clang extension, since ISO C++ doesn't support attributes in this
9419position. If the entity referred to by the using-declaration is found by name
9420lookup, the attribute has no effect. This attribute is useful for libraries
9421(primarily, libc++) that wish to redeclare a set of declarations in another
9422namespace, when the availability of those declarations is difficult or
9423impossible to detect at compile time with the preprocessor.)reST";
9424
9425static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
9426
9427static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
9428
9429static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
9430
9431static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
9432
9433static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
9434convention of a function to pass vector parameters in SSE registers.
9435
9436On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
9437The first two integer parameters are passed in ECX and EDX. Subsequent integer
9438parameters are passed in memory, and callee clears the stack. On x86_64
9439targets, the callee does *not* clear the stack, and integer parameters are
9440passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
9441convention.
9442
9443On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
9444passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
9445passed in sequential SSE registers if enough are available. If AVX is enabled,
9446256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
9447cannot be passed in registers for any reason is passed by reference, which
9448allows the caller to align the parameter memory.
9449
9450See the documentation for `__vectorcall`_ on MSDN for more details.
9451
9452.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
9453
9454static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
9455
9456static const char AttrDoc_WarnUnused[] = R"reST(The ``warn_unused`` attribute can be placed on the declaration of a structure or union type.
9457When the ``-Wunused-variable`` diagnostic is enabled, local variables of types which have a non-trivial constructor or destructor are considered "used" by virtue of the constructor or destructor invocations involved.
9458Those constructor or destructor invocations are not considered a use if the type is declared with the ``warn_unused`` attribute.
9459The variable is considered used if it is named outside of its declaration.
9460
9461This attribute is available in both C and C++ language modes but is primarily useful in C++ for classes which have a non-trivial constructor or destructor but act as a value type rather than an RAII type.
9462
9463.. code-block:: c++
9464
9465 struct [[gnu::warn_unused]] S {
9466 S();
9467 ~S();
9468 };
9469
9470 struct T {
9471 T();
9472 ~T();
9473 };
9474
9475 int func() {
9476 S s1; // -Wunused-variable warning
9477 S s2; // No -Wunused-variable warning because of the member access expression below
9478 S s3; // No -Wunused-variable warning because of the sizeof operand below
9479 T t; // No -Wunused-variable warning
9480
9481 s2.~S();
9482 return sizeof(s3);
9483 })reST";
9484
9485static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
9486expression are discarded under suspicious circumstances. A diagnostic is
9487generated when a function or its return type is marked with ``[[nodiscard]]``
9488(or ``__attribute__((warn_unused_result))``) and the function call appears as a
9489potentially-evaluated discarded-value expression that is not explicitly cast to
9490``void``.
9491
9492A string literal may optionally be provided to the attribute, which will be
9493reproduced in any resulting diagnostics. Redeclarations using different forms
9494of the attribute (with or without the string literal or with different string
9495literal contents) are allowed. If there are redeclarations of the entity with
9496differing string literals, it is unspecified which one will be used by Clang
9497in any resulting diagnostics.
9498
9499.. code-block:: c++
9500
9501 struct [[nodiscard]] error_info { /*...*/ };
9502 error_info enable_missile_safety_mode();
9503
9504 void launch_missiles();
9505 void test_missiles() {
9506 enable_missile_safety_mode(); // diagnoses
9507 launch_missiles();
9508 }
9509 error_info &foo();
9510 void f() { foo(); } // Does not diagnose, error_info is a reference.
9511
9512Additionally, discarded temporaries resulting from a call to a constructor
9513marked with ``[[nodiscard]]`` or a constructor of a type marked
9514``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
9515use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
9516
9517.. code-block:: c++
9518
9519 struct [[nodiscard]] marked_type {/*..*/ };
9520 struct marked_ctor {
9521 [[nodiscard]] marked_ctor();
9522 marked_ctor(int);
9523 };
9524
9525 struct S {
9526 operator marked_type() const;
9527 [[nodiscard]] operator int() const;
9528 };
9529
9530 void usages() {
9531 marked_type(); // diagnoses.
9532 marked_ctor(); // diagnoses.
9533 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
9534
9535 S s;
9536 static_cast<marked_type>(s); // diagnoses
9537 (int)s; // diagnoses
9538 })reST";
9539
9540static const char AttrDoc_Weak[] = R"reST(In supported output formats the ``weak`` attribute can be used to
9541specify that a variable or function should be emitted as a symbol with
9542``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
9543external symbol) `linkage
9544<https://llvm.org/docs/LangRef.html#linkage-types>`_.
9545
9546If there is a non-weak definition of the symbol the linker will select
9547that over the weak. They must have same type and alignment (variables
9548must also have the same size), but may have a different value.
9549
9550If there are multiple weak definitions of same symbol, but no non-weak
9551definition, they should have same type, size, alignment and value, the
9552linker will select one of them (see also selectany_ attribute).
9553
9554If the ``weak`` attribute is applied to a ``const`` qualified variable
9555definition that variable is no longer consider a compiletime constant
9556as its value can change during linking (or dynamic linking). This
9557means that it can e.g no longer be part of an initializer expression.
9558
9559.. code-block:: c
9560
9561 const int ANSWER __attribute__ ((weak)) = 42;
9562
9563 /* This function may be replaced link-time */
9564 __attribute__ ((weak)) void debug_log(const char *msg)
9565 {
9566 fprintf(stderr, "DEBUG: %s\n", msg);
9567 }
9568
9569 int main(int argc, const char **argv)
9570 {
9571 debug_log ("Starting up...");
9572
9573 /* This may print something else than "6 * 7 = 42",
9574 if there is a non-weak definition of "ANSWER" in
9575 an object linked in */
9576 printf("6 * 7 = %d\n", ANSWER);
9577
9578 return 0;
9579 }
9580
9581If an external declaration is marked weak and that symbol does not
9582exist during linking (possibly dynamic) the address of the symbol will
9583evaluate to NULL.
9584
9585.. code-block:: c
9586
9587 void may_not_exist(void) __attribute__ ((weak));
9588
9589 int main(int argc, const char **argv)
9590 {
9591 if (may_not_exist) {
9592 may_not_exist();
9593 } else {
9594 printf("Function did not exist\n");
9595 }
9596 return 0;
9597 })reST";
9598
9599static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
9600
9601static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
9602
9603static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9604attribute for the WebAssembly target. This attribute may be attached to a
9605function declaration, where it modifies how the symbol is to be exported
9606from the linked WebAssembly.
9607
9608WebAssembly functions are exported via string name. By default when a symbol
9609is exported, the export name for C/C++ symbols are the same as their C/C++
9610symbol names. This attribute can be used to override the default behavior, and
9611request a specific string name be used instead.)reST";
9612
9613static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9614attribute for the WebAssembly target. This attribute may be attached to a
9615function declaration, where it modifies how the symbol is to be exported
9616from the linked WebAssembly.
9617
9618WebAssembly functions are exported via string name. By default when a symbol
9619is exported, the export name for C/C++ symbols are the same as their C/C++
9620symbol names. This attribute can be used to override the default behavior, and
9621request a specific string name be used instead.)reST";
9622
9623static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the ``__attribute__((import_module(<module_name>)))``
9624attribute for the WebAssembly target. This attribute may be attached to a
9625function declaration, where it modifies how the symbol is to be imported
9626within the WebAssembly linking environment.
9627
9628WebAssembly imports use a two-level namespace scheme, consisting of a module
9629name, which typically identifies a module from which to import, and a field
9630name, which typically identifies a field from that module to import. By
9631default, module names for C/C++ symbols are assigned automatically by the
9632linker. This attribute can be used to override the default behavior, and
9633request a specific module name be used instead.)reST";
9634
9635static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the ``__attribute__((import_name(<name>)))``
9636attribute for the WebAssembly target. This attribute may be attached to a
9637function declaration, where it modifies how the symbol is to be imported
9638within the WebAssembly linking environment.
9639
9640WebAssembly imports use a two-level namespace scheme, consisting of a module
9641name, which typically identifies a module from which to import, and a field
9642name, which typically identifies a field from that module to import. By
9643default, field names for C/C++ symbols are the same as their C/C++ symbol
9644names. This attribute can be used to override the default behavior, and
9645request a specific field name be used instead.)reST";
9646
9647static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
9648
9649static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
9650
9651Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
9652(like 'movaps') that work with the stack require operands to be 16-byte aligned.
9653This attribute realigns the stack in the function prologue to make sure the
9654stack can be used with SSE instructions.
9655
9656Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
9657Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
9658rare cases where the caller does not align the stack properly (e.g. flow
9659jumps from i386 arch code).
9660
9661 .. code-block:: c
9662
9663 __attribute__ ((force_align_arg_pointer))
9664 void f () {
9665 ...
9666 })reST";
9667
9668static const char AttrDoc_XRayInstrument[] = R"reST(``__attribute__((xray_always_instrument))`` or
9669``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9670methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9671instrumented with XRay. This will cause the function to always have space at
9672the beginning and exit points to allow for runtime patching.
9673
9674Conversely, ``__attribute__((xray_never_instrument))`` or
9675``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9676instrumentation points.
9677
9678If a function has neither of these attributes, they become subject to the XRay
9679heuristics used to determine whether a function should be instrumented or
9680otherwise.
9681
9682``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9683used to preserve N function arguments for the logging function. Currently,
9684only N==1 is supported.)reST";
9685
9686static const char AttrDoc_XRayLogArgs[] = R"reST(``__attribute__((xray_always_instrument))`` or
9687``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9688methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9689instrumented with XRay. This will cause the function to always have space at
9690the beginning and exit points to allow for runtime patching.
9691
9692Conversely, ``__attribute__((xray_never_instrument))`` or
9693``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9694instrumentation points.
9695
9696If a function has neither of these attributes, they become subject to the XRay
9697heuristics used to determine whether a function should be instrumented or
9698otherwise.
9699
9700``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9701used to preserve N function arguments for the logging function. Currently,
9702only N==1 is supported.)reST";
9703
9704static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
9705subset of all call-used registers before the function returns. It's used to
9706increase program security by either mitigating `Return-Oriented Programming`_
9707(ROP) attacks or preventing information leakage through registers.
9708
9709The term "call-used" means registers which are not guaranteed to be preserved
9710unchanged for the caller by the current calling convention. This could also be
9711described as "caller-saved" or "not callee-saved".
9712
9713The `choice` parameters gives the programmer flexibility to choose the subset
9714of the call-used registers to be zeroed:
9715
9716- ``skip`` doesn't zero any call-used registers. This choice overrides any
9717 command-line arguments.
9718- ``used`` only zeros call-used registers used in the function. By ``used``, we
9719 mean a register whose contents have been set or referenced in the function.
9720- ``used-gpr`` only zeros call-used GPR registers used in the function.
9721- ``used-arg`` only zeros call-used registers used to pass arguments to the
9722 function.
9723- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to
9724 the function.
9725- ``all`` zeros all call-used registers.
9726- ``all-gpr`` zeros all call-used GPR registers.
9727- ``all-arg`` zeros all call-used registers used to pass arguments to the
9728 function.
9729- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to
9730 the function.
9731
9732The default for the attribute is controlled by the ``-fzero-call-used-regs``
9733flag.
9734
9735.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
9736