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][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_AMDGPUAvailableVisible[] = R"reST(This attribute controls availability and visibility as described in the [AMDGPU
53Memory Model](https://llvm.org/docs/AMDGPUMemoryModel.html). When placed on
54an atomic expression or fence, the resulting atomic or fence instruction carries
55the corresponding *AV Metadata*.
56
57The attribute takes a string literal as an argument, which currently has only
58one supported value:
59
60- `"none"`: Disable MakeAvailable and MakeVisible semantics on release and
61 acquire operations respectively.
62
63```c++
64[[clang::amdgpu_av("none")]] __atomic_thread_fence(__ATOMIC_SEQ_CST);
65[[clang::amdgpu_av("none")]] __atomic_fetch_add(ptr, 1, __ATOMIC_ACQ_REL);
66
67// Also works with _Atomic type qualifier operations.
68_Atomic int *p;
69[[clang::amdgpu_av("none")]] *p += 1;
70```)reST";
71
72static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size
73specified when the kernel is dispatched. It is the product of the sizes of the
74x, y, and z dimension of the work-group.
75
76Clang supports the
77`__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))` attribute for the
78AMDGPU target. This attribute may be attached to a kernel function definition
79and is an optimization hint.
80
81`<min>` parameter specifies the minimum flat work-group size, and `<max>`
82parameter specifies the maximum flat work-group size (must be greater than
83`<min>`) to which all dispatches of the kernel will conform. Passing `0, 0`
84as `<min>, <max>` implies the default behavior (`128, 256`).
85
86If specified, the AMDGPU target backend might be able to produce better machine
87code for barriers and perform scratch promotion by estimating available group
88segment size.
89
90An error will be given if:
91: - Specified values violate subtarget specifications;
92 - Specified values are not compatible with values provided through other
93 attributes.)reST";
94
95static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel
96is dispatched.
97
98Clang supports the
99`__attribute__((amdgpu_max_num_work_groups(<x>, <y>, <z>)))` or
100`[[clang::amdgpu_max_num_work_groups(<x>, <y>, <z>)]]` attribute for the
101AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
102definitions and is an optimization hint.
103
104The `<x>` parameter specifies the maximum number of work groups in the x dimension.
105Similarly `<y>` and `<z>` are for the y and z dimensions respectively.
106Each of the three values must be greater than 0 when provided. The `<x>` parameter
107is required, while `<y>` and `<z>` are optional with default value of 1.
108
109If specified, the AMDGPU target backend might be able to produce better machine
110code.
111
112An error will be given if:
113: - Specified values violate subtarget specifications;
114 - Specified values are not compatible with values provided through other
115 attributes.)reST";
116
117static const char AttrDoc_AMDGPUNamedBarrierWrapper[] = R"reST()reST";
118
119static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(:::{warning}
120These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to
121control SGPR and VGPR usage instead.
122:::
123
124Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and
125`__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU
126target. These attributes may be attached to a kernel function definition and are
127an optimization hint.
128
129If these attributes are specified, then the AMDGPU target backend will attempt
130to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
131number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
132allocation requirements or constraints of the subtarget. Passing `0` as
133`num_sgpr` and/or `num_vgpr` implies the default behavior (no limits).
134
135These attributes can be used to test the AMDGPU target backend. It is
136recommended that the `amdgpu_waves_per_eu` attribute be used to control
137resources such as SGPRs and VGPRs since it is aware of the limits for different
138subtargets.
139
140An error will be given if:
141: - Specified values violate subtarget specifications;
142 - Specified values are not compatible with values provided through other
143 attributes;
144 - The AMDGPU target backend is unable to create machine code that can meet the
145 request.)reST";
146
147static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(:::{warning}
148These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to
149control SGPR and VGPR usage instead.
150:::
151
152Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and
153`__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU
154target. These attributes may be attached to a kernel function definition and are
155an optimization hint.
156
157If these attributes are specified, then the AMDGPU target backend will attempt
158to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
159number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
160allocation requirements or constraints of the subtarget. Passing `0` as
161`num_sgpr` and/or `num_vgpr` implies the default behavior (no limits).
162
163These attributes can be used to test the AMDGPU target backend. It is
164recommended that the `amdgpu_waves_per_eu` attribute be used to control
165resources such as SGPRs and VGPRs since it is aware of the limits for different
166subtargets.
167
168An error will be given if:
169: - Specified values violate subtarget specifications;
170 - Specified values are not compatible with values provided through other
171 attributes;
172 - The AMDGPU target backend is unable to create machine code that can meet the
173 request.)reST";
174
175static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
176It is composed of one or more execution units (EU), which are responsible for
177executing the wavefronts. An EU can have enough resources to maintain the state
178of more than one executing wavefront. This allows an EU to hide latency by
179switching between wavefronts in a similar way to symmetric multithreading on a
180CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
181resources used by a single wavefront have to be limited. For example, the number
182of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
183but can result in having to spill some register state to memory.
184
185Clang supports the `__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`
186attribute for the AMDGPU target. This attribute may be attached to a kernel
187function definition and is an optimization hint.
188
189`<min>` parameter specifies the requested minimum number of waves per EU, and
190*optional* `<max>` parameter specifies the requested maximum number of waves
191per EU (must be greater than `<min>` if specified). If `<max>` is omitted,
192then there is no restriction on the maximum number of waves per EU other than
193the one dictated by the hardware for which the kernel is compiled. Passing
194`0, 0` as `<min>, <max>` implies the default behavior (no limits).
195
196If specified, this attribute allows an advanced developer to tune the number of
197wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
198target backend can use this information to limit resources, such as number of
199SGPRs, number of VGPRs, size of available group and private memory segments, in
200such a way that guarantees that at least `<min>` wavefronts and at most
201`<max>` wavefronts are able to fit within the resources of an EU. Requesting
202more wavefronts can hide memory latency but limits available registers which
203can result in spilling. Requesting fewer wavefronts can help reduce cache
204thrashing, but can reduce memory latency hiding.
205
206This attribute controls the machine code generated by the AMDGPU target backend
207to ensure it is capable of meeting the requested values. However, when the
208kernel is executed, there may be other reasons that prevent meeting the request,
209for example, there may be wavefronts from other kernels executing on the EU.
210
211An error will be given if:
212: - Specified values violate subtarget specifications;
213 - Specified values are not compatible with values provided through other
214 attributes;
215
216The AMDGPU target backend will emit a warning whenever it is unable to
217create machine code that meets the request.)reST";
218
219static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("TYPE")))` attribute on
220ARM targets. This attribute may be attached to a function definition and
221instructs the backend to generate appropriate function entry/exit code so that
222it can be used directly as an interrupt service routine.
223
224The parameter passed to the interrupt attribute is optional, but if
225provided it must be a string literal with one of the following values: "IRQ",
226"FIQ", "SWI", "ABORT", "UNDEF".
227
228The semantics are as follows:
229
230- If the function is AAPCS, Clang instructs the backend to realign the stack to
231 8 bytes on entry. This is a general requirement of the AAPCS at public
232 interfaces, but may not hold when an exception is taken. Doing this allows
233 other AAPCS functions to be called.
234
235- If the CPU is M-class this is all that needs to be done since the architecture
236 itself is designed in such a way that functions obeying the normal AAPCS ABI
237 constraints are valid exception handlers.
238
239- If the CPU is not M-class, the prologue and epilogue are modified to save all
240 non-banked registers that are used, so that upon return the user-mode state
241 will not be corrupted. Note that to avoid unnecessary overhead, only
242 general-purpose (integer) registers are saved in this way. If VFP operations
243 are needed, that state must be saved manually.
244
245 Specifically, interrupt kinds other than "FIQ" will save all core registers
246 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
247
248- If the CPU is not M-class, the return instruction is changed to one of the
249 canonical sequences permitted by the architecture for exception return. Where
250 possible the function itself will make the necessary "lr" adjustments so that
251 the "preferred return address" is selected.
252
253 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
254 handler, where the offset from "lr" to the preferred return address depends on
255 the execution state of the code which generated the exception. In this case
256 a sequence equivalent to "movs pc, lr" will be used.)reST";
257
258static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style `__attribute__((interrupt_save_fp("TYPE")))`
259on ARM targets. This attribute behaves the same way as the ARM interrupt
260attribute, except the general purpose floating point registers are also saved,
261along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
262point context can be automatically saved depending on the FPCCR, the general
263purpose floating point registers will be saved.)reST";
264
265static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
266
267static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on
268AVR targets. This attribute may be attached to a function definition and instructs
269the backend to generate appropriate function entry/exit code so that it can be used
270directly as an interrupt service routine.
271
272On the AVR, the hardware globally disables interrupts when an interrupt is executed.
273The first instruction of an interrupt handler declared with this attribute is a SEI
274instruction to re-enable interrupts. See also the signal attribute that
275does not insert a SEI instruction.)reST";
276
277static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style `__attribute__((signal))` attribute on
278AVR targets. This attribute may be attached to a function definition and instructs
279the backend to generate appropriate function entry/exit code so that it can be used
280directly as an interrupt service routine.
281
282Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
283
284static const char AttrDoc_AbiTag[] = R"reST(The `abi_tag` attribute can be applied to a function, variable, class or
285inline namespace declaration to modify the mangled name of the entity. It gives
286the ability to distinguish between different versions of the same entity but
287with different ABI versions supported. For example, a newer version of a class
288could have a different set of data members and thus have a different size. Using
289the `abi_tag` attribute, it is possible to have different mangled names for
290a global variable of the class type. Therefore, the old code could keep using
291the old mangled name and the new code will use the new mangled name with tags.)reST";
292
293static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
294
295static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
296a new handle. In case this annotation is on an output parameter,
297the function is assumed to fill the corresponding argument with a new
298handle. The attribute requires a string literal argument which used to
299identify the handle with later uses of `use_handle` or
300`release_handle`.
301
302```c++
303// Output arguments from Zircon.
304zx_status_t zx_socket_create(uint32_t options,
305 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
306 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
307
308
309// Returned handle.
310[[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
311int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));
312```)reST";
313
314static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
315
316static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
317
318static const char AttrDoc_AddressSpace[] = R"reST(:::{Note}
319This attribute is mainly intended to be used by target headers
320provided by the toolchain. End users should prefer the documented, named
321address space annotations for their platform, such as the
322[OpenCL address spaces](#opencl-address-spaces), `__global__`, `__local__`,
323or something else.
324:::
325
326The `address_space` attribute functions as a type qualifier that allows the
327programmer to specify the address space for a pointer or reference type.
328Qualified pointer types are considered distinct types for the purposes of
329overload resolution. The attribute takes a single, non-negative integer
330constant expression identifying the address space. For example:
331
332```c
333int * __attribute__((address_space(1))) ptr;
334
335void foo(__attribute__((address_space(2))) float *buf);
336```
337
338Only one address space qualifier may be applied to a given pointer or reference
339type. Where address spaces are allowed (e.g., variables, parameters, return
340types) and what values are valid depends on the target and language mode.
341
342The meaning of each value is defined by the target; multiple address spaces are
343used in environments such as OpenCL, CUDA, HIP, and other GPU programming
344models to distinguish global, local, constant, and private memory. See for
345example the address spaces defined in the [NVPTX User Guide][nvptx user guide] and the
346[AMDGPU User Guide][amdgpu user guide].
347
348Address spaces may partially overlap or be entirely distinct. The compiler may
349reject attempts to convert between distinct, incompatible address spaces.
350Pointer width may vary between different address spaces, so some explicit casts
351may truncate.
352
353For more information, refer to [ISO TR18037][iso tr18037], which covers embedded C language
354extensions. Section 5 covers named address spaces.
355
356[amdgpu user guide]: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
357[iso tr18037]: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip
358[nvptx user guide]: https://llvm.org/docs/NVPTXUsage.html#address-spaces)reST";
359
360static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
361
362static const char AttrDoc_AlignMac68k[] = R"reST()reST";
363
364static const char AttrDoc_AlignNatural[] = R"reST()reST";
365
366static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
367declaration of a variable of pointer or reference type. It specifies that the
368pointer will point to, or the reference will bind to, only objects with at
369least the provided alignment. This alignment value must be some positive power
370of 2.
371
372```c
373typedef double * aligned_double_ptr __attribute__((align_value(64)));
374void foo(double & x __attribute__((align_value(128))),
375 aligned_double_ptr y) { ... }
376```
377
378If the pointer value does not have the specified alignment at runtime, the
379behavior of the program is undefined.)reST";
380
381static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
382
383static const char AttrDoc_AllocAlign[] = R"reST(Use `__attribute__((alloc_align(<parameter-index>)))` on a declaration with a
384function prototype to specify that the prototype's return value (which must be a
385pointer type) is at least as aligned as the value of the indicated parameter.
386This includes functions, Objective-C methods, blocks, and declarations of
387function pointer, member function pointer, function reference, and block pointer
388types. The attribute can also be applied to typedef or type alias declarations
389whose underlying type has a function prototype.
390
391The parameter is given by its index in the list of formal parameters; the first
392parameter has index 1 unless the function is a C++ non-static member function,
393in which case the first parameter has index 2 to account for the implicit `this`
394parameter.
395
396```c++
397// The returned pointer has the alignment specified by the first parameter.
398void *a(size_t align) __attribute__((alloc_align(1)));
399
400// The function pointer's returned pointer has the alignment specified by
401// the first parameter of the pointed-to function.
402void *(*allocator)(size_t align) __attribute__((alloc_align(1)));
403
404// The returned pointer has the alignment specified by the second parameter.
405void *b(void *v, size_t align) __attribute__((alloc_align(2)));
406
407// The returned pointer has the alignment specified by the second visible
408// parameter, however it must be adjusted for the implicit 'this' parameter.
409void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
410```
411
412Note that this attribute merely informs the compiler that a function always
413returns a sufficiently aligned pointer. It does not cause the compiler to
414emit code to enforce that alignment. The behavior is undefined if the returned
415pointer is not sufficiently aligned.)reST";
416
417static const char AttrDoc_AllocSize[] = R"reST(The `alloc_size` attribute can be placed on functions that return pointers in
418order to hint to the compiler how many bytes of memory will be available at the
419returned pointer. `alloc_size` takes one or two arguments.
420
421- `alloc_size(N)` implies that argument number N equals the number of
422 available bytes at the returned pointer.
423- `alloc_size(N, M)` implies that the product of argument number N and
424 argument number M equals the number of available bytes at the returned
425 pointer.
426
427Argument numbers are 1-based.
428
429An example of how to use `alloc_size`
430
431```c
432void *my_malloc(int a) __attribute__((alloc_size(1)));
433void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
434
435int main() {
436 void *const p = my_malloc(100);
437 assert(__builtin_object_size(p, 0) == 100);
438 void *const a = my_calloc(20, 5);
439 assert(__builtin_object_size(a, 0) == 100);
440}
441```
442
443When `-Walloc-size` is enabled, this attribute allows the compiler to
444diagnose cases when the allocated memory is insufficient for the size of the
445type the returned pointer is cast to.
446
447```c
448void *my_malloc(int a) __attribute__((alloc_size(1)));
449void consumer_func(int *);
450
451int main() {
452 int *ptr = my_malloc(sizeof(int)); // no warning
453 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
454 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
455}
456```
457
458:::{Note}
459This attribute works differently in clang than it does in GCC.
460Specifically, clang will only trace `const` pointers (as above); we give up
461on pointers that are not marked as `const`. In the vast majority of cases,
462this is unimportant, because LLVM has support for the `alloc_size`
463attribute. However, this may cause mildly unintuitive behavior when used with
464other attributes, such as `enable_if`.
465:::)reST";
466
467static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
468of `nonallocating` by the compiler.)reST";
469
470static const char AttrDoc_AlwaysDestroy[] = R"reST(The `always_destroy` attribute specifies that a variable with static or thread
471storage duration should have its exit-time destructor run. This attribute is the
472default unless clang was invoked with `-fno-c++-static-destructors`.
473
474If a variable is explicitly declared with this attribute, Clang will silence
475otherwise applicable `-Wexit-time-destructors` warnings.)reST";
476
477static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
478optimization level.
479
480`[[clang::always_inline]]` spelling can be used as a statement attribute; other
481spellings of the attribute are not supported on statements. If a statement is
482marked `[[clang::always_inline]]` and contains calls, the compiler attempts
483to inline those calls.
484
485```c
486int example(void) {
487 int i;
488 [[clang::always_inline]] foo(); // attempts to inline foo
489 [[clang::always_inline]] i = bar(); // attempts to inline bar
490 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
491}
492```
493
494A declaration statement, which is a statement, is not a statement that can have an
495attribute associated with it (the attribute applies to the declaration, not the
496statement in that case). So this use case will not work:
497
498```c
499int example(void) {
500 [[clang::always_inline]] int i = bar();
501 return i;
502}
503```
504
505This attribute does not guarantee that inline substitution actually occurs.
506
507:::{Note}
508Note: applying this attribute to a coroutine at the `-O0` optimization level
509has no effect; other optimization levels may only partially inline and result in a
510diagnostic.
511:::
512
513See also [the Microsoft Docs on Inline Functions][the microsoft docs on inline functions], [the GCC Common Function
514Attribute docs][the gcc common function attribute docs], and [the GCC Inline docs][the gcc inline docs].
515
516[the gcc common function attribute docs]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
517[the gcc inline docs]: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
518[the microsoft docs on inline functions]: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp)reST";
519
520static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
521
522static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements,
523typically for use by static analysis tools that are not integrated into the
524core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools).
525It is a counterpart to the `annotate_type` attribute, which serves the same
526purpose, but for types.
527
528The attribute takes a mandatory string literal argument specifying the
529annotation category and an arbitrary number of optional arguments that provide
530additional information specific to the annotation category. The optional
531arguments must be constant expressions of arbitrary type.
532
533For example:
534
535```c++
536[[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) {
537 [[clang::annotate("category3")]] if (val) {
538
539 }
540}
541```)reST";
542
543static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
544analysis tools that are not integrated into the core Clang compiler (e.g.,
545Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
546`annotate` attribute, which serves the same purpose, but for declarations.
547
548The attribute takes a mandatory string literal argument specifying the
549annotation category and an arbitrary number of optional arguments that provide
550additional information specific to the annotation category. The optional
551arguments must be constant expressions of arbitrary type.
552
553For example:
554
555```c++
556int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
557```
558
559The attribute does not have any effect on the semantics of the type system,
560neither type checking rules, nor runtime semantics. In particular:
561
562- `std::is_same<T, T [[clang::annotate_type("foo")]]>` is true for all types
563 `T`.
564- It is not permissible for overloaded functions or template specializations
565 to differ merely by an `annotate_type` attribute.
566- The presence of an `annotate_type` attribute will not affect name
567 mangling.)reST";
568
569static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on X86
570targets. This attribute may be attached to a function definition and instructs
571the backend to generate appropriate function entry/exit code so that it can be
572used directly as an interrupt service routine.
573
574Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
575and return using the `IRET` instruction. All registers in an interrupt handler are callee-saved.
576Exception handlers also have access to the error code pushed onto the stack by the processor,
577when applicable.
578
579An interrupt handler must take the following arguments:
580
581```c
582__attribute__ ((interrupt))
583void f (struct stack_frame *frame) {
584 ...
585}
586```
587
588Where `struct stack_frame` is a suitable struct matching the stack frame pushed
589by the processor.
590
591An exception handler must take the following arguments:
592
593```c
594__attribute__ ((interrupt))
595void g (struct stack_frame *frame, unsigned long code) {
596 ...
597}
598```
599
600On 32-bit targets, the `code` argument should be of type `unsigned int`.
601
602Exception handlers should only be used when an error code is pushed by the processor.
603Using the incorrect handler type will crash the system.
604
605Interrupt and exception handlers cannot be called by other functions and must have return type `void`.
606
607Interrupt and exception handlers should only call functions with the `no_caller_saved_registers`
608attribute, or should be compiled with the `-mgeneral-regs-only` flag to avoid saving unused
609non-GPR registers.)reST";
610
611static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
612caller-saved registers. That is, all registers are callee-saved except for
613registers used for passing parameters to the function or returning parameters
614from the function.
615The compiler saves and restores any modified registers that were not used for
616passing or returning arguments to the function.
617
618The user can call functions specified with the `no_caller_saved_registers`
619attribute from an interrupt handler without saving and restoring all
620call-clobbered registers.
621
622Functions specified with the `no_caller_saved_registers` attribute should only
623call other functions with the `no_caller_saved_registers` attribute, or should be
624compiled with the `-mgeneral-regs-only` flag to avoid saving unused non-GPR registers.
625
626Note that `no_caller_saved_registers` attribute is not a calling convention.
627In fact, it only overrides the decision of which registers should be saved by
628the caller, but not how the parameters are passed from the caller to the callee.
629
630For example:
631
632```c
633__attribute__ ((no_caller_saved_registers, fastcall))
634void f (int arg1, int arg2) {
635 ...
636}
637```
638
639In this case parameters `arg1` and `arg2` will be passed in registers.
640In this case, on 32-bit x86 targets, the function `f` will use ECX and EDX as
641register parameters. However, it will not assume any scratch registers and
642should save and restore any modified registers except for ECX and EDX.)reST";
643
644static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
645indirect call / jmp, e.g. redirect control-flow to non-programmer
646intended bytes in the binary.
647X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
648Enforcement Technology (CET). IBT instruments ENDBR instructions used to
649specify valid targets of indirect call / jmp.
650The `nocf_check` attribute has two roles:
6511\. Appertains to a function - do not add ENDBR instruction at the beginning of
652the function.
6532\. Appertains to a function pointer - do not track the target function of this
654pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
655
656static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
657
658static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use `__attribute__((argument_with_type_tag(arg_kind, arg_idx,
659type_tag_idx)))` on a function declaration to specify that the function
660accepts a type tag that determines the type of some other argument.
661
662This attribute is primarily useful for checking arguments of variadic functions
663(`pointer_with_type_tag` can be used in most non-variadic cases).
664
665In the attribute prototype above:
666: - `arg_kind` is an identifier that should be used when annotating all
667 applicable type tags.
668 - `arg_idx` provides the position of a function argument. The expected type of
669 this function argument will be determined by the function argument specified
670 by `type_tag_idx`. In the code example below, "3" means that the type of the
671 function's third argument will be determined by `type_tag_idx`.
672 - `type_tag_idx` provides the position of a function argument. This function
673 argument will be a type tag. The type tag will determine the expected type of
674 the argument specified by `arg_idx`. In the code example below, "2" means
675 that the type tag associated with the function's second argument should agree
676 with the type of the argument specified by `arg_idx`.
677
678For example:
679
680```c++
681int fcntl(int fd, int cmd, ...)
682 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
683// The function's second argument will be a type tag; this type tag will
684// determine the expected type of the function's third argument.
685```)reST";
686
687static const char AttrDoc_ArmAgnostic[] = R"reST(The `__arm_agnostic` keyword applies to prototyped function types and
688affects the function's calling convention for a given state S. This
689attribute allows the user to describe a function that preserves S, without
690requiring the function to share S with its callers and without making
691the assumption that S exists.
692
693If a function has the `__arm_agnostic(S)` attribute and calls a function
694without this attribute, then the function's object code will contain code
695to preserve state S. Otherwise, the function's object code will be the same
696as if it did not have the attribute.
697
698The attribute takes string arguments to describe state S. The supported
699states are:
700
701- `"sme_za_state"` for state enabled by PSTATE.ZA, such as ZA and ZT0.
702
703The attribute `__arm_agnostic("sme_za_state")` cannot be used in conjunction
704with `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` or
705`__arm_preserves(S)` where state S describes state enabled by PSTATE.ZA,
706such as "za" or "zt0".)reST";
707
708static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
709It allows the intrinsic functions to
710be declared using the names defined in ACLE, and still be recognized
711as clang builtins equivalent to the underlying name. For example,
712`arm_mve.h` declares the function `vaddq_u32` with
713`__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))`,
714and similarly, one of the type-overloaded declarations of `vaddq`
715will have the same attribute. This ensures that both functions are
716recognized as that clang builtin, and in the latter case, the choice
717of which builtin to identify the function as can be deferred until
718after overload resolution.
719
720This attribute can only be used to set up the aliases for certain Arm
721intrinsic functions; it is intended for use only inside `arm_*.h`
722and is not a general mechanism for declaring arbitrary aliases for
723clang builtin functions.
724
725In order to avoid duplicating the attribute definitions for similar
726purpose for other architecture, there is a general form for the
727attribute `clang_builtin_alias`.)reST";
728
729static const char AttrDoc_ArmIn[] = R"reST(The `__arm_in` keyword applies to prototyped function types and specifies
730that the function shares a given state S with its caller. For `__arm_in`, the
731function takes the state S as input and returns with the state S unchanged.
732
733The attribute takes string arguments to instruct the compiler which state
734is shared. The supported states for S are:
735
736- `"za"` for Matrix Storage (requires SME)
737
738The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
739`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
740
741static const char AttrDoc_ArmInOut[] = R"reST(The `__arm_inout` keyword applies to prototyped function types and specifies
742that the function shares a given state S with its caller. For `__arm_inout`,
743the function takes the state S as input and returns new state for S.
744
745The attribute takes string arguments to instruct the compiler which state
746is shared. The supported states for S are:
747
748- `"za"` for Matrix Storage (requires SME)
749
750The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
751`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
752
753static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The `__arm_locally_streaming` keyword applies to function declarations
754and specifies that all the statements in the function are executed in
755streaming mode. This means that:
756
757- the function requires that the target processor implements the Scalable Matrix
758 Extension (SME).
759- the program automatically puts the machine into streaming mode before
760 executing the statements and automatically restores the previous mode
761 afterwards.
762
763Clang manages PSTATE.SM automatically; it is not the source code's
764responsibility to do this. For example, Clang will emit code to enable
765streaming mode at the start of the function, and disable streaming mode
766at the end of the function.)reST";
767
768static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
769MVE instruction set. It is used to define the vector types used by the MVE
770intrinsics.
771
772Its effect is to modify the behavior of a vector type with respect to function
773overloading. If a candidate function for overload resolution has a parameter
774type with this attribute, then the selection of that candidate function will be
775disallowed if the actual argument can only be converted via a lax vector
776conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
777intrinsics.
778
779```c++
780void overloaded(uint16x8_t vector, uint16_t scalar);
781void overloaded(int32x4_t vector, int32_t scalar);
782uint16x8_t myVector;
783uint16_t myScalar;
784
785// myScalar is promoted to int32_t as a side effect of the addition,
786// so if lax vector conversions are considered for myVector, then
787// the two overloads are equally good (one argument conversion
788// each). But if the vector has the __clang_arm_mve_strict_polymorphism
789// attribute, only the uint16x8_t,uint16_t overload will match.
790overloaded(myVector, myScalar + 1);
791```
792
793However, this attribute does not prohibit lax vector conversions in contexts
794other than overloading.
795
796```c++
797uint16x8_t function();
798
799// This is still permitted with lax vector conversion enabled, even
800// if the vector types have __clang_arm_mve_strict_polymorphism
801int32x4_t result = function();
802```)reST";
803
804static const char AttrDoc_ArmNew[] = R"reST(The `__arm_new` keyword applies to function declarations and specifies
805that the function will create a new scope for state S.
806
807The attribute takes string arguments to instruct the compiler for which state
808to create new scope. The supported states for S are:
809
810- `"za"` for Matrix Storage (requires SME)
811
812For state `"za"`, this means that:
813
814- the function requires that the target processor implements the Scalable Matrix
815 Extension (SME).
816- the function will commit any lazily saved ZA data.
817- the function will create a new ZA context and enable PSTATE.ZA.
818- the function will disable PSTATE.ZA (by setting it to 0) before returning.
819
820For `__arm_new("za")` functions Clang will set up the ZA context automatically
821on entry to the function and disable it before returning. For example, if ZA is
822in a dormant state Clang will generate the code to commit a lazy-save and set up
823a new ZA state before executing user code.)reST";
824
825static const char AttrDoc_ArmOut[] = R"reST(The `__arm_out` keyword applies to prototyped function types and specifies
826that the function shares a given state S with its caller. For `__arm_out`,
827the function ignores the incoming state for S and returns new state for S.
828
829The attribute takes string arguments to instruct the compiler which state
830is shared. The supported states for S are:
831
832- `"za"` for Matrix Storage (requires SME)
833
834The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
835`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
836
837static const char AttrDoc_ArmPreserves[] = R"reST(The `__arm_preserves` keyword applies to prototyped function types and
838specifies that the function does not read a given state S and returns
839with state S unchanged.
840
841The attribute takes string arguments to instruct the compiler which state
842is shared. The supported states for S are:
843
844- `"za"` for Matrix Storage (requires SME)
845
846The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
847`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
848
849static const char AttrDoc_ArmStreaming[] = R"reST(The `__arm_streaming` keyword applies to prototyped function types and specifies
850that the function has a "streaming interface". This means that:
851
852- the function requires that the processor implements the Scalable Matrix
853 Extension (SME).
854- the function must be entered in streaming mode (that is, with PSTATE.SM
855 set to 1)
856- the function must return in streaming mode
857
858Clang manages PSTATE.SM automatically; it is not the source code's
859responsibility to do this. For example, if a non-streaming
860function calls an `__arm_streaming` function, Clang generates code
861that switches into streaming mode before calling the function and
862switches back to non-streaming mode on return.)reST";
863
864static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The `__arm_streaming_compatible` keyword applies to prototyped function types and
865specifies that the function has a "streaming compatible interface". This
866means that:
867
868- the function may be entered in either non-streaming mode (PSTATE.SM=0) or
869 in streaming mode (PSTATE.SM=1).
870- the function must return in the same mode as it was entered.
871- the code executed in the function is compatible with either mode.
872
873Clang manages PSTATE.SM automatically; it is not the source code's
874responsibility to do this. Clang will ensure that the generated code in
875streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
876PSTATE.SM=1). For example, if an `__arm_streaming_compatible` function calls a
877non-streaming function, Clang generates code to temporarily switch out of streaming
878mode before calling the function and switch back to streaming-mode on return if
879`PSTATE.SM` is `1` on entry of the caller. If `PSTATE.SM` is `0` on
880entry to the `__arm_streaming_compatible` function, the call will be executed
881without changing modes.)reST";
882
883static const char AttrDoc_Artificial[] = R"reST(The `artificial` attribute can be applied to an inline function. If such a
884function is inlined, the attribute indicates that debuggers should associate
885the resulting instructions with the call site, rather than with the
886corresponding line within the inlined callee.)reST";
887
888static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
889
890On some targets, all C symbols are prefixed by default with a single character,
891typically `_`. This was done historically to distinguish them from symbols
892used by other languages. (This prefix is also added to the standard Itanium
893C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
894symbol name for a C++ variable declared as `int cppvar;` would be
895`__Z6cppvar`; note the two underscores.) This prefix is *not* added to the
896symbol names specified by the `__asm` attribute; programmers wishing to match
897a C symbol name must compensate for this.
898
899For example, consider the following C code:
900
901```c
902int var1 __asm("altvar") = 1; // "altvar" in symbol table.
903int var2 = 1; // "_var2" in symbol table.
904
905void func1(void) __asm("altfunc");
906void func1(void) {} // "altfunc" in symbol table.
907void func2(void) {} // "_func2" in symbol table.
908```
909
910Clang's implementation of this attribute is compatible with GCC's, [documented here](https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html).
911
912While it is possible to use this attribute to name a special symbol used
913internally by the compiler, such as an LLVM intrinsic, this is neither
914recommended nor supported and may cause the compiler to crash or miscompile.
915Users who wish to gain access to intrinsic behavior are strongly encouraged to
916request new builtin functions.)reST";
917
918static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
919the program if it is not held.)reST";
920
921static const char AttrDoc_AssumeAligned[] = R"reST(Use `__attribute__((assume_aligned(<alignment>[,<offset>]))` on a function
922declaration to specify that the return value of the function (which must be a
923pointer type) has the specified offset, in bytes, from an address with the
924specified alignment. The offset is taken to be zero if omitted.
925
926```c++
927// The returned pointer value has 32-byte alignment.
928void *a() __attribute__((assume_aligned (32)));
929
930// The returned pointer value is 4 bytes greater than an address having
931// 32-byte alignment.
932void *b() __attribute__((assume_aligned (32, 4)));
933```
934
935Note that this attribute provides information to the compiler regarding a
936condition that the code already ensures is true. It does not cause the compiler
937to enforce the provided alignment assumption.)reST";
938
939static const char AttrDoc_Atomic[] = R"reST(The `atomic` attribute can be applied to *compound statements* to override or
940further specify the default atomic code-generation behavior, especially on
941targets such as AMDGPU. You can annotate compound statements with options
942to modify how atomic instructions inside that statement are emitted at the IR
943level.
944
945For details, see the documentation for
946{ref}`@atomic <langext-atomic-code-generation>`)reST";
947
948static const char AttrDoc_Availability[] = R"reST(The `availability` attribute can be placed on declarations to describe the
949lifecycle of that declaration relative to operating system versions. Consider
950the function declaration for a hypothetical function `f`:
951
952```c++
953void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
954```
955
956The availability attribute states that `f` was introduced in macOS 10.4,
957deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
958is used by Clang to determine when it is safe to use `f`: for example, if
959Clang is instructed to compile code for macOS 10.5, a call to `f()`
960succeeds. If Clang is instructed to compile code for macOS 10.6, the call
961succeeds but Clang emits a warning specifying that the function is deprecated.
962Finally, if Clang is instructed to compile code for macOS 10.7, the call
963fails because `f()` is no longer available.
964
965Clang is instructed to compile code for a minimum deployment version using
966the `-target` or `-mtargetos` command line arguments. For example,
967macOS 10.7 would be specified as `-target x86_64-apple-macos10.7` or
968`-mtargetos=macos10.7`. Variants like Mac Catalyst are specified as
969`-target arm64-apple-ios15.0-macabi` or `-mtargetos=ios15.0-macabi`
970
971The availability attribute is a comma-separated list starting with the
972platform name and then including clauses specifying important milestones in the
973declaration's lifetime (in any order) along with additional information. Those
974clauses can be:
975
976introduced=*version*
977
978: The first version in which this declaration was introduced.
979
980deprecated=*version*
981
982: The first version in which this declaration was deprecated, meaning that
983 users should migrate away from this API.
984
985obsoleted=*version*
986
987: The first version in which this declaration was obsoleted, meaning that it
988 was removed completely and can no longer be used.
989
990unavailable
991
992: This declaration is never available on this platform.
993
994message=*string-literal*
995
996: Additional message text that Clang will provide when emitting a warning or
997 error about use of a deprecated or obsoleted declaration. Useful to direct
998 users to replacement APIs.
999
1000replacement=*string-literal*
1001
1002: Additional message text that Clang will use to provide Fix-It when emitting
1003 a warning about use of a deprecated declaration. The Fix-It will replace
1004 the deprecated declaration with the new declaration specified.
1005
1006environment=*identifier*
1007
1008: Target environment in which this declaration is available. If present,
1009 the availability attribute applies only to targets with the same platform
1010 and environment. The parameter is currently supported only in HLSL.
1011
1012Multiple availability attributes can be placed on a declaration, which may
1013correspond to different platforms. For most platforms, the availability
1014attribute with the platform corresponding to the target platform will be used;
1015any others will be ignored. However, the availability for `watchOS` and
1016`tvOS` can be implicitly inferred from an `iOS` availability attribute.
1017Any explicit availability attributes for those platforms are still preferred over
1018the implicitly inferred availability attributes. If no availability attribute
1019specifies availability for the current target platform, the availability
1020attributes are ignored. Supported platforms are:
1021
1022`iOS`
1023`macOS`
1024`tvOS`
1025`watchOS`
1026`iOSApplicationExtension`
1027`macOSApplicationExtension`
1028`tvOSApplicationExtension`
1029`watchOSApplicationExtension`
1030`macCatalyst`
1031`macCatalystApplicationExtension`
1032`visionOS`
1033`visionOSApplicationExtension`
1034`driverkit`
1035`anyAppleOS`
1036`swift`
1037`android`
1038`fuchsia`
1039`ohos`
1040`zos`
1041`ShaderModel`
1042
1043Some platforms have alias names:
1044
1045`ios`
1046`macos`
1047`macosx (deprecated)`
1048`tvos`
1049`watchos`
1050`ios_app_extension`
1051`macos_app_extension`
1052`macosx_app_extension (deprecated)`
1053`tvos_app_extension`
1054`watchos_app_extension`
1055`maccatalyst`
1056`maccatalyst_app_extension`
1057`visionos`
1058`visionos_app_extension`
1059`anyappleos`
1060`shadermodel`
1061
1062Supported environment names for the ShaderModel platform:
1063
1064`pixel`
1065`vertex`
1066`geometry`
1067`hull`
1068`domain`
1069`compute`
1070`raygeneration`
1071`intersection`
1072`anyhit`
1073`closesthit`
1074`miss`
1075`callable`
1076`mesh`
1077`amplification`
1078`library`
1079
1080The special platform `anyAppleOS` (alias: `anyappleos`) is a shorthand that
1081applies the availability attribute to all Apple Darwin platforms. An explicit
1082platform-specific availability attribute takes precedence over an `anyAppleOS`
1083attribute for that platform. Versions specified with `anyAppleOS` must be at
1084least 26.0, which is the first OS release where all supported Apple platforms
1085share a unified version number.
1086
1087A declaration can typically be used even when deploying back to a platform
1088version prior to when the declaration was introduced. When this happens, the
1089declaration is [weakly linked](https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html),
1090as if the `weak_import` attribute were added to the declaration. A
1091weakly-linked declaration may or may not be present a run-time, and a program
1092can determine whether the declaration is present by checking whether the
1093address of that declaration is non-NULL.
1094
1095The flag `strict` disallows using API when deploying back to a
1096platform version prior to when the declaration was introduced. An
1097attempt to use such API before its introduction causes a hard error.
1098Weakly-linking is almost always a better API choice, since it allows
1099users to query availability at runtime.
1100
1101If there are multiple declarations of the same entity, the availability
1102attributes must either match on a per-platform basis or later
1103declarations must not have availability attributes for that
1104platform. For example:
1105
1106```c
1107void g(void) __attribute__((availability(macos,introduced=10.4)));
1108void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1109void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1110void g(void); // okay, inherits both macos and ios availability from above.
1111void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1112```
1113
1114When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1115
1116```objc
1117@interface A
1118- (id)method __attribute__((availability(macos,introduced=10.4)));
1119- (id)method2 __attribute__((availability(macos,introduced=10.4)));
1120@end
1121
1122@interface B : A
1123- (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1124- (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1125@end
1126```
1127
1128Starting with the macOS 10.12 SDK, the `API_AVAILABLE` macro from
1129`<os/availability.h>` can simplify the spelling:
1130
1131```objc
1132@interface A
1133- (id)method API_AVAILABLE(macos(10.11)));
1134- (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1135@end
1136```
1137
1138Availability attributes can also be applied using a `#pragma clang attribute`.
1139Any explicit availability attribute whose platform corresponds to the target
1140platform is applied to a declaration regardless of the availability attributes
1141specified in the pragma. For example, in the code below,
1142`hasExplicitAvailabilityAttribute` will use the `macOS` availability
1143attribute that is specified with the declaration, whereas
1144`getsThePragmaAvailabilityAttribute` will use the `macOS` availability
1145attribute that is applied by the pragma.
1146
1147```c
1148#pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1149void getsThePragmaAvailabilityAttribute(void);
1150void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1151#pragma clang attribute pop
1152```
1153
1154For platforms like `watchOS` and `tvOS`, whose availability attributes can
1155be implicitly inferred from an `iOS` availability attribute, the logic is
1156slightly more complex. The explicit and the pragma-applied availability
1157attributes whose platform corresponds to the target platform are applied as
1158described in the previous paragraph. However, the implicitly inferred attributes
1159are applied to a declaration only when there is no explicit or pragma-applied
1160availability attribute whose platform corresponds to the target platform. For
1161example, the function below will receive the `tvOS` availability from the
1162pragma rather than using the inferred `iOS` availability from the declaration:
1163
1164```c
1165#pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1166void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1167#pragma clang attribute pop
1168```
1169
1170The compiler is also able to apply implicitly inferred attributes from a pragma
1171as well. For example, when targeting `tvOS`, the function below will receive
1172a `tvOS` availability attribute that is implicitly inferred from the `iOS`
1173availability attribute applied by the pragma:
1174
1175```c
1176#pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1177void infersTVOSAvailabilityFromPragma(void);
1178#pragma clang attribute pop
1179```
1180
1181The implicit attributes that are inferred from explicitly specified attributes
1182whose platform corresponds to the target platform are applied to the declaration
1183even if there is an availability attribute that can be inferred from a pragma.
1184For example, the function below will receive the `tvOS, introduced=11.0`
1185availability that is inferred from the attribute on the declaration rather than
1186inferring availability from the pragma:
1187
1188```c
1189#pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1190void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1191 __attribute__((availability(iOS,introduced=11.0)));
1192#pragma clang attribute pop
1193```
1194
1195Also see the documentation for
1196{ref}`@available <langext-objective-c-available>`)reST";
1197
1198static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1199
1200static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1201It is assumed that inlined implementation uses less caller saved registers,
1202than a regular function.
1203Specifically, the following registers are likely to be preserved:
1204- `R0` if function return value is `void`;
1205- `R2-R5` if function takes 1 argument;
1206- `R3-R5` if function takes 2 arguments;
1207- `R4-R5` if function takes 3 arguments;
1208- `R5` if function takes 4 arguments;
1209
1210For such functions Clang generates code pattern that allows BPF JIT
1211to recognize and remove unnecessary spills and fills of the preserved
1212registers.)reST";
1213
1214static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the `__attribute__((preserve_access_index))`
1215attribute for the BPF target. This attribute may be attached to a
1216struct or union declaration, where if -g is specified, it enables
1217preserving struct or union member access debuginfo indices of this
1218struct or union, similar to clang `__builtin_preserve_access_index()`.)reST";
1219
1220static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the `__attribute__((preserve_static_offset))`
1221attribute for the BPF target. This attribute may be attached to a
1222struct or union declaration. Reading or writing fields of types having
1223such annotation is guaranteed to generate LDX/ST/STX instruction with
1224offset corresponding to the field.
1225
1226For example:
1227
1228```c
1229struct foo {
1230 int a;
1231 int b;
1232};
1233
1234struct bar {
1235 int a;
1236 struct foo b;
1237} __attribute__((preserve_static_offset));
1238
1239void buz(struct bar *g) {
1240 g->b.a = 42;
1241}
1242```
1243
1244The assignment to `g`'s field would produce an ST instruction with
1245offset 8: `*(u32)(r1 + 8) = 42;`.
1246
1247Without this attribute generated instructions might be different,
1248depending on optimizations behavior. E.g. the example above could be
1249rewritten as `r1 += 8; *(u32)(r1 + 0) = 42;`.)reST";
1250
1251static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the `__attribute__((btf_decl_tag("ARGUMENT")))` attribute for
1252all targets. This attribute may be attached to a struct/union, struct/union
1253field, function, function parameter, variable or typedef declaration. If -g is
1254specified, the `ARGUMENT` info will be preserved in IR and be emitted to
1255dwarf. For BPF targets, the `ARGUMENT` info will be emitted to .BTF ELF
1256section too.)reST";
1257
1258static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the `__attribute__((btf_type_tag("ARGUMENT")))` attribute for
1259all targets. It only has effect when `-g` is specified on the command line.
1260
1261The attribute can be applied to a pointer type, in which case the tag is
1262associated with the pointee type, e.g.:
1263
1264```c
1265int __attribute__((btf_type_tag("tag"))) *p;
1266```
1267
1268It can also be applied to the underlying type of a typedef, in which case the
1269tag follows the typedef down to its base type, e.g.:
1270
1271```c
1272typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1273```
1274
1275The following is the corresponding btf:
1276
1277```
1278...
1279[2] TYPE_TAG 'tag' type_id=4
1280[3] TYPEDEF 'foo_t' type_id=2
1281[4] STRUCT 'foo' size=4 vlen=1
1282 'c' type_id=5 bits_offset=0
1283[5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
1284...
1285```
1286
1287The attribute is currently silently ignored in any other position (note: this
1288scenario may be diagnosed in the future).
1289
1290The `ARGUMENT` string will be preserved in IR and emitted to DWARF for the
1291types used in variable declarations, function declarations, or typedef
1292declarations.
1293
1294For BPF targets, the `ARGUMENT` string will also be emitted to .BTF ELF
1295section.)reST";
1296
1297static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of `nonblocking`
1298by the compiler.)reST";
1299
1300static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1301
1302static const char AttrDoc_Builtin[] = R"reST()reST";
1303
1304static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1305It allows the C intrinsic functions to be declared using the names defined
1306in target builtins, and still be recognized as clang builtins equivalent to the
1307underlying name. For example, `riscv_vector.h` declares the function `vadd`
1308with `__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))`.
1309This ensures that both functions are recognized as that clang builtin,
1310and in the latter case, the choice of which builtin to identify the
1311function as can be deferred until after overload resolution.
1312
1313This attribute can only be used to set up the aliases for certain ARM/RISC-V
1314C intrinsic functions; it is intended for use only inside `arm_*.h` and
1315`riscv_*.h` and is not a general mechanism for declaring arbitrary aliases
1316for clang builtin functions.)reST";
1317
1318static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as `_Noreturn` shall not return to its caller. The
1319compiler will generate a diagnostic for a function declared as `_Noreturn`
1320that appears to be capable of returning to its caller. Despite being a type
1321specifier, the `_Noreturn` attribute cannot be specified on a function
1322pointer type.)reST";
1323
1324static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1325
1326static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1327
1328static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1329(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1330convention (e.g. functions starting with "get" are assumed to return at
1331`+0`).
1332
1333It can be overridden using a family of the following attributes. In
1334Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1335a function communicates that the object is returned at `+1`, and the caller
1336is responsible for freeing it.
1337Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1338specifies that the object is returned at `+0` and the ownership remains with
1339the callee.
1340The annotation `__attribute__((ns_consumes_self))` specifies that
1341the Objective-C method call consumes the reference to `self`, e.g. by
1342attaching it to a supplied parameter.
1343Additionally, parameters can have an annotation
1344`__attribute__((ns_consumed))`, which specifies that passing an owned object
1345as that parameter effectively transfers the ownership, and the caller is no
1346longer responsible for it.
1347These attributes affect code generation when interacting with ARC code, and
1348they are used by the Clang Static Analyzer.
1349
1350In C programs using CoreFoundation, a similar set of attributes:
1351`__attribute__((cf_returns_not_retained))`,
1352`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1353have the same respective semantics when applied to CoreFoundation objects.
1354These attributes affect code generation when interacting with ARC code, and
1355they are used by the Clang Static Analyzer.
1356
1357(os-retained-attr-family)=
1358
1359Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1360the same attribute family is present:
1361`__attribute__((os_returns_not_retained))`,
1362`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1363with the same respective semantics.
1364Similar to `__attribute__((ns_consumes_self))`,
1365`__attribute__((os_consumes_this))` specifies that the method call consumes
1366the reference to "this" (e.g., when attaching it to a different object supplied
1367as a parameter).
1368Out parameters (parameters the function is meant to write into,
1369either via pointers-to-pointers or references-to-pointers)
1370may be annotated with `__attribute__((os_returns_retained))`
1371or `__attribute__((os_returns_not_retained))` which specifies that the object
1372written into the out parameter should (or respectively should not) be released
1373after use.
1374Since often out parameters may or may not be written depending on the exit
1375code of the function,
1376annotations `__attribute__((os_returns_retained_on_zero))`
1377and `__attribute__((os_returns_retained_on_non_zero))` specify that
1378an out parameter at `+1` is written if and only if the function returns a zero
1379(respectively non-zero) error code.
1380Observe that return-code-dependent out parameter annotations are only
1381available for retained out parameters, as non-retained object do not have to be
1382released by the callee.
1383These attributes are only used by the Clang Static Analyzer.
1384
1385The family of attributes `X_returns_X_retained` can be added to functions,
1386C++ methods, and Objective-C methods and properties.
1387Attributes `X_consumed` can be added to parameters of methods, functions,
1388and Objective-C methods.)reST";
1389
1390static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the `__declspec(guard(nocf))`
1391attribute. This directs the compiler to not insert any CFG checks for the entire
1392function. This approach is typically used only sparingly in specific situations
1393where the programmer has manually inserted "CFG-equivalent" protection. The
1394programmer knows that they are calling through some read-only function table
1395whose address is obtained through read-only memory references and for which the
1396index is masked to the function table limit. This approach may also be applied
1397to small wrapper functions that are not inlined and that do nothing more than
1398make a call through a function pointer. Since incorrect usage of this directive
1399can compromise the security of CFG, the programmer must be very careful using
1400the directive. Typically, this usage is limited to very small functions that
1401only call one function.
1402
1403Control Flow Guard documentation is available here:
1404<https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>)reST";
1405
1406static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use `__attribute__((cfi_canonical_jump_table))` on a function declaration to
1407make the function's CFI jump table canonical. See {ref}`the CFI documentation
1408<cfi-canonical-jump-tables>` for more details.)reST";
1409
1410static const char AttrDoc_CFISalt[] = R"reST(The `cfi_salt` attribute specifies a string literal that is used as a salt
1411for Control-Flow Integrity (CFI) checks to distinguish between functions with
1412the same type signature. This attribute can be applied to function declarations,
1413function definitions, and function pointer typedefs.
1414
1415The attribute prevents function pointers from being replaced with pointers to
1416functions that have a compatible type, which can be a CFI bypass vector.
1417
1418**Syntax:**
1419
1420- GNU-style: `__attribute__((cfi_salt("<salt_string>")))`
1421- C++11-style: `[[clang::cfi_salt("<salt_string>")]]`
1422
1423**Usage:**
1424
1425The attribute takes a single string literal argument that serves as the salt.
1426Functions or function types with different salt values will have different CFI
1427hashes, even if they have identical type signatures.
1428
1429**Motivation:**
1430
1431In large codebases like the Linux kernel, there are often hundreds of functions
1432with identical type signatures that are called indirectly:
1433
1434```
14351662 functions with void (*)(void)
14361179 functions with int (*)(void)
1437 ...
1438```
1439
1440By salting the CFI hashes, you can make CFI more robust by ensuring that
1441functions intended for different purposes have distinct CFI identities.
1442
1443**Type Compatibility:**
1444
1445- Functions with different salt values are considered to have incompatible types
1446- Function pointers with different salt values cannot be assigned to each other
1447- All declarations of the same function must use the same salt value
1448
1449**Example:**
1450
1451```c
1452// Header file - define convenience macros
1453#define __cfi_salt(s) __attribute__((cfi_salt(s)))
1454
1455// Typedef for regular function pointers
1456typedef int (*fptr_t)(void);
1457
1458// Typedef for salted function pointers
1459typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1460
1461struct widget_ops {
1462 fptr_t init; // Regular CFI
1463 fptr_salted_t exec; // Salted CFI
1464 fptr_t cleanup; // Regular CFI
1465};
1466
1467// Function implementations
1468static int widget_init(void) { return 0; }
1469static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1470static int widget_cleanup(void) { return 0; }
1471
1472static struct widget_ops ops = {
1473 .init = widget_init, // OK - compatible types
1474 .exec = widget_exec, // OK - both use "pepper" salt
1475 .cleanup = widget_cleanup // OK - compatible types
1476};
1477
1478// Using C++11 attribute syntax
1479void secure_callback(void) [[clang::cfi_salt("secure")]];
1480
1481// This would cause a compilation error:
1482// fptr_t bad_ptr = widget_exec; // Error: incompatible types
1483```
1484
1485**Notes:**
1486
1487- The salt string can contain non-NULL ASCII characters, including spaces and
1488 quotes
1489- This attribute only applies to function types; using it on non-function
1490 types will generate a warning
1491- All declarations and definitions of the same function must use identical
1492 salt values
1493- The attribute affects type compatibility during compilation and CFI hash
1494 generation during code generation)reST";
1495
1496static const char AttrDoc_CFIUncheckedCallee[] = R"reST(`cfi_unchecked_callee` is a function type attribute which prevents the
1497compiler from instrumenting
1498{doc}`Control Flow Integrity <ControlFlowIntegrity>` checks on indirect
1499function calls. This also includes control flow checks added by
1500`-fsanitize=function`; see {ref}`Available checks <ubsan-checks>`.
1501Specifically, the attribute has the following semantics:
1502
15031. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1504 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1505 on pointers to function types having this attribute. It does not prevent all indirect function calls
1506 for a given type from being checked.
15072. All direct references to a function whose type has this attribute will always reference the
1508 function definition rather than an entry in the CFI jump table.
15093. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1510 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1511 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1512 direct references to a function with a `cfi_unchecked_callee` attribute will still reference the
1513 function definition rather than the CFI jump table.
1514
1515```c
1516#define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1517
1518void no_cfi() CFI_UNCHECKED_CALLEE {}
1519
1520void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1521 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1522 // its jump table entry.
1523
1524void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1525 func(); // CFI will not instrument this indirect call.
1526
1527 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1528
1529 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1530 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1531 // fail because the reference will be to the function definition rather than the CFI jump
1532 // table entry.
1533}
1534```
1535
1536This attribute can only be applied on functions or member functions. This attribute can be a good
1537alternative to `no_sanitize("cfi")` if you only want to disable innstrumentation for specific indirect
1538calls rather than applying `no_sanitize("cfi")` on the whole function containing indirect call. Note
1539that `cfi_unchecked_attribute` is a type attribute doesn't disable CFI instrumentation on a function
1540body.)reST";
1541
1542static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1543(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1544convention (e.g. functions starting with "get" are assumed to return at
1545`+0`).
1546
1547It can be overridden using a family of the following attributes. In
1548Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1549a function communicates that the object is returned at `+1`, and the caller
1550is responsible for freeing it.
1551Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1552specifies that the object is returned at `+0` and the ownership remains with
1553the callee.
1554The annotation `__attribute__((ns_consumes_self))` specifies that
1555the Objective-C method call consumes the reference to `self`, e.g. by
1556attaching it to a supplied parameter.
1557Additionally, parameters can have an annotation
1558`__attribute__((ns_consumed))`, which specifies that passing an owned object
1559as that parameter effectively transfers the ownership, and the caller is no
1560longer responsible for it.
1561These attributes affect code generation when interacting with ARC code, and
1562they are used by the Clang Static Analyzer.
1563
1564In C programs using CoreFoundation, a similar set of attributes:
1565`__attribute__((cf_returns_not_retained))`,
1566`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1567have the same respective semantics when applied to CoreFoundation objects.
1568These attributes affect code generation when interacting with ARC code, and
1569they are used by the Clang Static Analyzer.
1570
1571(os-retained-attr-family)=
1572
1573Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1574the same attribute family is present:
1575`__attribute__((os_returns_not_retained))`,
1576`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1577with the same respective semantics.
1578Similar to `__attribute__((ns_consumes_self))`,
1579`__attribute__((os_consumes_this))` specifies that the method call consumes
1580the reference to "this" (e.g., when attaching it to a different object supplied
1581as a parameter).
1582Out parameters (parameters the function is meant to write into,
1583either via pointers-to-pointers or references-to-pointers)
1584may be annotated with `__attribute__((os_returns_retained))`
1585or `__attribute__((os_returns_not_retained))` which specifies that the object
1586written into the out parameter should (or respectively should not) be released
1587after use.
1588Since often out parameters may or may not be written depending on the exit
1589code of the function,
1590annotations `__attribute__((os_returns_retained_on_zero))`
1591and `__attribute__((os_returns_retained_on_non_zero))` specify that
1592an out parameter at `+1` is written if and only if the function returns a zero
1593(respectively non-zero) error code.
1594Observe that return-code-dependent out parameter annotations are only
1595available for retained out parameters, as non-retained object do not have to be
1596released by the callee.
1597These attributes are only used by the Clang Static Analyzer.
1598
1599The family of attributes `X_returns_X_retained` can be added to functions,
1600C++ methods, and Objective-C methods and properties.
1601Attributes `X_consumed` can be added to parameters of methods, functions,
1602and Objective-C methods.)reST";
1603
1604static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1605(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1606convention (e.g. functions starting with "get" are assumed to return at
1607`+0`).
1608
1609It can be overridden using a family of the following attributes. In
1610Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1611a function communicates that the object is returned at `+1`, and the caller
1612is responsible for freeing it.
1613Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1614specifies that the object is returned at `+0` and the ownership remains with
1615the callee.
1616The annotation `__attribute__((ns_consumes_self))` specifies that
1617the Objective-C method call consumes the reference to `self`, e.g. by
1618attaching it to a supplied parameter.
1619Additionally, parameters can have an annotation
1620`__attribute__((ns_consumed))`, which specifies that passing an owned object
1621as that parameter effectively transfers the ownership, and the caller is no
1622longer responsible for it.
1623These attributes affect code generation when interacting with ARC code, and
1624they are used by the Clang Static Analyzer.
1625
1626In C programs using CoreFoundation, a similar set of attributes:
1627`__attribute__((cf_returns_not_retained))`,
1628`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1629have the same respective semantics when applied to CoreFoundation objects.
1630These attributes affect code generation when interacting with ARC code, and
1631they are used by the Clang Static Analyzer.
1632
1633(os-retained-attr-family)=
1634
1635Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1636the same attribute family is present:
1637`__attribute__((os_returns_not_retained))`,
1638`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1639with the same respective semantics.
1640Similar to `__attribute__((ns_consumes_self))`,
1641`__attribute__((os_consumes_this))` specifies that the method call consumes
1642the reference to "this" (e.g., when attaching it to a different object supplied
1643as a parameter).
1644Out parameters (parameters the function is meant to write into,
1645either via pointers-to-pointers or references-to-pointers)
1646may be annotated with `__attribute__((os_returns_retained))`
1647or `__attribute__((os_returns_not_retained))` which specifies that the object
1648written into the out parameter should (or respectively should not) be released
1649after use.
1650Since often out parameters may or may not be written depending on the exit
1651code of the function,
1652annotations `__attribute__((os_returns_retained_on_zero))`
1653and `__attribute__((os_returns_retained_on_non_zero))` specify that
1654an out parameter at `+1` is written if and only if the function returns a zero
1655(respectively non-zero) error code.
1656Observe that return-code-dependent out parameter annotations are only
1657available for retained out parameters, as non-retained object do not have to be
1658released by the callee.
1659These attributes are only used by the Clang Static Analyzer.
1660
1661The family of attributes `X_returns_X_retained` can be added to functions,
1662C++ methods, and Objective-C methods and properties.
1663Attributes `X_consumed` can be added to parameters of methods, functions,
1664and Objective-C methods.)reST";
1665
1666static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1667
1668static const char AttrDoc_CPUDispatch[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1669resolve multiversioned functions. This form of multiversioning provides a
1670mechanism for declaring versions across translation units and manually
1671specifying the resolved function list. A specified CPU defines a set of minimum
1672features that are required for the function to be called. The result of this is
1673that future processors execute the most restrictive version of the function the
1674new processor can execute.
1675
1676In addition, unlike the ICC implementation of this feature, the selection of the
1677version does not consider the manufacturer or microarchitecture of the processor.
1678It tests solely the list of features that are both supported by the specified
1679processor and present in the compiler-rt library. This can be surprising at times,
1680as the runtime processor may be from a completely different manufacturer, as long
1681as it supports the same feature set.
1682
1683This can additionally be surprising, as some processors are indistringuishable from
1684others based on the list of testable features. When this happens, the variant
1685is selected in an unspecified manner.
1686
1687Function versions are defined with `cpu_specific`, which takes one or more CPU
1688names as a parameter. For example:
1689
1690```c
1691// Declares and defines the ivybridge version of single_cpu.
1692__attribute__((cpu_specific(ivybridge)))
1693void single_cpu(void){}
1694
1695// Declares and defines the atom version of single_cpu.
1696__attribute__((cpu_specific(atom)))
1697void single_cpu(void){}
1698
1699// Declares and defines both the ivybridge and atom version of multi_cpu.
1700__attribute__((cpu_specific(ivybridge, atom)))
1701void multi_cpu(void){}
1702```
1703
1704A dispatching (or resolving) function can be declared anywhere in a project's
1705source code with `cpu_dispatch`. This attribute takes one or more CPU names
1706as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1707are not expected to be defined, only declared. If such a marked function has a
1708definition, any side effects of the function are ignored; trivial function
1709bodies are permissible for ICC compatibility.
1710
1711```c
1712// Creates a resolver for single_cpu above.
1713__attribute__((cpu_dispatch(ivybridge, atom)))
1714void single_cpu(void){}
1715
1716// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1717// translation unit.
1718__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1719void multi_cpu(void){}
1720```
1721
1722Note that it is possible to have a resolving function that dispatches based on
1723more or fewer options than are present in the program. Specifying fewer will
1724result in the omitted options not being considered during resolution. Specifying
1725a version for resolution that isn't defined in the program will result in a
1726linking failure.
1727
1728It is also possible to specify a CPU name of `generic` which will be resolved
1729if the executing processor doesn't satisfy the features required in the CPU
1730name. The behavior of a program executing on a processor that doesn't satisfy
1731any option of a multiversioned function is undefined.)reST";
1732
1733static const char AttrDoc_CPUSpecific[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1734resolve multiversioned functions. This form of multiversioning provides a
1735mechanism for declaring versions across translation units and manually
1736specifying the resolved function list. A specified CPU defines a set of minimum
1737features that are required for the function to be called. The result of this is
1738that future processors execute the most restrictive version of the function the
1739new processor can execute.
1740
1741In addition, unlike the ICC implementation of this feature, the selection of the
1742version does not consider the manufacturer or microarchitecture of the processor.
1743It tests solely the list of features that are both supported by the specified
1744processor and present in the compiler-rt library. This can be surprising at times,
1745as the runtime processor may be from a completely different manufacturer, as long
1746as it supports the same feature set.
1747
1748This can additionally be surprising, as some processors are indistringuishable from
1749others based on the list of testable features. When this happens, the variant
1750is selected in an unspecified manner.
1751
1752Function versions are defined with `cpu_specific`, which takes one or more CPU
1753names as a parameter. For example:
1754
1755```c
1756// Declares and defines the ivybridge version of single_cpu.
1757__attribute__((cpu_specific(ivybridge)))
1758void single_cpu(void){}
1759
1760// Declares and defines the atom version of single_cpu.
1761__attribute__((cpu_specific(atom)))
1762void single_cpu(void){}
1763
1764// Declares and defines both the ivybridge and atom version of multi_cpu.
1765__attribute__((cpu_specific(ivybridge, atom)))
1766void multi_cpu(void){}
1767```
1768
1769A dispatching (or resolving) function can be declared anywhere in a project's
1770source code with `cpu_dispatch`. This attribute takes one or more CPU names
1771as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1772are not expected to be defined, only declared. If such a marked function has a
1773definition, any side effects of the function are ignored; trivial function
1774bodies are permissible for ICC compatibility.
1775
1776```c
1777// Creates a resolver for single_cpu above.
1778__attribute__((cpu_dispatch(ivybridge, atom)))
1779void single_cpu(void){}
1780
1781// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1782// translation unit.
1783__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1784void multi_cpu(void){}
1785```
1786
1787Note that it is possible to have a resolving function that dispatches based on
1788more or fewer options than are present in the program. Specifying fewer will
1789result in the omitted options not being considered during resolution. Specifying
1790a version for resolution that isn't defined in the program will result in a
1791linking failure.
1792
1793It is also possible to specify a CPU name of `generic` which will be resolved
1794if the executing processor doesn't satisfy the features required in the CPU
1795name. The behavior of a program executing on a processor that doesn't satisfy
1796any option of a multiversioned function is undefined.)reST";
1797
1798static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the `cluster_dims` attribute, conventionally exposed as the
1799`__cluster_dims__` macro, can be applied to a kernel function to set the dimensions of a
1800thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1801`__cluster_dims__` defines the cluster size as `(X, Y, Z)`, where each value is the number
1802of thread blocks in that dimension. The `cluster_dims` and `no_cluster` attributes are
1803mutually exclusive.
1804
1805```
1806__global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1807 ...
1808}
1809```)reST";
1810
1811static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1812
1813static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1814
1815static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The `device_builtin_surface_type` attribute can be applied to a class
1816template when declaring the surface reference. A surface reference variable
1817could be accessed on the host side and, on the device side, might be translated
1818into an internal surface object, which is established through surface bind and
1819unbind runtime APIs.)reST";
1820
1821static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The `device_builtin_texture_type` attribute can be applied to a class
1822template when declaring the texture reference. A texture reference variable
1823could be accessed on the host side and, on the device side, might be translated
1824into an internal texture object, which is established through texture bind and
1825unbind runtime APIs.)reST";
1826
1827static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1828
1829static const char AttrDoc_CUDAGridConstant[] = R"reST(The `__grid_constant__` attribute can be applied to a `const`-qualified kernel
1830function argument and allows compiler to take the address of that argument without
1831making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1832with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1833
1834static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1835
1836static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1837
1838static const char AttrDoc_CUDALaunchBounds[] = R"reST(The `__launch_bounds__` attribute (also spelled `launch_bounds`) originates
1839in CUDA. It informs the compiler of the launch configuration a kernel will be
1840dispatched with, allowing it to optimize the kernel accordingly. It takes the
1841form `__launch_bounds__(<max-threads-per-block>[,
1842<min-blocks-per-multiprocessor>[, <max-blocks-per-cluster>]])`. All arguments
1843are constant expressions.
1844
1845The attribute only takes effect on `__global__` (kernel) functions; like
1846NVCC, Clang ignores it on any other function.
1847
1848`<max-threads-per-block>` specifies the maximum number of threads per block
1849the kernel will be launched with. `<min-blocks-per-multiprocessor>` specifies
1850the desired minimum number of blocks resident per multiprocessor, and
1851`<max-blocks-per-cluster>` the maximum number of blocks per cluster.
1852
1853For the NVPTX target, `<max-threads-per-block>` and
1854`<min-blocks-per-multiprocessor>` map to the `.maxntid` and `.minnctapersm`
1855PTX directives, respectively, and `<max-blocks-per-cluster>` (which requires
1856`sm_90` or newer) maps to `.maxclusterrank`.
1857
1858For the AMDGPU target, the attribute is translated into the equivalent AMDGPU
1859kernel attributes:
1860
1861 - `<max-threads-per-block>` sets the maximum
1862 `amdgpu_flat_work_group_size` (as `1, <max-threads-per-block>`).
1863 - `<min-blocks-per-multiprocessor>` sets the minimum
1864 `amdgpu_waves_per_eu`. Note that HIP reinterprets this CUDA argument as a
1865 minimum number of waves per execution unit, so its meaning differs from the
1866 NVPTX interpretation.
1867 - `<max-blocks-per-cluster>` is currently ignored.
1868
1869An explicit `amdgpu_flat_work_group_size` or `amdgpu_waves_per_eu` attribute
1870takes precedence over the value derived from `__launch_bounds__`.
1871
1872When the same kernel is declared multiple times, the launch bounds from the most
1873recent declaration that specifies them are used; a definition without
1874`__launch_bounds__` inherits the bounds from an earlier declaration.)reST";
1875
1876static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1877at runtime, even without being annotated with `__cluster_dims__`. The LLVM/Clang-exclusive
1878`no_cluster` attribute, conventionally exposed as the `__no_cluster__` macro, can be applied to
1879a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1880compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1881without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1882kernel annotated with `__no_cluster__` if the cluster feature is enabled at runtime.
1883The `cluster_dims` and `no_cluster` attributes are mutually exclusive.
1884
1885```
1886__global__ __no_cluster__ void kernel(...) {
1887 ...
1888}
1889```)reST";
1890
1891static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1892
1893static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as `[[noreturn]]` shall not return to its caller. The
1894compiler will generate a diagnostic for a function declared as `[[noreturn]]`
1895that appears to be capable of returning to its caller.
1896
1897The `[[_Noreturn]]` spelling is deprecated and only exists to ease code
1898migration for code using `[[noreturn]]` after including `<stdnoreturn.h>`.)reST";
1899
1900static const char AttrDoc_CXXAssume[] = R"reST(The `assume` attribute is used to indicate to the optimizer that a
1901certain condition is assumed to be true at a certain point in the
1902program. If this condition is violated at runtime, the behavior is
1903undefined. `assume` can only be applied to a null statement.
1904
1905Different optimisers are likely to react differently to the presence of
1906this attribute; in some cases, adding `assume` may affect performance
1907negatively. It should be used with parsimony and care.
1908
1909Example:
1910
1911```c++
1912int f(int x, int y) {
1913 [[assume(x == 27)]];
1914 [[assume(x == y)]];
1915 return y + 1; // May be optimised to `return 28`.
1916}
1917```)reST";
1918
1919static const char AttrDoc_CallableWhen[] = R"reST(Use `__attribute__((callable_when(...)))` to indicate what states a method
1920may be called in. Valid states are unconsumed, consumed, or unknown. Each
1921argument to this attribute must be a quoted string. E.g.:
1922
1923`__attribute__((callable_when("unconsumed", "unknown")))`)reST";
1924
1925static const char AttrDoc_Callback[] = R"reST(The `callback` attribute specifies that the annotated function may invoke the
1926specified callback zero or more times. The callback, as well as the passed
1927arguments, are identified by their parameter name or position (starting with
19281!) in the annotated function. The first position in the attribute identifies
1929the callback callee, the following positions declare describe its arguments.
1930The callback callee is required to be callable with the number, and order, of
1931the specified arguments. The index `0`, or the identifier `this`, is used to
1932represent an implicit "this" pointer in class methods. If there is no implicit
1933"this" pointer it shall not be referenced. The index `-1`, or the name `__`,
1934represents an unknown callback callee argument. This can be a value which is
1935not present in the declared parameter list, or one that is, but is potentially
1936inspected, captured, or modified. Parameter names and indices can be mixed in
1937the callback attribute.
1938
1939The `callback` attribute, which is directly translated to `callback`
1940metadata (<http://llvm.org/docs/LangRef.html#callback-metadata>), make the
1941connection between the call to the annotated function and the callback callee.
1942This can enable interprocedural optimizations which were otherwise impossible.
1943If a function parameter is mentioned in the `callback` attribute, through its
1944position, it is undefined if that parameter is used for anything other than the
1945actual callback. Inspected, captured, or modified parameters shall not be
1946listed in the `callback` metadata.
1947
1948Example encodings for the callback performed by `pthread_create` are shown
1949below. The explicit attribute annotation indicates that the third parameter
1950(`start_routine`) is called zero or more times by the `pthread_create` function,
1951and that the fourth parameter (`arg`) is passed along. Note that the callback
1952behavior of `pthread_create` is automatically recognized by Clang. In addition,
1953the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for
1954`#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
1955automatically recognized as broker functions. Further functions might be added
1956in the future.
1957
1958```c
1959__attribute__((callback (start_routine, arg)))
1960int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1961 void *(*start_routine) (void *), void *arg);
1962
1963__attribute__((callback (3, 4)))
1964int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1965 void *(*start_routine) (void *), void *arg);
1966```)reST";
1967
1968static const char AttrDoc_CalledOnce[] = R"reST(The `called_once` attribute specifies that the annotated function or method
1969parameter is invoked exactly once on all execution paths. It only applies
1970to parameters with function-like types, i.e. function pointers or blocks. This
1971concept is particularly useful for asynchronous programs.
1972
1973Clang implements a check for `called_once` parameters,
1974`-Wcalled-once-parameter`. It is on by default and finds the following
1975violations:
1976
1977- Parameter is not called at all.
1978- Parameter is called more than once.
1979- Parameter is not called on one of the execution paths.
1980
1981In the latter case, Clang pinpoints the path where parameter is not invoked
1982by showing the control-flow statement where the path diverges.
1983
1984```objc
1985void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1986 if (somePredicate()) {
1987 ...
1988 callback();
1989 } else {
1990 callback(); // OK: callback is called on every path
1991 }
1992}
1993
1994void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1995 if (somePredicate()) {
1996 ...
1997 callback(); // note: previous call is here
1998 }
1999 callback(); // warning: callback is called twice
2000}
2001
2002void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
2003 if (somePredicate()) { // warning: callback is not called when condition is false
2004 ...
2005 callback();
2006 }
2007}
2008```
2009
2010This attribute is useful for API developers who want to double-check if they
2011implemented their method correctly.)reST";
2012
2013static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
2014
2015static const char AttrDoc_CapturedRecord[] = R"reST()reST";
2016
2017static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
2018scope. The attribute takes the identifier of a function with a parameter type
2019that is a pointer to the type with the attribute.
2020
2021```c
2022static void foo (int *) { ... }
2023static void bar (int *) { ... }
2024void baz (void) {
2025 int x __attribute__((cleanup(foo)));
2026 {
2027 int y __attribute__((cleanup(bar)));
2028 }
2029}
2030```
2031
2032The above example will result in a call to `bar` being passed the address of
2033`y` when `y` goes out of scope, then a call to `foo` being passed the
2034address of `x` when `x` goes out of scope. If two or more variables share
2035the same scope, their `cleanup` callbacks are invoked in the reverse order
2036the variables were declared in. It is not possible to check the return value
2037(if any) of these `cleanup` callback functions.)reST";
2038
2039static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by [clspv][clspv] (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from [libclc][libclc] (OpenCL-C builtin library).
2040
2041```c
2042void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
2043```
2044
2045[clspv]: https://github.com/google/clspv
2046[libclc]: https://libclc.llvm.org)reST";
2047
2048static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
2049state, a call to such a function would switch from secure to non-secure state.
2050All non-secure function calls must happen only through a function pointer, and
2051a non-secure function type should only be used as a base type of a pointer.
2052See [ARMv8-M Security Extensions: Requirements on Development
2053Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2054
2055static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
2056from secure state. Entering from and returning to non-secure state would switch
2057to and from secure state, respectively, and prevent flow of information
2058to non-secure state, except via return values. See [ARMv8-M Security Extensions:
2059Requirements on Development Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2060
2061static const char AttrDoc_CodeAlign[] = R"reST(The `clang::code_align(N)` attribute applies to a loop and specifies the byte
2062alignment for a loop. The attribute accepts a positive integer constant
2063initialization expression indicating the number of bytes for the minimum
2064alignment boundary. Its value must be a power of 2, between 1 and 4096
2065(inclusive).
2066
2067```c++
2068void foo() {
2069 int var = 0;
2070 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
2071}
2072
2073void Array(int *array, size_t n) {
2074 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
2075}
2076
2077void count () {
2078 int a1[10], int i = 0;
2079 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
2080}
2081
2082void check() {
2083 int a = 10;
2084 [[clang::code_align(8)]] do {
2085 a = a + 1;
2086 } while (a < 20);
2087}
2088
2089template<int A>
2090void func() {
2091 [[clang::code_align(A)]] for(;;) { }
2092}
2093```)reST";
2094
2095static const char AttrDoc_CodeModel[] = R"reST(The `model` attribute allows overriding the translation unit's
2096code model (specified by `-mcmodel`) for a specific global variable.
2097
2098On LoongArch, allowed values are "normal", "medium", "extreme".
2099
2100On x86-64, allowed values are `"small"` and `"large"`. `"small"` is
2101roughly equivalent to `-mcmodel=small`, meaning the global is considered
2102"small" placed closer to the `.text` section relative to "large" globals, and
2103to prefer using 32-bit relocations to access the global. `"large"` is roughly
2104equivalent to `-mcmodel=large`, meaning the global is considered "large" and
2105placed further from the `.text` section relative to "small" globals, and
210664-bit relocations must be used to access the global.)reST";
2107
2108static const char AttrDoc_CodeSeg[] = R"reST(The `__declspec(code_seg)` attribute enables the placement of code into separate
2109named segments that can be paged or locked in memory individually. This attribute
2110is used to control the placement of instantiated templates and compiler-generated
2111code. See the documentation for [`__declspec(code_seg)`][__declspec(code_seg)] on MSDN.
2112
2113[__declspec(code_seg)]: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
2114
2115static const char AttrDoc_Cold[] = R"reST(`__attribute__((cold))` marks a function as cold, as a manual alternative to PGO hotness data.
2116If PGO data is available, the profile count based hotness overrides the `__attribute__((cold))` annotation (unlike `__attribute__((hot))`).)reST";
2117
2118static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
2119
2120static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
2121
2122static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
2123to have a [*constant initializer*](http://en.cppreference.com/w/cpp/language/constant_initialization)
2124according to the rules of [basic.start.static]. The variable is required to
2125have static or thread storage duration. If the initialization of the variable
2126is not a constant initializer an error will be produced. This attribute may
2127only be used in C++; the `constinit` spelling is only accepted in C++20
2128onwards.
2129
2130Note that in C++03 strict constant expression checking is not done. Instead
2131the attribute reports if Clang can emit the variable as a constant, even if it's
2132not technically a *constant initializer*. This behavior is non-portable.
2133
2134Static storage duration variables with constant initializers avoid hard-to-find
2135bugs caused by the indeterminate order of dynamic initialization. They can also
2136be safely used during dynamic initialization across translation units.
2137
2138This attribute acts as a compile time assertion that the requirements
2139for constant initialization have been met. Since these requirements change
2140between dialects and have subtle pitfalls it's important to fail fast instead
2141of silently falling back on dynamic initialization.
2142
2143The first use of the attribute on a variable must be part of, or precede, the
2144initializing declaration of the variable. C++20 requires the `constinit`
2145spelling of the attribute to be present on the initializing declaration if it
2146is used anywhere. The other spellings can be specified on a forward declaration
2147and omitted on a later initializing declaration.
2148
2149```c++
2150// -std=c++14
2151#define SAFE_STATIC [[clang::require_constant_initialization]]
2152struct T {
2153 constexpr T(int) {}
2154 ~T(); // non-trivial
2155};
2156SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2157SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2158// copy initialization is not a constant expression on a non-literal type.
2159```)reST";
2160
2161static const char AttrDoc_Constructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2162`main()`, and the `destructor` attribute causes the function to be called
2163after returning from `main()` or when the `exit()` function has been
2164called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2165marked `destructor` from being called.
2166
2167The constructor or destructor function should not accept any arguments and its
2168return type should be `void`.
2169
2170The attributes accept an optional argument used to specify the priority order
2171in which to execute constructor and destructor functions. The priority is
2172given as an integer constant expression between 101 and 65535 (inclusive).
2173Priorities outside of that range are reserved for use by the implementation. A
2174lower value indicates a higher priority of initialization. Note that only the
2175relative ordering of values is important. For example:
2176
2177```c++
2178__attribute__((constructor(200))) void foo(void);
2179__attribute__((constructor(101))) void bar(void);
2180```
2181
2182`bar()` will be called before `foo()`, and both will be called before
2183`main()`. If no argument is given to the `constructor` or `destructor`
2184attribute, they default to the value `65535`.)reST";
2185
2186static const char AttrDoc_Consumable[] = R"reST(Each `class` that uses any of the typestate annotations must first be marked
2187using the `consumable` attribute. Failure to do so will result in a warning.
2188
2189This attribute accepts a single parameter that must be one of the following:
2190`unknown`, `consumed`, or `unconsumed`.)reST";
2191
2192static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2193
2194static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2195
2196static const char AttrDoc_Convergent[] = R"reST(The `convergent` attribute can be placed on a function declaration. It is
2197translated into the LLVM `convergent` attribute, which indicates that the call
2198instructions of a function with this attribute cannot be made control-dependent
2199on any additional values.
2200
2201This attribute is different from `noduplicate` because it allows duplicating
2202function calls if it can be proved that the duplicated function calls are
2203not made control-dependent on any additional values, e.g., unrolling a loop
2204executed by all work items.
2205
2206Sample usage:
2207
2208```c
2209void convfunc(void) __attribute__((convergent));
2210// Setting it as a C++11 attribute is also valid in a C++ program.
2211// void convfunc(void) [[clang::convergent]];
2212```)reST";
2213
2214static const char AttrDoc_CoroAwaitElidable[] = R"reST(The `[[clang::coro_await_elidable]]` is a class attribute which can be
2215applied to a coroutine return type. It provides a hint to the compiler to apply
2216Heap Allocation Elision more aggressively.
2217
2218When a coroutine function returns such a type, a direct call expression therein
2219that returns a prvalue of a type attributed `[[clang::coro_await_elidable]]`
2220is said to be under a safe elide context if one of the following is true:
2221
2222- it is the immediate right-hand side operand to a co_await expression.
2223- it is an argument to a `[[clang::coro_await_elidable_argument]]` parameter
2224 or parameter pack of another direct call expression under a safe elide context.
2225
2226Do note that the safe elide context applies only to the call expression itself,
2227and the context does not transitively include any of its subexpressions unless
2228exceptional rules of `[[clang::coro_await_elidable_argument]]` apply.
2229
2230The compiler performs heap allocation elision on call expressions under a safe
2231elide context, if the callee is a coroutine.
2232
2233Example:
2234
2235```c++
2236class [[clang::coro_await_elidable]] Task { ... };
2237
2238Task foo();
2239Task bar() {
2240 co_await foo(); // foo()'s coroutine frame on this line is elidable
2241 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2242 co_await t;
2243}
2244```
2245
2246Such elision replaces the heap allocated activation frame of the callee coroutine
2247with a local variable within the enclosing braces in the caller's stack frame.
2248The local variable, like other variables in coroutines, may be collected into the
2249coroutine frame, which may be allocated on the heap. The behavior is undefined
2250if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2251
2252static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The `[[clang::coro_await_elidable_argument]]` is a function parameter attribute.
2253It works in conjunction with `[[clang::coro_await_elidable]]` to propagate a
2254safe elide context to a parameter or parameter pack if the function is called
2255under a safe elide context.
2256
2257This is sometimes necessary on utility functions used to compose or modify the
2258behavior of a callee coroutine.
2259
2260Example:
2261
2262```c++
2263template <typename T>
2264class [[clang::coro_await_elidable]] Task { ... };
2265
2266template <typename... T>
2267class [[clang::coro_await_elidable]] WhenAll { ... };
2268
2269// `when_all` is a utility function that composes coroutines. It does not
2270// need to be a coroutine to propagate.
2271template <typename... T>
2272WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2273
2274Task<int> foo();
2275Task<int> bar();
2276Task<void> example1() {
2277 // `when_all`, `foo`, and `bar` are all elide safe because `when_all` is
2278 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2279 // attribute, such context is propagated to foo and bar.
2280 co_await when_all(foo(), bar());
2281}
2282
2283Task<void> example2() {
2284 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2285 auto f = foo();
2286 co_await when_all(f, bar());
2287}
2288
2289
2290Task<void> example3() {
2291 // None of the calls are elide safe.
2292 auto t = when_all(foo(), bar());
2293 co_await t;
2294}
2295```)reST";
2296
2297static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2298to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2299it should also be annotated with `[[clang::coro_return_type]]`).
2300
2301All parameters of a function are considered to be lifetime bound if the function returns a
2302coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2303This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2304with `[[clang::coro_disable_lifetimebound]]` function attribute .
2305See documentation of [lifetimebound] for details about lifetime bound analysis.
2306
2307Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2308
2309For example,
2310
2311```c++
2312task<int> coro(const int& a) { co_return a + 1; }
2313task<int> dangling_refs(int a) {
2314 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2315 auto foo = coro(1);
2316 // `coro` captures reference to local variable `a` which is destroyed after the return.
2317 return coro(a);
2318}
2319```
2320
2321Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2322which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2323`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2324temporaries or return address of a local variable.
2325
2326Both coroutines and coroutine wrappers are part of this analysis.
2327
2328```c++
2329template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2330 using promise_type = some_promise_type;
2331};
2332
2333Task<int> coro(const int& a) { co_return a + 1; }
2334[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2335 return a > b ? coro(a) : coro(b);
2336}
2337Task<int> temporary_reference() {
2338 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2339
2340 int a = 1;
2341 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2342
2343 co_return co_await coro(1); // fine.
2344}
2345[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2346 return coro(a); // warning: returning address of stack variable `a`.
2347}
2348```
2349
2350This analysis can be disabled for all calls to a particular function by annotating the function
2351with function attribute `[[clang::coro_disable_lifetimebound]]`.
2352For example, this could be useful for coroutine wrappers which accept reference parameters
2353but do not pass them to the underlying coroutine or pass them by value.
2354
2355```c++
2356Task<int> coro(int a) { co_return a + 1; }
2357[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2358 return coro(a + 1);
2359}
2360void use() {
2361 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2362}
2363```)reST";
2364
2365static const char AttrDoc_CoroLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2366to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2367it should also be annotated with `[[clang::coro_return_type]]`).
2368
2369All parameters of a function are considered to be lifetime bound if the function returns a
2370coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2371This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2372with `[[clang::coro_disable_lifetimebound]]` function attribute .
2373See documentation of [lifetimebound] for details about lifetime bound analysis.
2374
2375Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2376
2377For example,
2378
2379```c++
2380task<int> coro(const int& a) { co_return a + 1; }
2381task<int> dangling_refs(int a) {
2382 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2383 auto foo = coro(1);
2384 // `coro` captures reference to local variable `a` which is destroyed after the return.
2385 return coro(a);
2386}
2387```
2388
2389Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2390which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2391`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2392temporaries or return address of a local variable.
2393
2394Both coroutines and coroutine wrappers are part of this analysis.
2395
2396```c++
2397template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2398 using promise_type = some_promise_type;
2399};
2400
2401Task<int> coro(const int& a) { co_return a + 1; }
2402[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2403 return a > b ? coro(a) : coro(b);
2404}
2405Task<int> temporary_reference() {
2406 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2407
2408 int a = 1;
2409 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2410
2411 co_return co_await coro(1); // fine.
2412}
2413[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2414 return coro(a); // warning: returning address of stack variable `a`.
2415}
2416```
2417
2418This analysis can be disabled for all calls to a particular function by annotating the function
2419with function attribute `[[clang::coro_disable_lifetimebound]]`.
2420For example, this could be useful for coroutine wrappers which accept reference parameters
2421but do not pass them to the underlying coroutine or pass them by value.
2422
2423```c++
2424Task<int> coro(int a) { co_return a + 1; }
2425[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2426 return coro(a + 1);
2427}
2428void use() {
2429 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2430}
2431```)reST";
2432
2433static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2434whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2435reached the final suspend point.
2436
2437This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2438
2439For example,
2440
2441```c++
2442A foo() {
2443 dtor d;
2444 co_await something();
2445 dtor d1;
2446 co_await something();
2447 dtor d2;
2448 co_return 43;
2449}
2450```
2451
2452The compiler may generate the following pseudocode:
2453
2454```c++
2455void foo.destroy(foo.Frame *frame) {
2456 switch(frame->suspend_index()) {
2457 case 1:
2458 frame->d.~dtor();
2459 break;
2460 case 2:
2461 frame->d.~dtor();
2462 frame->d1.~dtor();
2463 break;
2464 case 3:
2465 frame->d.~dtor();
2466 frame->d1.~dtor();
2467 frame->d2.~dtor();
2468 break;
2469 default: // coroutine completed or haven't started
2470 break;
2471 }
2472
2473 frame->promise.~promise_type();
2474 delete frame;
2475}
2476```
2477
2478The `foo.destroy()` function's purpose is to release all of the resources
2479initialized for the coroutine when it is destroyed in a suspended state.
2480However, if the coroutine is only ever destroyed at the final suspend state,
2481the rest of the conditions are superfluous.
2482
2483The user can use the `coro_only_destroy_when_complete` attributo suppress
2484generation of the other destruction cases, optimizing the above `foo.destroy` to:
2485
2486```c++
2487void foo.destroy(foo.Frame *frame) {
2488 frame->promise.~promise_type();
2489 delete frame;
2490}
2491```)reST";
2492
2493static const char AttrDoc_CoroReturnType[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2494coroutines from the function signatures.
2495
2496The `coro_return_type` attribute should be marked on a C++ class to mark it as
2497a **coroutine return type (CRT)**.
2498
2499A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2500is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2501(i.e., `std::coroutine_traits<R, P1, .., PN>::promise_type` is a valid promise type).
2502
2503If the return type of a function is a `CRT` then the function must be a coroutine.
2504Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2505if the function is marked with `[[clang::coro_wrapper]]`.
2506
2507The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2508a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2509is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2510
2511Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2512with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2513
2514From a language perspective, it is not possible to differentiate between a coroutine and a
2515function returning a CRT by merely looking at the function signature.
2516
2517Coroutine wrappers, in particular, are susceptible to capturing
2518references to temporaries and other lifetime issues. This allows to avoid such lifetime
2519issues with coroutine wrappers.
2520
2521For example,
2522
2523```c++
2524// This is a CRT.
2525template <typename T> struct [[clang::coro_return_type]] Task {
2526 using promise_type = some_promise_type;
2527};
2528
2529Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2530Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2531
2532// Fine for a coroutine wrapper to return a CRT.
2533[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2534
2535void bar() {
2536 // Invalid. This intantiates a function which returns a CRT but is not marked as
2537 // a coroutine wrapper.
2538 std::function<Task<int>(int)> f = increment;
2539}
2540```
2541
2542Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2543implementation detail of any coroutine library.)reST";
2544
2545static const char AttrDoc_CoroWrapper[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2546coroutines from the function signatures.
2547
2548The `coro_return_type` attribute should be marked on a C++ class to mark it as
2549a **coroutine return type (CRT)**.
2550
2551A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2552is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2553(i.e., `std::coroutine_traits<R, P1, .., PN>::promise_type` is a valid promise type).
2554
2555If the return type of a function is a `CRT` then the function must be a coroutine.
2556Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2557if the function is marked with `[[clang::coro_wrapper]]`.
2558
2559The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2560a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2561is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2562
2563Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2564with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2565
2566From a language perspective, it is not possible to differentiate between a coroutine and a
2567function returning a CRT by merely looking at the function signature.
2568
2569Coroutine wrappers, in particular, are susceptible to capturing
2570references to temporaries and other lifetime issues. This allows to avoid such lifetime
2571issues with coroutine wrappers.
2572
2573For example,
2574
2575```c++
2576// This is a CRT.
2577template <typename T> struct [[clang::coro_return_type]] Task {
2578 using promise_type = some_promise_type;
2579};
2580
2581Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2582Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2583
2584// Fine for a coroutine wrapper to return a CRT.
2585[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2586
2587void bar() {
2588 // Invalid. This intantiates a function which returns a CRT but is not marked as
2589 // a coroutine wrapper.
2590 std::function<Task<int>(int)> f = increment;
2591}
2592```
2593
2594Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2595implementation detail of any coroutine library.)reST";
2596
2597static const char AttrDoc_CountedBy[] = R"reST(The `counted_by` attribute is applied to a pointer or flexible array member to
2598indicate that the pointer points to (or the flexible array member contains) at
2599least the number of *elements* given by the attribute's argument.
2600
2601This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
2602bounds information on API surfaces without any ABI changes. This attribute is
2603also used to improve the results of the array bound sanitizer and the
2604`__builtin_dynamic_object_size` builtin.
2605
2606Because the size of the pointee type must be known to compute the pointer's
2607bounds, such a pointer must not be used while its pointee type is incomplete; a
2608pointer to a forward-declared type is accepted on fields annotated with
2609`counted_by`, but the type must be completed before the pointer is used. If
2610the pointee type can never be completed, `counted_by` is rejected and
2611`sized_by` should be used instead. `void *` is a special case: as a GNU
2612extension (diagnosed by `-Wgnu-pointer-arith`), `counted_by` is accepted on
2613it, where it behaves like `sized_by` (the argument is treated as a byte count,
2614`void` having an assumed size of one byte).
2615
2616A pointer annotated with `counted_by` must have a count of zero when it is
2617null. This requirement is currently only enforced when compiling with
2618{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
2619-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
2620`counted_by_or_null` for a pointer that may be null while carrying a nonzero
2621count.
2622
2623#### Keeping pointer and count in sync
2624
2625The `counted_by` attribute establishes a relationship between the annotated
2626pointer and its count: the pointer must point to at least `count` elements.
2627Assigning to only one of them can break this relationship.
2628Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
2629responsibility to ensure the pointer and count remain in sync. With
2630`-fbounds-safety` it is automatically enforced. For example:
2631
2632```c
2633struct buffer {
2634 int *buf __attribute__((counted_by(count)));
2635 size_t count;
2636};
2637
2638void grow(struct buffer *b, size_t new_count) {
2639 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
2640 // smaller than new_count which would contradict the counted_by attribute.
2641 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
2642 b->count = new_count;
2643}
2644```
2645
2646Updating both together - so that `buf` points to `count` elements - keeps
2647the attribute true. For example:
2648
2649```c
2650void grow(struct buffer *b, size_t new_count) {
2651 // Allowed by -fbounds-safety
2652 int *new_buf = malloc(new_count * sizeof(int));
2653 // -fbounds-safety enforces that the `new_buf` points to at least `new_count`
2654 // integers at runtime. Without -fbounds-safety nothing enforces this.
2655 b->buf = new_buf;
2656 b->count = new_count;
2657}
2658```
2659
2660#### Flexible array members
2661
2662The `counted_by` attribute may also be applied to the flexible array member of
2663a structure in C. In this case the argument names the field member holding the
2664count of elements in the flexible array; that field must be within the same
2665non-anonymous, enclosing struct as the flexible array member.
2666
2667This example specifies that the flexible array member `array` has the number
2668of elements allocated for it in `count`:
2669
2670```c
2671struct bar;
2672
2673struct foo {
2674 size_t count;
2675 char other;
2676 struct bar *array[] __attribute__((counted_by(count)));
2677};
2678```
2679
2680This establishes a relationship between `array` and `count`. Specifically,
2681`array` must have at least `count` number of elements available. It's the
2682user's responsibility to ensure that this relationship is maintained through
2683changes to the structure.
2684
2685In the following example, the allocated array erroneously has fewer elements
2686than what's specified by `p->count`. This would result in an out-of-bounds
2687access not being detected.
2688
2689```c
2690#define SIZE_INCR 42
2691
2692struct foo *p;
2693
2694void foo_alloc(size_t count) {
2695 p = malloc(MAX(sizeof(struct foo),
2696 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2697 p->count = count + SIZE_INCR;
2698}
2699```
2700
2701The next example updates `p->count`, but breaks the relationship requirement
2702that `p->array` must have at least `p->count` number of elements available:
2703
2704```c
2705#define SIZE_INCR 42
2706
2707struct foo *p;
2708
2709void foo_alloc(size_t count) {
2710 p = malloc(MAX(sizeof(struct foo),
2711 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2712 p->count = count;
2713}
2714
2715void use_foo(int index, int val) {
2716 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2717 p->array[index] = val; /* The sanitizer can't properly check this access. */
2718}
2719```
2720
2721In this example, an update to `p->count` maintains the relationship
2722requirement:
2723
2724```c
2725void use_foo(int index, int val) {
2726 if (p->count == 0)
2727 return;
2728 --p->count;
2729 p->array[index] = val;
2730}
2731```)reST";
2732
2733static const char AttrDoc_CountedByOrNull[] = R"reST(The `counted_by_or_null` attribute is applied to a pointer to indicate that,
2734if the pointer is non-null, it points to memory containing at least the number
2735of *elements* given by the attribute's argument. If the pointer is null, the
2736value of the argument is ignored and the pointer points to zero elements.
2737
2738The `counted_by_or_null` attribute is identical to `counted_by` except that
2739it treats null pointers differently and cannot be applied to a flexible array
2740member. Whereas `counted_by` requires a null pointer to have a count of zero,
2741`counted_by_or_null` allows the pointer to be null regardless of the value of
2742the count. This supports the common idiom where a pointer is either null or
2743points to memory containing at least the given number of elements.
2744
2745Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
2746distinction between `counted_by_or_null` and `counted_by` (see
2747{ref}`Current status of -fbounds-safety support in upstream Clang
2748<bounds-safety-current-upstream-status>`).)reST";
2749
2750static const char AttrDoc_DLLExport[] = R"reST(The `__declspec(dllexport)` attribute declares a variable, function, or
2751Objective-C interface to be exported from the module. It is available under the
2752`-fdeclspec` flag for compatibility with various compilers. The primary use
2753is for COFF object files which explicitly specify what interfaces are available
2754for external use. See the [dllexport][dllexport] documentation on MSDN for more
2755information.
2756
2757[dllexport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2758
2759static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2760
2761static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2762
2763static const char AttrDoc_DLLImport[] = R"reST(The `__declspec(dllimport)` attribute declares a variable, function, or
2764Objective-C interface to be imported from an external module. It is available
2765under the `-fdeclspec` flag for compatibility with various compilers. The
2766primary use is for COFF object files which explicitly specify what interfaces
2767are imported from external modules. See the [dllimport][dllimport] documentation on MSDN
2768for more information.
2769
2770Note that a dllimport function may still be inlined, if its definition is
2771available and it doesn't reference any non-dllimport functions or global
2772variables.
2773
2774[dllimport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2775
2776static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2777
2778static const char AttrDoc_Deprecated[] = R"reST(The `deprecated` attribute can be applied to a function, a variable, or a
2779type. This is useful when identifying functions, variables, or types that are
2780expected to be removed in a future version of a program.
2781
2782Consider the function declaration for a hypothetical function `f`:
2783
2784```c++
2785void f(void) __attribute__((deprecated("message", "replacement")));
2786```
2787
2788When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
2789two optional string arguments. The first one is the message to display when
2790emitting the warning; the second one enables the compiler to provide a Fix-It
2791to replace the deprecated name with a new name. Otherwise, when spelled as
2792`[[gnu::deprecated]]` or `[[deprecated]]`, the attribute can have one optional
2793string argument which is the message to display when emitting the warning.)reST";
2794
2795static const char AttrDoc_Destructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2796`main()`, and the `destructor` attribute causes the function to be called
2797after returning from `main()` or when the `exit()` function has been
2798called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2799marked `destructor` from being called.
2800
2801The constructor or destructor function should not accept any arguments and its
2802return type should be `void`.
2803
2804The attributes accept an optional argument used to specify the priority order
2805in which to execute constructor and destructor functions. The priority is
2806given as an integer constant expression between 101 and 65535 (inclusive).
2807Priorities outside of that range are reserved for use by the implementation. A
2808lower value indicates a higher priority of initialization. Note that only the
2809relative ordering of values is important. For example:
2810
2811```c++
2812__attribute__((constructor(200))) void foo(void);
2813__attribute__((constructor(101))) void bar(void);
2814```
2815
2816`bar()` will be called before `foo()`, and both will be called before
2817`main()`. If no argument is given to the `constructor` or `destructor`
2818attribute, they default to the value `65535`.)reST";
2819
2820static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2821The specific semantics depend on the offloading language, target, and attribute spelling.
2822Here is a code example using the attribute to mark a function as a kernel:
2823
2824```c++
2825[[clang::device_kernel]] int foo(int x) { return ++x; }
2826```)reST";
2827
2828static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The `diagnose_as_builtin` attribute indicates that Fortify diagnostics are to
2829be applied to the declared function as if it were the function specified by the
2830attribute. The builtin function whose diagnostics are to be mimicked should be
2831given. In addition, the order in which arguments should be applied must also
2832be given.
2833
2834For example, the attribute can be used as follows.
2835
2836```c
2837__attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2838void *mymemset(int n, int c, void *s) {
2839 // ...
2840}
2841```
2842
2843This indicates that calls to `mymemset` should be diagnosed as if they were
2844calls to `__builtin_memset`. The arguments `3, 2, 1` indicate by index the
2845order in which arguments of `mymemset` should be applied to
2846`__builtin_memset`. The third argument should be applied first, then the
2847second, and then the first. Thus (when Fortify warnings are enabled) the call
2848`mymemset(n, c, s)` will diagnose overflows as if it were the call
2849`__builtin_memset(s, c, n)`.
2850
2851For variadic functions, the variadic arguments must come in the same order as
2852they would to the builtin function, after all normal arguments. For instance,
2853to diagnose a new function as if it were `sscanf`, we can use the attribute as
2854follows.
2855
2856```c
2857__attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2858int mysscanf(const char *str, const char *format, ...) {
2859 // ...
2860}
2861```
2862
2863Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2864if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2865
2866This attribute cannot be applied to non-static member functions.)reST";
2867
2868static const char AttrDoc_DiagnoseIf[] = R"reST(The `diagnose_if` attribute can be placed on function declarations to emit
2869warnings or errors at compile-time if calls to the attributed function meet
2870certain user-defined criteria. For example:
2871
2872```c
2873int abs(int a)
2874 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2875int must_abs(int a)
2876 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2877
2878int val = abs(1); // warning: Redundant abs call
2879int val2 = must_abs(1); // error: Redundant abs call
2880int val3 = abs(val);
2881int val4 = must_abs(val); // Because run-time checks are not emitted for
2882 // diagnose_if attributes, this executes without
2883 // issue.
2884```
2885
2886`diagnose_if` is closely related to `enable_if`, with a few key differences:
2887
2888- Overload resolution is not aware of `diagnose_if` attributes: they're
2889 considered only after we select the best candidate from a given candidate set.
2890- Function declarations that differ only in their `diagnose_if` attributes are
2891 considered to be redeclarations of the same function (not overloads).
2892- If the condition provided to `diagnose_if` cannot be evaluated, no
2893 diagnostic will be emitted.
2894
2895Otherwise, `diagnose_if` is essentially the logical negation of `enable_if`.
2896
2897As a result of bullet number two, `diagnose_if` attributes will stack on the
2898same function. For example:
2899
2900```c
2901int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2902int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2903
2904int bar = foo(); // warning: diag1
2905 // warning: diag2
2906int (*fooptr)(void) = foo; // warning: diag1
2907 // warning: diag2
2908
2909constexpr int supportsAPILevel(int N) { return N < 5; }
2910int baz(int a)
2911 __attribute__((diagnose_if(!supportsAPILevel(10),
2912 "Upgrade to API level 10 to use baz", "error")));
2913int baz(int a)
2914 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2915
2916int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2917int v = baz(0); // error: Upgrade to API level 10 to use baz
2918```
2919
2920Query for this feature with `__has_attribute(diagnose_if)`.)reST";
2921
2922static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the `disable_sanitizer_instrumentation` attribute on a function,
2923Objective-C method, or global variable, to specify that no sanitizer
2924instrumentation should be applied.
2925
2926This is not the same as `__attribute__((no_sanitize(...)))`, which depending
2927on the tool may still insert instrumentation to prevent false positive reports.)reST";
2928
2929static const char AttrDoc_DisableTailCalls[] = R"reST(The `disable_tail_calls` attribute instructs the backend to not perform tail
2930call optimization inside the marked function.
2931
2932For example:
2933
2934```c
2935int callee(int);
2936
2937int foo(int a) __attribute__((disable_tail_calls)) {
2938 return callee(a); // This call is not tail-call optimized.
2939}
2940```
2941
2942Marking virtual functions as `disable_tail_calls` is legal.
2943
2944```c++
2945int callee(int);
2946
2947class Base {
2948public:
2949 [[clang::disable_tail_calls]] virtual int foo1() {
2950 return callee(); // This call is not tail-call optimized.
2951 }
2952};
2953
2954class Derived1 : public Base {
2955public:
2956 int foo1() override {
2957 return callee(); // This call is tail-call optimized.
2958 }
2959};
2960```)reST";
2961
2962static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2963empty-base-optimization more frequently.
2964This attribute only applies to struct, class, and union types.
2965It is only supported when using the Microsoft C++ ABI.)reST";
2966
2967static const char AttrDoc_EnableIf[] = R"reST(:::{Note}
2968Some features of this attribute are experimental. The meaning of
2969multiple enable_if attributes on a single declaration is subject to change in
2970a future version of clang. Also, the ABI is not standardized and the name
2971mangling may change in future versions. To avoid that, use asm labels.
2972:::
2973
2974The `enable_if` attribute can be placed on function declarations to control
2975which overload is selected based on the values of the function's arguments.
2976When combined with the `overloadable` attribute, this feature is also
2977available in C.
2978
2979```c++
2980int isdigit(int c);
2981int isdigit(int c)
2982 __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range")))
2983 __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
2984
2985void foo(char c) {
2986 isdigit(c);
2987 isdigit(10);
2988 isdigit(-10); // results in a compile-time error.
2989}
2990```
2991
2992The enable_if attribute takes two arguments, the first is an expression written
2993in terms of the function parameters, the second is a string explaining why this
2994overload candidate could not be selected to be displayed in diagnostics. The
2995expression is part of the function signature for the purposes of determining
2996whether it is a redeclaration (following the rules used when determining
2997whether a C++ template specialization is ODR-equivalent), but is not part of
2998the type.
2999
3000The enable_if expression is evaluated as if it were the body of a
3001bool-returning constexpr function declared with the arguments of the function
3002it is being applied to, then called with the parameters at the call site. If the
3003result is false or could not be determined through constant expression
3004evaluation, then this overload will not be chosen and the provided string may
3005be used in a diagnostic if the compile fails as a result.
3006
3007Because the enable_if expression is an unevaluated context, there are no global
3008state changes, nor the ability to pass information from the enable_if
3009expression to the function body. For example, suppose we want calls to
3010strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
3011strbuf) only if the size of strbuf can be determined:
3012
3013```c++
3014__attribute__((always_inline))
3015static inline size_t strnlen(const char *s, size_t maxlen)
3016 __attribute__((overloadable))
3017 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
3018 "chosen when the buffer size is known but 'maxlen' is not")))
3019{
3020 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
3021}
3022```
3023
3024Multiple enable_if attributes may be applied to a single declaration. In this
3025case, the enable_if expressions are evaluated from left to right in the
3026following manner. First, the candidates whose enable_if expressions evaluate to
3027false or cannot be evaluated are discarded. If the remaining candidates do not
3028share ODR-equivalent enable_if expressions, the overload resolution is
3029ambiguous. Otherwise, enable_if overload resolution continues with the next
3030enable_if attribute on the candidates that have not been discarded and have
3031remaining enable_if attributes. In this way, we pick the most specific
3032overload out of a number of viable overloads using enable_if.
3033
3034```c++
3035void f() __attribute__((enable_if(true, ""))); // #1
3036void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
3037
3038void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
3039void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
3040```
3041
3042In this example, a call to f() is always resolved to #2, as the first enable_if
3043expression is ODR-equivalent for both declarations, but #1 does not have another
3044enable_if expression to continue evaluating, so the next round of evaluation has
3045only a single candidate. In a call to g(1, 1), the call is ambiguous even though
3046#2 has more enable_if attributes, because the first enable_if expressions are
3047not ODR-equivalent.
3048
3049Query for this feature with `__has_attribute(enable_if)`.
3050
3051Note that functions with one or more `enable_if` attributes may not have
3052their address taken, unless all of the conditions specified by said
3053`enable_if` are constants that evaluate to `true`. For example:
3054
3055```c
3056const int TrueConstant = 1;
3057const int FalseConstant = 0;
3058int f(int a) __attribute__((enable_if(a > 0, "")));
3059int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
3060int h(int a) __attribute__((enable_if(1, "")));
3061int i(int a) __attribute__((enable_if(TrueConstant, "")));
3062int j(int a) __attribute__((enable_if(FalseConstant, "")));
3063
3064void fn() {
3065 int (*ptr)(int);
3066 ptr = &f; // error: 'a > 0' is not always true
3067 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
3068 ptr = &h; // OK: 1 is a truthy constant
3069 ptr = &i; // OK: 'TrueConstant' is a truthy constant
3070 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
3071}
3072```
3073
3074Because `enable_if` evaluation happens during overload resolution,
3075`enable_if` may give unintuitive results when used with templates, depending
3076on when overloads are resolved. In the example below, clang will emit a
3077diagnostic about no viable overloads for `foo` in `bar`, but not in `baz`:
3078
3079```c++
3080double foo(int i) __attribute__((enable_if(i > 0, "")));
3081void *foo(int i) __attribute__((enable_if(i <= 0, "")));
3082template <int I>
3083auto bar() { return foo(I); }
3084
3085template <typename T>
3086auto baz() { return foo(T::number); }
3087
3088struct WithNumber { constexpr static int number = 1; };
3089void callThem() {
3090 bar<sizeof(WithNumber)>();
3091 baz<WithNumber>();
3092}
3093```
3094
3095This is because, in `bar`, `foo` is resolved prior to template
3096instantiation, so the value for `I` isn't known (thus, both `enable_if`
3097conditions for `foo` fail). However, in `baz`, `foo` is resolved during
3098template instantiation, so the value for `T::number` is known.)reST";
3099
3100static const char AttrDoc_EnforceTCB[] = R"reST(The `enforce_tcb` attribute can be placed on functions to enforce that a
3101trusted compute base (TCB) does not call out of the TCB. This generates a
3102warning every time a function not marked with an `enforce_tcb` attribute is
3103called from a function with the `enforce_tcb` attribute. A function may be a
3104part of multiple TCBs. Invocations through function pointers are currently
3105not checked. Builtins are considered to a part of every TCB.
3106
3107- `enforce_tcb(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3108
3109static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The `enforce_tcb_leaf` attribute satisfies the requirement enforced by
3110`enforce_tcb` for the marked function to be in the named TCB but does not
3111continue to check the functions called from within the leaf function.
3112
3113- `enforce_tcb_leaf(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3114
3115static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute `enum_extensibility` is used to distinguish between enum definitions
3116that are extensible and those that are not. The attribute can take either
3117`closed` or `open` as an argument. `closed` indicates a variable of the
3118enum type takes a value that corresponds to one of the enumerators listed in the
3119enum definition or, when the enum is annotated with `flag_enum`, a value that
3120can be constructed using values corresponding to the enumerators. `open`
3121indicates a variable of the enum type can take any values allowed by the
3122standard and instructs clang to be more lenient when issuing warnings.
3123
3124```c
3125enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3126 A0, A1
3127};
3128
3129enum __attribute__((enum_extensibility(open))) OpenEnum {
3130 B0, B1
3131};
3132
3133enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3134 C0 = 1 << 0, C1 = 1 << 1
3135};
3136
3137enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3138 D0 = 1 << 0, D1 = 1 << 1
3139};
3140
3141void foo1() {
3142 enum ClosedEnum ce;
3143 enum OpenEnum oe;
3144 enum ClosedFlagEnum cfe;
3145 enum OpenFlagEnum ofe;
3146
3147 ce = A1; // no warnings
3148 ce = 100; // warning issued
3149 oe = B1; // no warnings
3150 oe = 100; // no warnings
3151 cfe = C0 | C1; // no warnings
3152 cfe = C0 | C1 | 4; // warning issued
3153 ofe = D0 | D1; // no warnings
3154 ofe = D0 | D1 | 4; // no warnings
3155}
3156```)reST";
3157
3158static const char AttrDoc_Error[] = R"reST(The `error` and `warning` function attributes can be used to specify a
3159custom diagnostic to be emitted when a call to such a function is not
3160eliminated via optimizations. This can be used to create compile time
3161assertions that depend on optimizations, while providing diagnostics
3162pointing to precise locations of the call site in the source.
3163
3164```c++
3165__attribute__((warning("oh no"))) void dontcall();
3166void foo() {
3167 if (someCompileTimeAssertionThatsTrue)
3168 dontcall(); // Warning
3169
3170 dontcall(); // Warning
3171
3172 if (someCompileTimeAssertionThatsFalse)
3173 dontcall(); // No Warning
3174 sizeof(dontcall()); // No Warning
3175}
3176```
3177
3178When the call occurs through inlined functions, the
3179`-fdiagnostics-show-inlining-chain` option can be used to show the
3180inlining chain that led to the call. This helps identify which call site
3181triggered the diagnostic when the attributed function is called from
3182multiple locations through inline functions.
3183
3184When enabled, this option automatically uses debug info for accurate source
3185locations if available (`-gline-directives-only` (implicitly enabled at
3186`-g1`) or higher), or falls back to a heuristic based on metadata tracking.
3187When falling back, a note is emitted suggesting `-gline-directives-only` for
3188more accurate locations.)reST";
3189
3190static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The `exclude_from_explicit_instantiation` attribute opts-out a member of a
3191class template from being part of explicit template instantiations of that
3192class template. This means that an explicit instantiation will not instantiate
3193members of the class template marked with the attribute, but also that code
3194where an extern template declaration of the enclosing class template is visible
3195will not take for granted that an external instantiation of the class template
3196would provide those members (which would otherwise be a link error, since the
3197explicit instantiation won't provide those members). For example, let's say we
3198don't want the `data()` method to be part of libc++'s ABI. To make sure it
3199is not exported from the dylib, we give it hidden visibility:
3200
3201```c++
3202// in <string>
3203template <class CharT>
3204class basic_string {
3205public:
3206 __attribute__((__visibility__("hidden")))
3207 const value_type* data() const noexcept { ... }
3208};
3209
3210template class basic_string<char>;
3211```
3212
3213Since an explicit template instantiation declaration for `basic_string<char>`
3214is provided, the compiler is free to assume that `basic_string<char>::data()`
3215will be provided by another translation unit, and it is free to produce an
3216external call to this function. However, since `data()` has hidden visibility
3217and the explicit template instantiation is provided in a shared library (as
3218opposed to simply another translation unit), `basic_string<char>::data()`
3219won't be found and a link error will ensue. This happens because the compiler
3220assumes that `basic_string<char>::data()` is part of the explicit template
3221instantiation declaration, when it really isn't. To tell the compiler that
3222`data()` is not part of the explicit template instantiation declaration, the
3223`exclude_from_explicit_instantiation` attribute can be used:
3224
3225```c++
3226// in <string>
3227template <class CharT>
3228class basic_string {
3229public:
3230 __attribute__((__visibility__("hidden")))
3231 __attribute__((exclude_from_explicit_instantiation))
3232 const value_type* data() const noexcept { ... }
3233};
3234
3235template class basic_string<char>;
3236```
3237
3238Now, the compiler won't assume that `basic_string<char>::data()` is provided
3239externally despite there being an explicit template instantiation declaration:
3240the compiler will implicitly instantiate `basic_string<char>::data()` in the
3241TUs where it is used.
3242
3243This attribute can be used on static and non-static member functions of class
3244templates, static data members of class templates and member classes of class
3245templates.
3246
3247**Interaction with `__declspec(dllexport)` and `__declspec(dllimport)`**
3248
3249For a DLL platform (i.e., Windows), this attribute also means "this member will
3250never be exported or imported". Despite its name, this semantics applies to
3251implicit instantiations and non-template entities as well.
3252
3253```c++
3254// in <exception>
3255class __declspec(dllimport) nested_exception {
3256 ...
3257public:
3258 __attribute__((exclude_from_explicit_instantiation))
3259 exception_ptr nested_ptr() const noexcept { ... }
3260};
3261```
3262
3263In this case, `nested_exception::nested_ptr` will never be attempted to be
3264imported.)reST";
3265
3266static const char AttrDoc_ExplicitInit[] = R"reST(The `clang::require_explicit_initialization` attribute indicates that a
3267field of an aggregate must be initialized explicitly by the user when an object
3268of the aggregate type is constructed. The attribute supports both C and C++,
3269but its usage is invalid on non-aggregates.
3270
3271Note that this attribute is *not* a memory safety feature, and is *not* intended
3272to guard against use of uninitialized memory.
3273
3274Rather, it is intended for use in "parameter-objects", used to simulate,
3275for example, the passing of named parameters.
3276Except inside unevaluated contexts, the attribute generates a warning when
3277explicit initializers for such variables are not provided (this occurs
3278regardless of whether any in-class field initializers exist):
3279
3280```c++
3281struct Buffer {
3282 void *address [[clang::require_explicit_initialization]];
3283 size_t length [[clang::require_explicit_initialization]] = 0;
3284};
3285
3286struct ArrayIOParams {
3287 size_t count [[clang::require_explicit_initialization]];
3288 size_t element_size [[clang::require_explicit_initialization]];
3289 int flags = 0;
3290};
3291
3292size_t ReadArray(FILE *file, struct Buffer buffer,
3293 struct ArrayIOParams params);
3294
3295int main() {
3296 unsigned int buf[512];
3297 ReadArray(stdin, {
3298 buf
3299 // warning: field 'length' is not explicitly initialized
3300 }, {
3301 .count = sizeof(buf) / sizeof(*buf),
3302 // warning: field 'element_size' is not explicitly initialized
3303 // (Note that a missing initializer for 'flags' is not diagnosed, because
3304 // the field is not marked as requiring explicit initialization.)
3305 });
3306}
3307```)reST";
3308
3309static const char AttrDoc_ExtVectorType[] = R"reST(The `ext_vector_type(N)` attribute specifies that a type is a vector with N
3310elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3311allows element access the array subscript operator `[]`, `sN` where N is
3312a hexadecimal value, or `x, y, z, w` for graphics-style indexing.
3313This attribute enables efficient SIMD operations and is usable in
3314general-purpose code.
3315
3316```c++
3317template <typename T, uint32_t N>
3318constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3319 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3320 if constexpr (N == 1)
3321 return v[0];
3322 else
3323 return simd_reduce<T, N / 2>(v.hi + v.lo);
3324}
3325```
3326
3327The vector type also supports swizzling up to sixteen elements. This can be done
3328using the object accessors. The OpenCL documentation lists all of the accepted
3329values.
3330
3331```c++
3332using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3333
3334f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3335```
3336
3337See the OpenCL documentation for some more complete examples.)reST";
3338
3339static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The `external_source_symbol` attribute specifies that a declaration originates
3340from an external source and describes the nature of that source.
3341
3342The fact that Clang is capable of recognizing declarations that were defined
3343externally can be used to provide better tooling support for mixed-language
3344projects or projects that rely on auto-generated code. For instance, an IDE that
3345uses Clang and that supports mixed-language projects can use this attribute to
3346provide a correct "jump-to-definition" feature. For a concrete example,
3347consider a protocol that's defined in a Swift file:
3348
3349```swift
3350@objc public protocol SwiftProtocol {
3351 func method()
3352}
3353```
3354
3355This protocol can be used from Objective-C code by including a header file that
3356was generated by the Swift compiler. The declarations in that header can use
3357the `external_source_symbol` attribute to make Clang aware of the fact
3358that `SwiftProtocol` actually originates from a Swift module:
3359
3360```objc
3361__attribute__((external_source_symbol(language="Swift",defined_in="module")))
3362@protocol SwiftProtocol
3363@required
3364- (void) method;
3365@end
3366```
3367
3368Consequently, when "jump-to-definition" is performed at a location that
3369references `SwiftProtocol`, the IDE can jump to the original definition in
3370the Swift source file rather than jumping to the Objective-C declaration in the
3371auto-generated header file.
3372
3373The `external_source_symbol` attribute is a comma-separated list that includes
3374clauses that describe the origin and the nature of the particular declaration.
3375Those clauses can be:
3376
3377language=*string-literal*
3378
3379: The name of the source language in which this declaration was defined.
3380
3381defined_in=*string-literal*
3382
3383: The name of the source container in which the declaration was defined. The
3384 exact definition of source container is language-specific, e.g. Swift's
3385 source containers are modules, so `defined_in` should specify the Swift
3386 module name.
3387
3388USR=*string-literal*
3389
3390: String that specifies a unified symbol resolution (USR) value for this
3391 declaration. USR string uniquely identifies this particular declaration, and
3392 is typically used when constructing an index of a codebase.
3393 The USR value in this attribute is expected to be generated by an external
3394 compiler that compiled the native declaration using its original source
3395 language. The exact format of the USR string and its other attributes
3396 are determined by the specification of this declaration's source language.
3397 When not specified, Clang's indexer will use the Clang USR for this symbol.
3398 User can query to see if Clang supports the use of the `USR` clause in
3399 the `external_source_symbol` attribute with
3400 `__has_attribute(external_source_symbol) >= 20230206`.
3401
3402generated_declaration
3403
3404: This declaration was automatically generated by some tool.
3405
3406The clauses can be specified in any order. The clauses that are listed above are
3407all optional, but the attribute has to have at least one clause.)reST";
3408
3409static const char AttrDoc_FallThrough[] = R"reST(The `fallthrough` (or `clang::fallthrough`) attribute is used
3410to annotate intentional fall-through
3411between switch labels. It can only be applied to a null statement placed at a
3412point of execution between any statement and the next switch label. It is
3413common to mark these places with a specific comment, but this attribute is
3414meant to replace comments with a more strict annotation, which can be checked
3415by the compiler. This attribute doesn't change semantics of the code and can
3416be used wherever an intended fall-through occurs. It is designed to mimic
3417control-flow statements like `break;`, so it can be placed in most places
3418where `break;` can, but only if there are no statements on the execution path
3419between it and the next switch label.
3420
3421By default, Clang does not warn on unannotated fallthrough from one `switch`
3422case to another. Diagnostics on fallthrough without a corresponding annotation
3423can be enabled with the `-Wimplicit-fallthrough` argument.
3424
3425Here is an example:
3426
3427```c++
3428// compile with -Wimplicit-fallthrough
3429switch (n) {
3430case 22:
3431case 33: // no warning: no statements between case labels
3432 f();
3433case 44: // warning: unannotated fall-through
3434 g();
3435 [[clang::fallthrough]];
3436case 55: // no warning
3437 if (x) {
3438 h();
3439 break;
3440 }
3441 else {
3442 i();
3443 [[clang::fallthrough]];
3444 }
3445case 66: // no warning
3446 p();
3447 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3448 // directly precede case label
3449 q();
3450case 77: // warning: unannotated fall-through
3451 r();
3452}
3453```)reST";
3454
3455static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3456function to use ECX and EDX as register parameters and clear parameters off of
3457the stack on return. This convention does not support variadic calls or
3458unprototyped functions in C, and has no effect on x86_64 targets. This calling
3459convention is supported primarily for compatibility with existing code. Users
3460seeking register parameters should use the `regparm` attribute, which does
3461not require callee-cleanup. See the documentation for [`__fastcall`][__fastcall] on MSDN.
3462
3463[__fastcall]: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3464
3465static const char AttrDoc_Final[] = R"reST()reST";
3466
3467static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3468is intended to be used as a flag type. This will cause the compiler to assume
3469that the range of the type includes all of the values that you can get by
3470manipulating bits of the enumerator when issuing warnings.)reST";
3471
3472static const char AttrDoc_Flatten[] = R"reST(The `flatten` attribute causes calls within the attributed function to
3473be inlined unless it is impossible to do so, for example if the body of the
3474callee is unavailable or if the callee has the `noinline` attribute.)reST";
3475
3476static const char AttrDoc_Format[] = R"reST(Clang supports the `format` attribute, which indicates that the function
3477accepts (among other possibilities) a `printf` or `scanf`-like format string
3478and corresponding arguments or a `va_list` that contains these arguments.
3479
3480Please see [GCC documentation about format attribute](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) to find details
3481about attribute syntax.
3482
3483Clang implements two kinds of checks with this attribute.
3484
34851. Clang checks that the function with the `format` attribute is called with
3486 a format string that uses format specifiers that are allowed, and that
3487 arguments match the format string. This is the `-Wformat` warning, it is
3488 on by default.
3489
34902. Clang checks that the format string argument is a literal string. This is
3491 the `-Wformat-nonliteral` warning, it is off by default.
3492
3493 Clang implements this mostly the same way as GCC, but there is a difference
3494 for functions that accept a `va_list` argument (for example, `vprintf`).
3495 GCC does not emit `-Wformat-nonliteral` warning for calls to such
3496 functions. Clang does not warn if the format string comes from a function
3497 parameter, where the function is annotated with a compatible attribute,
3498 otherwise it warns. For example:
3499
3500 ```c
3501 __attribute__((__format__ (__scanf__, 1, 3)))
3502 void foo(const char* s, char *buf, ...) {
3503 va_list ap;
3504 va_start(ap, buf);
3505
3506 vprintf(s, ap); // warning: format string is not a string literal
3507 }
3508 ```
3509
3510 In this case we warn because `s` contains a format string for a
3511 `scanf`-like function, but it is passed to a `printf`-like function.
3512
3513 If the attribute is removed, clang still warns, because the format string is
3514 not a string literal.
3515
3516 Another example:
3517
3518 ```c
3519 __attribute__((__format__ (__printf__, 1, 3)))
3520 void foo(const char* s, char *buf, ...) {
3521 va_list ap;
3522 va_start(ap, buf);
3523
3524 vprintf(s, ap); // warning
3525 }
3526 ```
3527
3528 In this case Clang does not warn because the format string `s` and
3529 the corresponding arguments are annotated. If the arguments are
3530 incorrect, the caller of `foo` will receive a warning.
3531
3532As an extension to GCC's behavior, Clang accepts the `format` attribute on
3533non-variadic functions. Clang checks non-variadic format functions for the same
3534classes of issues that can be found on variadic functions, as controlled by the
3535same warning flags, except that the types of formatted arguments is forced by
3536the function signature. For example:
3537
3538```c
3539__attribute__((__format__(__printf__, 1, 2)))
3540void fmt(const char *s, const char *a, int b);
3541
3542void bar(void) {
3543 fmt("%s %i", "hello", 123); // OK
3544 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3545 extern const char *fmt;
3546 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3547}
3548```
3549
3550When using the format attribute on a variadic function, the first data parameter
3551must be the index of the ellipsis in the parameter list. Clang will generate
3552a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3553to `printf`-family functions. For instance, this is an error:
3554
3555```c
3556__attribute__((__format__(__printf__, 1, 2)))
3557void fmt(const char *s, int b, ...);
3558// ^ error: format attribute parameter 3 is out of bounds
3559// (must be __printf__, 1, 3)
3560```
3561
3562Using the `format` attribute on a non-variadic function emits a GCC
3563compatibility diagnostic.)reST";
3564
3565static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3566
3567static const char AttrDoc_FormatMatches[] = R"reST(The `format` attribute is the basis for the enforcement of diagnostics in the
3568`-Wformat` family, but it only handles the case where the format string is
3569passed along with the arguments it is going to format. It cannot handle the case
3570where the format string and the format arguments are passed separately from each
3571other. For instance:
3572
3573```c
3574static const char *first_name;
3575static double todays_temperature;
3576static int wind_speed;
3577
3578void say_hi(const char *fmt) {
3579 printf(fmt, first_name, todays_temperature);
3580 // ^ warning: format string is not a string literal
3581 printf(fmt, first_name, wind_speed);
3582 // ^ warning: format string is not a string literal
3583}
3584
3585int main() {
3586 say_hi("hello %s, it is %g degrees outside");
3587 say_hi("hello %s, it is %d degrees outside!");
3588 // ^ no diagnostic, but %d cannot format doubles
3589}
3590```
3591
3592In this example, `fmt` is expected to format a `const char *` and a
3593`double`, but these values are not passed to `say_hi`. Without the
3594`format` attribute (which cannot apply in this case), the -Wformat-nonliteral
3595diagnostic unnecessarily triggers in the body of `say_hi`, and incorrect
3596`say_hi` call sites do not trigger a diagnostic.
3597
3598To complement the `format` attribute, Clang also defines the
3599`format_matches` attribute. Its syntax is similar to the `format`
3600attribute's, but instead of taking the index of the first formatted value
3601argument, it takes a C string literal with the expected specifiers:
3602
3603```c
3604static const char *first_name;
3605static double todays_temperature;
3606static int wind_speed;
3607
3608__attribute__((__format_matches__(printf, 1, "%s %g")))
3609void say_hi(const char *fmt) {
3610 printf(fmt, first_name, todays_temperature); // no dignostic
3611 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3612}
3613
3614int main() {
3615 say_hi("hello %s, it is %g degrees outside");
3616 say_hi("it is %g degrees outside, have a good day %s!");
3617 // warning: format specifies 'double' where 'const char *' is required
3618 // warning: format specifies 'const char *' where 'double' is required
3619}
3620```
3621
3622The third argument to `format_matches` is expected to evaluate to a **C string
3623literal** even when the format string would normally be a different type for the
3624given flavor, like a `CFStringRef` or a `NSString *`.
3625
3626The only requirement on the format string literal is that it has specifiers
3627that are compatible with the arguments that will be used. It can contain
3628arbitrary non-format characters. For instance, for the purposes of compile-time
3629validation, `"%s scored %g%% on her test"` and `"%s%g"` are interchangeable
3630as the format string argument. As a means of self-documentation, users may
3631prefer the former when it provides a useful example of an expected format
3632string.
3633
3634In the implementation of a function with the `format_matches` attribute,
3635format verification works as if the format string was identical to the one
3636specified in the attribute.
3637
3638```c
3639__attribute__((__format_matches__(printf, 1, "%s %g")))
3640void say_hi(const char *fmt) {
3641 printf(fmt, "person", 546);
3642 // ^ warning: format specifies type 'double' but the
3643 // argument has type 'int'
3644 // note: format string is defined here:
3645 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3646 // ^~
3647}
3648```
3649
3650At the call sites of functions with the `format_matches` attribute, format
3651verification instead compares the two format strings to evaluate their
3652equivalence. Each format flavor defines equivalence between format specifiers.
3653Generally speaking, two specifiers are equivalent if they format the same type.
3654For instance, in the `printf` flavor, `%2i` and `%-0.5d` are compatible.
3655When `-Wformat-signedness` is disabled, `%d` and `%u` are compatible. For
3656a negative example, `%ld` is incompatible with `%d`.
3657
3658Do note the following un-obvious cases:
3659
3660- Passing `NULL` as the format string does not trigger format diagnostics.
3661- When the format string is not NULL, it cannot miss specifiers, even in
3662 trailing positions. For instance, `%d` is not accepted when the required
3663 format is `%d %d %d`.
3664- While checks for the `format` attribute tolerate sone size mismatches
3665 that standard argument promotion renders immaterial (such as formatting an
3666 `int` with `%hhd`, which specifies a `char`-sized integer), checks for
3667 `format_matches` require specified argument sizes to match exactly.
3668- Format strings expecting a variable modifier (such as `%*s`) are
3669 incompatible with format strings that would itemize the variable modifiers
3670 (such as `%i %s`), even if the two specify ABI-compatible argument lists.
3671- All pointer specifiers, modifiers aside, are mutually incompatible. For
3672 instance, `%s` is not compatible with `%p`, and `%p` is not compatible
3673 with `%n`, and `%hhn` is incompatible with `%s`, even if the pointers
3674 are ABI-compatible or identical on the selected platform. However, `%0.5s`
3675 is compatible with `%s`, since the difference only exists in modifier flags.
3676 This is not overridable with `-Wformat-pedantic` or its inverse, which
3677 control similar behavior in `-Wformat`.
3678
3679At this time, clang implements `format_matches` only for format types in the
3680`printf` family. This includes variants such as Apple's NSString format and
3681the FreeBSD `kprintf`, but excludes `scanf`. Using a known but unsupported
3682format silently fails in order to be compatible with other implementations that
3683would support these formats.)reST";
3684
3685static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute `function_return` can replace return instructions with jumps to
3686target-specific symbols. This attribute supports 2 possible values,
3687corresponding to the values supported by the `-mfunction-return=` command
3688line flag:
3689
3690- `__attribute__((function_return("keep")))` to disable related transforms.
3691 This is useful for undoing global setting from `-mfunction-return=` locally
3692 for individual functions.
3693- `__attribute__((function_return("thunk-extern")))` to replace returns with
3694 jumps, while NOT emitting the thunk.
3695
3696The values `thunk` and `thunk-inline` from GCC are not supported.
3697
3698The symbol used for `thunk-extern` is target specific:
3699
3700- X86: `__x86_return_thunk`
3701
3702As such, this function attribute is currently only supported on X86 targets.)reST";
3703
3704static const char AttrDoc_GCCStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
3705special record layout compatibility mode which mimics the layout of Microsoft or
3706Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3707requested ABI, the attribute does nothing. However, if it does not, annotated
3708structure or class is laid out in a special compatibility mode, which slightly
3709changes offsets for fields and bit-fields. The intention is to match the layout
3710of the requested ABI for structures which only use C features.
3711
3712Note that the default behavior can be controlled by `-mms-bitfields` and
3713`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
3714
3715The primary difference is for bitfields, where the MS variant only packs
3716adjacent fields into the same allocation unit if they have integral types
3717of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3718tightly.)reST";
3719
3720static const char AttrDoc_GNUInline[] = R"reST(The `gnu_inline` changes the meaning of `extern inline` to use GNU inline
3721semantics, meaning:
3722
3723- If any declaration that is declared `inline` is not declared `extern`,
3724 then the `inline` keyword is just a hint. In particular, an out-of-line
3725 definition is still emitted for a function with external linkage, even if all
3726 call sites are inlined, unlike in C99 and C++ inline semantics.
3727- If all declarations that are declared `inline` are also declared
3728 `extern`, then the function body is present only for inlining and no
3729 out-of-line version is emitted.
3730
3731Some important consequences: `static inline` emits an out-of-line
3732version if needed, a plain `inline` definition emits an out-of-line version
3733always, and an `extern inline` definition (in a header) followed by a
3734(non-`extern`) `inline` declaration in a source file emits an out-of-line
3735version of the function in that source file but provides the function body for
3736inlining to all includers of the header.
3737
3738Either `__GNUC_GNU_INLINE__` (GNU inline semantics) or
3739`__GNUC_STDC_INLINE__` (C99 semantics) will be defined (they are mutually
3740exclusive). If `__GNUC_STDC_INLINE__` is defined, then the `gnu_inline`
3741function attribute can be used to get GNU inline semantics on a per function
3742basis. If `__GNUC_GNU_INLINE__` is defined, then the translation unit is
3743already being compiled with GNU inline semantics as the implied default. It is
3744unspecified which macro is defined in a C++ compilation.
3745
3746GNU inline semantics are the default behavior with `-std=gnu89`,
3747`-std=c89`, `-fgnu89-inline`, or `-std=iso9899:199409`.)reST";
3748
3749static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3750
3751static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3752
3753static const char AttrDoc_HIPManaged[] = R"reST(The `__managed__` attribute can be applied to a global variable declaration in HIP.
3754A managed variable is emitted as an undefined global symbol in the device binary and is
3755registered by `__hipRegisterManagedVar` in init functions. The HIP runtime allocates
3756managed memory and uses it to define the symbol when loading the device binary.
3757A managed variable can be accessed in both device and host code.)reST";
3758
3759static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3760
3761static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3762
3763static const char AttrDoc_HLSLColumnMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3764of an HLSL matrix type.
3765
3766- `row_major`: Matrices are stored in memory row-by-row.
3767- `column_major`: Matrices are stored in memory column-by-column (default).
3768
3769Example:
3770
3771```hlsl
3772row_major float2x2 myMatrix;
3773```)reST";
3774
3775static const char AttrDoc_HLSLContainedType[] = R"reST(The `hlsl::contained_type` attribute specifies the type of the HLSL resource
3776represented by a member variable of type `__hlsl_resource_t`.
3777
3778This attribute is only valid for resource handles, and is an implementation
3779detail of clang's HLSL implementation. For more information see
3780{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3781
3782static const char AttrDoc_HLSLControlFlowHint[] = R"reST(The `branch` and `flatten` attributes can be applied to *if* and *switch*
3783statements in the HLSL language mode to provide hints for how the backend
3784should execute them.
3785
3786- `branch` means that control flow is preferred. The condition should be
3787 evaluated first and we should only execute the block guarded by it.
3788
3789- `flatten` means that control flow should be avoided. All blocks should be
3790 executed and variables that are modified should be conditionally assigned.
3791
3792These control flow hints are preserved through the compilation and emitted in a
3793backend-specific way.
3794
3795For details, see the Direct3D documentation for [if Statement][if Statement]
3796and [switch Statement][switch Statement].
3797
3798[if Statement]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-if
3799[switch Statement]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switch)reST";
3800
3801static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3802HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3803and so on to ensure the correct ordering of reads and writes to shared memory
3804in the shader and to avoid data races.
3805Here's an example to declare a groupshared variable.
3806
3807```c++
3808groupshared GSData data[5*5*1];
3809```
3810
3811The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared>)reST";
3812
3813static const char AttrDoc_HLSLInterpolationModifier[] = R"reST(The HLSL keywords `nointerpolation`, `linear`, `centroid`,
3814`noperspective`, `sample`, and `center` control interpolation of pixel
3815shader inputs and vertex shader outputs.
3816
3817When applied to an aggregate type, the modifier propagates recursively to every
3818scalar or vector of the type. A modifier on an inner field overrides one
3819inherited from an enclosing declaration.
3820
3821`nointerpolation` cannot be combined with another interpolation modifier.
3822For pixel shader inputs and vertex shader outputs, it cannot be used on
3823`SV_Position`. Integer, boolean, and 64-bit floating-point components only
3824support `nointerpolation`.
3825
3826Unqualified pixel shader inputs and vertex shader outputs default to `linear`
3827for floating-point components of at most 32 bits and `nointerpolation` otherwise.
3828`SV_Position` uses the corresponding `noperspective` mode. Vertex shader inputs,
3829pixel shader outputs, and signatures in other shader stages have no
3830interpolation mode; their interpolation modifiers are ignored.)reST";
3831
3832static const char AttrDoc_HLSLIsArray[] = R"reST(The `hlsl::is_array` attribute specifies that the HLSL resource represented
3833by a member variable of type `__hlsl_resource_t` has array dimensions.
3834
3835This attribute is only valid for resource handles, and is an implementation
3836detail of clang's HLSL implementation. For more information see
3837{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3838
3839static const char AttrDoc_HLSLIsCounter[] = R"reST(The `hlsl::is_counter` attribute specifies that the HLSL resource represented
3840by a member variable of type `__hlsl_resource_t` is a counter buffer.
3841
3842This attribute is only valid for resource handles, and is an implementation
3843detail of clang's HLSL implementation. For more information see
3844{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3845
3846static const char AttrDoc_HLSLIsMultiSampled[] = R"reST(The `hlsl::is_array` attribute specifies that the HLSL resource represented
3847by a member variable of type `__hlsl_resource_t` is multisampled.
3848
3849This attribute is only valid for resource handles, and is an implementation
3850detail of clang's HLSL implementation. For more information see
3851{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3852
3853static const char AttrDoc_HLSLIsROV[] = R"reST(The `hlsl::is_rov` attribute specifies that the HLSL resource represented by
3854a member variable of type `__hlsl_resource_t` is a rasterizer ordered view.
3855
3856This attribute is only valid for resource handles, and is an implementation
3857detail of clang's HLSL implementation. For more information see
3858{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3859
3860static const char AttrDoc_HLSLLoopHint[] = R"reST(The `[loop]` directive allows loop optimization hints to be
3861specified for the subsequent loop. The directive allows unrolling to
3862be disabled and is not compatible with `[unroll(x)]`.
3863
3864Specifying the parameter, `[loop]`, directs the
3865unroller to not unroll the loop.
3866
3867```hlsl
3868[loop]
3869for (...) {
3870 ...
3871}
3872```
3873
3874```hlsl
3875[loop]
3876while (...) {
3877 ...
3878}
3879```
3880
3881```hlsl
3882[loop]
3883do {
3884 ...
3885} while (...)
3886```
3887
3888See [hlsl loop extensions](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for)
3889for details.)reST";
3890
3891static const char AttrDoc_HLSLNumThreads[] = R"reST(The `numthreads` attribute applies to HLSL shaders where explcit thread counts
3892are required. The `X`, `Y`, and `Z` values provided to the attribute
3893dictate the thread id. Total number of threads executed is `X * Y * Z`.
3894
3895The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads>)reST";
3896
3897static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3898Attribute spelling in HLSL is: `packoffset( c[Subcomponent][.component] )`.
3899A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3900
3901Examples:
3902
3903```hlsl
3904cbuffer A {
3905 float3 a : packoffset(c0.y);
3906 float4 b : packoffset(c4);
3907}
3908```
3909
3910The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset>)reST";
3911
3912static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3913three qualifiers to denote parameter passing behavior. The three qualifiers are
3914`in`, `out` and `inout`.
3915
3916Parameters annotated with `in` or with no annotation are passed by value from
3917the caller to the callee.
3918
3919Parameters annotated with `out` are written to the argument after the callee
3920returns (Note: arguments values passed into `out` parameters *are not* copied
3921into the callee).
3922
3923Parameters annotated with `inout` are copied into the callee via a temporary,
3924and copied back to the argument after the callee returns.)reST";
3925
3926static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3927
3928static const char AttrDoc_HLSLRawBuffer[] = R"reST(The `hlsl::raw_buffer` attribute specifies that the HLSL resource represented
3929by a member variable of type `__hlsl_resource_t` has raw buffer semantics.
3930
3931This attribute is only valid for resource handles, and is an implementation
3932detail of clang's HLSL implementation. For more information see
3933{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3934
3935static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3936Attribute spelling in HLSL is: `register(slot [, space])`.
3937`slot` takes the format `[type][number]`,
3938where `type` is a single character specifying the resource type and `number` is the virtual register number.
3939
3940Register types are:
3941t for shader resource views (SRV),
3942s for samplers,
3943u for unordered access views (UAV),
3944b for constant buffer views (CBV).
3945
3946Register space is specified in the format `space[number]` and defaults to `space0` if omitted.
3947Here're resource binding examples with and without space:
3948
3949```hlsl
3950RWBuffer<float> Uav : register(u3, space1);
3951Buffer<float> Buf : register(t1);
3952```
3953
3954The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl>)reST";
3955
3956static const char AttrDoc_HLSLResourceClass[] = R"reST(The `hlsl::resource_class` attribute specifies the resource class of the HLSL
3957resource represented by a member variable of type `__hlsl_resource_t`,
3958declaring it to be an SRV, UAV, CBuffer, or Sampler resource.
3959
3960This attribute is only valid for resource handles, and is an implementation
3961detail of clang's HLSL implementation. For more information see
3962{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3963
3964static const char AttrDoc_HLSLResourceDimension[] = R"reST(The `hlsl::dimension` attribute specifies the dimensions of the HLSL resource
3965represented by a member variable of type `__hlsl_resource_t`, declaring the
3966resource to have Unknown, 1D, 2D, 3D, or Cube dimension.
3967
3968This attribute is only valid for resource handles, and is an implementation
3969detail of clang's HLSL implementation. For more information see
3970{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3971
3972static const char AttrDoc_HLSLRowMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3973of an HLSL matrix type.
3974
3975- `row_major`: Matrices are stored in memory row-by-row.
3976- `column_major`: Matrices are stored in memory column-by-column (default).
3977
3978Example:
3979
3980```hlsl
3981row_major float2x2 myMatrix;
3982```)reST";
3983
3984static const char AttrDoc_HLSLShader[] = R"reST(The `shader` type attribute applies to HLSL shader entry functions to
3985identify the shader type for the entry function.
3986The syntax is:
3987
3988```text
3989[shader(string-literal)]
3990```
3991
3992where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3993"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3994"miss", "callable", "mesh", "amplification". Normally the shader type is set
3995by shader target with the `-T` option like `-Tps_6_1`. When compiling to a
3996library target like `lib_6_3`, the shader type attribute can help the
3997compiler to identify the shader type. It is mostly used by Raytracing shaders
3998where shaders must be compiled into a library and linked at runtime.)reST";
3999
4000static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
4001
4002static const char AttrDoc_HLSLVkBinding[] = R"reST(The `[[vk::binding]]` attribute allows you to explicitly specify the descriptor
4003set and binding for a resource when targeting SPIR-V. This is particularly
4004useful when you need different bindings for SPIR-V and DXIL, as the `register`
4005attribute can be used for DXIL-specific bindings.
4006
4007The attribute takes two integer arguments: the binding and the descriptor set.
4008The descriptor set is optional and defaults to 0 if not provided.
4009
4010```c++
4011// A structured buffer with binding 23 in descriptor set 102.
4012[[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
4013
4014// A structured buffer with binding 14 in descriptor set 0.
4015[[vk::binding(14)]] StructuredBuffer<float> Buf2;
4016
4017// A cbuffer with binding 1 in descriptor set 2.
4018[[vk::binding(1, 2)]] cbuffer MyCBuffer {
4019 float4x4 worldViewProj;
4020};
4021```)reST";
4022
4023static const char AttrDoc_HLSLVkConstantId[] = R"reST(The `vk::constant_id` attribute specifies the id for a SPIR-V specialization
4024constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
4025In SPIR-V, the
4026variable will be replaced with an `OpSpecConstant` with the given id.
4027The syntax is:
4028
4029```text
4030[[vk::constant_id(<Id>)]] const T Name = <Init>
4031```)reST";
4032
4033static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
4034initialized by the driver/pipeline, but each copy is private to the current
4035lane.
4036
4037Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
4038like follows:
4039
4040```c++
4041[[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
4042static const uint3 groupid;
4043```
4044
4045This variable will be lowered into a module-level variable, with the `Input`
4046storage class, and the `BuiltIn 26` decoration.
4047
4048The full documentation for this inline SPIR-V attribute can be found here:
4049<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4050
4051static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
4052visible to the driver/pipeline, but each copy is private to the current
4053lane.
4054
4055Those builtins can be declared using the `[[vk::ext_builtin_output]]`
4056attribute like follows:
4057
4058```c++
4059[[vk::ext_builtin_output(/* Position */ 0)]]
4060static float4 position;
4061```
4062
4063This variable will be lowered into a module-level variable, with the `Output`
4064storage class, and the `BuiltIn 0` decoration.
4065
4066The full documentation for this inline SPIR-V attribute can be found here:
4067<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4068
4069static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
4070variables. Allowed on function parameters, function returns, and struct
4071fields. This parameter has no effect when used outside of an entrypoint
4072parameter/parameter field/return value.
4073
4074This attribute maps to the `Location` SPIR-V decoration.)reST";
4075
4076static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
4077
4078The `[[vk::push_constant]]` attribute allows you to declare this
4079global variable as a push constant when targeting Vulkan.
4080This attribute is ignored otherwise.
4081
4082This attribute must be applied to the variable, not underlying type.
4083The variable type must be a struct, per the requirements of Vulkan, "there
4084must be no more than one push constant block statically used per shader entry
4085point.")reST";
4086
4087static const char AttrDoc_HLSLWaveSize[] = R"reST(The `WaveSize` attribute specifies a wave size on a shader entry point in order
4088to indicate either that a shader depends on or strongly prefers a specific wave
4089size.
4090There're 2 versions of the attribute: `WaveSize` and `RangedWaveSize`.
4091The syntax for `WaveSize` is:
4092
4093```text
4094[WaveSize(<numLanes>)]
4095```
4096
4097The allowed wave sizes that an HLSL shader may specify are the powers of 2
4098between 4 and 128, inclusive.
4099In other words, the set: [4, 8, 16, 32, 64, 128].
4100
4101The syntax for `RangedWaveSize` is:
4102
4103```text
4104[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]
4105```
4106
4107Where minWaveSize is the minimum wave size supported by the shader representing
4108the beginning of the allowed range, maxWaveSize is the maximum wave size
4109supported by the shader representing the end of the allowed range, and
4110prefWaveSize is the optional preferred wave size representing the size expected
4111to be the most optimal for this shader.
4112
4113`WaveSize` is available for HLSL shader model 6.6 and later.
4114`RangedWaveSize` available for HLSL shader model 6.8 and later.
4115
4116The full documentation is available here: <https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html>
4117and <https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html>)reST";
4118
4119static const char AttrDoc_Hot[] = R"reST(`__attribute__((hot))` marks a function as hot, as a manual alternative to PGO hotness data.
4120If PGO data is available, the annotation `__attribute__((hot))` overrides the profile count based hotness (unlike `__attribute__((cold))`).)reST";
4121
4122static const char AttrDoc_HybridPatchable[] = R"reST(The `hybrid_patchable` attribute declares an ARM64EC function with an additional
4123x86-64 thunk, which may be patched at runtime.
4124
4125For more information see
4126[ARM64EC ABI documentation](https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi).)reST";
4127
4128static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
4129
4130static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
4131
4132static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
4133
4134static const char AttrDoc_IFunc[] = R"reST(`__attribute__((ifunc("resolver")))` is used to mark that the address of a
4135declaration should be resolved at runtime by calling a resolver function.
4136
4137The symbol name of the resolver function is given in quotes. A function with
4138this name (after mangling) must be defined in the current translation unit; it
4139may be `static`. The resolver function should return a pointer.
4140
4141The `ifunc` attribute may only be used on a function declaration. A function
4142declaration with an `ifunc` attribute is considered to be a definition of the
4143declared entity. The entity must not have weak linkage; for example, in C++,
4144it cannot be applied to a declaration if a definition at that location would be
4145considered inline.
4146
4147Not all targets support this attribute:
4148
4149- ELF target support depends on both the linker and runtime linker, and is
4150 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
4151 v2.11.1 and later, and FreeBSD 9.1 and later.
4152- Mach-O targets support it, but with slightly different semantics: the resolver
4153 is run at first call, instead of at load time by the runtime linker.
4154- Windows target supports it on AArch64, but with different semantics: the
4155 `ifunc` is replaced with a global function pointer, and the call is replaced
4156 with an indirect call. The function pointer is initialized by a constructor
4157 that calls the resolver.
4158- Baremetal target supports it on AVR.
4159- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
4160 regular function (has an entry point `.foo[PR]` and a function descriptor
4161 `foo[DS]`). The entry point is a stub that branches to the function address
4162 in the descriptor, and the descriptor is initialized via a constructor
4163 function (`__init_ifuncs`) that is linked into every shared object and
4164 executable. `__init_ifuncs` calls the resolver of each ifunc and stores the
4165 result in the corresponding descriptor.
4166- Other targets currently do not support this attribute.)reST";
4167
4168static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
4169
4170static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
4171units is unspecified, unlike the ordering within a single translation unit. The
4172`init_priority` attribute allows you to specify a relative ordering for the
4173initialization of objects declared at namespace scope in C++ within a single
4174linked image on supported platforms. The priority is given as an integer constant
4175expression between 101 and 65535 (inclusive). Priorities outside of that range are
4176reserved for use by the implementation. A lower value indicates a higher priority
4177of initialization. Note that only the relative ordering of values is important.
4178For example:
4179
4180```c++
4181struct SomeType { SomeType(); };
4182__attribute__((init_priority(200))) SomeType Obj1;
4183__attribute__((init_priority(101))) SomeType Obj2;
4184```
4185
4186`Obj2` will be initialized *before* `Obj1` despite the usual order of
4187initialization being the opposite.
4188
4189Note that this attribute does not control the initialization order of objects
4190across final linked image boundaries like shared objects and executables.
4191
4192On Windows, `init_seg(compiler)` is represented with a priority of 200 and
4193`init_seg(library)` is represented with a priority of 400. `init_seg(user)`
4194uses the default 65535 priority.
4195
4196On MachO platforms, this attribute also does not control the order of initialization
4197across translation units, where it only affects the order within a single TU.
4198
4199This attribute is only supported for C++ and Objective-C++ and is ignored in
4200other language modes.)reST";
4201
4202static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by `pragma init_seg()` controls the section into
4203which global initialization function pointers are emitted. It is only
4204available with `-fms-extensions`. Typically, this function pointer is
4205emitted into `.CRT$XCU` on Windows. The user can change the order of
4206initialization by using a different section name with the same
4207`.CRT$XC` prefix and a suffix that sorts lexicographically before or
4208after the standard `.CRT$XCU` sections. See the [init_seg][init_seg]
4209documentation on MSDN for more information.
4210
4211[init_seg]: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
4212
4213static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
4214
4215static const char AttrDoc_InternalLinkage[] = R"reST(The `internal_linkage` attribute changes the linkage type of the declaration
4216to internal. This is similar to C-style `static`, but can be used on classes
4217and class methods. When applied to a class definition, this attribute affects
4218all methods and static data members of that class. This can be used to contain
4219the ABI of a C++ library by excluding unwanted class methods from the export
4220tables.)reST";
4221
4222static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See {doc}`LTOVisibility`.)reST";
4223
4224static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
4225layout rules of a particular compiler version.
4226This attribute only applies to struct, class, and union types.
4227It is only supported when using the Microsoft C++ ABI.)reST";
4228
4229static const char AttrDoc_Leaf[] = R"reST(The `leaf` attribute is used as a compiler hint to improve dataflow analysis
4230in library functions. Functions marked with the `leaf` attribute are not allowed
4231to jump back into the caller's translation unit, whether through invoking a
4232callback function, an external function call, use of `longjmp`, or other means.
4233Therefore, they cannot use or modify any data that does not escape the caller function's
4234compilation unit.
4235
4236For more information see the
4237[GCC common attributes documentation](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html))reST";
4238
4239static const char AttrDoc_LifetimeBound[] = R"reST(The `lifetimebound` attribute on a function parameter or implicit object
4240parameter indicates that objects that are referred to by that parameter may
4241also be referred to by the return value of the annotated function (or, for a
4242parameter of a constructor, by the value of the constructed object).
4243
4244By default, a reference is considered to refer to its referenced object, a
4245pointer is considered to refer to its pointee, a `std::initializer_list<T>`
4246is considered to refer to its underlying array, and aggregates (arrays and
4247simple `struct`s) are considered to refer to all objects that their
4248transitive subobjects refer to.
4249
4250Clang warns if it is able to detect that an object or reference refers to
4251another object with a shorter lifetime. For example, Clang will warn if a
4252function returns a reference to a local variable, or if a reference is bound to
4253a temporary object whose lifetime is not extended. By using the
4254`lifetimebound` attribute, this determination can be extended to look through
4255user-declared functions. For example:
4256
4257```c++
4258#include <map>
4259#include <string>
4260
4261using namespace std::literals;
4262
4263// Returns m[key] if key is present, or default_value if not.
4264template<typename T, typename U>
4265const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4266 const T &key, /* note, not lifetimebound */
4267 const U &default_value [[clang::lifetimebound]]) {
4268 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4269 else return default_value;
4270}
4271
4272int main() {
4273 std::map<std::string, std::string> m;
4274 // warning: temporary bound to local reference 'val1' will be destroyed
4275 // at the end of the full-expression
4276 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4277
4278 // No warning in this case.
4279 std::string def_val = "bar"s;
4280 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4281
4282 return 0;
4283}
4284```
4285
4286The attribute can be applied to the implicit `this` parameter of a member
4287function by writing the attribute after the function type:
4288
4289```c++
4290struct string {
4291 // The returned pointer should not outlive '*this'.
4292 const char *data() const [[clang::lifetimebound]];
4293};
4294```
4295
4296This attribute is inspired by the C++ committee paper [P0936R0](http://wg21.link/p0936r0), but does not affect whether temporary objects
4297have their lifetimes extended.)reST";
4298
4299static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to [lifetimebound], the `lifetime_capture_by` attribute family on a
4300function parameter or implicit object parameter indicates that a capturing
4301entity may refer to the object referred to by that parameter. The capturing
4302entity can be named in `lifetime_capture_by(X)` or selected by one of the
4303standalone special forms listed below.
4304
4305Below is a list of types of the parameters and what they're considered to refer to:
4306
4307- A reference param (of non-view type) is considered to refer to its referenced object.
4308- A pointer param (of non-view type) is considered to refer to its pointee.
4309- View type param (type annotated with `[[gsl::Pointer()]]`) is considered to refer
4310 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4311 in the parameter. For example, both `std::string_view` and
4312 `const std::string_view &` are considered to refer to a `std::string`.
4313- A `std::initializer_list<T>` is considered to refer to its underlying array.
4314- Aggregates (arrays and simple `struct`s) are considered to refer to all
4315 objects that their transitive subobjects refer to.
4316
4317Clang would diagnose when a temporary object is used as an argument to such an
4318annotated parameter.
4319In this case, the capturing entity `X` could capture a dangling reference to this
4320temporary object.
4321
4322```c++
4323void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4324 s.insert(a);
4325}
4326void use() {
4327 std::set<std::string_view> s;
4328 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4329 // ^^^^^^^^^^^^^
4330 std::string local;
4331 addToSet(local, s); // Ok.
4332}
4333```
4334
4335The capturing entity can be one of the following:
4336
4337- Another (named) function parameter.
4338
4339 ```c++
4340 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4341 s.insert(a);
4342 }
4343 ```
4344
4345- `this` (in case of member functions), written as
4346 `lifetime_capture_by_this`.
4347
4348 ```c++
4349 class S {
4350 void addToSet(std::string_view a [[clang::lifetime_capture_by_this]]) {
4351 s.insert(a);
4352 }
4353 std::set<std::string_view> s;
4354 };
4355 ```
4356
4357 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by_this]]` is just an alias of `[[clang::lifetimebound]]`.
4358
4359- `global` and `unknown`, written as `lifetime_capture_by_global` and
4360 `lifetime_capture_by_unknown` respectively.
4361
4362 ```c++
4363 std::set<std::string_view> s;
4364 void addToSet(std::string_view a [[clang::lifetime_capture_by_global]]) {
4365 s.insert(a);
4366 }
4367 void addSomewhere(std::string_view a [[clang::lifetime_capture_by_unknown]]);
4368 ```
4369
4370The attribute can be applied to the implicit `this` parameter of a member
4371function by writing the attribute after the function type:
4372
4373```c++
4374struct S {
4375 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4376 s.insert(this);
4377 }
4378};
4379```
4380
4381The parameter-list form supports specifying more than one capturing entity:
4382
4383```c++
4384void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4385 std::set<std::string_view>& s1,
4386 std::set<std::string_view>& s2) {
4387 s1.insert(a);
4388 s2.insert(a);
4389}
4390```
4391
4392Distinct `lifetime_capture_by` forms can also be combined on the same
4393declaration, but each form can appear at most once. For example,
4394`[[clang::lifetime_capture_by(s), clang::lifetime_capture_by_this]]` is
4395allowed, but two `[[clang::lifetime_capture_by(...)]]` attributes or two
4396`[[clang::lifetime_capture_by_this]]` attributes on the same declaration are
4397rejected.
4398
4399Limitation: The capturing entity `X` is not used by the analysis and is
4400used for documentation purposes only. This is because the analysis is
4401statement-local and only detects use of a temporary as an argument to the
4402annotated parameter.
4403
4404```c++
4405void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4406void use() {
4407 std::set<std::string_view> s;
4408 if (foo()) {
4409 std::string str;
4410 addToSet(str, s); // Not detected.
4411 }
4412}
4413```)reST";
4414
4415static const char AttrDoc_Likely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
4416The attributes are used to aid the compiler to determine which branch is
4417likely or unlikely to be taken. This is done by marking the branch substatement
4418with one of the two attributes.
4419
4420It isn't allowed to annotate a single statement with both `likely` and
4421`unlikely`. Annotating the `true` and `false` branch of an `if`
4422statement with the same likelihood attribute will result in a diagnostic and
4423the attributes are ignored on both branches.
4424
4425In a `switch` statement it's allowed to annotate multiple `case` labels
4426or the `default` label with the same likelihood attribute. This makes
4427\* all labels without an attribute have a neutral likelihood,
4428\* all labels marked `[[likely]]` have an equally positive likelihood, and
4429\* all labels marked `[[unlikely]]` have an equally negative likelihood.
4430The neutral likelihood is the more likely of path execution than the negative
4431likelihood. The positive likelihood is the more likely of path of execution
4432than the neutral likelihood.
4433
4434These attributes have no effect on the generated code when using
4435PGO (Profile-Guided Optimization) or at optimization level 0.
4436
4437In Clang, the attributes will be ignored if they're not placed on
4438\* the `case` or `default` label of a `switch` statement,
4439\* or on the substatement of an `if` or `else` statement,
4440\* or on the substatement of an `for` or `while` statement.
4441The C++ Standard recommends to honor them on every statement in the
4442path of execution, but that can be confusing:
4443
4444```c++
4445if (b) {
4446 [[unlikely]] --b; // Per the standard this is in the path of
4447 // execution, so this branch should be considered
4448 // unlikely. However, Clang ignores the attribute
4449 // here since it is not on the substatement.
4450}
4451
4452if (b) {
4453 --b;
4454 if(b)
4455 return;
4456 [[unlikely]] --b; // Not in the path of execution,
4457} // the branch has no likelihood information.
4458
4459if (b) {
4460 --b;
4461 foo(b);
4462 // Whether or not the next statement is in the path of execution depends
4463 // on the declaration of foo():
4464 // In the path of execution: void foo(int);
4465 // Not in the path of execution: [[noreturn]] void foo(int);
4466 // This means the likelihood of the branch depends on the declaration
4467 // of foo().
4468 [[unlikely]] --b;
4469}
4470```
4471
4472Below are some example usages of the likelihood attributes and their effects:
4473
4474```c++
4475if (b) [[likely]] { // Placement on the first statement in the branch.
4476 // The compiler will optimize to execute the code here.
4477} else {
4478}
4479
4480if (b)
4481 [[unlikely]] b++; // Placement on the first statement in the branch.
4482else {
4483 // The compiler will optimize to execute the code here.
4484}
4485
4486if (b) {
4487 [[unlikely]] b++; // Placement on the second statement in the branch.
4488} // The attribute will be ignored.
4489
4490if (b) [[likely]] {
4491 [[unlikely]] b++; // No contradiction since the second attribute
4492} // is ignored.
4493
4494if (b)
4495 ;
4496else [[likely]] {
4497 // The compiler will optimize to execute the code here.
4498}
4499
4500if (b)
4501 ;
4502else
4503 // The compiler will optimize to execute the next statement.
4504 [[likely]] b = f();
4505
4506if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4507else [[likely]]; // and the attributes are ignored.
4508
4509if (b)
4510 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4511 // isn't allowed on a declaration.
4512
4513switch (i) {
4514 [[likely]] case 1: // This value is likely
4515 ...
4516 break;
4517
4518 [[unlikely]] case 2: // This value is unlikely
4519 ...
4520 [[fallthrough]];
4521
4522 case 3: // No likelihood attribute
4523 ...
4524 [[likely]] break; // No effect
4525
4526 case 4: [[likely]] { // attribute on substatement has no effect
4527 ...
4528 break;
4529 }
4530
4531 [[unlikely]] default: // All other values are unlikely
4532 ...
4533 break;
4534}
4535
4536switch (i) {
4537 [[likely]] case 0: // This value and code path is likely
4538 ...
4539 [[fallthrough]];
4540
4541 case 1: // No likelihood attribute, code path is neutral
4542 break; // falling through has no effect on the likelihood
4543
4544 case 2: // No likelihood attribute, code path is neutral
4545 [[fallthrough]];
4546
4547 [[unlikely]] default: // This value and code path are both unlikely
4548 break;
4549}
4550
4551for(int i = 0; i != size; ++i) [[likely]] {
4552 ... // The loop is the likely path of execution
4553}
4554
4555for(const auto &E : Elements) [[likely]] {
4556 ... // The loop is the likely path of execution
4557}
4558
4559while(i != size) [[unlikely]] {
4560 ... // The loop is the unlikely path of execution
4561} // The generated code will optimize to skip the loop body
4562
4563while(true) [[unlikely]] {
4564 ... // The attribute has no effect
4565} // Clang elides the comparison and generates an infinite
4566 // loop
4567```)reST";
4568
4569static const char AttrDoc_LoaderUninitialized[] = R"reST(The `loader_uninitialized` attribute can be placed on global variables to
4570indicate that the variable does not need to be zero initialized by the loader.
4571On most targets, zero-initialization does not incur any additional cost.
4572For example, most general purpose operating systems deliberately ensure
4573that all memory is properly initialized in order to avoid leaking privileged
4574information from the kernel or other programs. However, some targets
4575do not make this guarantee, and on these targets, avoiding an unnecessary
4576zero-initialization can have a significant impact on load times and/or code
4577size.
4578
4579A declaration with this attribute is a non-tentative definition just as if it
4580provided an initializer. Variables with this attribute are considered to be
4581uninitialized in the same sense as a local variable, and the programs must
4582write to them before reading from them. If the variable's type is a C++ class
4583type with a non-trivial default constructor, or an array thereof, this attribute
4584only suppresses the static zero-initialization of the variable, not the dynamic
4585initialization provided by executing the default constructor.)reST";
4586
4587static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4588
4589static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4590
4591static const char AttrDoc_LoopHint[] = R"reST(The `#pragma clang loop` directive allows loop optimization hints to be
4592specified for the subsequent loop. The directive allows pipelining to be
4593disabled, or vectorization, vector predication, interleaving, and unrolling to
4594be enabled or disabled. Vector width, vector predication, interleave count,
4595unrolling count, and the initiation interval for pipelining can be explicitly
4596specified. See
4597{ref}`loop hint optimizations <langext-loop-hint-optimizations>` for details.)reST";
4598
4599static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4600
4601static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4602to clear parameters off the stack on return. In other words, callee is
4603responsible for cleaning out the stack space allocated for incoming paramters.
4604This convention does not support variadic calls or unprototyped functions in C.
4605When targeting M68010 or newer CPUs, this calling convention is implemented
4606using the `rtd` instruction.)reST";
4607
4608static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4609
4610functions that follow it to only release arguments passed to them when they
4611return "success" (a `kern_return_t` error code that indicates that
4612no errors have occurred). Otherwise the release is performed by the MIG client
4613that called the function. The annotation `__attribute__((mig_server_routine))`
4614is applied in order to specify which functions are expected to follow the
4615convention. This allows the Static Analyzer to find bugs caused by violations of
4616that convention. The attribute would normally appear on the forward declaration
4617of the actual server routine in the MIG server header, but it may also be
4618added to arbitrary functions that need to follow the same convention - for
4619example, a user can add them to auxiliary functions called by the server routine
4620that have their return value of type `kern_return_t` unconditionally returned
4621from the routine. The attribute can be applied to C++ methods, and in this case
4622it will be automatically applied to overrides if the method is virtual. The
4623attribute can also be written using C++11 syntax: `[[mig::server_routine]]`.)reST";
4624
4625static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4626a function to match the default convention used on Windows. This
4627attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4628
4629static const char AttrDoc_MSAllocator[] = R"reST(The `__declspec(allocator)` attribute is applied to functions that allocate
4630memory, such as operator new in C++. When CodeView debug information is emitted
4631(enabled by `clang -gcodeview` or `clang-cl /Z7`), Clang will attempt to
4632record the code offset of heap allocation call sites in the debug info. It will
4633also record the type being allocated using some local heuristics. The Visual
4634Studio debugger uses this information to [profile memory usage][profile memory usage].
4635
4636This attribute does not affect optimizations in any way, unlike GCC's
4637`__attribute__((malloc))`.
4638
4639[profile memory usage]: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage)reST";
4640
4641static const char AttrDoc_MSConstexpr[] = R"reST(The `[[msvc::constexpr]]` attribute can be applied only to a function
4642definition or a `return` statement. It does not impact function declarations.
4643A `[[msvc::constexpr]]` function cannot be `constexpr` or `consteval`.
4644A `[[msvc::constexpr]]` function is treated as if it were a `constexpr` function
4645when it is evaluated in a constant context of `[[msvc::constexpr]] return` statement.
4646Otherwise, it is treated as a regular function.
4647
4648Semantics of this attribute are enabled only under MSVC compatibility
4649(`-fms-compatibility-version`) 19.33 and later.)reST";
4650
4651static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under `-fms-extensions` and controls
4652the pointer-to-member representation used on `*-*-win32` targets.
4653
4654The `*-*-win32` targets utilize a pointer-to-member representation which
4655varies in size and alignment depending on the definition of the underlying
4656class.
4657
4658However, this is problematic when a forward declaration is only available and
4659no definition has been made yet. In such cases, Clang is forced to utilize the
4660most general representation that is available to it.
4661
4662These keywords make it possible to use a pointer-to-member representation other
4663than the most general one regardless of whether or not the definition will ever
4664be present in the current translation unit.
4665
4666This family of keywords belong between the `class-key` and `class-name`:
4667
4668```c++
4669struct __single_inheritance S;
4670int S::*i;
4671struct S {};
4672```
4673
4674This keyword can be applied to class templates but only has an effect when used
4675on full specializations:
4676
4677```c++
4678template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4679template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4680template <> struct __single_inheritance A<int, float>;
4681```
4682
4683Note that choosing an inheritance model less general than strictly necessary is
4684an error:
4685
4686```c++
4687struct __multiple_inheritance S; // error: inheritance model does not match definition
4688int S::*i;
4689struct S {};
4690```)reST";
4691
4692static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4693the compiler that constructors and destructors will not reference the virtual
4694function table. It is only supported when using the Microsoft C++ ABI.)reST";
4695
4696static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4697
4698static const char AttrDoc_MSStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
4699special record layout compatibility mode which mimics the layout of Microsoft or
4700Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4701requested ABI, the attribute does nothing. However, if it does not, annotated
4702structure or class is laid out in a special compatibility mode, which slightly
4703changes offsets for fields and bit-fields. The intention is to match the layout
4704of the requested ABI for structures which only use C features.
4705
4706Note that the default behavior can be controlled by `-mms-bitfields` and
4707`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
4708
4709The primary difference is for bitfields, where the MS variant only packs
4710adjacent fields into the same allocation unit if they have integral types
4711of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4712tightly.)reST";
4713
4714static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4715
4716static const char AttrDoc_MallocSpan[] = R"reST(The `malloc_span` attribute can be used to mark that a function which acts
4717like a system memory allocation function and returns a span-like structure,
4718where the returned memory range does not alias storage from any other object
4719accessible to the caller.
4720
4721In this context, a span-like structure is assumed to have two non-static data
4722members, one of which is a pointer to the start of the allocated memory and
4723the other one is either an integer type containing the size of the actually
4724allocated memory or a pointer to the end of the allocated region. Note, static
4725data members do not impact whether a type is span-like or not.
4726
4727In combination with the `alloc_size` attribute, if the begin pointer is
4728non-null, the size of the returned span-like object has to be greater or equal
4729to the number of bytes guaranteed to be dereferenceable by `alloc_size`. It also
4730guarantees that the number of dereferenceable bytes is at least size.)reST";
4731
4732static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4733
4734static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4735
4736static const char AttrDoc_MaybeUndef[] = R"reST(The `maybe_undef` attribute can be placed on a function parameter. It indicates
4737that the parameter is allowed to use undef values. It informs the compiler
4738to insert a freeze LLVM IR instruction on the function parameter.
4739Please note that this is an attribute that is used as an internal
4740implementation detail and not intended to be used by external users.
4741
4742In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4743it is enough for only one or some threads to provide defined arguments.
4744Depending on semantics, undef arguments in some threads don't produce
4745undefined results in the function call. Since, these functions accept undefined
4746arguments, `maybe_undef` attribute can be placed.
4747
4748Sample usage:
4749
4750```c
4751void maybeundeffunc(int __attribute__((maybe_undef))param);
4752```)reST";
4753
4754static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
4755`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
4756may be attached to a function definition and instructs the backend to generate
4757or not to generate microMIPS code for that function.
4758
4759These attributes override the `-mmicromips` and `-mno-micromips` options
4760on the command line.)reST";
4761
4762static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4763make choices that keep the function code size as small as possible. Optimizations may
4764also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4765
4766static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the `__attribute__((min_vector_width(width)))` attribute. This
4767attribute may be attached to a function and informs the backend that this
4768function desires vectors of at least this width to be generated. Target-specific
4769maximum vector widths still apply. This means even if you ask for something
4770larger than the target supports, you will only get what the target supports.
4771This attribute is meant to be a hint to control target heuristics that may
4772generate narrower vectors than what the target hardware supports.
4773
4774This is currently used by the X86 target to allow some CPUs that support 512-bit
4775vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4776This is currently enabled with the `-prefer-vector-width=256` command line
4777option. The `min_vector_width` attribute can be used to prevent the backend
4778from trying to split vector operations to match the `prefer-vector-width`. All
4779X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4780use of any of the X86-specific vector builtins will implicitly set this
4781attribute on the calling function. The intent is that explicitly writing vector
4782code using the X86 intrinsics will prevent `prefer-vector-width` from
4783affecting the code.)reST";
4784
4785static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4786
4787static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("ARGUMENT")))` attribute on
4788MIPS targets. This attribute may be attached to a function definition and instructs
4789the backend to generate appropriate function entry/exit code so that it can be used
4790directly as an interrupt service routine.
4791
4792By default, the compiler will produce a function prologue and epilogue suitable for
4793an interrupt service routine that handles an External Interrupt Controller (eic)
4794generated interrupt. This behavior can be explicitly requested with the "eic"
4795argument.
4796
4797Otherwise, for use with vectored interrupt mode, the argument passed should be
4798of the form "vector=LEVEL" where LEVEL is one of the following values:
4799"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4800then set the interrupt mask to the corresponding level which will mask all
4801interrupts up to and including the argument.
4802
4803The semantics are as follows:
4804
4805- The prologue is modified so that the Exception Program Counter (EPC) and
4806 Status coprocessor registers are saved to the stack. The interrupt mask is
4807 set so that the function can only be interrupted by a higher priority
4808 interrupt. The epilogue will restore the previous values of EPC and Status.
4809- The prologue and epilogue are modified to save and restore all non-kernel
4810 registers as necessary.
4811- The FPU is disabled in the prologue, as the floating pointer registers are not
4812 spilled to the stack.
4813- The function return sequence is changed to use an exception return instruction.
4814- The parameter sets the interrupt mask for the function corresponding to the
4815 interrupt level specified. If no mask is specified the interrupt mask
4816 defaults to "eic".)reST";
4817
4818static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4819and `__attribute__((near))` attributes on MIPS targets. These attributes may
4820only be added to function declarations and change the code generated
4821by the compiler when directly calling the function. The `near` attribute
4822allows calls to the function to be made using the `jal` instruction, which
4823requires the function to be located in the same naturally aligned 256MB
4824segment as the caller. The `long_call` and `far` attributes are synonyms
4825and require the use of a different call sequence that works regardless
4826of the distance between the functions.
4827
4828These attributes have no effect for position-independent code.
4829
4830These attributes take priority over command line switches such
4831as `-mlong-calls` and `-mno-long-calls`.)reST";
4832
4833static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4834`__attribute__((short__call))`, and `__attribute__((near))` attributes
4835on MIPS targets. These attributes may only be added to function declarations
4836and change the code generated by the compiler when directly calling
4837the function. The `short_call` and `near` attributes are synonyms and
4838allow calls to the function to be made using the `jal` instruction, which
4839requires the function to be located in the same naturally aligned 256MB segment
4840as the caller. The `long_call` and `far` attributes are synonyms and
4841require the use of a different call sequence that works regardless
4842of the distance between the functions.
4843
4844These attributes have no effect for position-independent code.
4845
4846These attributes take priority over command line switches such
4847as `-mlong-calls` and `-mno-long-calls`.)reST";
4848
4849static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4850
4851static const char AttrDoc_ModularFormat[] = R"reST(The `modular_format` attribute can be applied to a function that bears the
4852`format` attribute (or standard library functions) to indicate that the
4853implementation is "modular", that is, that the implementation is logically
4854divided into a number of named aspects. When the compiler can determine that
4855not all aspects of the implementation are needed for a given call, the compiler
4856may redirect the call to the identifier given as the first argument to the
4857attribute (the modular implementation function).
4858
4859The second argument is an implementation name, and the remaining arguments are
4860aspects of the format string for the compiler to report. The implementation
4861name is an unevaluated identifier in the C namespace.
4862
4863The compiler reports that a call requires an aspect by issuing a relocation for
4864the symbol `<impl_name>_<aspect>` at the point of the call. This arranges for
4865code and data needed to support the aspect of the implementation to be brought
4866into the link to satisfy weak references in the modular implemenation function.
4867If the compiler does not understand an aspect, it must summarily consider any
4868call to require that aspect.
4869
4870For example, say `printf` is annotated with
4871`modular_format(__modular_printf, "__printf", "float")`. Then, a call to
4872`printf(var, 42)` would be untouched. A call to `printf("%d", 42)` would
4873become a call to `__modular_printf` with the same arguments, as would
4874`printf("%f", 42.0)`. The latter would be accompanied with a strong
4875relocation against the symbol `__printf_float`, which would bring floating
4876point support for `printf` into the link.
4877
4878If the attribute appears more than once on a declaration, or across a chain of
4879redeclarations, it is an error for the attributes to have different arguments,
4880excepting that the aspects may be in any order.
4881
4882The following aspects are currently supported:
4883
4884- `fixed`: The call has a C ISO 18037 fixed-point argument.
4885- `float`: The call has a floating-point argument.)reST";
4886
4887static const char AttrDoc_MustTail[] = R"reST(If a `return` statement is marked `musttail`, this indicates that the
4888compiler must generate a tail call for the program to be correct, even when
4889optimizations are disabled. This guarantees that the call will not cause
4890unbounded stack growth if it is part of a recursive cycle in the call graph.
4891
4892If the callee is a virtual function that is implemented by a thunk, there is
4893no guarantee in general that the thunk tail-calls the implementation of the
4894virtual function, so such a call in a recursive cycle can still result in
4895unbounded stack growth.
4896
4897`clang::musttail` can only be applied to a `return` statement whose value
4898is the result of a function call (even functions returning void must use
4899`return`, although no value is returned). The target function must have the
4900same number of arguments as the caller. The types of the return value and all
4901arguments must be similar according to C++ rules (differing only in cv
4902qualifiers or array size), including the implicit "this" argument, if any.
4903Any variables in scope, including all arguments to the function and the
4904return value must be trivially destructible. The calling convention of the
4905caller and callee must match, and they must not be variadic functions or have
4906old style K&R C function declarations.
4907
4908The lifetimes of all local variables and function parameters end immediately
4909before the call to the function. This means that it is undefined behaviour to
4910pass a pointer or reference to a local variable to the called function, which
4911is not the case without the attribute. Clang will emit a warning in common
4912cases where this happens.
4913
4914`clang::musttail` provides assurances that the tail call can be optimized on
4915all targets, not just one.)reST";
4916
4917static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4918(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4919convention (e.g. functions starting with "get" are assumed to return at
4920`+0`).
4921
4922It can be overridden using a family of the following attributes. In
4923Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4924a function communicates that the object is returned at `+1`, and the caller
4925is responsible for freeing it.
4926Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4927specifies that the object is returned at `+0` and the ownership remains with
4928the callee.
4929The annotation `__attribute__((ns_consumes_self))` specifies that
4930the Objective-C method call consumes the reference to `self`, e.g. by
4931attaching it to a supplied parameter.
4932Additionally, parameters can have an annotation
4933`__attribute__((ns_consumed))`, which specifies that passing an owned object
4934as that parameter effectively transfers the ownership, and the caller is no
4935longer responsible for it.
4936These attributes affect code generation when interacting with ARC code, and
4937they are used by the Clang Static Analyzer.
4938
4939In C programs using CoreFoundation, a similar set of attributes:
4940`__attribute__((cf_returns_not_retained))`,
4941`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
4942have the same respective semantics when applied to CoreFoundation objects.
4943These attributes affect code generation when interacting with ARC code, and
4944they are used by the Clang Static Analyzer.
4945
4946(os-retained-attr-family)=
4947
4948Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4949the same attribute family is present:
4950`__attribute__((os_returns_not_retained))`,
4951`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
4952with the same respective semantics.
4953Similar to `__attribute__((ns_consumes_self))`,
4954`__attribute__((os_consumes_this))` specifies that the method call consumes
4955the reference to "this" (e.g., when attaching it to a different object supplied
4956as a parameter).
4957Out parameters (parameters the function is meant to write into,
4958either via pointers-to-pointers or references-to-pointers)
4959may be annotated with `__attribute__((os_returns_retained))`
4960or `__attribute__((os_returns_not_retained))` which specifies that the object
4961written into the out parameter should (or respectively should not) be released
4962after use.
4963Since often out parameters may or may not be written depending on the exit
4964code of the function,
4965annotations `__attribute__((os_returns_retained_on_zero))`
4966and `__attribute__((os_returns_retained_on_non_zero))` specify that
4967an out parameter at `+1` is written if and only if the function returns a zero
4968(respectively non-zero) error code.
4969Observe that return-code-dependent out parameter annotations are only
4970available for retained out parameters, as non-retained object do not have to be
4971released by the callee.
4972These attributes are only used by the Clang Static Analyzer.
4973
4974The family of attributes `X_returns_X_retained` can be added to functions,
4975C++ methods, and Objective-C methods and properties.
4976Attributes `X_consumed` can be added to parameters of methods, functions,
4977and Objective-C methods.)reST";
4978
4979static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4980(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4981convention (e.g. functions starting with "get" are assumed to return at
4982`+0`).
4983
4984It can be overridden using a family of the following attributes. In
4985Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4986a function communicates that the object is returned at `+1`, and the caller
4987is responsible for freeing it.
4988Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4989specifies that the object is returned at `+0` and the ownership remains with
4990the callee.
4991The annotation `__attribute__((ns_consumes_self))` specifies that
4992the Objective-C method call consumes the reference to `self`, e.g. by
4993attaching it to a supplied parameter.
4994Additionally, parameters can have an annotation
4995`__attribute__((ns_consumed))`, which specifies that passing an owned object
4996as that parameter effectively transfers the ownership, and the caller is no
4997longer responsible for it.
4998These attributes affect code generation when interacting with ARC code, and
4999they are used by the Clang Static Analyzer.
5000
5001In C programs using CoreFoundation, a similar set of attributes:
5002`__attribute__((cf_returns_not_retained))`,
5003`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5004have the same respective semantics when applied to CoreFoundation objects.
5005These attributes affect code generation when interacting with ARC code, and
5006they are used by the Clang Static Analyzer.
5007
5008(os-retained-attr-family)=
5009
5010Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5011the same attribute family is present:
5012`__attribute__((os_returns_not_retained))`,
5013`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5014with the same respective semantics.
5015Similar to `__attribute__((ns_consumes_self))`,
5016`__attribute__((os_consumes_this))` specifies that the method call consumes
5017the reference to "this" (e.g., when attaching it to a different object supplied
5018as a parameter).
5019Out parameters (parameters the function is meant to write into,
5020either via pointers-to-pointers or references-to-pointers)
5021may be annotated with `__attribute__((os_returns_retained))`
5022or `__attribute__((os_returns_not_retained))` which specifies that the object
5023written into the out parameter should (or respectively should not) be released
5024after use.
5025Since often out parameters may or may not be written depending on the exit
5026code of the function,
5027annotations `__attribute__((os_returns_retained_on_zero))`
5028and `__attribute__((os_returns_retained_on_non_zero))` specify that
5029an out parameter at `+1` is written if and only if the function returns a zero
5030(respectively non-zero) error code.
5031Observe that return-code-dependent out parameter annotations are only
5032available for retained out parameters, as non-retained object do not have to be
5033released by the callee.
5034These attributes are only used by the Clang Static Analyzer.
5035
5036The family of attributes `X_returns_X_retained` can be added to functions,
5037C++ methods, and Objective-C methods and properties.
5038Attributes `X_consumed` can be added to parameters of methods, functions,
5039and Objective-C methods.)reST";
5040
5041static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
5042and categorize these enums with error domains.
5043
5044The `ns_error_domain` attribute indicates a global `NSString` or
5045`CFString` constant representing the error domain that an error code belongs
5046to. For pointer uniqueness and code size this is a constant symbol, not a
5047literal.
5048
5049The domain and error code need to be used together. The `ns_error_domain`
5050attribute links error codes to their domain at the source level.
5051
5052This metadata is useful for documentation purposes, for static analysis, and for
5053improving interoperability between Objective-C and Swift. It is not used for
5054code generation in Objective-C.
5055
5056For example:
5057
5058```objc
5059#define NS_ERROR_ENUM(_type, _name, _domain) \
5060 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
5061
5062extern NSString *const MyErrorDomain;
5063typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
5064 MyErrFirst,
5065 MyErrSecond,
5066};
5067```)reST";
5068
5069static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5070(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5071convention (e.g. functions starting with "get" are assumed to return at
5072`+0`).
5073
5074It can be overridden using a family of the following attributes. In
5075Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5076a function communicates that the object is returned at `+1`, and the caller
5077is responsible for freeing it.
5078Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5079specifies that the object is returned at `+0` and the ownership remains with
5080the callee.
5081The annotation `__attribute__((ns_consumes_self))` specifies that
5082the Objective-C method call consumes the reference to `self`, e.g. by
5083attaching it to a supplied parameter.
5084Additionally, parameters can have an annotation
5085`__attribute__((ns_consumed))`, which specifies that passing an owned object
5086as that parameter effectively transfers the ownership, and the caller is no
5087longer responsible for it.
5088These attributes affect code generation when interacting with ARC code, and
5089they are used by the Clang Static Analyzer.
5090
5091In C programs using CoreFoundation, a similar set of attributes:
5092`__attribute__((cf_returns_not_retained))`,
5093`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5094have the same respective semantics when applied to CoreFoundation objects.
5095These attributes affect code generation when interacting with ARC code, and
5096they are used by the Clang Static Analyzer.
5097
5098(os-retained-attr-family)=
5099
5100Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5101the same attribute family is present:
5102`__attribute__((os_returns_not_retained))`,
5103`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5104with the same respective semantics.
5105Similar to `__attribute__((ns_consumes_self))`,
5106`__attribute__((os_consumes_this))` specifies that the method call consumes
5107the reference to "this" (e.g., when attaching it to a different object supplied
5108as a parameter).
5109Out parameters (parameters the function is meant to write into,
5110either via pointers-to-pointers or references-to-pointers)
5111may be annotated with `__attribute__((os_returns_retained))`
5112or `__attribute__((os_returns_not_retained))` which specifies that the object
5113written into the out parameter should (or respectively should not) be released
5114after use.
5115Since often out parameters may or may not be written depending on the exit
5116code of the function,
5117annotations `__attribute__((os_returns_retained_on_zero))`
5118and `__attribute__((os_returns_retained_on_non_zero))` specify that
5119an out parameter at `+1` is written if and only if the function returns a zero
5120(respectively non-zero) error code.
5121Observe that return-code-dependent out parameter annotations are only
5122available for retained out parameters, as non-retained object do not have to be
5123released by the callee.
5124These attributes are only used by the Clang Static Analyzer.
5125
5126The family of attributes `X_returns_X_retained` can be added to functions,
5127C++ methods, and Objective-C methods and properties.
5128Attributes `X_consumed` can be added to parameters of methods, functions,
5129and Objective-C methods.)reST";
5130
5131static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5132(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5133convention (e.g. functions starting with "get" are assumed to return at
5134`+0`).
5135
5136It can be overridden using a family of the following attributes. In
5137Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5138a function communicates that the object is returned at `+1`, and the caller
5139is responsible for freeing it.
5140Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5141specifies that the object is returned at `+0` and the ownership remains with
5142the callee.
5143The annotation `__attribute__((ns_consumes_self))` specifies that
5144the Objective-C method call consumes the reference to `self`, e.g. by
5145attaching it to a supplied parameter.
5146Additionally, parameters can have an annotation
5147`__attribute__((ns_consumed))`, which specifies that passing an owned object
5148as that parameter effectively transfers the ownership, and the caller is no
5149longer responsible for it.
5150These attributes affect code generation when interacting with ARC code, and
5151they are used by the Clang Static Analyzer.
5152
5153In C programs using CoreFoundation, a similar set of attributes:
5154`__attribute__((cf_returns_not_retained))`,
5155`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5156have the same respective semantics when applied to CoreFoundation objects.
5157These attributes affect code generation when interacting with ARC code, and
5158they are used by the Clang Static Analyzer.
5159
5160(os-retained-attr-family)=
5161
5162Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5163the same attribute family is present:
5164`__attribute__((os_returns_not_retained))`,
5165`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5166with the same respective semantics.
5167Similar to `__attribute__((ns_consumes_self))`,
5168`__attribute__((os_consumes_this))` specifies that the method call consumes
5169the reference to "this" (e.g., when attaching it to a different object supplied
5170as a parameter).
5171Out parameters (parameters the function is meant to write into,
5172either via pointers-to-pointers or references-to-pointers)
5173may be annotated with `__attribute__((os_returns_retained))`
5174or `__attribute__((os_returns_not_retained))` which specifies that the object
5175written into the out parameter should (or respectively should not) be released
5176after use.
5177Since often out parameters may or may not be written depending on the exit
5178code of the function,
5179annotations `__attribute__((os_returns_retained_on_zero))`
5180and `__attribute__((os_returns_retained_on_non_zero))` specify that
5181an out parameter at `+1` is written if and only if the function returns a zero
5182(respectively non-zero) error code.
5183Observe that return-code-dependent out parameter annotations are only
5184available for retained out parameters, as non-retained object do not have to be
5185released by the callee.
5186These attributes are only used by the Clang Static Analyzer.
5187
5188The family of attributes `X_returns_X_retained` can be added to functions,
5189C++ methods, and Objective-C methods and properties.
5190Attributes `X_consumed` can be added to parameters of methods, functions,
5191and Objective-C methods.)reST";
5192
5193static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5194(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5195convention (e.g. functions starting with "get" are assumed to return at
5196`+0`).
5197
5198It can be overridden using a family of the following attributes. In
5199Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5200a function communicates that the object is returned at `+1`, and the caller
5201is responsible for freeing it.
5202Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5203specifies that the object is returned at `+0` and the ownership remains with
5204the callee.
5205The annotation `__attribute__((ns_consumes_self))` specifies that
5206the Objective-C method call consumes the reference to `self`, e.g. by
5207attaching it to a supplied parameter.
5208Additionally, parameters can have an annotation
5209`__attribute__((ns_consumed))`, which specifies that passing an owned object
5210as that parameter effectively transfers the ownership, and the caller is no
5211longer responsible for it.
5212These attributes affect code generation when interacting with ARC code, and
5213they are used by the Clang Static Analyzer.
5214
5215In C programs using CoreFoundation, a similar set of attributes:
5216`__attribute__((cf_returns_not_retained))`,
5217`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5218have the same respective semantics when applied to CoreFoundation objects.
5219These attributes affect code generation when interacting with ARC code, and
5220they are used by the Clang Static Analyzer.
5221
5222(os-retained-attr-family)=
5223
5224Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5225the same attribute family is present:
5226`__attribute__((os_returns_not_retained))`,
5227`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5228with the same respective semantics.
5229Similar to `__attribute__((ns_consumes_self))`,
5230`__attribute__((os_consumes_this))` specifies that the method call consumes
5231the reference to "this" (e.g., when attaching it to a different object supplied
5232as a parameter).
5233Out parameters (parameters the function is meant to write into,
5234either via pointers-to-pointers or references-to-pointers)
5235may be annotated with `__attribute__((os_returns_retained))`
5236or `__attribute__((os_returns_not_retained))` which specifies that the object
5237written into the out parameter should (or respectively should not) be released
5238after use.
5239Since often out parameters may or may not be written depending on the exit
5240code of the function,
5241annotations `__attribute__((os_returns_retained_on_zero))`
5242and `__attribute__((os_returns_retained_on_non_zero))` specify that
5243an out parameter at `+1` is written if and only if the function returns a zero
5244(respectively non-zero) error code.
5245Observe that return-code-dependent out parameter annotations are only
5246available for retained out parameters, as non-retained object do not have to be
5247released by the callee.
5248These attributes are only used by the Clang Static Analyzer.
5249
5250The family of attributes `X_returns_X_retained` can be added to functions,
5251C++ methods, and Objective-C methods and properties.
5252Attributes `X_consumed` can be added to parameters of methods, functions,
5253and Objective-C methods.)reST";
5254
5255static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
5256
5257static const char AttrDoc_NoAlias[] = R"reST(The `noalias` attribute indicates that the only memory accesses inside
5258function are loads and stores from objects pointed to by its pointer-typed
5259arguments, with arbitrary offsets.)reST";
5260
5261static const char AttrDoc_NoBuiltin[] = R"reST(The `__attribute__((no_builtin))` is similar to the `-fno-builtin` flag
5262except it is specific to the body of a function. The attribute may also be
5263applied to a virtual function but has no effect on the behavior of overriding
5264functions in a derived class.
5265
5266It accepts one or more strings corresponding to the specific names of the
5267builtins to disable (e.g. "memcpy", "memset").
5268If the attribute is used without parameters it will disable all buitins at
5269once.
5270
5271```c++
5272// The compiler is not allowed to add any builtin to foo's body.
5273void foo(char* data, size_t count) __attribute__((no_builtin)) {
5274 // The compiler is not allowed to convert the loop into
5275 // `__builtin_memset(data, 0xFE, count);`.
5276 for (size_t i = 0; i < count; ++i)
5277 data[i] = 0xFE;
5278}
5279
5280// The compiler is not allowed to add the `memcpy` builtin to bar's body.
5281void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5282 // The compiler is allowed to convert the loop into
5283 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5284 // `__builtin_memcpy`
5285 for (size_t i = 0; i < count; ++i)
5286 data[i] = 0xFE;
5287}
5288```)reST";
5289
5290static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5291
5292static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5293function is marked `noconvergent`, calls to that function are not
5294automatically assumed to be convergent, unless such calls are explicitly marked
5295as `convergent`. If a statement is marked as `noconvergent`, any calls to
5296inline `asm` in that statement are no longer treated as convergent.
5297
5298In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5299declarations and inline asm calls are treated as convergent by default for
5300correctness. This `noconvergent` attribute is helpful for developers to
5301prevent them from being treated as convergent when it's safe.
5302
5303```c
5304__device__ float bar(float);
5305__device__ float foo(float) __attribute__((noconvergent)) {}
5306
5307__device__ int example(void) {
5308 float x;
5309 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5310 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5311}
5312```)reST";
5313
5314static const char AttrDoc_NoDebug[] = R"reST(The `nodebug` attribute allows you to suppress debugging information for a
5315function or method, for a variable that is not a parameter or a non-static
5316data member, or for a typedef or using declaration.)reST";
5317
5318static const char AttrDoc_NoDeref[] = R"reST(The `noderef` attribute causes clang to diagnose dereferences of annotated pointer types.
5319This is ideally used with pointers that point to special memory which cannot be read
5320from or written to, but allowing for the pointer to be used in pointer arithmetic.
5321The following are examples of valid expressions where dereferences are diagnosed:
5322
5323```c
5324int __attribute__((noderef)) *p;
5325int x = *p; // warning
5326
5327int __attribute__((noderef)) **p2;
5328x = **p2; // warning
5329
5330int * __attribute__((noderef)) *p3;
5331p = *p3; // warning
5332
5333struct S {
5334 int a;
5335};
5336struct S __attribute__((noderef)) *s;
5337x = s->a; // warning
5338x = (*s).a; // warning
5339```
5340
5341Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5342accessed. The following are examples of valid expressions where may not be diagnosed:
5343
5344```c
5345int *q;
5346int __attribute__((noderef)) *p;
5347q = &*p;
5348q = *&p;
5349
5350struct S {
5351 int a;
5352};
5353struct S __attribute__((noderef)) *s;
5354p = &s->a;
5355p = &(*s).a;
5356```
5357
5358`noderef` is currently only supported for pointers and arrays and not usable
5359for references or Objective-C object pointers.
5360
5361```c++
5362int x = 2;
5363int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5364```
5365
5366```objc
5367id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
5368```)reST";
5369
5370static const char AttrDoc_NoDestroy[] = R"reST(The `no_destroy` attribute specifies that a variable with static or thread
5371storage duration shouldn't have its exit-time destructor run. Annotating every
5372static and thread duration variable with this attribute is equivalent to
5373invoking clang with `-fno-c++-static-destructors`.
5374
5375If a variable is declared with this attribute, clang doesn't access check or
5376generate the type's destructor. If you have a type that you only want to be
5377annotated with `no_destroy`, you can therefore declare the destructor private:
5378
5379```c++
5380struct only_no_destroy {
5381 only_no_destroy();
5382private:
5383 ~only_no_destroy();
5384};
5385
5386[[clang::no_destroy]] only_no_destroy global; // fine!
5387```
5388
5389Note that destructors are still required for subobjects of aggregates annotated
5390with this attribute. This is because previously constructed subobjects need to
5391be destroyed if an exception gets thrown before the initialization of the
5392complete object is complete. For instance:
5393
5394```c++
5395void f() {
5396 try {
5397 [[clang::no_destroy]]
5398 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5399 } catch (...) {
5400 // Handle the error
5401 }
5402}
5403```
5404
5405Here, if the construction of `array[9]` fails with an exception, `array[0..8]`
5406will be destroyed, so the element's destructor needs to be accessible.)reST";
5407
5408static const char AttrDoc_NoDuplicate[] = R"reST(The `noduplicate` attribute can be placed on function declarations to control
5409whether function calls to this function can be duplicated or not as a result of
5410optimizations. This is required for the implementation of functions with
5411certain special requirements, like the OpenCL "barrier" function, that might
5412need to be run concurrently by all the threads that are executing in lockstep
5413on the hardware. For example this attribute applied on the function
5414`nodupfunc` in the code below avoids that:
5415
5416```c
5417void nodupfunc() __attribute__((noduplicate));
5418// Setting it as a C++11 attribute is also valid
5419// void nodupfunc() [[clang::noduplicate]];
5420void foo();
5421void bar();
5422
5423nodupfunc();
5424if (a > n) {
5425 foo();
5426} else {
5427 bar();
5428}
5429```
5430
5431gets possibly modified by some optimizations into code similar to this:
5432
5433```c
5434if (a > n) {
5435 nodupfunc();
5436 foo();
5437} else {
5438 nodupfunc();
5439 bar();
5440}
5441```
5442
5443where the call to `nodupfunc` is duplicated and sunk into the two branches
5444of the condition.)reST";
5445
5446static const char AttrDoc_NoEscape[] = R"reST(`noescape` placed on a function parameter of a pointer type is used to inform
5447the compiler that the pointer cannot escape: that is, no reference to the object
5448the pointer points to that is derived from the parameter value will survive
5449after the function returns. Users are responsible for making sure parameters
5450annotated with `noescape` do not actually escape. The optimizer may make
5451assumptions based on the fact that it knows that a call to the function does
5452not escape a certain parameter, so incorrectly annotating a parameter with
5453`noescape` leads to undefined behavior. The callee is also not allowed to
5454deallocate memory through a `noescape` parameter: the optimizer does not make
5455assumptions based on this information at the moment, but may do so in the
5456future. Some cases of invalid uses of `noescape` can be found with
5457{ref}`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`.
5458
5459For example:
5460
5461```c
5462int *gp;
5463
5464void nonescapingFunc(__attribute__((noescape)) int *p) {
5465 *p += 100; // OK.
5466}
5467
5468void escapingFunc(__attribute__((noescape)) int *p) {
5469 gp = p; // Not OK.
5470}
5471
5472void freeingFunc(__attribute__((noescape)) int *p) {
5473 free(p); // Not OK.
5474}
5475```
5476
5477Since `noescape` is a parameter attribute and not a type attribute, it only
5478applies to the outermost pointer level, regardless of where in the parameter
5479declaration you place it:
5480
5481```c
5482int **gp;
5483
5484void nestingEscapes(__attribute__((noescape)) int **p) {
5485 gp = p; // Not OK.
5486 *gp = *p; // OK, p does not escape.
5487}
5488```
5489
5490Additionally, when the parameter is a
5491{doc}`block pointer <BlockLanguageSpec>`, the same restriction applies to
5492copies of the block. For example:
5493
5494```c
5495typedef void (^BlockTy)();
5496BlockTy g0, g1;
5497
5498void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5499 block(); // OK.
5500}
5501
5502void escapingFunc(__attribute__((noescape)) BlockTy block) {
5503 g0 = block; // Not OK.
5504 g1 = Block_copy(block); // Not OK either.
5505}
5506```
5507
5508The function *is* allowed to leak information about the memory address of the
5509pointer, but not any provenance of the allocation:
5510
5511```c
5512bool isNull(__attribute__((noescape)) void *p) {
5513 return !p; // OK.
5514}
5515
5516uintptr_t gi;
5517
5518void escapingAddress(__attribute__((noescape)) int *p) {
5519 // OK *if and only if* gi is never casted back to a pointer.
5520 gi = (uintptr_t)p;
5521}
5522
5523bool usingEscapedAddress(int *p) {
5524 return (uintptr_t)p > gi; // OK.
5525}
5526
5527bool usingEscapedPointer(int *p) {
5528 return p > (int*)gi; // Not OK.
5529}
5530
5531int *gp;
5532
5533void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) {
5534 gp = p + len; // Not OK.
5535}
5536```)reST";
5537
5538static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5539
5540static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5541of the function.
5542
5543`[[clang::noinline]]` spelling can be used as a statement attribute; other
5544spellings of the attribute are not supported on statements. If a statement is
5545marked `[[clang::noinline]]` and contains calls, those calls inside the
5546statement will not be inlined by the compiler.
5547
5548`__noinline__` can be used as a keyword in CUDA/HIP languages. This is to
5549avoid diagnostics due to usage of `__attribute__((__noinline__))`
5550with `__noinline__` defined as a macro as `__attribute__((noinline))`.
5551
5552```c
5553int example(void) {
5554 int r;
5555 [[clang::noinline]] foo();
5556 [[clang::noinline]] r = bar();
5557 return r;
5558}
5559```)reST";
5560
5561static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5562
5563static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked `nomerge` and contains call expressions, those call
5564expressions inside the statement will not be merged during optimization. This
5565attribute can be used to prevent the optimizer from obscuring the source
5566location of certain calls. For example, it will prevent tail merging otherwise
5567identical code sequences that raise an exception or terminate the program. Tail
5568merging normally reduces the precision of source location information, making
5569stack traces less useful for debugging. This attribute gives the user control
5570over the tradeoff between code size and debug information precision.
5571
5572`nomerge` attribute can also be used as function attribute to prevent all
5573calls to the specified function from merging. It has no effect on indirect
5574calls to such functions. For example:
5575
5576```c++
5577[[clang::nomerge]] void foo(int) {}
5578
5579void bar(int x) {
5580 auto *ptr = foo;
5581 if (x) foo(1); else foo(2); // will not be merged
5582 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5583}
5584```
5585
5586`nomerge` attribute can also be used for pointers to functions to
5587prevent calls through such pointer from merging. In such case the
5588effect applies only to a specific function pointer. For example:
5589
5590```c++
5591[[clang::nomerge]] void (*foo)(int);
5592
5593void bar(int x) {
5594 auto *ptr = foo;
5595 if (x) foo(1); else foo(2); // will not be merged
5596 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5597}
5598```)reST";
5599
5600static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
5601`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
5602may be attached to a function definition and instructs the backend to generate
5603or not to generate microMIPS code for that function.
5604
5605These attributes override the `-mmicromips` and `-mno-micromips` options
5606on the command line.)reST";
5607
5608static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5609
5610static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5611
5612Outlining is the process where common parts of separate functions are extracted
5613into a separate function (or assembly snippet), and calls to that function or
5614snippet are inserted in the original functions. In this way, it can be seen as
5615the opposite of inlining. It can help to reduce code size.)reST";
5616
5617static const char AttrDoc_NoProfileFunction[] = R"reST(Use the `no_profile_instrument_function` attribute on a function declaration
5618to denote that the compiler should not instrument the function with
5619profile-related instrumentation, such as via the
5620`-fprofile-generate` / `-fprofile-instr-generate` /
5621`-fcs-profile-generate` / `-fprofile-arcs` flags.)reST";
5622
5623static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
5624for structure layout field randomization; a compile-time hardening technique. A
5625"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
5626For example:
5627
5628```bash
5629SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5630make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5631```
5632
5633You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
5634For example:
5635
5636```bash
5637od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5638make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5639```
5640
5641The randomization is deterministic based for a given seed, so the entire
5642program should be compiled with the same seed, but keep the seed safe
5643otherwise.
5644
5645The attribute `no_randomize_layout`, when attached to a C structure,
5646instructs the compiler that this structure should not have its field layout
5647randomized.)reST";
5648
5649static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5650
5651static const char AttrDoc_NoSanitize[] = R"reST(Use the `no_sanitize` attribute on a function or a global variable
5652declaration to specify that a particular instrumentation or set of
5653instrumentations should not be applied.
5654
5655The attribute takes a list of string literals with the following accepted
5656values:
5657
5658- all values accepted by `-fno-sanitize=`;
5659- `coverage`, to disable SanitizerCoverage instrumentation.
5660
5661For example, `__attribute__((no_sanitize("address", "thread")))` specifies
5662that AddressSanitizer and ThreadSanitizer should not be applied to the function
5663or variable. Using `__attribute__((no_sanitize("coverage")))` specifies that
5664SanitizerCoverage should not be applied to the function.
5665
5666See {ref}`Controlling Code Generation <controlling-code-generation>` for a
5667full list of supported sanitizer flags.)reST";
5668
5669static const char AttrDoc_NoSpecializations[] = R"reST(`[[clang::no_specializations]]` can be applied to function, class, or variable
5670templates for which neither an explicit specialization nor a partial specialization should be declared by users. This is primarily
5671used to diagnose user specializations of standard library type traits.)reST";
5672
5673static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5674that [Speculative Load Hardening][slh] is *not* needed for the function body.
5675This can also be applied to a method in Objective C. This attribute will take
5676precedence over the command line flag in the case where
5677{option}`-mspeculative-load-hardening` is specified.
5678
5679Warning: This attribute may not prevent Speculative Load Hardening from being
5680enabled for a function which inlines a function that has the
5681`speculative_load_hardening` attribute. This is intended to provide a
5682maximally conservative model where the code that is marked with the
5683`speculative_load_hardening` attribute will always (even when inlined)
5684be hardened. A user of this attribute may want to mark functions called by
5685a function they do not want to be hardened with the `noinline` attribute.
5686
5687For example:
5688
5689```c
5690__attribute__((speculative_load_hardening))
5691int foo(int i) {
5692 return i;
5693}
5694
5695// Note: bar() may still have speculative load hardening enabled if
5696// foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5697// to avoid this situation.
5698__attribute__((no_speculative_load_hardening))
5699int bar(int i) {
5700 return foo(i);
5701}
5702```)reST";
5703
5704static const char AttrDoc_NoSplitStack[] = R"reST(The `no_split_stack` attribute disables the emission of the split stack
5705preamble for a particular function. It has no effect if `-fsplit-stack`
5706is not specified.)reST";
5707
5708static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style `__attribute__((no_stack_protector))` and Microsoft
5709style `__declspec(safebuffers)` attribute which disables
5710the stack protector on the specified function. This attribute is useful for
5711selectively disabling the stack protector on some functions when building with
5712`-fstack-protector` compiler option.
5713
5714For example, it disables the stack protector for the function `foo` but function
5715`bar` will still be built with the stack protector with the `-fstack-protector`
5716option.
5717
5718```c
5719int __attribute__((no_stack_protector))
5720foo (int x); // stack protection will be disabled for foo.
5721
5722int bar(int y); // bar can be built with the stack protector.
5723```)reST";
5724
5725static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5726
5727static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style `__attribute__((nothrow))` and Microsoft style
5728`__declspec(nothrow)` attribute as an equivalent of `noexcept` on function
5729declarations. This attribute informs the compiler that the annotated function
5730does not throw an exception. This prevents exception-unwinding. This attribute
5731is particularly useful on functions in the C Standard Library that are
5732guaranteed to not throw an exception.)reST";
5733
5734static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The `__declspec(no_init_all)` attribute disables the automatic initialization
5735that the {option}`-ftrivial-auto-var-init` flag would have applied to locals in
5736a marked function, or instances of a marked type. Note that this attribute has
5737no effect for locals that are automatically initialized without the
5738{option}`-ftrivial-auto-var-init` flag.)reST";
5739
5740static const char AttrDoc_NoUniqueAddress[] = R"reST(The `no_unique_address` attribute allows tail padding in a non-static data
5741member to overlap other members of the enclosing class (and in the special
5742case when the type is empty, permits it to fully overlap other members).
5743The field is laid out as if a base class were encountered at the corresponding
5744point within the class (except that it does not share a vptr with the enclosing
5745object).
5746
5747Example usage:
5748
5749```c++
5750template<typename T, typename Alloc> struct my_vector {
5751 T *p;
5752 [[no_unique_address]] Alloc alloc;
5753 // ...
5754};
5755static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5756```
5757
5758`[[no_unique_address]]` is a standard C++20 attribute. Clang supports its use
5759in C++11 onwards.
5760
5761On MSVC targets, `[[no_unique_address]]` is ignored; use
5762`[[msvc::no_unique_address]]` instead. Currently there is no guarantee of ABI
5763compatibility or stability with MSVC.)reST";
5764
5765static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the `nouwtable` attribute which skips emitting
5766the unwind table entry for the specified function. This attribute is useful for
5767selectively emitting the unwind table entry on some functions when building with
5768`-funwind-tables` compiler option.)reST";
5769
5770static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5771to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5772is false, the attribute is equivalent to `allocating`.)reST";
5773
5774static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5775to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5776is false, the attribute is equivalent to `blocking`.
5777
5778For the purposes of diagnostics, `nonblocking` is considered to include the
5779`nonallocating` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5780
5781static const char AttrDoc_NonNull[] = R"reST(The `nonnull` attribute indicates that some function parameters must not be
5782null, and can be used in several different ways. It's original usage
5783([from GCC](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes))
5784is as a function (or Objective-C method) attribute that specifies which
5785parameters of the function are nonnull in a comma-separated list. For example:
5786
5787```c
5788extern void * my_memcpy (void *dest, const void *src, size_t len)
5789 __attribute__((nonnull (1, 2)));
5790```
5791
5792Here, the `nonnull` attribute indicates that parameters 1 and 2
5793cannot have a null value. Omitting the parenthesized list of parameter indices
5794means that all parameters of pointer type cannot be null:
5795
5796```c
5797extern void * my_memcpy (void *dest, const void *src, size_t len)
5798 __attribute__((nonnull));
5799```
5800
5801Clang also allows the `nonnull` attribute to be placed directly on a function
5802(or Objective-C method) parameter, eliminating the need to specify the
5803parameter index ahead of type. For example:
5804
5805```c
5806extern void * my_memcpy (void *dest __attribute__((nonnull)),
5807 const void *src __attribute__((nonnull)), size_t len);
5808```
5809
5810Note that the `nonnull` attribute indicates that passing null to a non-null
5811parameter is undefined behavior, which the optimizer may take advantage of to,
5812e.g., remove null checks. The `_Nonnull` type qualifier indicates that a
5813pointer cannot be null in a more general manner (because it is part of the type
5814system) and does not imply undefined behavior, making it more widely applicable.)reST";
5815
5816static const char AttrDoc_NonString[] = R"reST(The `nonstring` attribute can be applied to the declaration of a variable or
5817a field whose type is a character pointer or character array to specify that
5818the buffer is not intended to behave like a null-terminated string. This will
5819silence diagnostics with code like:
5820
5821```c
5822char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5823__attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed
5824```)reST";
5825
5826static const char AttrDoc_NotTailCalled[] = R"reST(The `not_tail_called` attribute prevents tail-call optimization on statically
5827bound calls. Objective-c methods, and functions marked as `always_inline`
5828cannot be marked as `not_tail_called`.
5829
5830For example, it prevents tail-call optimization in the following case:
5831
5832```c
5833int __attribute__((not_tail_called)) foo1(int);
5834
5835int foo2(int a) {
5836 return foo1(a); // No tail-call optimization on direct calls.
5837}
5838```
5839
5840However, it doesn't prevent tail-call optimization in this case:
5841
5842```c
5843int __attribute__((not_tail_called)) foo1(int);
5844
5845int foo2(int a) {
5846 int (*fn)(int) = &foo1;
5847
5848 // not_tail_called has no effect on an indirect call even if the call can
5849 // be resolved at compile time.
5850 return (*fn)(a);
5851}
5852```
5853
5854Generally, marking an overriding virtual function as `not_tail_called` is
5855not useful, because this attribute is a property of the static type. Calls
5856made through a pointer or reference to the base class type will respect
5857the `not_tail_called` attribute of the base class's member function,
5858regardless of the runtime destination of the call:
5859
5860```c++
5861struct Foo { virtual void f(); };
5862struct Bar : Foo {
5863 [[clang::not_tail_called]] void f() override;
5864};
5865void callera(Bar& bar) {
5866 Foo& foo = bar;
5867 // not_tail_called has no effect on here, even though the
5868 // underlying method is f from Bar.
5869 foo.f();
5870 bar.f(); // No tail-call optimization on here.
5871}
5872```)reST";
5873
5874static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5875
5876static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the `[[omp::assume("assumption")]]` attribute to
5877provide additional information to the optimizer. The string-literal, here
5878"assumption", will be attached to the function declaration such that later
5879analysis and optimization passes can assume the "assumption" to hold.
5880This is similar to {ref}`__builtin_assume <langext-__builtin_assume>` but
5881instead of an expression that can be assumed to be non-zero, the assumption is
5882expressed as a string and it holds for the entire function.
5883
5884A function can have multiple assume attributes and they propagate from prior
5885declarations to later definitions. Multiple assumptions are aggregated into a
5886single comma separated string. Thus, one can provide multiple assumptions via
5887a comma separated string, i.a.,
5888`[[omp::assume("assumption1,assumption2")]]`.
5889
5890While LLVM plugins might provide more assumption strings, the default LLVM
5891optimization passes are aware of the following assumptions:
5892
5893```none
5894"omp_no_openmp"
5895"omp_no_openmp_routines"
5896"omp_no_parallelism"
5897"omp_no_openmp_constructs"
5898```
5899
5900The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5901spelled "XYZ" in the [OpenMP 5.1 Standard][openmp 5.1 standard]).
5902
5903[openmp 5.1 standard]: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5904
5905static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5906
5907static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5908
5909static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The `declare simd` construct can be applied to a function to enable the creation
5910of one or more versions that can process multiple arguments using SIMD
5911instructions from a single invocation in a SIMD loop. The `declare simd`
5912directive is a declarative directive. There may be multiple `declare simd`
5913directives for a function. The use of a `declare simd` construct on a function
5914enables the creation of SIMD versions of the associated function that can be
5915used to process multiple arguments from a single invocation from a SIMD loop
5916concurrently.
5917The syntax of the `declare simd` construct is as follows:
5918
5919```none
5920#pragma omp declare simd [clause[[,] clause] ...] new-line
5921[#pragma omp declare simd [clause[[,] clause] ...] new-line]
5922[...]
5923function definition or declaration
5924```
5925
5926where clause is one of the following:
5927
5928```none
5929simdlen(length)
5930linear(argument-list[:constant-linear-step])
5931aligned(argument-list[:alignment])
5932uniform(argument-list)
5933inbranch
5934notinbranch
5935```)reST";
5936
5937static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The `declare target` directive specifies that variables and functions are mapped
5938to a device for OpenMP offload mechanism.
5939
5940The syntax of the declare target directive is as follows:
5941
5942```c
5943#pragma omp declare target new-line
5944declarations-definition-seq
5945#pragma omp end declare target new-line
5946```
5947
5948or
5949
5950```c
5951#pragma omp declare target (extended-list) new-line
5952```
5953
5954or
5955
5956```c
5957#pragma omp declare target clause[ [,] clause ... ] new-line
5958```
5959
5960where clause is one of the following:
5961
5962```c
5963to(extended-list)
5964link(list)
5965device_type(host | nohost | any)
5966```)reST";
5967
5968static const char AttrDoc_OMPDeclareVariant[] = R"reST(The `declare variant` directive declares a specialized variant of a base
5969function and specifies the context in which that specialized variant is used.
5970The declare variant directive is a declarative directive.
5971The syntax of the `declare variant` construct is as follows:
5972
5973```none
5974#pragma omp declare variant(variant-func-id) clause new-line
5975[#pragma omp declare variant(variant-func-id) clause new-line]
5976[...]
5977function definition or declaration
5978```
5979
5980where clause is one of the following:
5981
5982```none
5983match(context-selector-specification)
5984```
5985
5986and where `variant-func-id` is the name of a function variant that is either a
5987base language identifier or, for C++, a template-id.
5988
5989Clang provides the following context selector extensions, used via
5990`implementation={extension(EXTENSION)}`:
5991
5992```none
5993match_all
5994match_any
5995match_none
5996disable_implicit_base
5997allow_templates
5998bind_to_declaration
5999```
6000
6001The match extensions change when the *entire* context selector is considered a
6002match for an OpenMP context. The default is `all`, with `none` no trait in the
6003selector is allowed to be in the OpenMP context, with `any` a single trait in
6004both the selector and OpenMP context is sufficient. Only a single match
6005extension trait is allowed per context selector.
6006The disable extensions remove default effects of the `begin declare variant`
6007applied to a definition. If `disable_implicit_base` is given, we will not
6008introduce an implicit base function for a variant if no base function was
6009found. The variant is still generated but will never be called, due to the
6010absence of a base function and consequently calls to a base function.
6011The allow extensions change when the `begin declare variant` effect is
6012applied to a definition. If `allow_templates` is given, template function
6013definitions are considered as specializations of existing or assumed template
6014declarations with the same name. The template parameters for the base functions
6015are used to instantiate the specialization. If `bind_to_declaration` is given,
6016apply the same variant rules to function declarations. This allows the user to
6017override declarations with only a function declaration.)reST";
6018
6019static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
6020
6021static const char AttrDoc_OMPInvariantPredicateBound[] = R"reST()reST";
6022
6023static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
6024
6025static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
6026
6027static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
6028
6029static const char AttrDoc_OSConsumed[] = 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
6058(os-retained-attr-family)=
6059
6060Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6061the same attribute family is present:
6062`__attribute__((os_returns_not_retained))`,
6063`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6064with the same respective semantics.
6065Similar to `__attribute__((ns_consumes_self))`,
6066`__attribute__((os_consumes_this))` specifies that the method call consumes
6067the reference to "this" (e.g., when attaching it to a different object supplied
6068as a parameter).
6069Out parameters (parameters the function is meant to write into,
6070either via pointers-to-pointers or references-to-pointers)
6071may be annotated with `__attribute__((os_returns_retained))`
6072or `__attribute__((os_returns_not_retained))` which specifies that the object
6073written into the out parameter should (or respectively should not) be released
6074after use.
6075Since often out parameters may or may not be written depending on the exit
6076code of the function,
6077annotations `__attribute__((os_returns_retained_on_zero))`
6078and `__attribute__((os_returns_retained_on_non_zero))` specify that
6079an out parameter at `+1` is written if and only if the function returns a zero
6080(respectively non-zero) error code.
6081Observe that return-code-dependent out parameter annotations are only
6082available for retained out parameters, as non-retained object do not have to be
6083released by the callee.
6084These attributes are only used by the Clang Static Analyzer.
6085
6086The family of attributes `X_returns_X_retained` can be added to functions,
6087C++ methods, and Objective-C methods and properties.
6088Attributes `X_consumed` can be added to parameters of methods, functions,
6089and Objective-C methods.)reST";
6090
6091static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6092(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6093convention (e.g. functions starting with "get" are assumed to return at
6094`+0`).
6095
6096It can be overridden using a family of the following attributes. In
6097Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6098a function communicates that the object is returned at `+1`, and the caller
6099is responsible for freeing it.
6100Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6101specifies that the object is returned at `+0` and the ownership remains with
6102the callee.
6103The annotation `__attribute__((ns_consumes_self))` specifies that
6104the Objective-C method call consumes the reference to `self`, e.g. by
6105attaching it to a supplied parameter.
6106Additionally, parameters can have an annotation
6107`__attribute__((ns_consumed))`, which specifies that passing an owned object
6108as that parameter effectively transfers the ownership, and the caller is no
6109longer responsible for it.
6110These attributes affect code generation when interacting with ARC code, and
6111they are used by the Clang Static Analyzer.
6112
6113In C programs using CoreFoundation, a similar set of attributes:
6114`__attribute__((cf_returns_not_retained))`,
6115`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6116have the same respective semantics when applied to CoreFoundation objects.
6117These attributes affect code generation when interacting with ARC code, and
6118they are used by the Clang Static Analyzer.
6119
6120(os-retained-attr-family)=
6121
6122Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6123the same attribute family is present:
6124`__attribute__((os_returns_not_retained))`,
6125`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6126with the same respective semantics.
6127Similar to `__attribute__((ns_consumes_self))`,
6128`__attribute__((os_consumes_this))` specifies that the method call consumes
6129the reference to "this" (e.g., when attaching it to a different object supplied
6130as a parameter).
6131Out parameters (parameters the function is meant to write into,
6132either via pointers-to-pointers or references-to-pointers)
6133may be annotated with `__attribute__((os_returns_retained))`
6134or `__attribute__((os_returns_not_retained))` which specifies that the object
6135written into the out parameter should (or respectively should not) be released
6136after use.
6137Since often out parameters may or may not be written depending on the exit
6138code of the function,
6139annotations `__attribute__((os_returns_retained_on_zero))`
6140and `__attribute__((os_returns_retained_on_non_zero))` specify that
6141an out parameter at `+1` is written if and only if the function returns a zero
6142(respectively non-zero) error code.
6143Observe that return-code-dependent out parameter annotations are only
6144available for retained out parameters, as non-retained object do not have to be
6145released by the callee.
6146These attributes are only used by the Clang Static Analyzer.
6147
6148The family of attributes `X_returns_X_retained` can be added to functions,
6149C++ methods, and Objective-C methods and properties.
6150Attributes `X_consumed` can be added to parameters of methods, functions,
6151and Objective-C methods.)reST";
6152
6153static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6154(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6155convention (e.g. functions starting with "get" are assumed to return at
6156`+0`).
6157
6158It can be overridden using a family of the following attributes. In
6159Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6160a function communicates that the object is returned at `+1`, and the caller
6161is responsible for freeing it.
6162Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6163specifies that the object is returned at `+0` and the ownership remains with
6164the callee.
6165The annotation `__attribute__((ns_consumes_self))` specifies that
6166the Objective-C method call consumes the reference to `self`, e.g. by
6167attaching it to a supplied parameter.
6168Additionally, parameters can have an annotation
6169`__attribute__((ns_consumed))`, which specifies that passing an owned object
6170as that parameter effectively transfers the ownership, and the caller is no
6171longer responsible for it.
6172These attributes affect code generation when interacting with ARC code, and
6173they are used by the Clang Static Analyzer.
6174
6175In C programs using CoreFoundation, a similar set of attributes:
6176`__attribute__((cf_returns_not_retained))`,
6177`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6178have the same respective semantics when applied to CoreFoundation objects.
6179These attributes affect code generation when interacting with ARC code, and
6180they are used by the Clang Static Analyzer.
6181
6182(os-retained-attr-family)=
6183
6184Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6185the same attribute family is present:
6186`__attribute__((os_returns_not_retained))`,
6187`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6188with the same respective semantics.
6189Similar to `__attribute__((ns_consumes_self))`,
6190`__attribute__((os_consumes_this))` specifies that the method call consumes
6191the reference to "this" (e.g., when attaching it to a different object supplied
6192as a parameter).
6193Out parameters (parameters the function is meant to write into,
6194either via pointers-to-pointers or references-to-pointers)
6195may be annotated with `__attribute__((os_returns_retained))`
6196or `__attribute__((os_returns_not_retained))` which specifies that the object
6197written into the out parameter should (or respectively should not) be released
6198after use.
6199Since often out parameters may or may not be written depending on the exit
6200code of the function,
6201annotations `__attribute__((os_returns_retained_on_zero))`
6202and `__attribute__((os_returns_retained_on_non_zero))` specify that
6203an out parameter at `+1` is written if and only if the function returns a zero
6204(respectively non-zero) error code.
6205Observe that return-code-dependent out parameter annotations are only
6206available for retained out parameters, as non-retained object do not have to be
6207released by the callee.
6208These attributes are only used by the Clang Static Analyzer.
6209
6210The family of attributes `X_returns_X_retained` can be added to functions,
6211C++ methods, and Objective-C methods and properties.
6212Attributes `X_consumed` can be added to parameters of methods, functions,
6213and Objective-C methods.)reST";
6214
6215static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6216(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6217convention (e.g. functions starting with "get" are assumed to return at
6218`+0`).
6219
6220It can be overridden using a family of the following attributes. In
6221Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6222a function communicates that the object is returned at `+1`, and the caller
6223is responsible for freeing it.
6224Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6225specifies that the object is returned at `+0` and the ownership remains with
6226the callee.
6227The annotation `__attribute__((ns_consumes_self))` specifies that
6228the Objective-C method call consumes the reference to `self`, e.g. by
6229attaching it to a supplied parameter.
6230Additionally, parameters can have an annotation
6231`__attribute__((ns_consumed))`, which specifies that passing an owned object
6232as that parameter effectively transfers the ownership, and the caller is no
6233longer responsible for it.
6234These attributes affect code generation when interacting with ARC code, and
6235they are used by the Clang Static Analyzer.
6236
6237In C programs using CoreFoundation, a similar set of attributes:
6238`__attribute__((cf_returns_not_retained))`,
6239`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6240have the same respective semantics when applied to CoreFoundation objects.
6241These attributes affect code generation when interacting with ARC code, and
6242they are used by the Clang Static Analyzer.
6243
6244(os-retained-attr-family)=
6245
6246Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6247the same attribute family is present:
6248`__attribute__((os_returns_not_retained))`,
6249`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6250with the same respective semantics.
6251Similar to `__attribute__((ns_consumes_self))`,
6252`__attribute__((os_consumes_this))` specifies that the method call consumes
6253the reference to "this" (e.g., when attaching it to a different object supplied
6254as a parameter).
6255Out parameters (parameters the function is meant to write into,
6256either via pointers-to-pointers or references-to-pointers)
6257may be annotated with `__attribute__((os_returns_retained))`
6258or `__attribute__((os_returns_not_retained))` which specifies that the object
6259written into the out parameter should (or respectively should not) be released
6260after use.
6261Since often out parameters may or may not be written depending on the exit
6262code of the function,
6263annotations `__attribute__((os_returns_retained_on_zero))`
6264and `__attribute__((os_returns_retained_on_non_zero))` specify that
6265an out parameter at `+1` is written if and only if the function returns a zero
6266(respectively non-zero) error code.
6267Observe that return-code-dependent out parameter annotations are only
6268available for retained out parameters, as non-retained object do not have to be
6269released by the callee.
6270These attributes are only used by the Clang Static Analyzer.
6271
6272The family of attributes `X_returns_X_retained` can be added to functions,
6273C++ methods, and Objective-C methods and properties.
6274Attributes `X_consumed` can be added to parameters of methods, functions,
6275and Objective-C methods.)reST";
6276
6277static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6278(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6279convention (e.g. functions starting with "get" are assumed to return at
6280`+0`).
6281
6282It can be overridden using a family of the following attributes. In
6283Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6284a function communicates that the object is returned at `+1`, and the caller
6285is responsible for freeing it.
6286Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6287specifies that the object is returned at `+0` and the ownership remains with
6288the callee.
6289The annotation `__attribute__((ns_consumes_self))` specifies that
6290the Objective-C method call consumes the reference to `self`, e.g. by
6291attaching it to a supplied parameter.
6292Additionally, parameters can have an annotation
6293`__attribute__((ns_consumed))`, which specifies that passing an owned object
6294as that parameter effectively transfers the ownership, and the caller is no
6295longer responsible for it.
6296These attributes affect code generation when interacting with ARC code, and
6297they are used by the Clang Static Analyzer.
6298
6299In C programs using CoreFoundation, a similar set of attributes:
6300`__attribute__((cf_returns_not_retained))`,
6301`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6302have the same respective semantics when applied to CoreFoundation objects.
6303These attributes affect code generation when interacting with ARC code, and
6304they are used by the Clang Static Analyzer.
6305
6306(os-retained-attr-family)=
6307
6308Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6309the same attribute family is present:
6310`__attribute__((os_returns_not_retained))`,
6311`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6312with the same respective semantics.
6313Similar to `__attribute__((ns_consumes_self))`,
6314`__attribute__((os_consumes_this))` specifies that the method call consumes
6315the reference to "this" (e.g., when attaching it to a different object supplied
6316as a parameter).
6317Out parameters (parameters the function is meant to write into,
6318either via pointers-to-pointers or references-to-pointers)
6319may be annotated with `__attribute__((os_returns_retained))`
6320or `__attribute__((os_returns_not_retained))` which specifies that the object
6321written into the out parameter should (or respectively should not) be released
6322after use.
6323Since often out parameters may or may not be written depending on the exit
6324code of the function,
6325annotations `__attribute__((os_returns_retained_on_zero))`
6326and `__attribute__((os_returns_retained_on_non_zero))` specify that
6327an out parameter at `+1` is written if and only if the function returns a zero
6328(respectively non-zero) error code.
6329Observe that return-code-dependent out parameter annotations are only
6330available for retained out parameters, as non-retained object do not have to be
6331released by the callee.
6332These attributes are only used by the Clang Static Analyzer.
6333
6334The family of attributes `X_returns_X_retained` can be added to functions,
6335C++ methods, and Objective-C methods and properties.
6336Attributes `X_consumed` can be added to parameters of methods, functions,
6337and Objective-C methods.)reST";
6338
6339static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6340(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6341convention (e.g. functions starting with "get" are assumed to return at
6342`+0`).
6343
6344It can be overridden using a family of the following attributes. In
6345Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6346a function communicates that the object is returned at `+1`, and the caller
6347is responsible for freeing it.
6348Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6349specifies that the object is returned at `+0` and the ownership remains with
6350the callee.
6351The annotation `__attribute__((ns_consumes_self))` specifies that
6352the Objective-C method call consumes the reference to `self`, e.g. by
6353attaching it to a supplied parameter.
6354Additionally, parameters can have an annotation
6355`__attribute__((ns_consumed))`, which specifies that passing an owned object
6356as that parameter effectively transfers the ownership, and the caller is no
6357longer responsible for it.
6358These attributes affect code generation when interacting with ARC code, and
6359they are used by the Clang Static Analyzer.
6360
6361In C programs using CoreFoundation, a similar set of attributes:
6362`__attribute__((cf_returns_not_retained))`,
6363`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6364have the same respective semantics when applied to CoreFoundation objects.
6365These attributes affect code generation when interacting with ARC code, and
6366they are used by the Clang Static Analyzer.
6367
6368(os-retained-attr-family)=
6369
6370Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6371the same attribute family is present:
6372`__attribute__((os_returns_not_retained))`,
6373`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6374with the same respective semantics.
6375Similar to `__attribute__((ns_consumes_self))`,
6376`__attribute__((os_consumes_this))` specifies that the method call consumes
6377the reference to "this" (e.g., when attaching it to a different object supplied
6378as a parameter).
6379Out parameters (parameters the function is meant to write into,
6380either via pointers-to-pointers or references-to-pointers)
6381may be annotated with `__attribute__((os_returns_retained))`
6382or `__attribute__((os_returns_not_retained))` which specifies that the object
6383written into the out parameter should (or respectively should not) be released
6384after use.
6385Since often out parameters may or may not be written depending on the exit
6386code of the function,
6387annotations `__attribute__((os_returns_retained_on_zero))`
6388and `__attribute__((os_returns_retained_on_non_zero))` specify that
6389an out parameter at `+1` is written if and only if the function returns a zero
6390(respectively non-zero) error code.
6391Observe that return-code-dependent out parameter annotations are only
6392available for retained out parameters, as non-retained object do not have to be
6393released by the callee.
6394These attributes are only used by the Clang Static Analyzer.
6395
6396The family of attributes `X_returns_X_retained` can be added to functions,
6397C++ methods, and Objective-C methods and properties.
6398Attributes `X_consumed` can be added to parameters of methods, functions,
6399and Objective-C methods.)reST";
6400
6401static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the `objc_boxable` attribute can be used
6402with the Objective-C boxed expression syntax, `@(...)`.
6403
6404**Usage**: `__attribute__((objc_boxable))`. This attribute
6405can only be placed on a declaration of a trivially-copyable struct or union:
6406
6407```objc
6408struct __attribute__((objc_boxable)) some_struct {
6409 int i;
6410};
6411union __attribute__((objc_boxable)) some_union {
6412 int i;
6413 float f;
6414};
6415typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6416
6417// ...
6418
6419some_struct ss;
6420NSValue *boxed = @(ss);
6421```)reST";
6422
6423static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6424
6425static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6426
6427static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6428
6429static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6430instantiated at runtime.
6431
6432Unlike `__attribute__((objc_runtime_visible))`, a class having this attribute
6433still has a "class stub" that is visible to the linker. This allows categories
6434to be defined. Static message sends with the class as a receiver use a special
6435access pattern to ensure the class is lazily instantiated from the class stub.
6436
6437Classes annotated with this attribute cannot be subclassed and cannot have
6438implementations defined for them. This attribute is intended for use in
6439Swift-generated headers for classes defined in Swift.
6440
6441Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6442
6443static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6444
6445static const char AttrDoc_ObjCDirect[] = R"reST(The `objc_direct` attribute can be used to mark an Objective-C method as
6446being *direct*. A direct method is treated statically like an ordinary method,
6447but dynamically it behaves more like a C function. This lowers some of the costs
6448associated with the method but also sacrifices some of the ordinary capabilities
6449of Objective-C methods.
6450
6451A message send of a direct method calls the implementation directly, as if it
6452were a C function, rather than using ordinary Objective-C method dispatch. This
6453is substantially faster and potentially allows the implementation to be inlined,
6454but it also means the method cannot be overridden in subclasses or replaced
6455dynamically, as ordinary Objective-C methods can.
6456
6457Furthermore, a direct method is not listed in the class's method lists. This
6458substantially reduces the code-size overhead of the method but also means it
6459cannot be called dynamically using ordinary Objective-C method dispatch at all;
6460in particular, this means that it cannot override a superclass method or satisfy
6461a protocol requirement.
6462
6463Because a direct method cannot be overridden, it is an error to perform
6464a `super` message send of one.
6465
6466Although a message send of a direct method causes the method to be called
6467directly as if it were a C function, it still obeys Objective-C semantics in other
6468ways:
6469
6470- If the receiver is `nil`, the message send does nothing and returns the zero value
6471 for the return type.
6472- A message send of a direct class method will cause the class to be initialized,
6473 including calling the `+initialize` method if present.
6474- The implicit `_cmd` parameter containing the method's selector is still defined.
6475 In order to minimize code-size costs, the implementation will not emit a reference
6476 to the selector if the parameter is unused within the method.
6477
6478Symbols for direct method implementations are implicitly given hidden
6479visibility, meaning that they can only be called within the same linkage unit.
6480
6481It is an error to do any of the following:
6482
6483- declare a direct method in a protocol,
6484- declare an override of a direct method with a method in a subclass,
6485- declare an override of a non-direct method with a direct method in a subclass,
6486- declare a method with different directness in different class interfaces, or
6487- implement a non-direct method (as declared in any class interface) with a direct method.
6488
6489If any of these rules would be violated if every method defined in an
6490`@implementation` within a single linkage unit were declared in an
6491appropriate class interface, the program is ill-formed with no diagnostic
6492required. If a violation of this rule is not diagnosed, behavior remains
6493well-defined; this paragraph is simply reserving the right to diagnose such
6494conflicts in the future, not to treat them as undefined behavior.
6495
6496Additionally, Clang will warn about any `@selector` expression that
6497names a selector that is only known to be used for direct methods.
6498
6499For the purpose of these rules, a "class interface" includes a class's primary
6500`@interface` block, its class extensions, its categories, its declared protocols,
6501and all the class interfaces of its superclasses.
6502
6503An Objective-C property can be declared with the `direct` property
6504attribute. If a direct property declaration causes an implicit declaration of
6505a getter or setter method (that is, if the given method is not explicitly
6506declared elsewhere), the method is declared to be direct.
6507
6508Some programmers may wish to make many methods direct at once. In order
6509to simplify this, the `objc_direct_members` attribute is provided; see its
6510documentation for more information.)reST";
6511
6512static const char AttrDoc_ObjCDirectMembers[] = R"reST(The `objc_direct_members` attribute can be placed on an Objective-C
6513`@interface` or `@implementation` to mark that methods declared
6514therein should be considered direct by default. See the documentation
6515for `objc_direct` for more information about direct methods.
6516
6517When `objc_direct_members` is placed on an `@interface` block, every
6518method in the block is considered to be declared as direct. This includes any
6519implicit method declarations introduced by property declarations. If the method
6520redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6521method was annotated with the `objc_direct` attribute.
6522
6523When `objc_direct_members` is placed on an `@implementation` block,
6524methods defined in the block are considered to be declared as direct unless
6525they have been previously declared as non-direct in any interface of the class.
6526This includes the implicit method definitions introduced by synthesized
6527properties, including auto-synthesized properties.)reST";
6528
6529static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6530
6531static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6532
6533static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The `objc_externally_retained` attribute can be applied to strong local
6534variables, functions, methods, or blocks to opt into
6535{ref}`externally-retained semantics <arc.misc.externally_retained>`.
6536
6537When applied to the definition of a function, method, or block, every parameter
6538of the function with implicit strong retainable object pointer type is
6539considered externally-retained, and becomes `const`. By explicitly annotating
6540a parameter with `__strong`, you can opt back into the default
6541non-externally-retained behavior for that parameter. For instance,
6542`first_param` is externally-retained below, but not `second_param`:
6543
6544```objc
6545__attribute__((objc_externally_retained))
6546void f(NSArray *first_param, __strong NSArray *second_param) {
6547 // ...
6548}
6549```
6550
6551Likewise, when applied to a strong local variable, that variable becomes
6552`const` and is considered externally-retained.
6553
6554When compiled without `-fobjc-arc`, this attribute is ignored.)reST";
6555
6556static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6557
6558static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6559
6560static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6561
6562static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6563
6564static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6565selectors. It is sometimes useful to be able to mark a method as having a
6566particular conventional meaning despite not having the right selector, or as
6567not having the conventional meaning that its selector would suggest. For these
6568use cases, we provide an attribute to specifically describe the "method family"
6569that a method belongs to.
6570
6571**Usage**: `__attribute__((objc_method_family(X)))`, where `X` is one of
6572`none`, `alloc`, `copy`, `init`, `mutableCopy`, or `new`. This
6573attribute can only be placed at the end of a method declaration:
6574
6575```objc
6576- (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6577```
6578
6579Users who do not wish to change the conventional meaning of a method, and who
6580merely want to document its non-standard retain and release semantics, should
6581use the retaining behavior attributes (`ns_returns_retained`,
6582`ns_returns_not_retained`, etc).
6583
6584Query for this feature with `__has_attribute(objc_method_family)`.)reST";
6585
6586static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6587
6588static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C `@interface` or
6589`@implementation` declaration to add the class to the list of non-lazily
6590initialized classes. A non-lazy class will be initialized eagerly when the
6591Objective-C runtime is loaded. This is required for certain system classes which
6592have instances allocated in non-standard ways, such as the classes for blocks
6593and constant strings. Adding this attribute is essentially equivalent to
6594providing a trivial `+load` method but avoids the (fairly small) load-time
6595overheads associated with defining and calling such a method.)reST";
6596
6597static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The `objc_non_runtime_protocol` attribute can be used to mark that an
6598Objective-C protocol is only used during static type-checking and doesn't need
6599to be represented dynamically. This avoids several small code-size and run-time
6600overheads associated with handling the protocol's metadata. A non-runtime
6601protocol cannot be used as the operand of a `@protocol` expression, and
6602dynamic attempts to find it with `objc_getProtocol` will fail.
6603
6604If a non-runtime protocol inherits from any ordinary protocols, classes and
6605derived protocols that declare conformance to the non-runtime protocol will
6606dynamically list their conformance to those bare protocols.)reST";
6607
6608static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6609
6610static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6611
6612static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6613
6614static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6615parent class but expect that the overriding method also calls the overridden
6616method in the parent class. For these cases, we provide an attribute to
6617designate that a method requires a "call to `super`" in the overriding
6618method in the subclass.
6619
6620**Usage**: `__attribute__((objc_requires_super))`. This attribute can only
6621be placed at the end of a method declaration:
6622
6623```objc
6624- (void)foo __attribute__((objc_requires_super));
6625```
6626
6627This attribute can only be applied the method declarations within a class, and
6628not a protocol. Currently this attribute does not enforce any placement of
6629where the call occurs in the overriding method (such as in the case of
6630`-dealloc` where the call must appear at the end). It checks only that it
6631exists.
6632
6633Note that on both OS X and iOS that the Foundation framework provides a
6634convenience macro `NS_REQUIRES_SUPER` that provides syntactic sugar for this
6635attribute:
6636
6637```objc
6638- (void)foo NS_REQUIRES_SUPER;
6639```
6640
6641This macro is conditionally defined depending on the compiler's support for
6642this attribute. If the compiler does not support the attribute the macro
6643expands to nothing.
6644
6645Operationally, when a method has this annotation the compiler will warn if the
6646implementation of an override in a subclass does not call super. For example:
6647
6648```objc
6649warning: method possibly missing a [super AnnotMeth] call
6650- (void) AnnotMeth{};
6651 ^
6652```)reST";
6653
6654static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6655
6656static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6657
6658static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6659in the metadata name for that object. The `objc_runtime_name`
6660attribute allows annotated interfaces or protocols to use the
6661specified string argument in the object's metadata name instead of the
6662default name.
6663
6664**Usage**: `__attribute__((objc_runtime_name("MyLocalName")))`. This attribute
6665can only be placed before an @protocol or @interface declaration:
6666
6667```objc
6668__attribute__((objc_runtime_name("MyLocalName")))
6669@interface Message
6670@end
6671```)reST";
6672
6673static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6674visible to the Objective-C runtime but not to the linker. Classes annotated
6675with this attribute cannot be subclassed and cannot have categories defined for
6676them.)reST";
6677
6678static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C `@interface` declaration to
6679ensure that this class cannot be subclassed.)reST";
6680
6681static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6682
6683static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6684
6685static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6686to declare if they are being read or written by a kernel or function.
6687
6688The `read_only`, `__read_only`, `write_only`, `__write_only`, `read_write`, and `__read_write`
6689names are reserved for use as access qualifiers and shall not be used otherwise.
6690
6691```c
6692kernel void
6693foo (read_only image2d_t imageA,
6694 write_only image2d_t imageB) {
6695 ...
6696}
6697```
6698
6699In the above example imageA is a read-only 2D image object, and imageB is a
6700write-only 2D image object.
6701
6702The `read_write` (or `__read_write`) qualifier cannot be used with pipe arguments.
6703
6704More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6705
6706static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6707a constant (non-modifiable) memory region. It is available to all work items.
6708Any type can be annotated with the constant address space attribute. Objects
6709with the constant address space qualifier can be declared in any scope and must
6710have an initializer.)reST";
6711
6712static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6713It can be used with pointer types. Variables in global and local scope and
6714function parameters in non-kernel functions can have the generic address space
6715type attribute. It is intended to be a placeholder for any other address space
6716except for `__constant` in OpenCL code which can be used with multiple address
6717spaces.)reST";
6718
6719static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6720global memory, which is accessible by all work items. The content stored in this
6721memory area persists between kernel executions. Pointer types to the global
6722address space are allowed as function parameters or local variables. Starting
6723with OpenCL v2.0, the global address space can be used with global (program
6724scope) variables and static local variable as well.)reST";
6725
6726static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6727an object is allocated in global memory on the device/host. It helps to
6728distinguish USM (Unified Shared Memory) pointers that access global device
6729memory from those that access global host memory. These new address spaces are
6730a subset of the `__global/opencl_global` address space, the full address space
6731set model for OpenCL 2.0 with the extension looks as follows:
6732
6733```text
6734generic->global->host
6735 ->device
6736 ->private
6737 ->local
6738constant
6739```
6740
6741As `global_device` and `global_host` are a subset of
6742`__global/opencl_global` address spaces it is allowed to convert
6743`global_device` and `global_host` address spaces to
6744`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6745"Address space nesting and rules for pointers").
6746
6747These attributes are deprecated and may be removed in a future version of Clang.)reST";
6748
6749static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6750an object is allocated in global memory on the device/host. It helps to
6751distinguish USM (Unified Shared Memory) pointers that access global device
6752memory from those that access global host memory. These new address spaces are
6753a subset of the `__global/opencl_global` address space, the full address space
6754set model for OpenCL 2.0 with the extension looks as follows:
6755
6756```text
6757generic->global->host
6758 ->device
6759 ->private
6760 ->local
6761constant
6762```
6763
6764As `global_device` and `global_host` are a subset of
6765`__global/opencl_global` address spaces it is allowed to convert
6766`global_device` and `global_host` address spaces to
6767`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6768"Address space nesting and rules for pointers").
6769
6770These attributes are deprecated and may be removed in a future version of Clang.)reST";
6771
6772static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6773the kernel must be compiled and executed with the specified subgroup size. When
6774this attribute is present, get_max_sub_group_size() is guaranteed to return the
6775specified integer value. This is important for the correctness of many subgroup
6776algorithms, and in some cases may be used by the compiler to generate more optimal
6777code. See
6778[`cl_intel_required_subgroup_size`](https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.html)
6779for details.)reST";
6780
6781static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6782group) memory area, which is accessible to all work items in the same work
6783group. The content stored in this memory region is not accessible after
6784the kernel execution ends. In a kernel function scope, any variable can be in
6785the local address space. In other scopes, only pointer types to the local address
6786space are allowed. Local address space variables cannot have an initializer.)reST";
6787
6788static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6789(work item) memory. Other work items cannot access the same memory area and its
6790content is destroyed after work item execution ends. Local variables can be
6791declared in the private address space. Function arguments are always in the
6792private address space. Kernel function arguments of a pointer or an array type
6793cannot point to the private address space.)reST";
6794
6795static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The `opencl_unroll_hint` attribute qualifier can be used to specify that a loop
6796(for, while and do loops) can be unrolled. This attribute qualifier can be
6797used to specify full unrolling or partial unrolling by a specified amount.
6798This is a compiler hint and the compiler may ignore this directive. See
6799[OpenCL v2.0](https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf)
6800s6.11.5 for details.)reST";
6801
6802static const char AttrDoc_OptimizeNone[] = R"reST(The `optnone` attribute suppresses essentially all optimizations
6803on a function or method, regardless of the optimization level applied to
6804the compilation unit as a whole. This is particularly useful when you
6805need to debug a particular function, but it is infeasible to build the
6806entire application without optimization. Avoiding optimization on the
6807specified function can improve the quality of the debugging information
6808for that function.
6809
6810This attribute is incompatible with the `always_inline` and `minsize`
6811attributes.
6812
6813Note that this attribute does not apply recursively to nested functions such as
6814lambdas or blocks when using declaration-specific attribute syntaxes such as double
6815square brackets (`[[]]`) or `__attribute__`. The `#pragma` syntax can be
6816used to apply the attribute to all functions, including nested functions, in a
6817range of source code.)reST";
6818
6819static const char AttrDoc_OverflowBehavior[] = R"reST(The `overflow_behavior` attribute provides fine-grained, type-level control
6820over how arithmetic operations on an integer type behave on overflow. It may be
6821applied to a `typedef`, to a variable or data member, or to an integer type
6822directly, and accepts one of two behaviors as its argument:
6823
6824- `wrap`: arithmetic on the attributed type wraps on overflow, using two's
6825 complement semantics. This is equivalent to `-fwrapv` but scoped to the
6826 attributed type, and works for both signed and unsigned types. UBSan's
6827 `signed-integer-overflow`, `unsigned-integer-overflow`,
6828 `implicit-signed-integer-truncation`, and
6829 `implicit-unsigned-integer-truncation` checks are suppressed for the type.
6830- `trap`: arithmetic on the attributed type is checked for overflow, enabling
6831 overflow checks for the type even when `-fwrapv` is in effect globally.
6832
6833```c++
6834typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint;
6835
6836non_wrapping_uint add_one(non_wrapping_uint a) {
6837 return a + 1; // Overflow is checked for this operation.
6838}
6839
6840int mul_alot(int n) {
6841 int __attribute__((overflow_behavior(wrap))) a = n;
6842 return a * 1337; // Overflow is not checked and is well-defined.
6843}
6844```
6845
6846The keyword spellings `__ob_wrap` and `__ob_trap` are equivalent to
6847`overflow_behavior(wrap)` and `overflow_behavior(trap)` respectively.
6848
6849The attribute wholly overrides global flags (`-ftrapv`, `-fwrapv`,
6850sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can
6851only be applied to integer types.
6852
6853This feature is experimental and must be enabled with the `-cc1` option
6854`-fexperimental-overflow-behavior-types`. For full details on promotion and
6855conversion rules, pointer semantics, diagnostics, and interaction with
6856sanitizers, see {doc}`OverflowBehaviorTypes`.)reST";
6857
6858static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6859in C is introduced using the `overloadable` attribute. For example, one
6860might provide several overloaded versions of a `tgsin` function that invokes
6861the appropriate standard function computing the sine of a value with `float`,
6862`double`, or `long double` precision:
6863
6864```c
6865#include <math.h>
6866float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6867double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6868long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6869```
6870
6871Given these declarations, one can call `tgsin` with a `float` value to
6872receive a `float` result, with a `double` to receive a `double` result,
6873etc. Function overloading in C follows the rules of C++ function overloading
6874to pick the best overload given the call arguments, with a few C-specific
6875semantics:
6876
6877- Conversion from `float` or `double` to `long double` is ranked as a
6878 floating-point promotion (per C99) rather than as a floating-point conversion
6879 (as in C++).
6880- A conversion from a pointer of type `T*` to a pointer of type `U*` is
6881 considered a pointer conversion (with conversion rank) if `T` and `U` are
6882 compatible types.
6883- A conversion from type `T` to a value of type `U` is permitted if `T`
6884 and `U` are compatible types. This conversion is given "conversion" rank.
6885- If no viable candidates are otherwise available, we allow a conversion from a
6886 pointer of type `T*` to a pointer of type `U*`, where `T` and `U` are
6887 incompatible. This conversion is ranked below all other types of conversions.
6888 Please note: `U` lacking qualifiers that are present on `T` is sufficient
6889 for `T` and `U` to be incompatible.
6890
6891The declaration of `overloadable` functions is restricted to function
6892declarations and definitions. If a function is marked with the `overloadable`
6893attribute, then all declarations and definitions of functions with that name,
6894except for at most one (see the note below about unmarked overloads), must have
6895the `overloadable` attribute. In addition, redeclarations of a function with
6896the `overloadable` attribute must have the `overloadable` attribute, and
6897redeclarations of a function without the `overloadable` attribute must *not*
6898have the `overloadable` attribute. e.g.,
6899
6900```c
6901int f(int) __attribute__((overloadable));
6902float f(float); // error: declaration of "f" must have the "overloadable" attribute
6903int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6904
6905int g(int) __attribute__((overloadable));
6906int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6907
6908int h(int);
6909int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6910 // have the "overloadable" attribute
6911```
6912
6913Functions marked `overloadable` must have prototypes. Therefore, the
6914following code is ill-formed:
6915
6916```c
6917int h() __attribute__((overloadable)); // error: h does not have a prototype
6918```
6919
6920However, `overloadable` functions are allowed to use a ellipsis even if there
6921are no named parameters (as is permitted in C++). This feature is particularly
6922useful when combined with the `unavailable` attribute:
6923
6924```c++
6925void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6926```
6927
6928Functions declared with the `overloadable` attribute have their names mangled
6929according to the same rules as C++ function names. For example, the three
6930`tgsin` functions in our motivating example get the mangled names
6931`_Z5tgsinf`, `_Z5tgsind`, and `_Z5tgsine`, respectively. There are two
6932caveats to this use of name mangling:
6933
6934- Future versions of Clang may change the name mangling of functions overloaded
6935 in C, so you should not depend on an specific mangling. To be completely
6936 safe, we strongly urge the use of `static inline` with `overloadable`
6937 functions.
6938- The `overloadable` attribute has almost no meaning when used in C++,
6939 because names will already be mangled and functions are already overloadable.
6940 However, when an `overloadable` function occurs within an `extern "C"`
6941 linkage specification, its name *will* be mangled in the same way as it
6942 would in C.
6943
6944For the purpose of backwards compatibility, at most one function with the same
6945name as other `overloadable` functions may omit the `overloadable`
6946attribute. In this case, the function without the `overloadable` attribute
6947will not have its name mangled.
6948
6949For example:
6950
6951```c
6952// Notes with mangled names assume Itanium mangling.
6953int f(int);
6954int f(double) __attribute__((overloadable));
6955void foo() {
6956 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6957 // was marked with overloadable).
6958 f(1.0); // Emits a call to _Z1fd.
6959}
6960```
6961
6962Support for unmarked overloads is not present in some versions of clang. You may
6963query for it using `__has_extension(overloadable_unmarked)`.
6964
6965Query for this attribute with `__has_attribute(overloadable)`.)reST";
6966
6967static const char AttrDoc_Override[] = R"reST()reST";
6968
6969static const char AttrDoc_Owner[] = R"reST(:::{Note}
6970This attribute is experimental and its effect on analysis is subject to change in
6971a future version of clang.
6972:::
6973
6974The attribute `[[gsl::Owner(T)]]` applies to structs and classes that own an
6975object of type `T`:
6976
6977```
6978class [[gsl::Owner(int)]] IntOwner {
6979private:
6980 int value;
6981public:
6982 int *getInt() { return &value; }
6983};
6984```
6985
6986The argument `T` is optional and is ignored.
6987This attribute may be used by analysis tools and has no effect on code
6988generation. A `void` argument means that the class can own any type.
6989
6990See [Pointer](#pointer) for an example.)reST";
6991
6992static const char AttrDoc_Ownership[] = R"reST(:::{note}
6993In order for the Clang Static Analyzer to acknowledge these attributes, the
6994`Optimistic` config needs to be set to true for the checker
6995`unix.DynamicMemoryModeling`:
6996
6997`-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true`
6998:::
6999
7000These attributes are used by the Clang Static Analyzer's dynamic memory modeling
7001facilities to mark custom allocating/deallocating functions.
7002
7003All 3 attributes' first parameter of type string is the type of the allocation:
7004`malloc`, `new`, etc. to allow for catching {ref}`mismatched deallocation
7005<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
7006a function annotated with
7007returning a piece of memory of type `lasagna` but freed with a function
7008annotated to release `cheese` typed memory will result in mismatched
7009deallocation warning.
7010
7011The (currently) only allocation type having special meaning is `malloc` --
7012the Clang Static Analyzer makes sure that allocating functions annotated with
7013`malloc` are treated like they used the standard `malloc()`, and can be
7014safely deallocated with the standard `free()`.
7015
7016- Use `ownership_returns` to mark a function as an allocating function.
7017 It takes 1 or 2 arguments.
7018 The first argument is a user-provided identifier representing the "kind" of the allocation.
7019 This is basically what is enforced when checking the deallocation. This is mandatory.
7020 The second argument is optional.
7021 It represents the index of the parameter that represents the allocation size in bytes (counting from 1).
7022 The referenced parameter must have some integral type.
7023 This attribute may appear at most once per declaration.
7024 If this argument is not set, then tooling, such as the Clang Static Analyzer,
7025 won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses.
7026 However, such tooling could still warn if the wrong deallocation function
7027 was used for the `ownership_returns` attributed resource.
7028 If forward declarations have this attribute, those must have the same arguments.
7029- Use `ownership_takes` to mark a function as a deallocating function. Takes 2
7030 arguments: the allocation type, and the index of the parameter that is being
7031 deallocated (counting from 1).
7032- Use `ownership_holds` to mark that a function takes over the ownership of a
7033 piece of memory and will free it at some unspecified point in the future. Like
7034 `ownership_takes`, this takes 2 arguments: the allocation type, and the
7035 index of the parameter whose ownership will be taken over (counting from 1).
7036
7037The annotations `ownership_takes` and `ownership_holds` both prevent memory
7038leak reports (concerning the specified parameter); the difference between them
7039is that using taken memory is a use-after-free error, while using held memory
7040is assumed to be legitimate. However, releasing the held memory or passing it
7041to another holding call is reported by the analyzer as an "attempt to release
7042non-owned memory".
7043
7044Example:
7045
7046```c
7047// Denotes that my_malloc will return with a dynamically allocated piece of
7048// memory using malloc().
7049void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz);
7050
7051// 'sz' (parameter 1) is the allocation size.
7052void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz);
7053
7054// Denotes that my_free will deallocate its argument using free().
7055void __attribute((ownership_takes(malloc, 1))) my_free(void *);
7056
7057// Denotes that my_hold will take over the ownership of its argument that was
7058// allocated via malloc().
7059void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
7060```
7061
7062Further reading about dynamic memory modeling in the Clang Static Analyzer is
7063found in these checker docs:
7064{ref}`unix.Malloc <unix-Malloc>`, {ref}`unix.MallocSizeof <unix-MallocSizeof>`,
7065{ref}`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
7066{ref}`cplusplus.NewDelete <cplusplus-NewDelete>`,
7067{ref}`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
7068{ref}`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
7069Mind that many more checkers are affected by dynamic memory modeling changes to
7070some extent.
7071
7072Further reading for other annotations:
7073{doc}`Static Analyzer source annotations <analyzer/user-docs/Annotations>`.)reST";
7074
7075static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
7076
7077static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
7078function with annotated parameters will issue a warning if the corresponding
7079argument isn't in the expected state. The attribute is also used to set the
7080initial state of the parameter when analyzing the function's body.)reST";
7081
7082static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
7083
7084static const char AttrDoc_PassObjectSize[] = R"reST(:::{Note}
7085The mangling of functions with parameters that are annotated with
7086`pass_object_size` is subject to change. You can get around this by
7087using `__asm__("foo")` to explicitly name your functions, thus preserving
7088your ABI; also, non-overloadable C functions with `pass_object_size` are
7089not mangled.
7090:::
7091
7092The `pass_object_size(Type)` attribute can be placed on function parameters to
7093instruct clang to call `__builtin_object_size(param, Type)` at each callsite
7094of said function, and implicitly pass the result of this call in as an invisible
7095argument of type `size_t` directly after the parameter annotated with
7096`pass_object_size`. Clang will also replace any calls to
7097`__builtin_object_size(param, Type)` in the function by said implicit
7098parameter.
7099
7100Example usage:
7101
7102```c
7103int bzero1(char *const p __attribute__((pass_object_size(0))))
7104 __attribute__((noinline)) {
7105 int i = 0;
7106 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
7107 p[i] = 0;
7108 }
7109 return i;
7110}
7111
7112int main() {
7113 char chars[100];
7114 int n = bzero1(&chars[0]);
7115 assert(n == sizeof(chars));
7116 return 0;
7117}
7118```
7119
7120If successfully evaluating `__builtin_object_size(param, Type)` at the
7121callsite is not possible, then the "failed" value is passed in. So, using the
7122definition of `bzero1` from above, the following code would exit cleanly:
7123
7124```c
7125int main2(int argc, char *argv[]) {
7126 int n = bzero1(argv);
7127 assert(n == -1);
7128 return 0;
7129}
7130```
7131
7132`pass_object_size` plays a part in overload resolution. If two overload
7133candidates are otherwise equally good, then the overload with one or more
7134parameters with `pass_object_size` is preferred. This implies that the choice
7135between two identical overloads both with `pass_object_size` on one or more
7136parameters will always be ambiguous; for this reason, having two such overloads
7137is illegal. For example:
7138
7139```c++
7140#define PS(N) __attribute__((pass_object_size(N)))
7141// OK
7142void Foo(char *a, char *b); // Overload A
7143// OK -- overload A has no parameters with pass_object_size.
7144void Foo(char *a PS(0), char *b PS(0)); // Overload B
7145// Error -- Same signature (sans pass_object_size) as overload B, and both
7146// overloads have one or more parameters with the pass_object_size attribute.
7147void Foo(void *a PS(0), void *b);
7148
7149// OK
7150void Bar(void *a PS(0)); // Overload C
7151// OK
7152void Bar(char *c PS(1)); // Overload D
7153
7154void main() {
7155 char known[10], *unknown;
7156 Foo(unknown, unknown); // Calls overload B
7157 Foo(known, unknown); // Calls overload B
7158 Foo(unknown, known); // Calls overload B
7159 Foo(known, known); // Calls overload B
7160
7161 Bar(known); // Calls overload D
7162 Bar(unknown); // Calls overload D
7163}
7164```
7165
7166Currently, `pass_object_size` is a bit restricted in terms of its usage:
7167
7168- Only one use of `pass_object_size` is allowed per parameter.
7169- It is an error to take the address of a function with `pass_object_size` on
7170 any of its parameters. If you wish to do this, you can create an overload
7171 without `pass_object_size` on any parameters.
7172- It is an error to apply the `pass_object_size` attribute to parameters that
7173 are not pointers. Additionally, any parameter that `pass_object_size` is
7174 applied to must be marked `const` at its function's definition.
7175
7176Clang also supports the `pass_dynamic_object_size` attribute, which behaves
7177identically to `pass_object_size`, but evaluates a call to
7178`__builtin_dynamic_object_size` at the callee instead of
7179`__builtin_object_size`. `__builtin_dynamic_object_size` provides some extra
7180runtime checks when the object size can't be determined at compile-time. You can
7181read more about `__builtin_dynamic_object_size` in
7182{ref}`Evaluating Object Size <langext-evaluating-object-size>`.)reST";
7183
7184static const char AttrDoc_PatchableFunctionEntry[] = R"reST(`__attribute__((patchable_function_entry(N,M,Section)))` is used to generate M
7185NOPs before the function entry and N-M NOPs after the function entry, with a record of
7186the entry stored in section `Section`. This attribute takes precedence over the
7187command line option `-fpatchable-function-entry=N,M,Section`. `M` defaults to 0
7188if omitted. `Section` defaults to the `-fpatchable-function-entry` section name if
7189set, or to `__patchable_function_entries` otherwise.
7190
7191This attribute is only supported on
7192aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
7193For ppc/ppc64 targets, AIX is still not supported.)reST";
7194
7195static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
7196similar to `stdcall` on x86. Valid parameter values are "aapcs" and
7197"aapcs-vfp".)reST";
7198
7199static const char AttrDoc_Personality[] = R"reST(`__attribute__((personality(<routine>)))` is used to specify a personality
7200routine that is different from the language that is being used to implement the
7201function. This is a targeted, low-level feature aimed at language runtime
7202implementors who write runtime support code in C/C++ but need that code to
7203participate in a foreign language's exception-handling or unwinding model.
7204
7205A personality routine is a language-specific callback attached to each stack
7206frame that the unwinder invokes to determine whether that frame handles a given
7207exception and what cleanup actions to perform. It effectively colors the
7208language-agnostic unwinding mechanism with language-specific semantics, enabling
7209different languages to coexist on the same call stack while each interpreting
7210exceptions according to their own rules.)reST";
7211
7212static const char AttrDoc_Pointer[] = R"reST(:::{Note}
7213This attribute is experimental and its effect on analysis is subject to change in
7214a future version of clang.
7215:::
7216
7217The attribute `[[gsl::Pointer(T)]]` applies to structs and classes that behave
7218like pointers to an object of type `T`:
7219
7220```
7221class [[gsl::Pointer(int)]] IntPointer {
7222private:
7223 int *valuePointer;
7224public:
7225 IntPointer(const IntOwner&);
7226 int *getInt() { return valuePointer; }
7227};
7228```
7229
7230The argument `T` is optional and is ignored.
7231This attribute may be used by analysis tools and has no effect on code
7232generation. A `void` argument means that the pointer can point to any type.
7233
7234Example:
7235When constructing an instance of a class annotated like this (a Pointer) from
7236an instance of a class annotated with `[[gsl::Owner]]` (an Owner),
7237then the analysis will consider the Pointer to point inside the Owner.
7238When the Owner's lifetime ends, it will consider the Pointer to be dangling.
7239
7240```c++
7241int f() {
7242 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
7243 P.getInt(); // P is dangling
7244}
7245```
7246
7247**Transparent Member Functions**
7248
7249The analysis automatically tracks certain member functions of `[[gsl::Pointer]]` types
7250that provide transparent access to the pointed-to object. These include:
7251
7252- Dereference operators: `operator*`, `operator->`
7253- Data access methods: `data()`, `c_str()`, `get()`
7254- Iterator operations: `begin()`, `end()`, `rbegin()`, `rend()`, `cbegin()`, `cend()`, `crbegin()`, `crend()`, `operator+`, `operator-`, `operator++`, `operator--`
7255
7256When these methods return pointers, view types, or references, the analysis treats them as
7257transparently borrowing from the same object that the pointer itself borrows from,
7258enabling detection of use-after-free through these access patterns:
7259
7260```c++
7261// For example, .data() here returns a borrow to 's' instead of 'v'.
7262const char* f() {
7263 std::string s = "hello";
7264 std::string_view v = s; // warning: address of stack memory returned
7265 return v.data(); // note: returned here
7266}
7267
7268const MyObj& g(MyObj obj) {
7269 View v = obj; // warning: address of stack memory returned
7270 return *v; // note: returned here
7271}
7272```
7273
7274This tracking also applies to range-based for loops, where the `begin()` and `end()`
7275iterators are used to access elements:
7276
7277```c++
7278std::string_view f(std::vector<std::string> vec) {
7279 for (const std::string& s : vec) { // warning: address of stack memory returned
7280 return s; // note: returned here
7281 }
7282}
7283```
7284
7285**Container Template Specialization**
7286
7287If a template class is annotated with `[[gsl::Owner]]`, and the first
7288instantiated template argument is a pointer type (raw pointer, or `[[gsl::Pointer]]`),
7289the analysis will consider the instantiated class as a container of the pointer.
7290When constructing such an object from a GSL owner object, the analysis will
7291assume that the container holds a pointer to the owner object. Consequently,
7292when the owner object is destroyed, the pointer will be considered dangling.
7293
7294```c++
7295int f() {
7296 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
7297 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
7298}
7299```)reST";
7300
7301static const char AttrDoc_PointerAuth[] = R"reST(The `__ptrauth` qualifier allows the programmer to directly control
7302how pointers are signed when they are stored in a particular variable.
7303This can be used to strengthen the default protections of pointer
7304authentication and make it more difficult for an attacker to escalate
7305an ability to alter memory into full control of a process.
7306
7307```c
7308#include <ptrauth.h>
7309
7310typedef void (*my_callback)(const void*);
7311my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
7312```
7313
7314The first argument to `__ptrauth` is the name of the signing key.
7315Valid key names for the target are defined in `<ptrauth.h>`.
7316
7317The second argument to `__ptrauth` is a flag (0 or 1) specifying whether
7318the object should use address discrimination.
7319
7320The third argument to `__ptrauth` is a 16-bit non-negative integer which
7321allows additional discrimination between objects.)reST";
7322
7323static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
7324
7325static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
7326
7327static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
7328
7329static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
7330
7331static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
7332
7333static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
7334
7335static const char AttrDoc_PreferredName[] = R"reST(The `preferred_name` attribute can be applied to a class template, and
7336specifies a preferred way of naming a specialization of the template. The
7337preferred name will be used whenever the corresponding template specialization
7338would otherwise be printed in a diagnostic or similar context.
7339
7340The preferred name must be a typedef or type alias declaration that refers to a
7341specialization of the class template (not including any type qualifiers). In
7342general this requires the template to be declared at least twice. For example:
7343
7344```c++
7345template<typename T> struct basic_string;
7346using string = basic_string<char>;
7347using wstring = basic_string<wchar_t>;
7348template<typename T> struct [[clang::preferred_name(string),
7349 clang::preferred_name(wstring)]] basic_string {
7350 // ...
7351};
7352```
7353
7354Note that the `preferred_name` attribute will be ignored when the compiler
7355writes a C++20 Module interface now. This is due to a compiler issue
7356(<https://github.com/llvm/llvm-project/issues/56490>) that blocks users to modularize
7357declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
7358
7359static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
7360This can be helpful when a bit-field is intended to store an enumeration value,
7361but has to be specified as having the enumeration's underlying type in order to
7362facilitate compiler optimizations or bit-field packing behavior. Normally, the
7363underlying type is what is emitted in debug information, which can make it hard
7364for debuggers to know to map a bit-field's value back to a particular enumeration.
7365
7366```c++
7367enum Colors { Red, Green, Blue };
7368
7369struct S {
7370 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
7371 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
7372} s = { Green, false };
7373```
7374
7375Without the attribute, a debugger is likely to display the value `1` for `ColorVal`
7376and `0` for `UseAlternateColorSpace`. With the attribute, the debugger may now
7377display `Green` and `false` instead.
7378
7379This can be used to map a bit-field to an arbitrary type that isn't integral
7380or an enumeration type. For example:
7381
7382```c++
7383struct A {
7384 short a1;
7385 short a2;
7386};
7387
7388struct B {
7389 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7390};
7391```
7392
7393will associate the type `A` with the `b1` bit-field and is intended to display
7394something like this in the debugger:
7395
7396```text
7397Process 2755547 stopped
7398* thread #1, name = 'test-preferred-', stop reason = step in
7399 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7400 10 int main()
7401 11 {
7402 12 B b;
7403-> 13 return b.b1;
7404 14 }
7405(lldb) v -T
7406(B) b = {
7407 (A:32) b1 = {
7408 (short) a1 = 12
7409 (short) a2 = 15
7410 }
7411}
7412```
7413
7414Note that debuggers may not be able to handle more complex mappings, and so
7415this usage is debugger-dependent.)reST";
7416
7417static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7418a function. The `preserve_all` calling convention attempts to make the code
7419in the caller even less intrusive than the `preserve_most` calling convention.
7420This calling convention also behaves identical to the `C` calling convention
7421on how arguments and return values are passed, but it uses a different set of
7422caller/callee-saved registers. This removes the burden of saving and
7423recovering a large register set before and after the call in the caller. If
7424the arguments are passed in callee-saved registers, then they will be
7425preserved by the callee across the call. This doesn't apply for values
7426returned in callee-saved registers.
7427
7428- On X86-64 the callee preserves all general purpose registers, except for
7429 R11. R11 can be used as a scratch register. Furthermore it also preserves
7430 all floating-point registers (XMMs/YMMs).
7431- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7432 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7433 point registers.
7434
7435The idea behind this convention is to support calls to runtime functions
7436that don't need to call out to any other functions.
7437
7438This calling convention, like the `preserve_most` calling convention, will be
7439used by a future version of the Objective-C runtime and should be considered
7440experimental at this time.)reST";
7441
7442static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7443a function. The `preserve_most` calling convention attempts to make the code
7444in the caller as unintrusive as possible. This convention behaves identically
7445to the `C` calling convention on how arguments and return values are passed,
7446but it uses a different set of caller/callee-saved registers. This alleviates
7447the burden of saving and recovering a large register set before and after the
7448call in the caller. If the arguments are passed in callee-saved registers,
7449then they will be preserved by the callee across the call. This doesn't
7450apply for values returned in callee-saved registers.
7451
7452- On X86-64 the callee preserves all general purpose registers, except for
7453 R11. R11 can be used as a scratch register. Floating-point registers
7454 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7455- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7456 X16-X18.
7457
7458The idea behind this convention is to support calls to runtime functions
7459that have a hot path and a cold path. The hot path is usually a small piece
7460of code that doesn't use many registers. The cold path might need to call out to
7461another function and therefore only needs to preserve the caller-saved
7462registers, which haven't already been saved by the caller. The
7463`preserve_most` calling convention is very similar to the `cold` calling
7464convention in terms of caller/callee-saved registers, but they are used for
7465different types of function calls. `coldcc` is for function calls that are
7466rarely executed, whereas `preserve_most` function calls are intended to be
7467on the hot path and definitely executed a lot. Furthermore `preserve_most`
7468doesn't prevent the inliner from inlining the function call.
7469
7470This convention was created to optimize certain runtime calls to the
7471Objective-C runtime, but it is not limited to that runtime; it is also used by
7472other runtimes and libraries, such as the Swift runtime and the Linux kernel.
7473The current implementation only supports X86-64 and AArch64, but the intention
7474is to support more architectures in the future.)reST";
7475
7476static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7477The `preserve_none` calling convention tries to preserve as few general
7478registers as possible. So all general registers are caller saved registers. It
7479also uses more general registers to pass arguments. This attribute doesn't
7480impact floating-point registers. `preserve_none`'s ABI is still unstable, and
7481may be changed in the future.
7482
7483- On X86-64, only RSP and RBP are preserved by the callee.
7484 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7485 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7486 follow the C calling convention.
7487- On AArch64, only LR and FP are preserved by the callee.
7488 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7489 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7490 convention. X15 is not available for argument passing on Windows, but is
7491 used to pass arguments on other platforms.)reST";
7492
7493static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7494
7495static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7496
7497static const char AttrDoc_Ptr32[] = R"reST(The `__ptr32` qualifier represents a native pointer on a 32-bit system. On a
749864-bit system, a pointer with `__ptr32` is extended to a 64-bit pointer. The
7499`__sptr` and `__uptr` qualifiers can be used to specify whether the pointer
7500is sign extended or zero extended. This qualifier is enabled under
7501`-fms-extensions`.)reST";
7502
7503static const char AttrDoc_Ptr64[] = R"reST(The `__ptr64` qualifier represents a native pointer on a 64-bit system. On a
750432-bit system, a `__ptr64` pointer is truncated to a 32-bit pointer. This
7505qualifier is enabled under `-fms-extensions`.)reST";
7506
7507static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7508
7509static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on RISCV
7510targets. This attribute may be attached to a function definition and instructs
7511the backend to generate appropriate function entry/exit code so that it can be
7512used directly as an interrupt service routine.
7513
7514Permissible values for this parameter are `machine`, `supervisor`,
7515`rnmi`, `qci-nest`, `qci-nonest`, `SiFive-CLIC-preemptible`, and
7516`SiFive-CLIC-stack-swap`. If there is no parameter, then it defaults to
7517`machine`.
7518
7519The `rnmi` value is used for resumable non-maskable interrupts. It requires the
7520standard Smrnmi extension.
7521
7522The `qci-nest` and `qci-nonest` values require Qualcomm's Xqciint extension
7523and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7524interrupts. These use the following instructions from Xqciint to save and
7525restore interrupt state to the stack -- the `qci-nest` value will use
7526`qc.c.mienter.nest` and the `qci-nonest` value will use `qc.c.mienter` to
7527begin the interrupt handler. Both of these will use `qc.c.mileaveret` to
7528restore the state and return to the previous context.
7529
7530The `SiFive-CLIC-preemptible` and `SiFive-CLIC-stack-swap` values are used
7531for machine-mode interrupts. For `SiFive-CLIC-preemptible` interrupts, the
7532values of `mcause` and `mepc` are saved onto the stack, and interrupts are
7533re-enabled. For `SiFive-CLIC-stack-swap` interrupts, the stack pointer is
7534swapped with `mscratch` before its first use and after its last use.
7535
7536The SiFive CLIC values may be combined with each other and with the `machine`
7537attribute value. Any other combination of different values is not allowed.
7538
7539Repeated interrupt attribute on the same declaration will cause a warning
7540to be emitted. In case of repeated declarations, the last one prevails.
7541
7542References:
7543- [GCC RISC-V Attributes](https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html)
7544- [The RISC-V Instruction Set Manual Volume II: Privileged Architecture Version 1.10](https://docs.riscv.org/reference/isa/v1.10/_attachments/riscv-privileged.pdf)
7545- [Xqci extension v0.13](https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0)
7546- [SiFive Interrupt Cookbook Version 1.2](https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf))reST";
7547
7548static const char AttrDoc_RISCVVLSCC[] = R"reST(The `riscv_vls_cc` attribute can be applied to a function. Functions
7549declared with this attribute will utilize the standard fixed-length vector
7550calling convention variant instead of the default calling convention defined by
7551the ABI. This variant aims to pass fixed-length vectors via vector registers,
7552if possible, rather than through general-purpose registers.)reST";
7553
7554static const char AttrDoc_RISCVVectorCC[] = R"reST(The `riscv_vector_cc` attribute can be applied to a function. It preserves 15
7555registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7556to save these registers before function calls, and callees only need to save
7557them if they use them.)reST";
7558
7559static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
7560for structure layout field randomization; a compile-time hardening technique. A
7561"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
7562For example:
7563
7564```bash
7565SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7566make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7567```
7568
7569You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
7570For example:
7571
7572```bash
7573od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7574make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7575```
7576
7577The randomization is deterministic based for a given seed, so the entire
7578program should be compiled with the same seed, but keep the seed safe
7579otherwise.
7580
7581The attribute `no_randomize_layout`, when attached to a C structure,
7582instructs the compiler that this structure should not have its field layout
7583randomized.)reST";
7584
7585static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7586
7587: When attached to a record declaration/definition, it checks if all instances
7588 of this type can be placed in the read-only data segment of the program. If it
7589 finds an instance that can not be placed in a read-only segment, the compiler
7590 emits a warning at the source location where the type was used.
7591
7592 Examples:
7593 - `struct __attribute__((enforce_read_only_placement)) Foo;`
7594 - `struct __attribute__((enforce_read_only_placement)) Bar { ... };`
7595
7596 Both `Foo` and `Bar` types have the `enforce_read_only_placement` attribute.
7597
7598 The goal of introducing this attribute is to assist developers with writing secure
7599 code. A `const`-qualified global is generally placed in the read-only section
7600 of the memory that has additional run time protection from malicious writes. By
7601 attaching this attribute to a declaration, the developer can express the intent
7602 to place all instances of the annotated type in the read-only program memory.
7603
7604 Note 1: The attribute doesn't guarantee that the object will be placed in the
7605 read-only data segment as it does not instruct the compiler to ensure such
7606 a placement. It emits a warning if something in the code can be proven to prevent
7607 an instance from being placed in the read-only data segment.
7608
7609 Note 2: Currently, clang only checks if all global declarations of a given type `T`
7610 are `const`-qualified. The following conditions would also prevent the data to be
7611 put into read only segment, but the corresponding warnings are not yet implemented.
7612
7613 1. An instance of type `T` is allocated on the heap/stack.
7614 2. Type `T` defines/inherits a mutable field.
7615 3. Type `T` defines/inherits non-constexpr constructor(s) for initialization.
7616 4. A field of type `T` is defined by type `Q`, which does not bear the
7617 `enforce_read_only_placement` attribute.
7618 5. A type `Q` inherits from type `T` and it does not have the
7619 `enforce_read_only_placement` attribute.)reST";
7620
7621static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7622
7623static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7624[`__regcall`][__regcall] convention. This convention aims to pass as many arguments
7625as possible in registers. It also tries to utilize registers for the
7626return value whenever it is possible.
7627
7628[__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";
7629
7630static const char AttrDoc_Reinitializes[] = R"reST(The `reinitializes` attribute can be applied to a non-static, non-const C++
7631member function to indicate that this member function reinitializes the entire
7632object to a known state, independent of the previous state of the object.
7633
7634This attribute can be interpreted by static analyzers that warn about uses of an
7635object that has been left in an indeterminate state by a move operation. If a
7636member function marked with the `reinitializes` attribute is called on a
7637moved-from object, the analyzer can conclude that the object is no longer in an
7638indeterminate state.
7639
7640A typical example where this attribute would be used is on functions that clear
7641a container class:
7642
7643```c++
7644template <class T>
7645class Container {
7646public:
7647 ...
7648 [[clang::reinitializes]] void Clear();
7649 ...
7650};
7651```)reST";
7652
7653static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7654
7655static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with `release_handle(tag)` it is assumed to
7656close the handle. It is also assumed to require an open handle to work with. The
7657attribute requires a string literal argument to identify the handle being released.
7658
7659```c++
7660zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);
7661```)reST";
7662
7663static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7664
7665static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7666
7667static const char AttrDoc_Restrict[] = R"reST(The `malloc` attribute has two forms with different functionality. The first
7668is when it is used without arguments, where it marks that a function acts like
7669a system memory allocation function, returning a pointer to allocated storage
7670that does not alias storage from any other object accessible to the caller.
7671
7672The second form is when `malloc` takes one or two arguments. The first
7673argument names a function that should be associated with this function as its
7674deallocation function. When this form is used, it enables the compiler to
7675diagnose when the incorrect deallocation function is used with this variable.
7676However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7677yet implemented in clang.)reST";
7678
7679static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7680section garbage collection in the linker. It does not prevent other discard
7681mechanisms, such as archive member selection, and COMDAT group resolution.
7682
7683If the compiler does not emit the definition, e.g. because it was not used in
7684the translation unit or the compiler was able to eliminate all of the uses,
7685this attribute has no effect. This attribute is typically combined with the
7686`used` attribute to force the definition to be emitted and preserved into the
7687final linked image.
7688
7689This attribute is only necessary on ELF targets; other targets prevent section
7690garbage collection by the linker when using the `used` attribute alone.
7691Using the attributes together should result in consistent behavior across
7692targets.
7693
7694This attribute requires the linker to support the `SHF_GNU_RETAIN` extension.
7695This support is available in GNU `ld` and `gold` as of binutils 2.36, as
7696well as in `ld.lld` 13.)reST";
7697
7698static const char AttrDoc_ReturnTypestate[] = R"reST(The `return_typestate` attribute can be applied to functions or parameters.
7699When applied to a function the attribute specifies the state of the returned
7700value. The function's body is checked to ensure that it always returns a value
7701in the specified state. On the caller side, values returned by the annotated
7702function are initialized to the given state.
7703
7704When applied to a function parameter it modifies the state of an argument after
7705a call to the function returns. The function's body is checked to ensure that
7706the parameter is in the expected state before returning.)reST";
7707
7708static const char AttrDoc_ReturnsNonNull[] = R"reST(The `returns_nonnull` attribute indicates that a particular function (or
7709Objective-C method) always returns a non-null pointer. For example, a
7710particular system `malloc` might be defined to terminate a process when
7711memory is not available rather than returning a null pointer:
7712
7713```c
7714extern void * malloc (size_t size) __attribute__((returns_nonnull));
7715```
7716
7717The `returns_nonnull` attribute implies that returning a null pointer is
7718undefined behavior, which the optimizer may take advantage of. The `_Nonnull`
7719type qualifier indicates that a pointer cannot be null in a more general manner
7720(because it is part of the type system) and does not imply undefined behavior,
7721making it more widely applicable)reST";
7722
7723static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7724
7725static const char AttrDoc_RootSignature[] = R"reST(The `RootSignature` attribute applies to HLSL entry functions to define what
7726types of resources are bound to the graphics pipeline.
7727
7728For details about the use and specification of Root Signatures please see here:
7729<https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures>)reST";
7730
7731static const char AttrDoc_SPtr[] = R"reST(The `__sptr` qualifier specifies that a 32-bit pointer should be sign
7732extended when converted to a 64-bit pointer.)reST";
7733
7734static const char AttrDoc_SYCLConstantAddressSpace[] = R"reST(:::{Note}
7735These attributes are intended for use in the implementation of SYCL run-time
7736libraries and should not be used in any other context.
7737Programmers writing code intended to conform to the SYCL specification should
7738use the address space facilities specified in the following sections of the
7739SYCL 2020 specification.
7740
7741* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
7742* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
7743* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
7744* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
7745* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
7746:::
7747
7748The SYCL address space attributes listed below correspond to the five address
7749spaces described by
7750[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
7751[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
7752
7753::: {list-table} SYCL address space attributes
7754:header-rows: 1
7755
7756* - Address space attribute
7757 - SYCL address space
7758 - Description
7759* - `[[clang::sycl_global]]`
7760 - global
7761 - A memory region accessible by all work-items executing on a device.
7762* - `[[clang::sycl_local]]`
7763 - local
7764 - A memory region accessible by all work-items of a single work-group.
7765* - `[[clang::sycl_private]]`
7766 - private
7767 - A memory region that is private to a single work-item.
7768* - `[[clang::sycl_generic]]`
7769 - generic
7770 - A virtual memory region from which the global, local, and private memory
7771 regions may all be accessed.
7772* - `[[clang::sycl_constant]]`
7773 - constant
7774 - (*deprecated*) A memory region that holds constant data for an executing
7775 kernel.
7776:::
7777
7778The SYCL address space attributes are type attributes that may be applied to
7779non-function non-reference types to specify an address space qualified type.
7780
7781A type with a SYCL address space qualifier is a distinct type from the
7782otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
7783designate distinct pointer types which participate in overload resolution and
7784template specialization.
7785
7786The top-level type of a variable declaration cannot have a SYCL address space
7787qualifier. For example:
7788
7789```c++
7790int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7791int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7792```
7793
7794Conversions between SYCL address space attributed types are permitted as
7795follows.
7796
7797- Types attributed with the global, local, or private address space attributes
7798 are implicitly convertible to matching types with the generic address space
7799 attribute.
7800
7801The mapping of SYCL address spaces to physical address spaces is target
7802dependent.
7803
7804For OpenCL device targets, the SYCL address space attributes are aligned with
7805the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
7806`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
7807distinct types both of which map to the same underlying address space.
7808Corresponding SYCL and OpenCL address space attributed types are implicitly
7809convertible; other conversions are permitted as described above; e.g.,
7810`int [[clang::sycl_global]]*` is implicitly convertible to
7811`int [[clang::opencl_generic]]*`.
7812
7813[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
7814[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
7815[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
7816[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
7817[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
7818[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
7819
7820static const char AttrDoc_SYCLExternal[] = R"reST(The `sycl_external` attribute indicates that a function defined in another
7821translation unit may be called by a device function defined in the current
7822translation unit or, if defined in the current translation unit, the function
7823may be called by device functions defined in other translation units.
7824The attribute is intended for use in the implementation of the `SYCL_EXTERNAL`
7825macro as specified in section 5.10.1, "SYCL functions and member functions
7826linkage", of the SYCL 2020 specification.
7827
7828The attribute only appertains to functions and only those that meet the
7829following requirements:
7830
7831- Has external linkage
7832- Is not explicitly defined as deleted (the function may be an explicitly
7833 defaulted function that is defined as deleted)
7834
7835The attribute shall be present on the first declaration of a function and
7836may optionally be present on subsequent declarations.
7837
7838When compiling for a SYCL device target that does not support the generic
7839address space, the function shall not specify a raw pointer or reference type
7840as the return type or as a parameter type.
7841See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7842The following examples demonstrate the use of this attribute:
7843
7844```c++
7845[[clang::sycl_external]] void Foo(); // Ok.
7846
7847[[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7848
7849[[clang::sycl_external]] extern void Baz(); // Ok.
7850
7851[[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.
7852```)reST";
7853
7854static const char AttrDoc_SYCLGenericAddressSpace[] = R"reST(:::{Note}
7855These attributes are intended for use in the implementation of SYCL run-time
7856libraries and should not be used in any other context.
7857Programmers writing code intended to conform to the SYCL specification should
7858use the address space facilities specified in the following sections of the
7859SYCL 2020 specification.
7860
7861* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
7862* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
7863* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
7864* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
7865* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
7866:::
7867
7868The SYCL address space attributes listed below correspond to the five address
7869spaces described by
7870[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
7871[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
7872
7873::: {list-table} SYCL address space attributes
7874:header-rows: 1
7875
7876* - Address space attribute
7877 - SYCL address space
7878 - Description
7879* - `[[clang::sycl_global]]`
7880 - global
7881 - A memory region accessible by all work-items executing on a device.
7882* - `[[clang::sycl_local]]`
7883 - local
7884 - A memory region accessible by all work-items of a single work-group.
7885* - `[[clang::sycl_private]]`
7886 - private
7887 - A memory region that is private to a single work-item.
7888* - `[[clang::sycl_generic]]`
7889 - generic
7890 - A virtual memory region from which the global, local, and private memory
7891 regions may all be accessed.
7892* - `[[clang::sycl_constant]]`
7893 - constant
7894 - (*deprecated*) A memory region that holds constant data for an executing
7895 kernel.
7896:::
7897
7898The SYCL address space attributes are type attributes that may be applied to
7899non-function non-reference types to specify an address space qualified type.
7900
7901A type with a SYCL address space qualifier is a distinct type from the
7902otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
7903designate distinct pointer types which participate in overload resolution and
7904template specialization.
7905
7906The top-level type of a variable declaration cannot have a SYCL address space
7907qualifier. For example:
7908
7909```c++
7910int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7911int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7912```
7913
7914Conversions between SYCL address space attributed types are permitted as
7915follows.
7916
7917- Types attributed with the global, local, or private address space attributes
7918 are implicitly convertible to matching types with the generic address space
7919 attribute.
7920
7921The mapping of SYCL address spaces to physical address spaces is target
7922dependent.
7923
7924For OpenCL device targets, the SYCL address space attributes are aligned with
7925the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
7926`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
7927distinct types both of which map to the same underlying address space.
7928Corresponding SYCL and OpenCL address space attributed types are implicitly
7929convertible; other conversions are permitted as described above; e.g.,
7930`int [[clang::sycl_global]]*` is implicitly convertible to
7931`int [[clang::opencl_generic]]*`.
7932
7933[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
7934[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
7935[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
7936[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
7937[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
7938[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
7939
7940static const char AttrDoc_SYCLGlobalAddressSpace[] = R"reST(:::{Note}
7941These attributes are intended for use in the implementation of SYCL run-time
7942libraries and should not be used in any other context.
7943Programmers writing code intended to conform to the SYCL specification should
7944use the address space facilities specified in the following sections of the
7945SYCL 2020 specification.
7946
7947* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
7948* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
7949* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
7950* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
7951* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
7952:::
7953
7954The SYCL address space attributes listed below correspond to the five address
7955spaces described by
7956[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
7957[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
7958
7959::: {list-table} SYCL address space attributes
7960:header-rows: 1
7961
7962* - Address space attribute
7963 - SYCL address space
7964 - Description
7965* - `[[clang::sycl_global]]`
7966 - global
7967 - A memory region accessible by all work-items executing on a device.
7968* - `[[clang::sycl_local]]`
7969 - local
7970 - A memory region accessible by all work-items of a single work-group.
7971* - `[[clang::sycl_private]]`
7972 - private
7973 - A memory region that is private to a single work-item.
7974* - `[[clang::sycl_generic]]`
7975 - generic
7976 - A virtual memory region from which the global, local, and private memory
7977 regions may all be accessed.
7978* - `[[clang::sycl_constant]]`
7979 - constant
7980 - (*deprecated*) A memory region that holds constant data for an executing
7981 kernel.
7982:::
7983
7984The SYCL address space attributes are type attributes that may be applied to
7985non-function non-reference types to specify an address space qualified type.
7986
7987A type with a SYCL address space qualifier is a distinct type from the
7988otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
7989designate distinct pointer types which participate in overload resolution and
7990template specialization.
7991
7992The top-level type of a variable declaration cannot have a SYCL address space
7993qualifier. For example:
7994
7995```c++
7996int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7997int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7998```
7999
8000Conversions between SYCL address space attributed types are permitted as
8001follows.
8002
8003- Types attributed with the global, local, or private address space attributes
8004 are implicitly convertible to matching types with the generic address space
8005 attribute.
8006
8007The mapping of SYCL address spaces to physical address spaces is target
8008dependent.
8009
8010For OpenCL device targets, the SYCL address space attributes are aligned with
8011the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
8012`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
8013distinct types both of which map to the same underlying address space.
8014Corresponding SYCL and OpenCL address space attributed types are implicitly
8015convertible; other conversions are permitted as described above; e.g.,
8016`int [[clang::sycl_global]]*` is implicitly convertible to
8017`int [[clang::opencl_generic]]*`.
8018
8019[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8020[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8021[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8022[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8023[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8024[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8025
8026static const char AttrDoc_SYCLKernel[] = R"reST(The `sycl_kernel` attribute specifies that a function template will be used
8027to outline device code and to generate an OpenCL kernel.
8028Here is a code example of the SYCL program, which demonstrates the compiler's
8029outlining job:
8030
8031```c++
8032int foo(int x) { return ++x; }
8033
8034using namespace cl::sycl;
8035queue Q;
8036buffer<int, 1> a(range<1>{1024});
8037Q.submit([&](handler& cgh) {
8038 auto A = a.get_access<access::mode::write>(cgh);
8039 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
8040 A[index] = index[0] + foo(42);
8041 });
8042}
8043```
8044
8045A C++ function object passed to the `parallel_for` is called a "SYCL kernel".
8046A SYCL kernel defines the entry point to the "device part" of the code. The
8047compiler will emit all symbols accessible from a "kernel". In this code
8048example, the compiler will emit "foo" function. More details about the
8049compilation of functions for the device part can be found in the SYCL 1.2.1
8050specification Section 6.4.
8051To show to the compiler entry point to the "device part" of the code, the SYCL
8052runtime can use the `sycl_kernel` attribute in the following way:
8053
8054```c++
8055namespace cl {
8056namespace sycl {
8057class handler {
8058 template <typename KernelName, typename KernelType/*, ...*/>
8059 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
8060 // ...
8061 KernelFuncObj();
8062 }
8063
8064 template <typename KernelName, typename KernelType, int Dims>
8065 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
8066#ifdef __SYCL_DEVICE_ONLY__
8067 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
8068#else
8069 // Host implementation
8070#endif
8071 }
8072};
8073} // namespace sycl
8074} // namespace cl
8075```
8076
8077The compiler will also generate an OpenCL kernel using the function marked with
8078the `sycl_kernel` attribute.
8079Here is the list of SYCL device compiler expectations with regard to the
8080function marked with the `sycl_kernel` attribute:
8081
8082- The function must be a template with at least two type template parameters.
8083 The compiler generates an OpenCL kernel and uses the first template parameter
8084 as a unique name for the generated OpenCL kernel. The host application uses
8085 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
8086 specialized by this name and second template parameter `KernelType` (which
8087 might be an unnamed function object type).
8088- The function must have at least one parameter. The first parameter is
8089 required to be a function object type (named or unnamed i.e. lambda). The
8090 compiler uses function object type fields to generate OpenCL kernel
8091 parameters.
8092- The function must return void. The compiler reuses the body of marked functions to
8093 generate the OpenCL kernel body, and the OpenCL kernel must return `void`.
8094
8095The SYCL kernel in the previous code sample meets these expectations.)reST";
8096
8097static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The `sycl_kernel_entry_point` attribute facilitates the launch of a SYCL
8098kernel and the generation of an offload kernel entry point, sometimes called
8099a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
8100offload device. The attribute is intended for use in the implementation of
8101SYCL kernel invocation functions like the `single_task` and `parallel_for`
8102member functions of the `sycl::handler` class specified in section 4.9.4,
8103"Command group `handler` class", of the SYCL 2020 specification.
8104
8105The attribute requires a single type argument that meets the requirements for
8106a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
8107SYCL 2020 specification. A unique kernel name type is required for each
8108function declared with the attribute. The attribute may not first appear on a
8109declaration that follows a definition of the function.
8110
8111The attribute only appertains to functions and only those that meet the
8112following requirements.
8113
8114- Has a non-deduced `void` return type.
8115- Is not a constructor or destructor.
8116- Is not a non-static member function with an explicit object parameter.
8117- Is not a C variadic function.
8118- Is not a coroutine.
8119- Is not defined as deleted or as defaulted.
8120- Is not defined with a function try block.
8121- Is not declared with the `constexpr` or `consteval` specifiers.
8122- Is not declared with the `[[noreturn]]` attribute.
8123
8124Use in the implementation of a SYCL kernel invocation function might look as
8125follows.
8126
8127```c++
8128namespace sycl {
8129class handler {
8130 template<typename KernelName, typename... Ts>
8131 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
8132 // This code will run on the host and is responsible for calling functions
8133 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
8134 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
8135 // to a device and to schedule an invocation of the offload kernel entry
8136 // point denoted by kernelSymbol with the copied arguments.
8137 }
8138
8139 template<typename KernelName, typename KernelType>
8140 [[ clang::sycl_kernel_entry_point(KernelName) ]]
8141 void kernel_entry_point(KernelType kernelFunc) {
8142 // This code will run on the device. The call to kernelFunc() invokes
8143 // the SYCL kernel.
8144 kernelFunc();
8145 }
8146
8147public:
8148 template<typename KernelName, typename KernelType>
8149 void single_task(const KernelType& kernelFunc) {
8150 // This code will run on the host. kernel_entry_point() is called to
8151 // trigger generation of an offload kernel entry point and to schedule
8152 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
8153 // passed as a kernel argument. This call will result in an implicit call
8154 // to sycl_kernel_launch() with the symbol name for the generated offload
8155 // kernel entry point passed as the first function argument followed by
8156 // kernelFunc.
8157 kernel_entry_point<KernelName>(kernelFunc);
8158 }
8159};
8160} // namespace sycl
8161```
8162
8163A SYCL kernel object is a callable object of class type that is constructed on
8164a host, often via a lambda expression, and then passed to a SYCL kernel
8165invocation function to be executed on an offload device. The `kernelFunc`
8166parameters in the example code above correspond to SYCL kernel objects.
8167
8168A SYCL kernel object type is required to satisfy the device copyability
8169requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
8170specification. Additionally, any data members of the kernel object type are
8171required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
8172For most types, these rules require that the type is trivially copyable.
8173However, the SYCL specification mandates that certain special SYCL types, such
8174as `sycl::accessor` and `sycl::stream`, be device copyable even if they are
8175not trivially copyable. These types require special handling because they cannot
8176necessarily be copied to device memory as if by `memcpy()`.
8177
8178The SYCL kernel object and its data members constitute the parameters of an
8179offload kernel. An offload kernel consists of an offload entry point function
8180and the set of all functions and variables that are directly or indirectly used
8181by the entry point function.
8182
8183A SYCL kernel invocation function is responsible for performing the following
8184tasks (likely with the help of an offload backend like OpenCL):
8185
81861. Identifying the offload kernel entry point to be used for the SYCL kernel.
81872. Validating that the SYCL kernel object type and its data members meet the
8188 SYCL device copyability and kernel parameter requirements noted above.
81893. Copying the SYCL kernel object and any other kernel arguments to device
8190 memory including any special handling required for SYCL special types.
81914. Initiating execution of the offload kernel entry point.
8192
8193The offload kernel entry point for a SYCL kernel performs the following tasks:
8194
81951. Calling the `operator()` member function of the SYCL kernel object.
8196
8197The `sycl_kernel_entry_point` attribute facilitates or automates these tasks
8198by providing generation of an offload kernel entry point with a unique symbol
8199name, type checking of kernel argument requirements, and initiation of kernel
8200execution via synthesized calls to a `sycl_kernel_launch` template.
8201
8202A function declared with the `sycl_kernel_entry_point` attribute specifies
8203the parameters and body of an offload entry point function. Consider the
8204following call to the `single_task()` SYCL kernel invocation function assuming
8205an implementation similar to the one shown above.
8206
8207```c++
8208struct S { int i; };
8209void f(sycl::handler &handler, sycl::stream &sout, S s) {
8210 handler.single_task<struct KN>([=] {
8211 sout << "The value of s.i is " << s.i << "\n";
8212 });
8213}
8214```
8215
8216The SYCL kernel object is the result of the lambda expression. The call to
8217`kernel_entry_point()` via the call to `single_task()` triggers the
8218generation of an offload kernel entry point function that looks approximately
8219as follows.
8220
8221```c++
8222void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
8223 kernelFunc();
8224}
8225```
8226
8227There are a few items worthy of note:
8228
82291. `sycl-kernel-caller-for-KN` is an exposition only name; the actual name
8230 generated for an entry point is an implementation detail and subject to
8231 change. However, the name will incorporate the SYCL kernel name, `KN`,
8232 that was passed as the `KernelName` template parameter to
8233 `single_task()` and eventually provided as the argument to the
8234 `sycl_kernel_entry_point` attribute in order to ensure that a unique
8235 name is generated for each entry point. There is a one-to-one correspondence
8236 between SYCL kernel names and offload kernel entry points.
82372. The SYCL kernel is a lambda closure type and therefore has no name;
8238 `kernel-type` is substituted above and corresponds to the `KernelType`
8239 template parameter deduced in the call to `single_task()`.
82403. The parameter and the call to `kernelFunc()` in the function body
8241 correspond to the definition of `kernel_entry_point()` as called by
8242 `single_task()`.
82434. The parameter is type checked for conformance with the SYCL device
8244 copyability and kernel parameter requirements.
8245
8246Within `single_task()`, the call to `kernel_entry_point()` is effectively
8247replaced with a synthesized call to a `sycl_kernel_launch` template that
8248looks approximately as follows.
8249
8250```c++
8251sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
8252```
8253
8254There are a few items worthy of note:
8255
82561. Lookup for the `sycl_kernel_launch` template is performed as if from the
8257 body of the (possibly instantiated) definition of `kernel_entry_point()`.
8258 If name lookup or overload resolution fails, the program is ill-formed.
8259 If the selected overload is a non-static member function, then `this` is
8260 passed as the implicit object parameter.
82612. Function arguments passed to `sycl_kernel_launch()` are passed
8262 as if by `std::move(x)`.
82633. The `sycl_kernel_launch` template is expected to be provided by the SYCL
8264 library implementation. It is responsible for copying the kernel arguments
8265 to device memory and for scheduling execution of the generated offload
8266 kernel entry point identified by the symbol name passed as the first
8267 function argument. `sycl-kernel-caller-for-KN` is substituted above for
8268 the actual symbol name that would be generated for the offload kernel entry
8269 point.
8270
8271It is not necessary for a function declared with the `sycl_kernel_entry_point`
8272attribute to be called for the offload kernel entry point to be emitted. For
8273inline functions and function templates, any ODR-use will suffice. For other
8274functions, an ODR-use is not required; the offload kernel entry point will be
8275emitted if the function is defined. In any case, a call to the function is
8276required for the synthesized call to `sycl_kernel_launch()` to occur.
8277
8278A function declared with the `sycl_kernel_entry_point` attribute may include
8279an exception specification. If a non-throwing exception specification is
8280present, an exception propagating from the implicit call to the
8281`sycl_kernel_launch` template will result in a call to `std::terminate()`.
8282Otherwise, such an exception will propagate normally.
8283
8284Functions declared with the `sycl_kernel_entry_point` attribute are not
8285limited to the simple example shown above. They may have additional template
8286parameters, declare additional function parameters, and have complex control
8287flow in the function body. The function must abide by the language feature
8288restrictions described in section 5.4, "Language restrictions for device
8289functions" in the SYCL 2020 specification. If the function is a non-static
8290member function, `this` shall not be used in a potentially evaluated
8291expression.)reST";
8292
8293static const char AttrDoc_SYCLLocalAddressSpace[] = R"reST(:::{Note}
8294These attributes are intended for use in the implementation of SYCL run-time
8295libraries and should not be used in any other context.
8296Programmers writing code intended to conform to the SYCL specification should
8297use the address space facilities specified in the following sections of the
8298SYCL 2020 specification.
8299
8300* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
8301* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
8302* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
8303* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
8304* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
8305:::
8306
8307The SYCL address space attributes listed below correspond to the five address
8308spaces described by
8309[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
8310[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
8311
8312::: {list-table} SYCL address space attributes
8313:header-rows: 1
8314
8315* - Address space attribute
8316 - SYCL address space
8317 - Description
8318* - `[[clang::sycl_global]]`
8319 - global
8320 - A memory region accessible by all work-items executing on a device.
8321* - `[[clang::sycl_local]]`
8322 - local
8323 - A memory region accessible by all work-items of a single work-group.
8324* - `[[clang::sycl_private]]`
8325 - private
8326 - A memory region that is private to a single work-item.
8327* - `[[clang::sycl_generic]]`
8328 - generic
8329 - A virtual memory region from which the global, local, and private memory
8330 regions may all be accessed.
8331* - `[[clang::sycl_constant]]`
8332 - constant
8333 - (*deprecated*) A memory region that holds constant data for an executing
8334 kernel.
8335:::
8336
8337The SYCL address space attributes are type attributes that may be applied to
8338non-function non-reference types to specify an address space qualified type.
8339
8340A type with a SYCL address space qualifier is a distinct type from the
8341otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
8342designate distinct pointer types which participate in overload resolution and
8343template specialization.
8344
8345The top-level type of a variable declaration cannot have a SYCL address space
8346qualifier. For example:
8347
8348```c++
8349int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8350int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8351```
8352
8353Conversions between SYCL address space attributed types are permitted as
8354follows.
8355
8356- Types attributed with the global, local, or private address space attributes
8357 are implicitly convertible to matching types with the generic address space
8358 attribute.
8359
8360The mapping of SYCL address spaces to physical address spaces is target
8361dependent.
8362
8363For OpenCL device targets, the SYCL address space attributes are aligned with
8364the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
8365`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
8366distinct types both of which map to the same underlying address space.
8367Corresponding SYCL and OpenCL address space attributed types are implicitly
8368convertible; other conversions are permitted as described above; e.g.,
8369`int [[clang::sycl_global]]*` is implicitly convertible to
8370`int [[clang::opencl_generic]]*`.
8371
8372[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8373[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8374[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8375[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8376[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8377[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8378
8379static const char AttrDoc_SYCLPrivateAddressSpace[] = R"reST(:::{Note}
8380These attributes are intended for use in the implementation of SYCL run-time
8381libraries and should not be used in any other context.
8382Programmers writing code intended to conform to the SYCL specification should
8383use the address space facilities specified in the following sections of the
8384SYCL 2020 specification.
8385
8386* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
8387* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
8388* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
8389* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
8390* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
8391:::
8392
8393The SYCL address space attributes listed below correspond to the five address
8394spaces described by
8395[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
8396[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
8397
8398::: {list-table} SYCL address space attributes
8399:header-rows: 1
8400
8401* - Address space attribute
8402 - SYCL address space
8403 - Description
8404* - `[[clang::sycl_global]]`
8405 - global
8406 - A memory region accessible by all work-items executing on a device.
8407* - `[[clang::sycl_local]]`
8408 - local
8409 - A memory region accessible by all work-items of a single work-group.
8410* - `[[clang::sycl_private]]`
8411 - private
8412 - A memory region that is private to a single work-item.
8413* - `[[clang::sycl_generic]]`
8414 - generic
8415 - A virtual memory region from which the global, local, and private memory
8416 regions may all be accessed.
8417* - `[[clang::sycl_constant]]`
8418 - constant
8419 - (*deprecated*) A memory region that holds constant data for an executing
8420 kernel.
8421:::
8422
8423The SYCL address space attributes are type attributes that may be applied to
8424non-function non-reference types to specify an address space qualified type.
8425
8426A type with a SYCL address space qualifier is a distinct type from the
8427otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
8428designate distinct pointer types which participate in overload resolution and
8429template specialization.
8430
8431The top-level type of a variable declaration cannot have a SYCL address space
8432qualifier. For example:
8433
8434```c++
8435int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8436int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8437```
8438
8439Conversions between SYCL address space attributed types are permitted as
8440follows.
8441
8442- Types attributed with the global, local, or private address space attributes
8443 are implicitly convertible to matching types with the generic address space
8444 attribute.
8445
8446The mapping of SYCL address spaces to physical address spaces is target
8447dependent.
8448
8449For OpenCL device targets, the SYCL address space attributes are aligned with
8450the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
8451`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
8452distinct types both of which map to the same underlying address space.
8453Corresponding SYCL and OpenCL address space attributed types are implicitly
8454convertible; other conversions are permitted as described above; e.g.,
8455`int [[clang::sycl_global]]*` is implicitly convertible to
8456`int [[clang::opencl_generic]]*`.
8457
8458[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8459[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8460[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8461[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8462[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8463[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8464
8465static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
8466specific handling during the generation of the SPIR entry point.
8467The `__attribute__((sycl_special_class))` attribute is used in SYCL
8468headers to indicate that a class or a struct needs a specific handling when
8469it is passed from host to device.
8470Special classes will have a mandatory `__init` method and an optional
8471`__finalize` method (the `__finalize` method is used only with the
8472`stream` type). Kernel parameters types are extract from the `__init` method
8473parameters. The kernel function arguments list is derived from the
8474arguments of the `__init` method. The arguments of the `__init` method are
8475copied into the kernel function argument list and the `__init` and
8476`__finalize` methods are called at the beginning and the end of the kernel,
8477respectively.
8478The `__init` and `__finalize` methods must be defined inside the
8479special class.
8480Please note that this is an attribute that is used as an internal
8481implementation detail and not intended to be used by external users.
8482
8483The syntax of the attribute is as follows:
8484
8485```text
8486class __attribute__((sycl_special_class)) accessor {};
8487class [[clang::sycl_special_class]] accessor {};
8488```
8489
8490This is a code example that illustrates the use of the attribute:
8491
8492```c++
8493class __attribute__((sycl_special_class)) SpecialType {
8494 int F1;
8495 int F2;
8496 void __init(int f1) {
8497 F1 = f1;
8498 F2 = f1;
8499 }
8500 void __finalize() {}
8501public:
8502 SpecialType() = default;
8503 int getF2() const { return F2; }
8504};
8505
8506int main () {
8507 SpecialType T;
8508 cgh.single_task([=] {
8509 T.getF2();
8510 });
8511}
8512```
8513
8514This would trigger the following kernel entry point in the AST:
8515
8516```c++
8517void __sycl_kernel(int f1) {
8518 SpecialType T;
8519 T.__init(f1);
8520 ...
8521 T.__finalize()
8522}
8523```)reST";
8524
8525static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
8526
8527static const char AttrDoc_Section[] = R"reST(The `section` attribute allows you to specify a specific section a
8528global variable or function should be in after translation.)reST";
8529
8530static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
8531definition ([linkonce](https://llvm.org/docs/LangRef.html#linkage-types)),
8532allowing the linker to select any definition.
8533
8534For more information see
8535[gcc documentation](https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html)
8536or [msvc documentation](https://docs.microsoft.com/pl-pl/cpp/cpp/selectany).)reST";
8537
8538static const char AttrDoc_Sentinel[] = R"reST(The `sentinel` attribute can be applied to variadic functions and pointers to
8539variadic functions, to diagnose each function call that does not pass a
8540sentinel value (a null pointer constant) as the last argument to the function
8541call. The attribute accepts two optional arguments: the first argument is the
8542position of the expected sentinel value, starting from the last parameter. The
8543second argument describes whether the last fixed parameter is treated as a
8544valid sentinel value when set to `1`.
8545All arguments described above default to `0` when elided.
8546The attribute is also supported with blocks and in Objective-C.
8547
8548```c
8549void foo(const char*, ...) __attribute__((sentinel));
8550void bar(int, ...) __attribute__((sentinel(1)));
8551void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1)));
8552
8553void example() {
8554 foo("Example", (void*)0);
8555 foo("Another", "example", NULL);
8556 foo("Missing", "sentinel"); // Not OK
8557
8558 bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position
8559 bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23
8560 bar(1, 2, 3, 4, NULL); // Not OK
8561
8562 baz("Test", "with", "multiple", "args", NULL);
8563 baz("One", NULL); // OK: last fixed parameter is a valid sentinel
8564
8565 void (*ptr) (int arg, ...) __attribute__ ((__sentinel__));
8566 ptr(1, 2, 3, NULL);
8567}
8568```
8569
8570```c++
8571struct Ty {
8572 int value;
8573
8574 template<typename T>
8575 auto&& foo(T&& val, ...) __attribute__((sentinel(1))) {
8576 return std::forward<T>(val);
8577 }
8578
8579 template<class Self>
8580 auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) {
8581 return std::forward<Self>(self).value;
8582 }
8583};
8584
8585void example2() {
8586 auto sty = Ty{};
8587 sty.foo(1, nullptr, 3);
8588 sty.bar(1, nullptr, 3);
8589
8590 auto lmbd = [](int a, ...) __attribute__((sentinel)) {};
8591 lmbd(1, 2, nullptr);
8592}
8593```)reST";
8594
8595static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
8596`__attribute__((set_typestate(new_state)))`. The new state must be
8597unconsumed, consumed, or unknown.)reST";
8598
8599static const char AttrDoc_SizedBy[] = R"reST(The `sized_by` attribute is applied to a pointer to indicate that the pointer
8600points to memory containing at least the number of *bytes* given by the
8601attribute's argument. It is closely related to `counted_by`; the difference is
8602that `counted_by` counts the number of *elements* of the pointee type, whereas
8603`sized_by` counts the number of *bytes*. This makes `sized_by` the natural
8604choice for `void *` and other byte buffers.
8605
8606This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
8607bounds information on API surfaces without any ABI changes. This attribute is
8608also used to improve the results of the array bound sanitizer and the
8609`__builtin_dynamic_object_size` builtin.
8610
8611The argument is an expression of integer type, following the same rules as the
8612argument of `counted_by`. Unlike `counted_by`, `sized_by` cannot be
8613applied to a C99 flexible array member; it applies to pointers only. For
8614example:
8615
8616```c
8617struct object {
8618 unsigned long size;
8619 void *data __attribute__((sized_by(size)));
8620};
8621```
8622
8623A pointer annotated with `sized_by` must have a size of zero when it is null.
8624This requirement is currently only enforced when compiling with
8625{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
8626-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
8627`sized_by_or_null` for a pointer that may be null while carrying a nonzero
8628size.
8629
8630#### Keeping pointer and size in sync
8631
8632The `sized_by` attribute establishes a relationship between the annotated
8633pointer and its size: the pointer must point to at least `size` bytes.
8634Assigning to only one of them can break this relationship.
8635Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
8636responsibility to ensure the pointer and size remain in sync. With
8637`-fbounds-safety` it is automatically enforced. For example:
8638
8639```c
8640struct buffer {
8641 uint8_t *buf __attribute__((sized_by(size)));
8642 size_t size;
8643};
8644
8645void grow(struct buffer *b, size_t new_size) {
8646 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
8647 // smaller than new_size which would contradict the sized_by attribute.
8648 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
8649 b->size = new_size;
8650}
8651```
8652
8653Updating both together - so that `buf` points to `size` bytes - keeps
8654the attribute true. For example:
8655
8656```c
8657void grow(struct buffer *b, size_t new_size) {
8658 // Allowed by -fbounds-safety
8659 uint8_t *new_buf = malloc(new_size);
8660 // -fbounds-safety enforces that the `new_buf` points to at least `new_size`
8661 // bytes at runtime. Without -fbounds-safety nothing enforces this.
8662 b->buf = new_buf;
8663 b->size = new_size;
8664}
8665```
8666
8667#### Incomplete and variable-length pointees
8668
8669`sized_by` is typically applied to `void *` or a pointer to a byte-sized
8670type, but it may be used with any pointee type. Two situations call for this,
8671both of which rule out counting fixed-size elements:
8672
8673First, the pointee type may be incomplete, such as an opaque type. Its element
8674size is then unavailable, so `counted_by` cannot be used, whereas `sized_by`
8675bounds the memory in bytes and imposes no completeness requirement.
8676
8677Second, the buffer may hold variable-length elements, so there is no fixed
8678element size to count, even though the total byte size is well defined. For
8679example, a buffer might pack together several structures that each end in a
8680flexible array member of differing length:
8681
8682```c
8683struct var_len {
8684 int fam_size;
8685 char data[] __attribute__((counted_by(fam_size)));
8686};
8687
8688struct buffer_view {
8689 int byte_size;
8690 struct var_len *buf __attribute__((sized_by(byte_size)));
8691};
8692```
8693
8694Here `counted_by` cannot be applied to `buf` because its pointee is a
8695variable-length structure, but `sized_by` bounds the whole region in bytes;
8696the region is traversed by advancing a byte offset rather than by indexing
8697elements.)reST";
8698
8699static const char AttrDoc_SizedByOrNull[] = R"reST(The `sized_by_or_null` attribute is applied to a pointer to indicate that, if
8700the pointer is non-null, it points to memory containing at least the number of
8701*bytes* given by the attribute's argument. If the pointer is null, the value of
8702the argument is ignored and the pointer points to zero bytes.
8703
8704The `sized_by_or_null` attribute is identical to `sized_by` except in how
8705it treats null pointers. Whereas `sized_by` requires a null pointer to have a
8706size of zero, `sized_by_or_null` allows the pointer to be null regardless of
8707the value of the size. This supports the common idiom where a pointer is either
8708null or points to memory containing at least the given number of bytes.
8709
8710Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
8711distinction between `sized_by_or_null` and `sized_by` (see
8712{ref}`Current status of -fbounds-safety support in upstream Clang
8713<bounds-safety-current-upstream-status>`).)reST";
8714
8715static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
8716that [Speculative Load Hardening][slh]
8717should be enabled for the function body. This can also be applied to a method
8718in Objective C. This attribute will take precedence over the command line flag
8719in the case where {option}`-mno-speculative-load-hardening` is specified.
8720
8721[slh]: https://llvm.org/docs/SpeculativeLoadHardening.html
8722
8723Speculative Load Hardening is a best-effort mitigation against
8724information leak attacks that make use of control flow
8725miss-speculation - specifically miss-speculation of whether a branch
8726is taken or not. Typically vulnerabilities enabling such attacks are
8727classified as "Spectre variant #1". Notably, this does not attempt to
8728mitigate against miss-speculation of branch target, classified as
8729"Spectre variant #2" vulnerabilities.
8730
8731When inlining, the attribute is sticky. Inlining a function that
8732carries this attribute will cause the caller to gain the
8733attribute. This is intended to provide a maximally conservative model
8734where the code in a function annotated with this attribute will always
8735(even after inlining) end up hardened.)reST";
8736
8737static const char AttrDoc_StackProtectorIgnore[] = R"reST(The `stack_protector_ignore` attribute skips analysis of the given local
8738variable when determining if a function should use a stack protector.
8739
8740The `-fstack-protector` option uses a heuristic to only add stack protectors
8741to functions which contain variables or buffers over some size threshold. This
8742attribute overrides that heuristic for the attached variable, opting
8743them out. If this results in no variables or buffers remaining over the stack
8744protector threshold, then the function will no longer use a stack protector.)reST";
8745
8746static const char AttrDoc_StandaloneDebug[] = R"reST(The `standalone_debug` attribute causes debug info to be emitted for a record
8747type regardless of the debug info optimizations that are enabled with
8748-fno-standalone-debug. This attribute only has an effect when debug info
8749optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
8750
8751static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8752function to clear parameters off of the stack on return. This convention does
8753not support variadic calls or unprototyped functions in C, and has no effect on
8754x86_64 targets. This calling convention is used widely by the Windows API and
8755COM applications. See the documentation for [`__stdcall`][__stdcall] on MSDN.
8756
8757[__stdcall]: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
8758
8759static const char AttrDoc_StrictFP[] = R"reST()reST";
8760
8761static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style `__declspec((strict_gs_check))` attribute
8762which upgrades the stack protector check from `-fstack-protector` to
8763`-fstack-protector-strong`.
8764
8765For example, it upgrades the stack protector for the function `foo` to
8766`-fstack-protector-strong` but function `bar` will still be built with the
8767stack protector with the `-fstack-protector` option.
8768
8769```c
8770__declspec((strict_gs_check))
8771int foo(int x); // stack protection will be upgraded for foo.
8772
8773int bar(int y); // bar can be built with the standard stack protector checks.
8774```)reST";
8775
8776static const char AttrDoc_Suppress[] = R"reST(The `suppress` attribute suppresses unwanted warnings coming from static
8777analysis tools such as the Clang Static Analyzer. The tool will not report
8778any issues in source code annotated with the attribute.
8779
8780The attribute cannot be used to suppress traditional Clang warnings, because
8781many such warnings are emitted before the attribute is fully parsed.
8782Consider using `#pragma clang diagnostic` to control such diagnostics,
8783as described in
8784{ref}`Controlling Diagnostics via Pragmas <pragma-gcc-diagnostic>`.
8785
8786The `suppress` attribute can be placed on an individual statement in order to
8787suppress warnings about undesirable behavior occurring at that statement:
8788
8789```c++
8790int foo() {
8791 int *x = nullptr;
8792 ...
8793 [[clang::suppress]]
8794 return *x; // null pointer dereference warning suppressed here
8795}
8796```
8797
8798Putting the attribute on a compound statement suppresses all warnings in scope:
8799
8800```c++
8801int foo() {
8802 [[clang::suppress]] {
8803 int *x = nullptr;
8804 ...
8805 return *x; // warnings suppressed in the entire scope
8806 }
8807}
8808```
8809
8810The attribute can also be placed on entire declarations of functions, classes,
8811variables, member variables, and so on, to suppress warnings related
8812to the declarations themselves. When used this way, the attribute additionally
8813suppresses all warnings in the lexical scope of the declaration:
8814
8815```c++
8816class [[clang::suppress]] C {
8817 int foo() {
8818 int *x = nullptr;
8819 ...
8820 return *x; // warnings suppressed in the entire class scope
8821 }
8822
8823 int bar();
8824};
8825
8826int C::bar() {
8827 int *x = nullptr;
8828 ...
8829 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
8830}
8831```
8832
8833Some static analysis warnings are accompanied by one or more notes, and the
8834line of code against which the warning is emitted isn't necessarily the best
8835for suppression purposes. In such cases the tools are allowed to implement
8836additional ways to suppress specific warnings based on the attribute attached
8837to a note location.
8838
8839For example, the Clang Static Analyzer suppresses memory leak warnings when
8840the suppression attribute is placed at the allocation site (highlited by
8841a "note: memory is allocated"), which may be different from the line of code
8842at which the program "loses track" of the pointer (where the warning
8843is ultimately emitted):
8844
8845```c
8846int bar1(bool coin_flip) {
8847 __attribute__((suppress))
8848 int *result = (int *)malloc(sizeof(int));
8849 if (coin_flip)
8850 return 1; // warning about this leak path is suppressed
8851
8852 return *result; // warning about this leak path is also suppressed
8853}
8854
8855int bar2(bool coin_flip) {
8856 int *result = (int *)malloc(sizeof(int));
8857 if (coin_flip)
8858 return 1; // leak warning on this path NOT suppressed
8859
8860 __attribute__((suppress))
8861 return *result; // leak warning is suppressed only on this path
8862}
8863```
8864
8865When written as `[[gsl::suppress]]`, this attribute suppresses specific
8866clang-tidy diagnostics for rules of the [C++ Core Guidelines][c++ core guidelines] in a portable
8867way. The attribute can be attached to declarations, statements, and at
8868namespace scope.
8869
8870```c++
8871[[gsl::suppress("Rh-public")]]
8872void f_() {
8873 int *p;
8874 [[gsl::suppress("type")]] {
8875 p = reinterpret_cast<int*>(7);
8876 }
8877}
8878namespace N {
8879 [[clang::suppress("type", "bounds")]];
8880 ...
8881}
8882```
8883
8884[c++ core guidelines]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8885
8886static const char AttrDoc_SwiftAsync[] = R"reST(The `swift_async` attribute specifies if and how a particular function or
8887Objective-C method is imported into a swift async method. For instance:
8888
8889```objc
8890@interface MyClass : NSObject
8891-(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8892 __attribute__((swift_async(none)));
8893
8894-(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8895 __attribute__((swift_async(swift_private, 1)));
8896@end
8897```
8898
8899Here, `notActuallyAsync:withCompletionHandler` would have been imported as
8900`async` (because it's last parameter's selector piece is
8901`withCompletionHandler`) if not for the `swift_async(none)` attribute.
8902Conversely, `actuallyAsync:callThisAsync` wouldn't have been imported as
8903`async` if not for the `swift_async` attribute because it doesn't match the
8904naming convention.
8905
8906When using `swift_async` to enable importing, the first argument to the
8907attribute is either `swift_private` or `not_swift_private` to indicate
8908whether the function/method is private to the current framework, and the second
8909argument is the index of the completion handler parameter.)reST";
8910
8911static const char AttrDoc_SwiftAsyncCall[] = R"reST(The `swiftasynccall` attribute indicates that a function is
8912compatible with the low-level conventions of Swift async functions,
8913provided it declares the right formal arguments.
8914
8915In most respects, this is similar to the `swiftcall` attribute, except for
8916the following:
8917
8918- A parameter may be marked `swift_async_context`, `swift_context`
8919 or `swift_indirect_result` (with the same restrictions on parameter
8920 ordering as `swiftcall`) but the parameter attribute
8921 `swift_error_result` is not permitted.
8922- A `swiftasynccall` function must have return type `void`.
8923- Within a `swiftasynccall` function, a call to a `swiftasynccall`
8924 function that is the immediate operand of a `return` statement is
8925 guaranteed to be performed as a tail call. This syntax is allowed even
8926 in C as an extension (a call to a void-returning function cannot be a
8927 return operand in standard C). If something in the calling function would
8928 semantically be performed after a guaranteed tail call, such as the
8929 non-trivial destruction of a local variable or temporary,
8930 then the program is ill-formed.
8931
8932Query for this attribute with `__has_attribute(swiftasynccall)`. Query if
8933the target supports the calling convention with
8934`__has_extension(swiftasynccc)`.
8935
8936Since this attribute follows the Swift async calling convention, it is
8937considered ABI-unstable except on targets where the Swift project
8938has declared ABI stability. Users are responsible for ensuring that
8939calls and definitions of functions with this attribute are compiled
8940with compatible compilers. Note that different operating systems
8941on the same architecture may use different ABIs and therefore may
8942have different standards for ABI stability.)reST";
8943
8944static const char AttrDoc_SwiftAsyncContext[] = R"reST(The `swift_async_context` attribute marks a parameter of a `swiftasynccall`
8945function as having the special asynchronous context-parameter ABI treatment.
8946
8947If the function is not `swiftasynccall`, this attribute only generates
8948extended frame information.
8949
8950A context parameter must have pointer or reference type.)reST";
8951
8952static const char AttrDoc_SwiftAsyncError[] = R"reST(The `swift_async_error` attribute specifies how an error state will be
8953represented in a swift async method. It's a bit analogous to the `swift_error`
8954attribute for the generated async method. The `swift_async_error` attribute
8955can indicate a variety of different ways of representing an error.
8956
8957- `__attribute__((swift_async_error(zero_argument, N)))`, specifies that the
8958 async method is considered to have failed if the Nth argument to the
8959 completion handler is zero.
8960- `__attribute__((swift_async_error(nonzero_argument, N)))`, specifies that
8961 the async method is considered to have failed if the Nth argument to the
8962 completion handler is non-zero.
8963- `__attribute__((swift_async_error(nonnull_error)))`, specifies that the
8964 async method is considered to have failed if the `NSError *` argument to the
8965 completion handler is non-null.
8966- `__attribute__((swift_async_error(none)))`, specifies that the async method
8967 cannot fail.
8968
8969For instance:
8970
8971```objc
8972@interface MyClass : NSObject
8973-(void)asyncMethod:(void (^)(char, int, float))handler
8974 __attribute__((swift_async(swift_private, 1)))
8975 __attribute__((swift_async_error(zero_argument, 2)));
8976@end
8977```
8978
8979Here, the `swift_async` attribute specifies that `handler` is the completion
8980handler for this method, and the `swift_async_error` attribute specifies that
8981the `int` parameter is the one that represents the error.)reST";
8982
8983static const char AttrDoc_SwiftAsyncName[] = R"reST(The `swift_async_name` attribute provides the name of the `async` overload for
8984the given declaration in Swift. If this attribute is absent, the name is
8985transformed according to the algorithm built into the Swift compiler.
8986
8987The argument is a string literal that contains the Swift name of the function or
8988method. The name may be a compound Swift name. The function or method with such
8989an attribute must have more than zero parameters, as its last parameter is
8990assumed to be a callback that's eliminated in the Swift `async` name.
8991
8992```objc
8993@interface URL
8994+ (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8995@end
8996```)reST";
8997
8998static const char AttrDoc_SwiftAttr[] = R"reST(The `swift_attr` provides a Swift-specific annotation for the declaration
8999or type to which the attribute appertains to. It can be used on any declaration
9000or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
9001semantic meaning in languages supported by Clang. The Swift compiler can
9002interpret these annotations according to its own rules when importing C or
9003Objective-C declarations.)reST";
9004
9005static const char AttrDoc_SwiftBridge[] = R"reST(The `swift_bridge` attribute indicates that the declaration to which the
9006attribute appertains is bridged to the named Swift type.
9007
9008```objc
9009__attribute__((__objc_root__))
9010@interface Base
9011- (instancetype)init;
9012@end
9013
9014__attribute__((__swift_bridge__("BridgedI")))
9015@interface I : Base
9016@end
9017```
9018
9019In this example, the Objective-C interface `I` will be made available to Swift
9020with the name `BridgedI`. It would be possible for the compiler to refer to
9021`I` still in order to bridge the type back to Objective-C.)reST";
9022
9023static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The `swift_bridged_typedef` attribute indicates that when the typedef to which
9024the attribute appertains is imported into Swift, it should refer to the bridged
9025Swift type (e.g. Swift's `String`) rather than the Objective-C type as written
9026(e.g. `NSString`).
9027
9028```objc
9029@interface NSString;
9030typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
9031
9032extern void acceptsAliasedString(AliasedString _Nonnull parameter);
9033```
9034
9035In this case, the function `acceptsAliasedString` will be imported into Swift
9036as a function which accepts a `String` type parameter.)reST";
9037
9038static const char AttrDoc_SwiftCall[] = R"reST(The `swiftcall` attribute indicates that a function should be called
9039using the Swift calling convention for a function or function pointer.
9040
9041The lowering for the Swift calling convention, as described by the Swift
9042ABI documentation, occurs in multiple phases. The first, "high-level"
9043phase breaks down the formal parameters and results into innately direct
9044and indirect components, adds implicit parameters for the generic
9045signature, and assigns the context and error ABI treatments to parameters
9046where applicable. The second phase breaks down the direct parameters
9047and results from the first phase and assigns them to registers or the
9048stack. The `swiftcall` convention only handles this second phase of
9049lowering; the C function type must accurately reflect the results
9050of the first phase, as follows:
9051
9052- Results classified as indirect by high-level lowering should be
9053 represented as parameters with the `swift_indirect_result` attribute.
9054
9055- Results classified as direct by high-level lowering should be represented
9056 as follows:
9057
9058 - First, remove any empty direct results.
9059 - If there are no direct results, the C result type should be `void`.
9060 - If there is one direct result, the C result type should be a type with
9061 the exact layout of that result type.
9062 - If there are a multiple direct results, the C result type should be
9063 a struct type with the exact layout of a tuple of those results.
9064
9065- Parameters classified as indirect by high-level lowering should be
9066 represented as parameters of pointer type.
9067
9068- Parameters classified as direct by high-level lowering should be
9069 omitted if they are empty types; otherwise, they should be represented
9070 as a parameter type with a layout exactly matching the layout of the
9071 Swift parameter type.
9072
9073- The context parameter, if present, should be represented as a trailing
9074 parameter with the `swift_context` attribute.
9075
9076- The error result parameter, if present, should be represented as a
9077 trailing parameter (always following a context parameter) with the
9078 `swift_error_result` attribute.
9079
9080`swiftcall` does not support variadic arguments or unprototyped functions.
9081
9082The parameter ABI treatment attributes are aspects of the function type.
9083A function type which applies an ABI treatment attribute to a
9084parameter is a different type from an otherwise-identical function type
9085that does not. A single parameter may not have multiple ABI treatment
9086attributes.
9087
9088Support for this feature is target-dependent, although it should be
9089supported on every target that Swift supports. Query for this attribute
9090with `__has_attribute(swiftcall)`. Query if the target supports the
9091calling convention with `__has_extension(swiftcc)`. This implies
9092support for the `swift_context`, `swift_error_result`, and
9093`swift_indirect_result` attributes.
9094
9095Since this attribute follows the Swift calling convention, it is
9096considered ABI-unstable except on targets where the Swift project
9097has declared ABI stability. Users are responsible for ensuring that
9098calls and definitions of functions with this attribute are compiled
9099with compatible compilers. Note that different operating systems
9100on the same architecture may use different ABIs and therefore may
9101have different standards for ABI stability.)reST";
9102
9103static const char AttrDoc_SwiftContext[] = R"reST(The `swift_context` attribute marks a parameter of a `swiftcall`
9104or `swiftasynccall` function as having the special context-parameter
9105ABI treatment.
9106
9107This treatment generally passes the context value in a special register
9108which is normally callee-preserved.
9109
9110A `swift_context` parameter must either be the last parameter or must be
9111followed by a `swift_error_result` parameter (which itself must always be
9112the last parameter).
9113
9114A context parameter must have pointer or reference type.)reST";
9115
9116static const char AttrDoc_SwiftError[] = R"reST(The `swift_error` attribute controls whether a particular function (or
9117Objective-C method) is imported into Swift as a throwing function, and if so,
9118which dynamic convention it uses.
9119
9120All of these conventions except `none` require the function to have an error
9121parameter. Currently, the error parameter is always the last parameter of type
9122`NSError**` or `CFErrorRef*`. Swift will remove the error parameter from
9123the imported API. When calling the API, Swift will always pass a valid address
9124initialized to a null pointer.
9125
9126- `swift_error(none)` means that the function should not be imported as
9127 throwing. The error parameter and result type will be imported normally.
9128- `swift_error(null_result)` means that calls to the function should be
9129 considered to have thrown if they return a null value. The return type must be
9130 a pointer type, and it will be imported into Swift with a non-optional type.
9131 This is the default error convention for Objective-C methods that return
9132 pointers.
9133- `swift_error(zero_result)` means that calls to the function should be
9134 considered to have thrown if they return a zero result. The return type must be
9135 an integral type. If the return type would have been imported as `Bool`, it
9136 is instead imported as `Void`. This is the default error convention for
9137 Objective-C methods that return a type that would be imported as `Bool`.
9138- `swift_error(nonzero_result)` means that calls to the function should be
9139 considered to have thrown if they return a non-zero result. The return type must
9140 be an integral type. If the return type would have been imported as `Bool`,
9141 it is instead imported as `Void`.
9142- `swift_error(nonnull_error)` means that calls to the function should be
9143 considered to have thrown if they leave a non-null error in the error parameter.
9144 The return type is left unmodified.)reST";
9145
9146static const char AttrDoc_SwiftErrorResult[] = R"reST(The `swift_error_result` attribute marks a parameter of a `swiftcall`
9147function as having the special error-result ABI treatment.
9148
9149This treatment generally passes the underlying error value in and out of
9150the function through a special register which is normally callee-preserved.
9151This is modeled in C by pretending that the register is addressable memory:
9152
9153- The caller appears to pass the address of a variable of pointer type.
9154 The current value of this variable is copied into the register before
9155 the call; if the call returns normally, the value is copied back into the
9156 variable.
9157- The callee appears to receive the address of a variable. This address
9158 is actually a hidden location in its own stack, initialized with the
9159 value of the register upon entry. When the function returns normally,
9160 the value in that hidden location is written back to the register.
9161
9162A `swift_error_result` parameter must be the last parameter, and it must be
9163preceded by a `swift_context` parameter.
9164
9165A `swift_error_result` parameter must have type `T**` or `T*&` for some
9166type T. Note that no qualifiers are permitted on the intermediate level.
9167
9168It is undefined behavior if the caller does not pass a pointer or
9169reference to a valid object.
9170
9171The standard convention is that the error value itself (that is, the
9172value stored in the apparent argument) will be null upon function entry,
9173but this is not enforced by the ABI.)reST";
9174
9175static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
9176
9177static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
9178
9179static const char AttrDoc_SwiftIndirectResult[] = R"reST(The `swift_indirect_result` attribute marks a parameter of a `swiftcall`
9180or `swiftasynccall` function as having the special indirect-result ABI
9181treatment.
9182
9183This treatment gives the parameter the target's normal indirect-result
9184ABI treatment, which may involve passing it differently from an ordinary
9185parameter. However, only the first indirect result will receive this
9186treatment. Furthermore, low-level lowering may decide that a direct result
9187must be returned indirectly; if so, this will take priority over the
9188`swift_indirect_result` parameters.
9189
9190A `swift_indirect_result` parameter must either be the first parameter or
9191follow another `swift_indirect_result` parameter.
9192
9193A `swift_indirect_result` parameter must have type `T*` or `T&` for
9194some object type `T`. If `T` is a complete type at the point of
9195definition of a function, it is undefined behavior if the argument
9196value does not point to storage of adequate size and alignment for a
9197value of type `T`.
9198
9199Making indirect results explicit in the signature allows C functions to
9200directly construct objects into them without relying on language
9201optimizations like C++'s named return value optimization (NRVO).)reST";
9202
9203static const char AttrDoc_SwiftName[] = R"reST(The `swift_name` attribute provides the name of the declaration in Swift. If
9204this attribute is absent, the name is transformed according to the algorithm
9205built into the Swift compiler.
9206
9207The argument is a string literal that contains the Swift name of the function,
9208variable, or type. When renaming a function, the name may be a compound Swift
9209name. For a type, enum constant, property, or variable declaration, the name
9210must be a simple or qualified identifier.
9211
9212```objc
9213@interface URL
9214- (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
9215@end
9216
9217void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
9218}
9219```)reST";
9220
9221static const char AttrDoc_SwiftNewType[] = R"reST(The `swift_newtype` attribute indicates that the typedef to which the
9222attribute appertains is imported as a new Swift type of the typedef's name.
9223Previously, the attribute was spelt `swift_wrapper`. While the behaviour of
9224the attribute is identical with either spelling, `swift_wrapper` is
9225deprecated, only exists for compatibility purposes, and should not be used in
9226new code.
9227
9228- `swift_newtype(struct)` means that a Swift struct will be created for this
9229 typedef.
9230
9231- `swift_newtype(enum)` means that a Swift enum will be created for this
9232 typedef.
9233
9234 ```c
9235 // Import UIFontTextStyle as an enum type, with enumerated values being
9236 // constants.
9237 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
9238
9239 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
9240 // values being members of the type structure.
9241 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));
9242 ```)reST";
9243
9244static const char AttrDoc_SwiftNullability[] = R"reST()reST";
9245
9246static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
9247of this class will be implicitly marked with the `@objcMembers` Swift
9248attribute, exposing them back to Objective-C.)reST";
9249
9250static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the `swift_private` attribute are hidden from the
9251framework client but are still made available for use within the framework or
9252Swift SDK overlay.
9253
9254The purpose of this attribute is to permit a more idomatic implementation of
9255declarations in Swift while hiding the non-idiomatic one.)reST";
9256
9257static const char AttrDoc_SwiftType[] = R"reST()reST";
9258
9259static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
9260
9261static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
9262
9263static const char AttrDoc_SwiftVersionedSlice[] = R"reST()reST";
9264
9265static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
9266function to match the default convention used on Sys V targets such as Linux,
9267Mac, and BSD. This attribute has no effect on other targets.)reST";
9268
9269static const char AttrDoc_TLSModel[] = R"reST(The `tls_model` attribute allows you to specify which thread-local storage
9270model to use. It accepts the following strings:
9271
9272- global-dynamic
9273- local-dynamic
9274- initial-exec
9275- local-exec
9276
9277TLS models are mutually exclusive.)reST";
9278
9279static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style `__attribute__((target("OPTIONS")))` attribute.
9280This attribute may be attached to a function definition and instructs
9281the backend to use different code generation options than were passed on the
9282command line.
9283
9284The current set of options correspond to the existing "subtarget features" for
9285the target with or without a "-mno-" in front corresponding to the absence
9286of the feature, as well as `arch="CPU"` which will change the default "CPU"
9287for the function.
9288
9289For X86, the attribute also allows `tune="CPU"` to optimize the generated
9290code for the given CPU without changing the available instructions.
9291
9292For AArch64, `arch="Arch"` will set the architecture, similar to the -march
9293command line options. `cpu="CPU"` can be used to select a specific cpu,
9294as per the `-mcpu` option, similarly for `tune=`. The attribute also allows the
9295`branch-protection=<args>` option, where the permissible arguments and their
9296effect on code generation are the same as for the command-line option
9297`-mbranch-protection`.
9298
9299Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
9300"avx", "xop" and largely correspond to the machine specific options handled by
9301the front end.
9302
9303Note that this attribute does not apply transitively to nested functions such
9304as blocks or C++ lambdas.
9305
9306Additionally, this attribute supports function multiversioning for ELF based
9307x86/x86-64 targets, which can be used to create multiple implementations of the
9308same function that will be resolved at runtime based on the priority of their
9309`target` attribute strings. A function is considered a multiversioned function
9310if either two declarations of the function have different `target` attribute
9311strings, or if it has a `target` attribute string of `default`. For
9312example:
9313
9314```c++
9315__attribute__((target("arch=atom")))
9316void foo() {} // will be called on 'atom' processors.
9317__attribute__((target("default")))
9318void foo() {} // will be called on any other processors.
9319```
9320
9321All multiversioned functions must contain a `default` (fallback)
9322implementation, otherwise usages of the function are considered invalid.
9323Additionally, a function may not become multiversioned after its first use.)reST";
9324
9325static const char AttrDoc_TargetClones[] = R"reST(Clang supports the `target_clones("OPTIONS")` attribute. This attribute may be
9326attached to a function declaration and causes function multiversioning, where
9327multiple versions of the function will be emitted with different code
9328generation options. Additionally, these versions will be resolved at runtime
9329based on the priority of their attribute options. All `target_clone` functions
9330are considered multiversioned functions.
9331
9332For AArch64 target:
9333The attribute contains comma-separated strings of target features joined by "+"
9334sign. For example:
9335
9336```c++
9337__attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
9338void foo() {}
9339```
9340
9341For every multiversioned function a `default` (fallback) implementation
9342always generated if not specified directly.
9343
9344For x86/x86-64 targets:
9345All multiversioned functions must contain a `default` (fallback)
9346implementation, otherwise usages of the function are considered invalid.
9347Additionally, a function may not become multiversioned after its first use.
9348
9349The options to `target_clones` can either be a target-specific architecture
9350(specified as `arch=CPU`), or one of a list of subtarget features.
9351
9352Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
9353"avx", "xop" and largely correspond to the machine specific options handled by
9354the front end.
9355
9356The versions can either be listed as a comma-separated sequence of string
9357literals or as a single string literal containing a comma-separated list of
9358versions. For compatibility with GCC, the two formats can be mixed. For
9359example, the following will emit 4 versions of the function:
9360
9361```c++
9362__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
9363void foo() {}
9364```
9365
9366For targets that support the GNU indirect function (IFUNC) feature, dispatch
9367is performed by emitting an indirect function that is resolved to the appropriate
9368target clone at load time. The indirect function is given the name the
9369multiversioned function would have if it had been declared without the attribute.
9370For backward compatibility with earlier Clang releases, a function alias with an
9371`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
9372feature and support for it may be removed in the future.
9373
9374For PowerPC targets, `target_clones` is supported on AIX only. The attribute
9375contains comma-separated strings of one of:
9376(a) `default`, (b) `cpu=CPU`, (c) `FEATURE` or `no-FEATURE`.
9377The minimum CPU supported is `pwr7` (long spelling such as `power7` is accepted).
9378The list of target features is a subset of what's allowed on `target`, limited
9379to what is detectable at runtime using `__builtin_cpu_supports`. IFUNC is supported
9380on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
9381An FMV function that is only declared in a translation unit is treated as a
9382non-FMV. The resolver and the function clones are given internal linkage.)reST";
9383
9384static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
9385`__attribute__((target_version("OPTIONS")))` attribute. When applied to a
9386function it instructs compiler to emit multiple function versions based on
9387`target_version` attribute strings, which resolved at runtime depend on their
9388priority and target features availability. One of the versions is always
9389(implicitly or explicitly) the `default` (fallback). Attribute strings can
9390contain dependent features names joined by the "+" sign.
9391
9392For targets that support the GNU indirect function (IFUNC) feature, dispatch
9393is performed by emitting an indirect function that is resolved to the appropriate
9394target clone at load time. The indirect function is given the name the
9395multiversioned function would have if it had been declared without the attribute.
9396For backward compatibility with earlier Clang releases, a function alias with an
9397`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
9398feature and support for it may be removed in the future.)reST";
9399
9400static const char AttrDoc_TestTypestate[] = R"reST(Use `__attribute__((test_typestate(tested_state)))` to indicate that a method
9401returns true if the object is in the specified state..)reST";
9402
9403static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
9404function to use ECX for the first parameter (typically the implicit `this`
9405parameter of C++ methods) and clear parameters off of the stack on return. This
9406convention does not support variadic calls or unprototyped functions in C, and
9407has no effect on x86_64 targets. See the documentation for [`__thiscall`][__thiscall] on
9408MSDN.
9409
9410[__thiscall]: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
9411
9412static const char AttrDoc_Thread[] = R"reST(The `__declspec(thread)` attribute declares a variable with thread local
9413storage. It is available under the `-fms-extensions` flag for MSVC
9414compatibility. See the documentation for [`__declspec(thread)`][__declspec(thread)] on MSDN.
9415
9416In Clang, `__declspec(thread)` is generally equivalent in functionality to the
9417GNU `__thread` keyword. The variable must not have a destructor and must have
9418a constant initializer, if any. The attribute only applies to variables
9419declared with static storage duration, such as globals, class static data
9420members, and static locals.
9421
9422[__declspec(thread)]: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx)reST";
9423
9424static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
9425functions that have an argument with a transparent union type. The compiler
9426behavior is changed in the following manner:
9427
9428- A value whose type is any member of the transparent union can be passed as an
9429 argument without the need to cast that value.
9430- The argument is passed to the function using the calling convention of the
9431 first member of the transparent union. Consequently, all the members of the
9432 transparent union should have the same calling convention as its first member.
9433
9434Transparent unions are not supported in C++.)reST";
9435
9436static const char AttrDoc_TrivialABI[] = R"reST(The `trivial_abi` attribute can be applied to a C++ class, struct, or union.
9437It instructs the compiler to pass and return the type using the C ABI for the
9438underlying type when the type would otherwise be considered non-trivial for the
9439purpose of calls.
9440A class annotated with `trivial_abi` can have non-trivial destructors or
9441copy/move constructors without automatically becoming non-trivial for the
9442purposes of calls. For example:
9443
9444```c++
9445// A is trivial for the purposes of calls because `trivial_abi` makes the
9446// user-provided special functions trivial.
9447struct __attribute__((trivial_abi)) A {
9448 ~A();
9449 A(const A &);
9450 A(A &&);
9451 int x;
9452};
9453
9454// B's destructor and copy/move constructor are considered trivial for the
9455// purpose of calls because A is trivial.
9456struct B {
9457 A a;
9458};
9459```
9460
9461If a type is trivial for the purposes of calls, has a non-trivial destructor,
9462and is passed as an argument by value, the convention is that the callee will
9463destroy the object before returning. The lifetime of the copy of the parameter
9464in the caller ends without a destructor call when the call begins.
9465
9466If a type is trivial for the purpose of calls, it is assumed to be trivially
9467relocatable for the purpose of `__is_trivially_relocatable` and
9468`__builtin_is_cpp_trivially_relocatable`.
9469When a type marked with `[[trivial_abi]]` is used as a function argument,
9470the compiler may omit the call to the copy constructor.
9471Thus, side effects of the copy constructor are potentially not performed.
9472For example, objects that contain pointers to themselves or otherwise depend
9473on their address (or the address or their subobjects) should not be declared
9474`[[trivial_abi]]`.
9475
9476Attribute `trivial_abi` has no effect in the following cases:
9477
9478- The class directly declares a virtual base or virtual methods.
9479
9480- Copy constructors and move constructors of the class are all deleted.
9481
9482- The class has a base class that is non-trivial for the purposes of calls.
9483
9484- The class has a non-static data member whose type is non-trivial for the
9485 purposes of calls, which includes:
9486
9487 - classes that are non-trivial for the purposes of calls
9488 - `__weak`-qualified types in Objective-C++
9489 - arrays of any of the above)reST";
9490
9491static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
9492actually acquire the capability; they accept a Boolean value determining
9493whether acquiring the capability means success (true), or failing to acquire
9494the capability means success (false).)reST";
9495
9496static const char AttrDoc_TypeNonNull[] = R"reST(The `_Nonnull` nullability qualifier indicates that null is not a meaningful
9497value for a value of the `_Nonnull` pointer type. For example, given a
9498declaration such as:
9499
9500```c
9501int fetch(int * _Nonnull ptr);
9502```
9503
9504a caller of `fetch` should not provide a null value, and the compiler will
9505produce a warning if it sees a literal null value passed to `fetch`. Note
9506that, unlike the declaration attribute `nonnull`, the presence of
9507`_Nonnull` does not imply that passing null is undefined behavior: `fetch`
9508is free to consider null undefined behavior or (perhaps for
9509backward-compatibility reasons) defensively handle null.)reST";
9510
9511static const char AttrDoc_TypeNullUnspecified[] = R"reST(The `_Null_unspecified` nullability qualifier indicates that neither the
9512`_Nonnull` nor `_Nullable` qualifiers make sense for a particular pointer
9513type. It is used primarily to indicate that the role of null with specific
9514pointers in a nullability-annotated header is unclear, e.g., due to
9515overly-complex implementations or historical factors with a long-lived API.)reST";
9516
9517static const char AttrDoc_TypeNullable[] = R"reST(The `_Nullable` nullability qualifier indicates that a value of the
9518`_Nullable` pointer type can be null. For example, given:
9519
9520```c
9521int fetch_or_zero(int * _Nullable ptr);
9522```
9523
9524a caller of `fetch_or_zero` can provide null.
9525
9526The `_Nullable` attribute on classes indicates that the given class can
9527represent null values, and so the `_Nullable`, `_Nonnull` etc qualifiers
9528make sense for this type. For example:
9529
9530```c
9531class _Nullable ArenaPointer { ... };
9532
9533ArenaPointer _Nonnull x = ...;
9534ArenaPointer _Nullable y = nullptr;
9535```)reST";
9536
9537static const char AttrDoc_TypeNullableResult[] = R"reST(The `_Nullable_result` nullability qualifier means that a value of the
9538`_Nullable_result` pointer can be `nil`, just like `_Nullable`. Where this
9539attribute differs from `_Nullable` is when it's used on a parameter to a
9540completion handler in a Swift async method. For instance, here:
9541
9542```objc
9543-(void)fetchSomeDataWithID:(int)identifier
9544 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
9545```
9546
9547This method asynchronously calls `completionHandler` when the data is
9548available, or calls it with an error. `_Nullable_result` indicates to the
9549Swift importer that this is the uncommon case where `result` can get `nil`
9550even if no error has occurred, and will therefore import it as a Swift optional
9551type. Otherwise, if `result` was annotated with `_Nullable`, the Swift
9552importer will assume that `result` will always be non-nil unless an error
9553occurred.)reST";
9554
9555static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
9556`__attribute__((type_tag_for_datatype(kind, type)))` to create a type tag that
9557is tied to the `type` argument given to the attribute.
9558
9559In the attribute prototype above:
9560: - `kind` is an identifier that should be used when annotating all applicable
9561 type tags.
9562 - `type` indicates the name of the type.
9563
9564Clang supports annotating type tags of two forms.
9565
9566- **Type tag that is a reference to a declared identifier.**
9567 Use `__attribute__((type_tag_for_datatype(kind, type)))` when declaring that
9568 identifier:
9569
9570 ```c++
9571 typedef int MPI_Datatype;
9572 extern struct mpi_datatype mpi_datatype_int
9573 __attribute__(( type_tag_for_datatype(mpi,int) ));
9574 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
9575 // &mpi_datatype_int is a type tag. It is tied to type "int".
9576 ```
9577
9578- **Type tag that is an integral literal.**
9579 Declare a `static const` variable with an initializer value and attach
9580 `__attribute__((type_tag_for_datatype(kind, type)))` on that declaration:
9581
9582 ```c++
9583 typedef int MPI_Datatype;
9584 static const MPI_Datatype mpi_datatype_int
9585 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
9586 #define MPI_INT ((MPI_Datatype) 42)
9587 // The number 42 is a type tag. It is tied to type "int".
9588 ```
9589
9590The `type_tag_for_datatype` attribute also accepts an optional third argument
9591that determines how the type of the function argument specified by either
9592`arg_idx` or `ptr_idx` is compared against the type associated with the type
9593tag. (Recall that for the `argument_with_type_tag` attribute, the type of the
9594function argument specified by `arg_idx` is compared against the type
9595associated with the type tag. Also recall that for the `pointer_with_type_tag`
9596attribute, the pointee type of the function argument specified by `ptr_idx` is
9597compared against the type associated with the type tag.) There are two supported
9598values for this optional third argument:
9599
9600- `layout_compatible` will cause types to be compared according to
9601 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
9602 layout-compatibility rules for two standard-layout struct types and for two
9603 standard-layout union types). This is useful when creating a type tag
9604 associated with a struct or union type. For example:
9605
9606 ```c++
9607 /* In mpi.h */
9608 typedef int MPI_Datatype;
9609 struct internal_mpi_double_int { double d; int i; };
9610 extern struct mpi_datatype mpi_datatype_double_int
9611 __attribute__(( type_tag_for_datatype(mpi,
9612 struct internal_mpi_double_int, layout_compatible) ));
9613
9614 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
9615
9616 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9617 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9618
9619 /* In user code */
9620 struct my_pair { double a; int b; };
9621 struct my_pair *buffer;
9622 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
9623 // layout of my_pair is
9624 // compatible with that of
9625 // internal_mpi_double_int
9626
9627 struct my_int_pair { int a; int b; }
9628 struct my_int_pair *buffer2;
9629 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
9630 // layout of my_int_pair
9631 // does not match that of
9632 // internal_mpi_double_int
9633 ```
9634
9635- `must_be_null` specifies that the function argument specified by either
9636 `arg_idx` (for the `argument_with_type_tag` attribute) or `ptr_idx` (for
9637 the `pointer_with_type_tag` attribute) should be a null pointer constant.
9638 The second argument to the `type_tag_for_datatype` attribute is ignored. For
9639 example:
9640
9641 ```c++
9642 /* In mpi.h */
9643 typedef int MPI_Datatype;
9644 extern struct mpi_datatype mpi_datatype_null
9645 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
9646
9647 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
9648 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9649 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9650
9651 /* In user code */
9652 struct my_pair { double a; int b; };
9653 struct my_pair *buffer;
9654 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
9655 // was specified but buffer
9656 // is not a null pointer
9657 ```)reST";
9658
9659static const char AttrDoc_TypeVisibility[] = R"reST(The `type_visibility` attribute allows the visibility of a type and its vague
9660linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
9661the visibility of functions and data members of the type.
9662
9663For example, this can be used to give default visibility to the typeinfo and the vtable
9664of a type while still keeping hidden visibility on its member functions and static data
9665members.
9666
9667This attribute can only be applied to types and namespaces.
9668
9669If both `visibility` and `type_visibility` are applied to a type or a namespace, the
9670visibility specified with the `type_visibility` attribute overrides the visibility
9671provided with the regular `visibility` attribute.)reST";
9672
9673static const char AttrDoc_UPtr[] = R"reST(The `__uptr` qualifier specifies that a 32-bit pointer should be zero
9674extended when converted to a 64-bit pointer.)reST";
9675
9676static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
9677
9678static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter `-ftrivial-auto-var-init=*` can be used to
9679initialize trivial automatic stack variables. By default, trivial automatic
9680stack variables are uninitialized. This attribute is used to override the
9681command-line parameter, forcing variables to remain uninitialized. It has no
9682semantic meaning in that using uninitialized values is undefined behavior,
9683it rather documents the programmer's intent.)reST";
9684
9685static const char AttrDoc_Unlikely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
9686The attributes are used to aid the compiler to determine which branch is
9687likely or unlikely to be taken. This is done by marking the branch substatement
9688with one of the two attributes.
9689
9690It isn't allowed to annotate a single statement with both `likely` and
9691`unlikely`. Annotating the `true` and `false` branch of an `if`
9692statement with the same likelihood attribute will result in a diagnostic and
9693the attributes are ignored on both branches.
9694
9695In a `switch` statement it's allowed to annotate multiple `case` labels
9696or the `default` label with the same likelihood attribute. This makes
9697\* all labels without an attribute have a neutral likelihood,
9698\* all labels marked `[[likely]]` have an equally positive likelihood, and
9699\* all labels marked `[[unlikely]]` have an equally negative likelihood.
9700The neutral likelihood is the more likely of path execution than the negative
9701likelihood. The positive likelihood is the more likely of path of execution
9702than the neutral likelihood.
9703
9704These attributes have no effect on the generated code when using
9705PGO (Profile-Guided Optimization) or at optimization level 0.
9706
9707In Clang, the attributes will be ignored if they're not placed on
9708\* the `case` or `default` label of a `switch` statement,
9709\* or on the substatement of an `if` or `else` statement,
9710\* or on the substatement of an `for` or `while` statement.
9711The C++ Standard recommends to honor them on every statement in the
9712path of execution, but that can be confusing:
9713
9714```c++
9715if (b) {
9716 [[unlikely]] --b; // Per the standard this is in the path of
9717 // execution, so this branch should be considered
9718 // unlikely. However, Clang ignores the attribute
9719 // here since it is not on the substatement.
9720}
9721
9722if (b) {
9723 --b;
9724 if(b)
9725 return;
9726 [[unlikely]] --b; // Not in the path of execution,
9727} // the branch has no likelihood information.
9728
9729if (b) {
9730 --b;
9731 foo(b);
9732 // Whether or not the next statement is in the path of execution depends
9733 // on the declaration of foo():
9734 // In the path of execution: void foo(int);
9735 // Not in the path of execution: [[noreturn]] void foo(int);
9736 // This means the likelihood of the branch depends on the declaration
9737 // of foo().
9738 [[unlikely]] --b;
9739}
9740```
9741
9742Below are some example usages of the likelihood attributes and their effects:
9743
9744```c++
9745if (b) [[likely]] { // Placement on the first statement in the branch.
9746 // The compiler will optimize to execute the code here.
9747} else {
9748}
9749
9750if (b)
9751 [[unlikely]] b++; // Placement on the first statement in the branch.
9752else {
9753 // The compiler will optimize to execute the code here.
9754}
9755
9756if (b) {
9757 [[unlikely]] b++; // Placement on the second statement in the branch.
9758} // The attribute will be ignored.
9759
9760if (b) [[likely]] {
9761 [[unlikely]] b++; // No contradiction since the second attribute
9762} // is ignored.
9763
9764if (b)
9765 ;
9766else [[likely]] {
9767 // The compiler will optimize to execute the code here.
9768}
9769
9770if (b)
9771 ;
9772else
9773 // The compiler will optimize to execute the next statement.
9774 [[likely]] b = f();
9775
9776if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
9777else [[likely]]; // and the attributes are ignored.
9778
9779if (b)
9780 [[likely]] int i = 5; // Issues a diagnostic since the attribute
9781 // isn't allowed on a declaration.
9782
9783switch (i) {
9784 [[likely]] case 1: // This value is likely
9785 ...
9786 break;
9787
9788 [[unlikely]] case 2: // This value is unlikely
9789 ...
9790 [[fallthrough]];
9791
9792 case 3: // No likelihood attribute
9793 ...
9794 [[likely]] break; // No effect
9795
9796 case 4: [[likely]] { // attribute on substatement has no effect
9797 ...
9798 break;
9799 }
9800
9801 [[unlikely]] default: // All other values are unlikely
9802 ...
9803 break;
9804}
9805
9806switch (i) {
9807 [[likely]] case 0: // This value and code path is likely
9808 ...
9809 [[fallthrough]];
9810
9811 case 1: // No likelihood attribute, code path is neutral
9812 break; // falling through has no effect on the likelihood
9813
9814 case 2: // No likelihood attribute, code path is neutral
9815 [[fallthrough]];
9816
9817 [[unlikely]] default: // This value and code path are both unlikely
9818 break;
9819}
9820
9821for(int i = 0; i != size; ++i) [[likely]] {
9822 ... // The loop is the likely path of execution
9823}
9824
9825for(const auto &E : Elements) [[likely]] {
9826 ... // The loop is the likely path of execution
9827}
9828
9829while(i != size) [[unlikely]] {
9830 ... // The loop is the unlikely path of execution
9831} // The generated code will optimize to skip the loop body
9832
9833while(true) [[unlikely]] {
9834 ... // The attribute has no effect
9835} // Clang elides the comparison and generates an infinite
9836 // loop
9837```)reST";
9838
9839static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute `[[clang::unsafe_buffer_usage]]` should be placed on functions
9840that need to be avoided as they are prone to buffer overflows or unsafe buffer
9841struct fields. It is designed to work together with the off-by-default compiler
9842warning `-Wunsafe-buffer-usage` to help codebases transition away from raw pointer
9843based buffer management, in favor of safer abstractions such as C++20 `std::span`.
9844The attribute causes `-Wunsafe-buffer-usage` to warn on every use of the function or
9845the field it is attached to, and it may also lead to emission of automatic fix-it
9846hints which would help the user replace the use of unsafe functions(/fields) with safe
9847alternatives, though the attribute can be used even when the fix can't be automated.
9848
9849- Attribute attached to functions: The attribute suppresses all
9850 `-Wunsafe-buffer-usage` warnings within the function it is attached to, as the
9851 function is now classified as unsafe. The attribute should be used carefully, as it
9852 will silence all unsafe operation warnings inside the function; including any new
9853 unsafe operations introduced in the future.
9854
9855 The attribute is warranted even if the only way a function can overflow
9856 the buffer is by violating the function's preconditions. For example, it
9857 would make sense to put the attribute on function `foo()` below because
9858 passing an incorrect size parameter would cause a buffer overflow:
9859
9860 ```c++
9861 [[clang::unsafe_buffer_usage]]
9862 void foo(int *buf, size_t size) {
9863 for (size_t i = 0; i < size; ++i) {
9864 buf[i] = i;
9865 }
9866 }
9867 ```
9868
9869 The attribute is NOT warranted when the function uses safe abstractions,
9870 assuming that these abstractions weren't misused outside the function.
9871 For example, function `bar()` below doesn't need the attribute,
9872 because assuming that the container `buf` is well-formed (has size that
9873 fits the original buffer it refers to), overflow cannot occur:
9874
9875 ```c++
9876 void bar(std::span<int> buf) {
9877 for (size_t i = 0; i < buf.size(); ++i) {
9878 buf[i] = i;
9879 }
9880 }
9881 ```
9882
9883 In this case function `bar()` enables the user to keep the buffer
9884 "containerized" in a span for as long as possible. On the other hand,
9885 Function `foo()` in the previous example may have internal
9886 consistency, but by accepting a raw buffer it requires the user to unwrap
9887 their span, which is undesirable according to the programming model
9888 behind `-Wunsafe-buffer-usage`.
9889
9890 The attribute is warranted when a function accepts a raw buffer only to
9891 immediately put it into a span:
9892
9893 ```c++
9894 [[clang::unsafe_buffer_usage]]
9895 void baz(int *buf, size_t size) {
9896 std::span<int> sp{ buf, size };
9897 for (size_t i = 0; i < sp.size(); ++i) {
9898 sp[i] = i;
9899 }
9900 }
9901 ```
9902
9903 In this case `baz()` does not contain any unsafe operations, but the awkward
9904 parameter type causes the caller to unwrap the span unnecessarily.
9905 Note that regardless of the attribute, code inside `baz()` isn't flagged
9906 by `-Wunsafe-buffer-usage` as unsafe. It is definitely undesirable,
9907 but if `baz()` is on an API surface, there is no way to improve it
9908 to make it as safe as `bar()` without breaking the source and binary
9909 compatibility with existing users of the function. In such cases
9910 the proper solution would be to create a different function (possibly
9911 an overload of `baz()`) that accepts a safe container like `bar()`,
9912 and then use the attribute on the original `baz()` to help the users
9913 update their code to use the new function.
9914
9915- Attribute attached to fields: The attribute should only be attached to
9916 struct fields, if the fields can not be updated to a safe type with bounds
9917 check, such as `std::span`. In other words, the buffers prone to unsafe accesses
9918 should always be updated to use safe containers/views and attaching the attribute
9919 must be last resort when such an update is infeasible.
9920
9921 The attribute can be placed on individual fields or a set of them as shown below.
9922
9923 ```c++
9924 struct A {
9925 [[clang::unsafe_buffer_usage]]
9926 int *ptr1;
9927
9928 [[clang::unsafe_buffer_usage]]
9929 int *ptr2, buf[10];
9930
9931 [[clang::unsafe_buffer_usage]]
9932 size_t sz;
9933 };
9934 ```
9935
9936 Here, every read/write to the fields `ptr1`, `ptr2`, `buf` and `sz` will trigger a warning
9937 that the field has been explicitly marked as unsafe due to unsafe-buffer operations.
9938
9939- Attribute attached to container constructors and factory functions: The
9940 spellings `[[clang::unsafe_buffer_usage_in_container]]` and
9941 `[[clang::unsafe_buffer_usage("container")]]` are equivalent and can be
9942 placed on two-parameter constructors and factory functions of container or
9943 view types (such as custom span types taking a `(pointer, size)` or
9944 `(begin, end)` pair) to opt them in to `-Wunsafe-buffer-usage-in-container`.
9945
9946 Unlike the general `[[clang::unsafe_buffer_usage]]` attribute, which warns on
9947 every call, this form suppresses the warning when the argument pair is
9948 provably safe -- for example, when constructing from `c.data(), c.size()` or
9949 `c.begin(), c.end()` on the same container object `c`, a constant-sized array
9950 with a matching bound, `&var, 1`, or a `0` size:
9951
9952 ```c++
9953 template <typename T>
9954 class CustomSpan {
9955 public:
9956 [[clang::unsafe_buffer_usage_in_container]]
9957 CustomSpan(T *ptr, size_t size);
9958
9959 template <typename It>
9960 [[clang::unsafe_buffer_usage("container")]]
9961 CustomSpan(It first, It last);
9962 };
9963
9964 template <typename T>
9965 [[clang::unsafe_buffer_usage("container")]]
9966 CustomSpan<T> MakeCustomSpan(T *ptr, size_t size);
9967
9968 void example(int *p, size_t n, MyVector<int> &v) {
9969 CustomSpan<int> s1(p, n); // warning: decoupled pointer and size
9970 auto s2 = MakeCustomSpan(p, n); // warning: decoupled pointer and size
9971 CustomSpan<int> s3(v.data(), v.size()); // no warning
9972 CustomSpan<int> s4(v.begin(), v.end()); // no warning
9973 auto s5 = MakeCustomSpan(v.data(), v.size()); // no warning
9974 }
9975 ```)reST";
9976
9977static const char AttrDoc_Unused[] = R"reST(When passing the `-Wunused` flag to Clang, entities that are unused by the
9978program may be diagnosed. The `[[maybe_unused]]` (or
9979`__attribute__((unused))`) attribute can be used to silence such diagnostics
9980when the entity cannot be removed. For instance, a local variable may exist
9981solely for use in an `assert()` statement, which makes the local variable
9982unused when `NDEBUG` is defined.
9983
9984The attribute may be applied to the declaration of a class, a typedef, a
9985variable, a function or method, a function parameter, an enumeration, an
9986enumerator, a non-static data member, or a label.
9987
9988```c++
9989#include <cassert>
9990
9991[[maybe_unused]] void f([[maybe_unused]] bool thing1,
9992 [[maybe_unused]] bool thing2) {
9993 [[maybe_unused]] bool b = thing1 && thing2;
9994 assert(b);
9995}
9996```)reST";
9997
9998static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9999parameter is annotated with `use_handle(tag)` it is assumed to not to change
10000the state of the handle. It is also assumed to require an open handle to work with.
10001The attribute requires a string literal argument to identify the handle being used.
10002
10003```c++
10004zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
10005 zx_time_t deadline,
10006 zx_port_packet_t* packet);
10007```)reST";
10008
10009static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
10010that there may be references to the entity which are not apparent in the source
10011code. For example, it may be referenced from inline `asm`, or it may be
10012found through a dynamic symbol or section lookup.
10013
10014The compiler must emit the definition even if it appears to be unused, and it
10015must not apply optimizations which depend on fully understanding how the entity
10016is used.
10017
10018Whether this attribute has any effect on the linker depends on the target and
10019the linker. Most linkers support the feature of section garbage collection
10020(`--gc-sections`), also known as "dead stripping" (`ld64 -dead_strip`) or
10021discarding unreferenced sections (`link.exe /OPT:REF`). On COFF and Mach-O
10022targets (Windows and Apple platforms), the `used` attribute prevents symbols
10023from being removed by linker section GC. On ELF targets, it has no effect on its
10024own, and the linker may remove the definition if it is not otherwise referenced.
10025This linker GC can be avoided by also adding the `retain` attribute. Note
10026that `retain` requires special support from the linker; see that attribute's
10027documentation for further information.)reST";
10028
10029static const char AttrDoc_UsingIfExists[] = R"reST(The `using_if_exists` attribute applies to a using-declaration. It allows
10030programmers to import a declaration that potentially does not exist, instead
10031deferring any errors to the point of use. For instance:
10032
10033```c++
10034namespace empty_namespace {};
10035__attribute__((using_if_exists))
10036using empty_namespace::does_not_exist; // no error!
10037
10038does_not_exist x; // error: use of unresolved 'using_if_exists'
10039```
10040
10041The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
10042supported as a clang extension, since ISO C++ doesn't support attributes in this
10043position. If the entity referred to by the using-declaration is found by name
10044lookup, the attribute has no effect. This attribute is useful for libraries
10045(primarily, libc++) that wish to redeclare a set of declarations in another
10046namespace, when the availability of those declarations is difficult or
10047impossible to detect at compile time with the preprocessor.)reST";
10048
10049static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
10050
10051static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
10052
10053static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
10054
10055static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
10056
10057static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
10058convention of a function to pass vector parameters in SSE registers.
10059
10060On 32-bit x86 targets, this calling convention is similar to `__fastcall`.
10061The first two integer parameters are passed in ECX and EDX. Subsequent integer
10062parameters are passed in memory, and callee clears the stack. On x86_64
10063targets, the callee does *not* clear the stack, and integer parameters are
10064passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
10065convention.
10066
10067On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
10068passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
10069passed in sequential SSE registers if enough are available. If AVX is enabled,
10070256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
10071cannot be passed in registers for any reason is passed by reference, which
10072allows the caller to align the parameter memory.
10073
10074See the documentation for [`__vectorcall`][__vectorcall] on MSDN for more details.
10075
10076[__vectorcall]: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
10077
10078static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
10079
10080static const char AttrDoc_WarnUnused[] = R"reST(The `warn_unused` attribute can be placed on the declaration of a structure or union type.
10081When 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.
10082Those constructor or destructor invocations are not considered a use if the type is declared with the `warn_unused` attribute.
10083The variable is considered used if it is named outside of its declaration.
10084
10085This 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.
10086
10087```c++
10088struct [[gnu::warn_unused]] S {
10089 S();
10090 ~S();
10091};
10092
10093struct T {
10094 T();
10095 ~T();
10096 };
10097
10098 int func() {
10099 S s1; // -Wunused-variable warning
10100 S s2; // No -Wunused-variable warning because of the member access expression below
10101 S s3; // No -Wunused-variable warning because of the sizeof operand below
10102 T t; // No -Wunused-variable warning
10103
10104 s2.~S();
10105 return sizeof(s3);
10106 }
10107```)reST";
10108
10109static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
10110expression are discarded under suspicious circumstances. A diagnostic is
10111generated when a function or its return type is marked with `[[nodiscard]]`
10112(or `__attribute__((warn_unused_result))`) and the function call appears as a
10113potentially-evaluated discarded-value expression that is not explicitly cast to
10114`void`.
10115
10116A string literal may optionally be provided to the attribute, which will be
10117reproduced in any resulting diagnostics. Redeclarations using different forms
10118of the attribute (with or without the string literal or with different string
10119literal contents) are allowed. If there are redeclarations of the entity with
10120differing string literals, it is unspecified which one will be used by Clang
10121in any resulting diagnostics.
10122
10123```c++
10124struct [[nodiscard]] error_info { /*...*/ };
10125error_info enable_missile_safety_mode();
10126
10127void launch_missiles();
10128void test_missiles() {
10129 enable_missile_safety_mode(); // diagnoses
10130 launch_missiles();
10131}
10132error_info &foo();
10133void f() { foo(); } // Does not diagnose, error_info is a reference.
10134```
10135
10136Additionally, discarded temporaries resulting from a call to a constructor
10137marked with `[[nodiscard]]` or a constructor of a type marked
10138`[[nodiscard]]` will also diagnose. This also applies to type conversions that
10139use the annotated `[[nodiscard]]` constructor or result in an annotated type.
10140
10141```c++
10142struct [[nodiscard]] marked_type {/*..*/ };
10143struct marked_ctor {
10144 [[nodiscard]] marked_ctor();
10145 marked_ctor(int);
10146};
10147
10148struct S {
10149 operator marked_type() const;
10150 [[nodiscard]] operator int() const;
10151};
10152
10153void usages() {
10154 marked_type(); // diagnoses.
10155 marked_ctor(); // diagnoses.
10156 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
10157
10158 S s;
10159 static_cast<marked_type>(s); // diagnoses
10160 (int)s; // diagnoses
10161}
10162```)reST";
10163
10164static const char AttrDoc_Weak[] = R"reST(In supported output formats the `weak` attribute can be used to
10165specify that a variable or function should be emitted as a symbol with
10166`weak` (if a definition) or `extern_weak` (if a declaration of an
10167external symbol) [linkage](https://llvm.org/docs/LangRef.html#linkage-types).
10168
10169If there is a non-weak definition of the symbol the linker will select
10170that over the weak. They must have same type and alignment (variables
10171must also have the same size), but may have a different value.
10172
10173If there are multiple weak definitions of same symbol, but no non-weak
10174definition, they should have same type, size, alignment and value, the
10175linker will select one of them (see also [selectany] attribute).
10176
10177If the `weak` attribute is applied to a `const` qualified variable
10178definition that variable is no longer consider a compiletime constant
10179as its value can change during linking (or dynamic linking). This
10180means that it can e.g no longer be part of an initializer expression.
10181
10182```c
10183const int ANSWER __attribute__ ((weak)) = 42;
10184
10185/* This function may be replaced link-time */
10186__attribute__ ((weak)) void debug_log(const char *msg)
10187{
10188 fprintf(stderr, "DEBUG: %s\n", msg);
10189}
10190
10191int main(int argc, const char **argv)
10192{
10193 debug_log ("Starting up...");
10194
10195 /* This may print something else than "6 * 7 = 42",
10196 if there is a non-weak definition of "ANSWER" in
10197 an object linked in */
10198 printf("6 * 7 = %d\n", ANSWER);
10199
10200 return 0;
10201 }
10202```
10203
10204If an external declaration is marked weak and that symbol does not
10205exist during linking (possibly dynamic) the address of the symbol will
10206evaluate to NULL.
10207
10208```c
10209void may_not_exist(void) __attribute__ ((weak));
10210
10211int main(int argc, const char **argv)
10212{
10213 if (may_not_exist) {
10214 may_not_exist();
10215 } else {
10216 printf("Function did not exist\n");
10217 }
10218 return 0;
10219}
10220```)reST";
10221
10222static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
10223
10224static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
10225
10226static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
10227attribute for the WebAssembly target. This attribute may be attached to a
10228function declaration, where it modifies how the symbol is to be exported
10229from the linked WebAssembly.
10230
10231WebAssembly functions are exported via string name. By default when a symbol
10232is exported, the export name for C/C++ symbols are the same as their C/C++
10233symbol names. This attribute can be used to override the default behavior, and
10234request a specific string name be used instead.)reST";
10235
10236static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
10237attribute for the WebAssembly target. This attribute may be attached to a
10238function declaration, where it modifies how the symbol is to be exported
10239from the linked WebAssembly.
10240
10241WebAssembly functions are exported via string name. By default when a symbol
10242is exported, the export name for C/C++ symbols are the same as their C/C++
10243symbol names. This attribute can be used to override the default behavior, and
10244request a specific string name be used instead.)reST";
10245
10246static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the `__attribute__((import_module(<module_name>)))`
10247attribute for the WebAssembly target. This attribute may be attached to a
10248function declaration, where it modifies how the symbol is to be imported
10249within the WebAssembly linking environment.
10250
10251WebAssembly imports use a two-level namespace scheme, consisting of a module
10252name, which typically identifies a module from which to import, and a field
10253name, which typically identifies a field from that module to import. By
10254default, module names for C/C++ symbols are assigned automatically by the
10255linker. This attribute can be used to override the default behavior, and
10256request a specific module name be used instead.)reST";
10257
10258static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the `__attribute__((import_name(<name>)))`
10259attribute for the WebAssembly target. This attribute may be attached to a
10260function declaration, where it modifies how the symbol is to be imported
10261within the WebAssembly linking environment.
10262
10263WebAssembly imports use a two-level namespace scheme, consisting of a module
10264name, which typically identifies a module from which to import, and a field
10265name, which typically identifies a field from that module to import. By
10266default, field names for C/C++ symbols are the same as their C/C++ symbol
10267names. This attribute can be used to override the default behavior, and
10268request a specific field name be used instead.)reST";
10269
10270static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
10271
10272static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
10273
10274Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
10275(like 'movaps') that work with the stack require operands to be 16-byte aligned.
10276This attribute realigns the stack in the function prologue to make sure the
10277stack can be used with SSE instructions.
10278
10279Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
10280Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
10281rare cases where the caller does not align the stack properly (e.g. flow
10282jumps from i386 arch code).
10283
10284```c
10285__attribute__ ((force_align_arg_pointer))
10286void f () {
10287 ...
10288}
10289```)reST";
10290
10291static const char AttrDoc_XRayInstrument[] = R"reST(`__attribute__((xray_always_instrument))` or
10292`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
10293methods (in Objective C), and free functions (in C, C++, and Objective C) to be
10294instrumented with XRay. This will cause the function to always have space at
10295the beginning and exit points to allow for runtime patching.
10296
10297Conversely, `__attribute__((xray_never_instrument))` or
10298`[[clang::xray_never_instrument]]` will inhibit the insertion of these
10299instrumentation points.
10300
10301If a function has neither of these attributes, they become subject to the XRay
10302heuristics used to determine whether a function should be instrumented or
10303otherwise.
10304
10305`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
10306used to preserve N function arguments for the logging function. Currently,
10307only N==1 is supported.)reST";
10308
10309static const char AttrDoc_XRayLogArgs[] = R"reST(`__attribute__((xray_always_instrument))` or
10310`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
10311methods (in Objective C), and free functions (in C, C++, and Objective C) to be
10312instrumented with XRay. This will cause the function to always have space at
10313the beginning and exit points to allow for runtime patching.
10314
10315Conversely, `__attribute__((xray_never_instrument))` or
10316`[[clang::xray_never_instrument]]` will inhibit the insertion of these
10317instrumentation points.
10318
10319If a function has neither of these attributes, they become subject to the XRay
10320heuristics used to determine whether a function should be instrumented or
10321otherwise.
10322
10323`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
10324used to preserve N function arguments for the logging function. Currently,
10325only N==1 is supported.)reST";
10326
10327static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
10328subset of all call-used registers before the function returns. It's used to
10329increase program security by either mitigating [Return-Oriented Programming][return-oriented programming]
10330(ROP) attacks or preventing information leakage through registers.
10331
10332The term "call-used" means registers which are not guaranteed to be preserved
10333unchanged for the caller by the current calling convention. This could also be
10334described as "caller-saved" or "not callee-saved".
10335
10336The `choice` parameters gives the programmer flexibility to choose the subset
10337of the call-used registers to be zeroed:
10338
10339- `skip` doesn't zero any call-used registers. This choice overrides any
10340 command-line arguments.
10341- `used` only zeros call-used registers used in the function. By `used`, we
10342 mean a register whose contents have been set or referenced in the function.
10343- `used-gpr` only zeros call-used GPR registers used in the function.
10344- `used-arg` only zeros call-used registers used to pass arguments to the
10345 function.
10346- `used-gpr-arg` only zeros call-used GPR registers used to pass arguments to
10347 the function.
10348- `all` zeros all call-used registers.
10349- `all-gpr` zeros all call-used GPR registers.
10350- `all-arg` zeros all call-used registers used to pass arguments to the
10351 function.
10352- `all-gpr-arg` zeros all call-used GPR registers used to pass arguments to
10353 the function.
10354
10355The default for the attribute is controlled by the `-fzero-call-used-regs`
10356flag.
10357
10358[return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
10359