Debian Codegraph @

libphobos/libdruntime/gcc/attributes.d

raw
1 // GNU D Compiler attribute support declarations.
2 // Copyright (C) 2021-2025 Free Software Foundation, Inc.
3
4 // GCC is free software; you can redistribute it and/or modify it under
5 // the terms of the GNU General Public License as published by the Free
6 // Software Foundation; either version 3, or (at your option) any later
7 // version.
8
9 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
10 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 // for more details.
13
14 // Under Section 7 of GPL version 3, you are granted additional
15 // permissions described in the GCC Runtime Library Exception, version
16 // 3.1, as published by the Free Software Foundation.
17
18 // You should have received a copy of the GNU General Public License and
19 // a copy of the GCC Runtime Library Exception along with this program;
20 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
21 // <http://www.gnu.org/licenses/>.
22
23 module gcc.attributes;
24
25 // Private helper templates.
26 private struct Attribute(A...)
27 {
28 A arguments;
29 }
30
31 private enum bool isStringValue(alias T) = is(typeof(T) == string);
32
33 private enum bool isStringOrIntValue(alias T)
34 = is(typeof(T) == string) || is(typeof(T) == int);
35
36 private template allSatisfy(alias F, T...)
37 {
38 static if (T.length == 0)
39 enum allSatisfy = true;
40 else static if (T.length == 1)
41 enum allSatisfy = F!(T[0]);
42 else
43 {
44 enum allSatisfy = allSatisfy!(F, T[ 0 .. $/2])
45 && allSatisfy!(F, T[$/2 .. $ ]);
46 }
47 }
48
49 /**
50 * Generic entrypoint for applying GCC attributes to a function or type.
51 * There is no type checking done, as well as no deprecation path for
52 * attributes removed from the compiler. So the recommendation is to use any
53 , of the other UDAs available unless it is a target-specific attribute.
54 *
55 * Function attributes introduced by the @attribute UDA are used in the
56 * declaration of a function, followed by an attribute name string and
57 * any arguments separated by commas enclosed in parentheses.
58 *
59 * Example:
60 * ---
61 * import gcc.attributes;
62 *
63 * @attribute("regparm", 1) int func(int size);
64 * ---
65 */
66 @system
67 auto attribute(A...)(A arguments)
68 if (A.length > 0 && is(A[0] == string))
69 {
70 return Attribute!A(arguments);
71 }
72
73
74 ///////////////////////////////////////////////////////////////////////////////
75 //
76 // Supported common attributes exposed by GDC.
77 //
78 ///////////////////////////////////////////////////////////////////////////////
79
80 /**
81 * The `@alloc_size` attribute may be applied to a function that returns a
82 * pointer and takes at least one argument of an integer or enumerated type.
83 * It indicates that the returned pointer points to memory whose size is given
84 * by the function argument at `sizeArgIdx`, or by the product of the arguments
85 * at `sizeArgIdx` and `numArgIdx`. Meaningful sizes are positive values less
86 * than `ptrdiff_t.max`. Unless `zeroBasedNumbering` is true, argument
87 * numbering starts at one for ordinary functions, and at two for non-static
88 * member functions.
89 *
90 * If `numArgIdx` is less than `0`, it is taken to mean there is no argument
91 * specifying the element count.
92 *
93 * Example:
94 * ---
95 * import gcc.attributes;
96 *
97 * @alloc_size(1) extern(C) void* malloc(size_t size);
98 * @alloc_size(3,2) extern(C) void* reallocarray(void *ptr, size_t nmemb,
99 * size_t size);
100 * @alloc_size(1,2) void* my_calloc(size_t element_size, size_t count,
101 * bool irrelevant);
102 * ---
103 */
104 auto alloc_size(int sizeArgIdx)
105 {
106 return attribute("alloc_size", sizeArgIdx);
107 }
108
109 /// ditto
110 auto alloc_size(int sizeArgIdx, int numArgIdx)
111 {
112 return attribute("alloc_size", sizeArgIdx, numArgIdx);
113 }
114
115 /// ditto
116 auto alloc_size(int sizeArgIdx, int numArgIdx, bool zeroBasedNumbering)
117 {
118 return attribute("alloc_size", sizeArgIdx, numArgIdx, zeroBasedNumbering);
119 }
120
121 auto alloc_size(A...)(A arguments)
122 {
123 assert(false, "alloc_size attribute argument value is not an integer constant");
124 }
125
126 /**
127 * The `@always_inline` attribute inlines the function independent of any
128 * restrictions that otherwise apply to inlining. Failure to inline such a
129 * function is diagnosed as an error.
130 *
131 * Example:
132 * ---
133 * import gcc.attributes;
134 *
135 * @always_inline int func();
136 * ---
137 */
138 enum always_inline = attribute("always_inline");
139
140 /**
141 * The `@cold` attribute on functions is used to inform the compiler that the
142 * function is unlikely to be executed. The function is optimized for size
143 * rather than speed and on many targets it is placed into a special subsection
144 * of the text section so all cold functions appear close together, improving
145 * code locality of non-cold parts of program. The paths leading to calls of
146 * cold functions within code are considered to be cold too.
147 *
148 * Example:
149 * ---
150 * import gcc.attributes;
151 *
152 * @cold int func();
153 * ---
154 */
155 enum cold = attribute("cold");
156
157 /**
158 * The `@flatten` attribute is used to inform the compiler that every call
159 * inside this function should be inlined, if possible. Functions declared with
160 * attribute `@noinline` and similar are not inlined.
161 *
162 * Example:
163 * ---
164 * import gcc.attributes;
165 *
166 * @flatten int func();
167 * ---
168 */
169 enum flatten = attribute("flatten");
170
171 /**
172 * The `@no_icf` attribute prevents a functions from being merged with another
173 * semantically equivalent function.
174 *
175 * Example:
176 * ---
177 * import gcc.attributes;
178 *
179 * @no_icf int func();
180 * ---
181 */
182 enum no_icf = attribute("no_icf");
183
184 /**
185 * The `@no_sanitize` attribute on functions is used to inform the compiler
186 * that it should not do sanitization of any option mentioned in
187 * sanitize_option. A list of values acceptable by the `-fsanitize` option
188 * can be provided.
189 *
190 * Example:
191 * ---
192 * import gcc.attributes;
193 *
194 * @no_sanitize("alignment", "object-size") void func1() { }
195 * @no_sanitize("alignment,object-size") void func2() { }
196 * ---
197 */
198
199 auto no_sanitize(A...)(A arguments)
200 if (allSatisfy!(isStringValue, arguments))
201 {
202 return attribute("no_sanitize", arguments);
203 }
204
205 auto no_sanitize(A...)(A arguments)
206 if (!allSatisfy!(isStringValue, arguments))
207 {
208 assert(false, "no_sanitize attribute argument not a string constant");
209 }
210
211 /**
212 * The `@noclone` attribute prevents a function from being considered for
213 * cloning - a mechanism that produces specialized copies of functions and
214 * which is (currently) performed by interprocedural constant propagation.
215 *
216 * Example:
217 * ---
218 * import gcc.attributes;
219 *
220 * @noclone int func();
221 * ---
222 */
223 enum noclone = attribute("noclone");
224
225 /**
226 * The `@noinline` attribute prevents a function from being considered for
227 * inlining. If the function does not have side effects, there are
228 * optimizations other than inlining that cause function calls to be optimized
229 * away, although the function call is live. To keep such calls from being
230 * optimized away, put `asm { ""; }` in the called function, to serve as a
231 * special side effect.
232 *
233 * Example:
234 * ---
235 * import gcc.attributes;
236 *
237 * @noinline int func();
238 * ---
239 */
240 enum noinline = attribute("noinline");
241
242 /**
243 * The `@noipa` attribute disables interprocedural optimizations between the
244 * function with this attribute and its callers, as if the body of the function
245 * is not available when optimizing callers and the callers are unavailable when
246 * optimizing the body. This attribute implies `@noinline`, `@noclone`, and
247 * `@no_icf` attributes. However, this attribute is not equivalent to a
248 * combination of other attributes, because its purpose is to suppress existing
249 * and future optimizations employing interprocedural analysis, including those
250 * that do not have an attribute suitable for disabling them individually.
251 *
252 * This attribute is supported mainly for the purpose of testing the compiler.
253 *
254 * Example:
255 * ---
256 * import gcc.attributes;
257 *
258 * @noipa int func();
259 * ---
260 */
261 enum noipa = attribute("noipa");
262
263 /**
264 * The `@optimize` attribute is used to specify that a function is to be
265 * compiled with different optimization options than specified on the command
266 * line. Valid `arguments` are constant non-negative integers and strings.
267 * Multiple arguments can be provided, separated by commas to specify multiple
268 * options. Each numeric argument specifies an optimization level. Each string
269 * argument that begins with the letter O refers to an optimization option such
270 * as `-O0` or `-Os`. Other options are taken as suffixes to the `-f` prefix
271 * jointly forming the name of an optimization option.
272 *
273 * Not every optimization option that starts with the `-f` prefix specified by
274 * the attribute necessarily has an effect on the function. The `@optimize`
275 * attribute should be used for debugging purposes only. It is not suitable in
276 * production code.
277 *
278 * Example:
279 * ---
280 * import gcc.attributes;
281 *
282 * @optimize(2) double fn0(double x);
283 * @optimize("2") double fn1(double x);
284 * @optimize("s") double fn2(double x);
285 * @optimize("Ofast") double fn3(double x);
286 * @optimize("-O2") double fn4(double x);
287 * @optimize("tree-vectorize") double fn5(double x);
288 * @optimize("-ftree-vectorize") double fn6(double x);
289 * @optimize("no-finite-math-only", 3) double fn7(double x);
290 * ---
291 */
292 auto optimize(A...)(A arguments)
293 if (allSatisfy!(isStringOrIntValue, arguments))
294 {
295 return attribute("optimize", arguments);
296 }
297
298 auto optimize(A...)(A arguments)
299 if (!allSatisfy!(isStringOrIntValue, arguments))
300 {
301 assert(false, "optimize attribute argument not a string or integer constant");
302 }
303
304 /**
305 * The `@register` attribute specifies that a local or `__gshared` variable
306 * is to be given a register storage-class in the C99 sense of the term, and
307 * will be placed into a register named `registerName`.
308 *
309 * The variable needs to boiled down to a data type that fits the target
310 * register. It also cannot have either thread-local or `extern` storage.
311 * It is an error to take the address of a register variable.
312 *
313 * Example:
314 * ---
315 * import gcc.attributes;
316 *
317 * @register("ebx") __gshared int ebx = void;
318 *
319 * void func() { @register("r10") long r10 = 0x2a; }
320 * ---
321 */
322 auto register(string registerName)
323 {
324 return attribute("register", registerName);
325 }
326
327 auto register(A...)(A arguments)
328 {
329 assert(false, "register attribute argument not a string constant");
330 }
331
332 /**
333 * The `@restrict` attribute specifies that a function parameter is to be
334 * restrict-qualified in the C99 sense of the term. The parameter needs to
335 * boil down to either a pointer or reference type, such as a D pointer,
336 * class reference, or a `ref` parameter.
337 *
338 * Example:
339 * ---
340 * import gcc.attributes;
341 *
342 * void func(@restrict ref const float[16] array);
343 * ---
344 */
345 enum restrict = attribute("restrict");
346
347 /**
348 * The `@section` attribute specifies that a function lives in a particular
349 * section. For when you need certain particular functions to appear in
350 * special sections.
351 *
352 * Some file formats do not support arbitrary sections so the section attribute
353 * is not available on all platforms. If you need to map the entire contents
354 * of a module to a particular section, consider using the facilities of the
355 * linker instead.
356 *
357 * Example:
358 * ---
359 * import gcc.attributes;
360 *
361 * @section("bar") extern void func();
362 * ---
363 */
364 auto section(string sectionName)
365 {
366 return attribute("section", sectionName);
367 }
368
369 auto section(A...)(A arguments)
370 {
371 assert(false, "section attribute argument not a string constant");
372 }
373
374 /**
375 * The `@simd` attribute enables creation of one or more function versions that
376 * can process multiple arguments using SIMD instructions from a single
377 * invocation. Specifying this attribute allows compiler to assume that such
378 * versions are available at link time (provided in the same or another module).
379 * Generated versions are target-dependent and described in the corresponding
380 * Vector ABI document. For x86_64 target this document can be found here.
381 * https://sourceware.org/glibc/wiki/libmvec?action=AttachFile&do=view&target=VectorABI.txt
382 *
383 * The `@simd_clones` attribute is the same as `@simd`, but also includes a
384 * `mask` argument. Valid masks values are `notinbranch` or `inbranch`, and
385 * instructs the compiler to generate non-masked or masked clones
386 * correspondingly.
387 *
388 * Example:
389 * ---
390 * import gcc.attributes;
391 *
392 * @simd double sqrt(double x);
393 * @simd("notinbranch") double atan2(double y, double x);
394 * ---
395 */
396 enum simd = attribute("simd");
397
398 auto simd_clones(string mask)
399 {
400 if (mask == "notinbranch" || mask == "inbranch")
401 return attribute("simd", mask);
402 else
403 {
404 assert(false, "unrecognized parameter `" ~ mask
405 ~ "` for `gcc.attribute.simd_clones`");
406 }
407 }
408
409 auto simd_clones(A...)(A arguments)
410 {
411 assert(false, "simd_clones attribute argument not a string constant");
412 }
413
414 /**
415 * The `@symver` attribute creates a symbol version on ELF targets. The syntax
416 * of the string parameter is `name@nodename`. The `name` part of the parameter
417 * is the actual name of the symbol by which it will be externally referenced.
418 * The `nodename` portion should be the name of a node specified in the version
419 * script supplied to the linker when building a shared library. Versioned
420 * symbol must be defined and must be exported with default visibility.
421 *
422 * Finally if the parameter is `name@@nodename` then in addition to creating a
423 * symbol version (as if `name@nodename` was used) the version will be also used
424 * to resolve `name` by the linker.
425 *
426 * Example:
427 * ---
428 * import gcc.attributes;
429 *
430 * @symver("foo@VERS_1") int foo_v1();
431 * ---
432 */
433 auto symver(A...)(A arguments)
434 if (allSatisfy!(isStringValue, arguments))
435 {
436 return attribute("symver", arguments);
437 }
438
439 auto symver(A...)(A arguments)
440 if (!allSatisfy!(isStringValue, arguments))
441 {
442 assert(false, "symver attribute argument not a string constant");
443 }
444
445 /**
446 * The `@target` attribute is used to specify that a function is to be
447 * compiled with different target options than specified on the command line.
448 * One or more strings can be provided as arguments, separated by commas to
449 * specify multiple options. Each string consists of one or more
450 * comma-separated suffixes to the `-m` prefix jointly forming the name of a
451 * machine-dependent option.
452 *
453 * The target attribute can be used for instance to have a function compiled
454 * with a different ISA (instruction set architecture) than the default.
455 *
456 * The options supported are specific to each target.
457 *
458 * Example:
459 * ---
460 * import gcc.attributes;
461 *
462 * @target("arch=core2") void core2_func();
463 * @target("sse3") void sse3_func();
464 * ---
465 */
466 auto target(A...)(A arguments)
467 if (allSatisfy!(isStringValue, arguments))
468 {
469 return attribute("target", arguments);
470 }
471
472 auto target(A...)(A arguments)
473 if (!allSatisfy!(isStringValue, arguments))
474 {
475 assert(false, "target attribute argument not a string constant");
476 }
477
478 /**
479 * The `@target_clones` attribute is used to specify that a function be cloned
480 * into multiple versions compiled with different target `options` than
481 * specified on the command line. The supported options and restrictions are
482 * the same as for `@target` attribute.
483 *
484 * It also creates a resolver function that dynamically selects a clone suitable
485 * for current architecture. The resolver is created only if there is a usage
486 * of a function with `@target_clones` attribute.
487 *
488 * Example:
489 * ---
490 * import gcc.attributes;
491 *
492 * @target_clones("sse4.1,avx,default") double func(double x);
493 * ---
494 */
495 auto target_clones(A...)(A arguments)
496 if (allSatisfy!(isStringValue, arguments))
497 {
498 return attribute("target_clones", arguments);
499 }
500
501 auto target_clones(A...)(A arguments)
502 if (!allSatisfy!(isStringValue, arguments))
503 {
504 assert(false, "target attribute argument not a string constant");
505 }
506
507 /**
508 * The `@used` attribute, annotated to a function, means that code must be
509 * emitted for the function even if it appears that the function is not
510 * referenced. This is useful, for example, when the function is referenced
511 * only in inline assembly.
512 *
513 * Example:
514 * ---
515 * import gcc.attributes;
516 *
517 * @used __gshared int var = 0x1000;
518 * ---
519 */
520 enum used = attribute("used");
521
522 /**
523 * The `@visibility` attribute affects the linkage of the declaration to which
524 * it is attached. It can be applied to variables, types, and functions.
525 *
526 * There are four supported visibility_type values: `default`, `hidden`,
527 * `protected`, or `internal` visibility.
528 *
529 * Example:
530 * ---
531 * import gcc.attributes;
532 *
533 * @visibility("protected") void func() { }
534 * ---
535 */
536 auto visibility(string visibilityName)
537 {
538 return attribute("visibility", visibilityName);
539 }
540
541 auto visibility(A...)(A arguments)
542 {
543 assert(false, "visibility attribute argument not a string constant");
544 }
545
546 /**
547 * The `@weak` attribute causes a declaration of an external symbol to be
548 * emitted as a weak symbol rather than a global. This is primarily useful in
549 * defining library functions that can be overridden in user code, though it can
550 * also be used with non-function declarations. The overriding symbol must have
551 * the same type as the weak symbol. In addition, if it designates a variable
552 * it must also have the same size and alignment as the weak symbol.
553 *
554 * Weak symbols are supported for ELF targets, and also for a.out targets when
555 * using the GNU assembler and linker.
556 *
557 * Example:
558 * ---
559 * import gcc.attributes;
560 *
561 * @weak int func() { return 1; }
562 * ---
563 */
564 enum weak = attribute("weak");
565
566 /**
567 * The `@noplt` attribute is the counterpart to option `-fno-plt`. Calls to
568 * functions marked with this attribute in position-independent code do not use
569 * the PLT in position-independent code.
570 *
571 * In position-dependant code, a few targets also convert call to functions
572 * that are marked to not use the PLT to use the GOT instead.
573 *
574 * Example:
575 * ---
576 * import gcc.attributes;
577 *
578 * @noplt int func();
579 *
580 * ---
581 */
582 enum noplt = attribute("noplt");
583
584 ///////////////////////////////////////////////////////////////////////////////
585 //
586 // Attributes defined for compatibility with LDC.
587 //
588 ///////////////////////////////////////////////////////////////////////////////
589
590 /**
591 * Specifies that the function returns `null` or a pointer to at least a
592 * certain number of allocated bytes. `sizeArgIdx` and `numArgIdx` specify
593 * the 0-based index of the function arguments that should be used to calculate
594 * the number of bytes returned.
595 *
596 * Example:
597 * ---
598 * import gcc.attributes;
599 *
600 * @allocSize(0) extern(C) void* malloc(size_t size);
601 * @allocSize(2,1) extern(C) void* reallocarray(void *ptr, size_t nmemb,
602 * size_t size);
603 * @allocSize(0,1) void* my_calloc(size_t element_size, size_t count,
604 * bool irrelevant);
605 * ---
606 */
607 auto allocSize(int sizeArgIdx, int numArgIdx = int.min)
608 {
609 return alloc_size(sizeArgIdx, numArgIdx, true);
610 }
611
612 auto allocSize(A...)(A arguments)
613 {
614 assert(false, "allocSize attribute argument value is not an integer constant");
615 }
616
617 /**
618 * When applied to a global symbol, the compiler, assembler, and linker are
619 * required to treat the symbol as if there is a reference to the symbol that
620 * it cannot see (which is why they have to be named). For example, it
621 * prevents the deletion by the linker of an unreferenced symbol.
622 *
623 * Example:
624 * ---
625 * import gcc.attributes;
626 *
627 * @assumeUsed __gshared int var = 0x1000;
628 * ---
629 */
630 alias assumeUsed = used;
631
632 /// This attribute has no effect.
633 enum dynamicCompile = false;
634
635 /// ditto
636 enum dynamicCompileConst = false;
637
638 /// ditto
639 enum dynamicCompileEmit = false;
640
641 /**
642 * Explicitly sets "fast-math" for a function, enabling aggressive math
643 * optimizations. These optimizations may dramatically change the outcome of
644 * floating point calculations (e.g. because of reassociation).
645 *
646 * Example:
647 * ---
648 * import gcc.attributes;
649 *
650 * @fastmath
651 * double dot(double[] a, double[] b) {
652 * double s = 0;
653 * foreach(size_t i; 0..a.length)
654 * {
655 * // will result in vectorized fused-multiply-add instructions
656 * s += a * b;
657 * }
658 * return s;
659 * }
660 * ---
661 */
662 enum fastmath = optimize("Ofast");
663
664 /**
665 * Sets the visibility of a function or global variable to "hidden".
666 * Such symbols aren't directly accessible from outside the DSO
667 * (executable or DLL/.so/.dylib) and are resolved inside the DSO
668 * during linking. If unreferenced within the DSO, the linker can
669 * strip a hidden symbol.
670 * An `export` visibility overrides this attribute.
671 */
672 enum hidden = visibility("hidden");
673
674 /**
675 * Adds GCC's "naked" attribute to a function, disabling function prologue /
676 * epilogue emission.
677 * Intended to be used in combination with basic `asm` statement. While using
678 * extended `asm` or a mixture of basic `asm` and D code may appear to work,
679 * they cannot be depended upon to work reliably and are not supported.
680 *
681 * Example:
682 * ---
683 * import gcc.attributes;
684 *
685 * @naked void abort() {
686 * asm { "ud2"; }
687 * }
688 * ---
689 */
690 enum naked = attribute("naked");
691
692 /**
693 * Disables a particular sanitizer for this function.
694 * Valid sanitizer names are all names accepted by `-fsanitize=` commandline option.
695 * Multiple sanitizers can be disabled by applying this UDA multiple times, e.g.
696 * `@noSanitize("address") `@noSanitize("thread")` to disable both ASan and TSan.
697 */
698 alias noSanitize = no_sanitize;
699
700 /**
701 * Sets the optimization strategy for a function.
702 * Valid strategies are "none", "optsize", "minsize". The strategies are
703 * mutually exclusive.
704 *
705 * Example:
706 * ---
707 * import gcc.attributes;
708 *
709 * @optStrategy("none")
710 * int func() {
711 * return call();
712 * }
713 * ---
714 */
715 auto optStrategy(string strategy)
716 {
717 if (strategy == "none")
718 return optimize("O0");
719 else if (strategy == "optsize" || strategy == "minsize")
720 return optimize("Os");
721 else
722 {
723 assert(false, "unrecognized parameter `" ~ strategy
724 ~ "` for `gcc.attribute.optStrategy`");
725 }
726 }
727
728 auto optStrategy(A...)(A arguments)
729 {
730 assert(false, "optStrategy attribute argument value is not a string constant");
731 }
732
733 /**
734 * When applied to a function, specifies that the function should be optimzed
735 * by Graphite, GCC's polyhedral optimizer. Useful for optimizing loops for
736 * data locality, vectorization and parallelism.
737 *
738 * Experimental!
739 *
740 * Only effective when GDC was built with ISL included.
741 */
742 enum polly = optimize("loop-parallelize-all", "loop-nest-optimize");