2 Copyright (C) 2022-2023 Free Software Foundation, Inc.
3 This is part of the GNU D manual.
4 For copying conditions, see the file gdc.texi.
8 @chapter Language Reference
9 @cindex language reference, D language
11 The implementation of the D programming language used by the GNU D compiler is
12 shared with parts of the front-end for the Digital Mars D compiler, hosted at
13 @uref{https://github.com/dlang/dmd/}. This common front-end covers lexical
14 analysis, parsing, and semantic analysis of the D programming language defined
15 in the documents at @uref{https://dlang.org/}.
17 The implementation details described in this manual are GNU D extensions to the
18 D programming language. If you want to write code that checks whether these
19 features are available, you can test for the predefined version @code{GNU}, or
20 you can check whether a specific feature is compilable using
21 @code{__traits(compiles)}.
27 return __builtin_atan2(x, y);
30 static if (__traits(compiles, @{ asm @{"";@} @}))
32 asm @{ "magic instruction"; @}
37 * Attributes:: Implementation-defined attributes.
38 * Builtin Functions:: GCC built-ins module.
39 * ImportC:: Importing C sources into D.
40 * Inline Assembly:: Interfacing D with assembler.
41 * Intrinsics:: Intrinsic functions supported by GDC.
42 * Predefined Pragmas:: Pragmas accepted by GDC.
43 * Predefined Versions:: List of versions for conditional compilation.
44 * Special Enums:: Intrinsic type interoperability with C and C++.
45 * Traits:: Compile-time reflection extensions.
46 * Vector Extensions:: Using vector types and supported operations.
47 * Vector Intrinsics:: Vector instructions through intrinsics.
48 * Missing Features:: Deviations from the D2 specification in GDC.
52 @c --------------------------------------------------------
58 User-Defined Attributes (UDA) are compile-time expressions introduced by the
59 @code{@@} token that can be attached to a declaration. These attributes can
60 then be queried, extracted, and manipulated at compile time.
62 GNU D provides a number of extra special attributes to control specific
63 compiler behavior that may help the compiler optimize or check code more
64 carefully for correctness. The attributes are defined in the
65 @code{gcc.attributes} module.
67 There is some overlap between the purposes of attributes and pragmas. It has
68 been found more convenient to use @code{@@attribute} to achieve a natural
69 attachment of attributes to their corresponding declarations, whereas
70 @code{pragma} is of use for compatibility with other compilers or constructs
71 that do not naturally form part of the grammar.
80 @c --------------------------------------------------------
82 @node Attribute Syntax
83 @subsection Attribute Syntax
85 @code{@@(gcc.attributes.attribute)} is the generic entrypoint for applying GCC
86 attributes to a function, variable, or type. There is no type checking done,
87 as well as no deprecation path for attributes removed from the compiler. So
88 the recommendation is to use any of the other UDAs available as described in
89 @ref{Common Attributes} unless it is a target-specific attribute
90 (@xref{Target Attributes}).
92 Function attributes introduced by the @code{@@attribute} UDA are used in the
93 declaration of a function, followed by an attribute name string and any
94 arguments separated by commas enclosed in parentheses.
97 import gcc.attributes;
98 @@attribute("regparm", 1) int func(int size);
102 Multiple attributes can be applied to a single declaration either with multiple
103 @code{@@attribute} attributes, or passing all attributes as a comma-separated
104 list enclosed by parentheses.
107 // Both func1 and func2 have the same attributes applied.
108 @@attribute("noinline") @@attribute("noclone") void func1();
109 @@(attribute("noinline"), attribute("noclone")) void func2();
113 There are some problems with the semantics of such attributes in D. For
114 example, there are no manglings for attributes, although they may affect code
115 generation, so problems may arise when attributed types are used in conjunction
116 with templates or overloading. Similarly, @code{typeid} does not distinguish
117 between types with different attributes. Support for attributes in D are
118 restricted to declarations only.
120 @c --------------------------------------------------------
122 @node Common Attributes
123 @subsection Common Attributes
125 The following attributes are supported on most targets.
129 @cindex @code{alloc_size} function attribute
130 @cindex @code{alloc_size} variable attribute
131 @item @@(gcc.attributes.alloc_size (@var{sizeArgIdx}))
132 @itemx @@(gcc.attributes.alloc_size (@var{sizeArgIdx}, @var{numArgIdx}))
133 @itemx @@(gcc.attributes.alloc_size (@var{sizeArgIdx}, @var{numArgIdx}, @var{zeroBasedNumbering}))
135 The @code{@@alloc_size} attribute may be applied to a function - or a function
136 pointer variable - that returns a pointer and takes at least one argument of
137 an integer or enumerated type. It indicates that the returned pointer points
138 to memory whose size is given by the function argument at @code{sizeArgIdx}, or
139 by the product of the arguments at @code{sizeArgIdx} and @code{numArgIdx}.
140 Meaningful sizes are positive values less than @code{ptrdiff_t.max}. Unless
141 @code{zeroBasedNumbering} is true, argument numbering starts at one for
142 ordinary functions, and at two for non-static member functions.
144 If @code{numArgIdx} is less than @code{0}, it is taken to mean there is no
145 argument specifying the element count.
148 @@alloc_size(1) void* malloc(size_t);
149 @@alloc_size(3,2) void* reallocarray(void *, size_t, size_t);
150 @@alloc_size(1,2) void* my_calloc(size_t, size_t, bool);
151 void malloc_cb(@@alloc_size(1) void* function(size_t) ptr) @{ @}
154 @cindex @code{always_inline} function attribute
155 @item @@(gcc.attributes.always_inline)
157 The @code{@@always_inline} attribute inlines the function independent of any
158 restrictions that otherwise apply to inlining. Failure to inline such a
159 function is diagnosed as an error.
162 @@always_inline int func();
165 @cindex @code{cold} function attribute
166 @item @@(gcc.attributes.cold)
168 The @code{@@cold} attribute on functions is used to inform the compiler that the
169 function is unlikely to be executed. The function is optimized for size
170 rather than speed and on many targets it is placed into a special subsection
171 of the text section so all cold functions appear close together, improving
172 code locality of non-cold parts of program. The paths leading to calls of
173 cold functions within code are considered to be cold too.
179 @cindex @code{flatten} function attribute
180 @item @@(gcc.attributes.flatten)
182 The @code{@@flatten} attribute is used to inform the compiler that every call
183 inside this function should be inlined, if possible. Functions declared with
184 attribute @code{@@noinline} and similar are not inlined.
187 @@flatten int func();
190 @cindex @code{no_icf} function attribute
191 @item @@(gcc.attributes.no_icf)
193 The @code{@@no_icf} attribute prevents a function from being merged with
194 another semantically equivalent function.
200 @cindex @code{no_sanitize} function attribute
201 @item @@(gcc.attributes.no_sanitize ("@var{sanitize_option}"))
203 The @code{@@no_sanitize} attribute on functions is used to inform the compiler
204 that it should not do sanitization of any option mentioned in
205 @var{sanitize_option}. A list of values acceptable by the @option{-fsanitize}
206 option can be provided.
209 @@no_sanitize("alignment", "object-size") void func1() @{ @}
210 @@no_sanitize("alignment,object-size") void func2() @{ @}
213 @cindex @code{noclone} function attribute
214 @item @@(gcc.attributes.noclone)
216 The @code{@@noclone} attribute prevents a function from being considered for
217 cloning - a mechanism that produces specialized copies of functions and which
218 is (currently) performed by interprocedural constant propagation.
221 @@noclone int func();
224 @cindex @code{noinline} function attribute
225 @item @@(gcc.attributes.noinline)
227 The @code{@@noinline} attribute prevents a function from being considered for
228 inlining. If the function does not have side effects, there are optimizations
229 other than inlining that cause function calls to be optimized away, although
230 the function call is live. To keep such calls from being optimized away, put
231 @code{asm @{ ""; @}} in the called function, to serve as a special side effect.
234 @@noinline int func();
237 @cindex @code{noipa} function attribute
238 @item @@(gcc.attributes.noipa)
240 The @code{@@noipa} attribute disables interprocedural optimizations between the
241 function with this attribute and its callers, as if the body of the function is
242 not available when optimizing callers and the callers are unavailable when
243 optimizing the body. This attribute implies @code{@@noinline},
244 @code{@@noclone}, and @code{@@no_icf} attributes. However, this attribute is
245 not equivalent to a combination of other attributes, because its purpose is to
246 suppress existing and future optimizations employing interprocedural analysis,
247 including those that do not have an attribute suitable for disabling them
250 This attribute is supported mainly for the purpose of testing the compiler.
256 @cindex @code{noplt} function attribute
257 @item @@(gcc.attributes.noplt)
259 The @code{@@noplt} attribute is the counterpart to option @option{-fno-plt}.
260 Calls to functions marked with this attribute in position-independent code do
261 not use the PLT in position-independent code.
263 In position-dependant code, a few targets also convert call to functions that
264 are marked to not use the PLT to use the GOT instead.
270 @cindex @code{optimize} function attribute
271 @item @@(gcc.attributes.optimize (@var{arguments}))
273 The @code{@@optimize} attribute is used to specify that a function is to be
274 compiled with different optimization options than specified on the command
275 line. Valid @var{arguments} are constant non-negative integers and strings.
276 Multiple arguments can be provided, separated by commas to specify multiple
277 options. Each numeric argument specifies an optimization level. Each string
278 argument that begins with the letter @code{O} refers to an optimization option
279 such as @option{-O0} or @option{-Os}. Other options are taken as suffixes to
280 the @code{-f} prefix jointly forming the name of an optimization option.
282 Not every optimization option that starts with the @code{-f} prefix
283 specified by the attribute necessarily has an effect on the function.
284 The @code{@@optimize} attribute should be used for debugging purposes only.
285 It is not suitable in production code.
288 @@optimize(2) double fn0(double x);
289 @@optimize("2") double fn1(double x);
290 @@optimize("s") double fn2(double x);
291 @@optimize("Ofast") double fn3(double x);
292 @@optimize("-O2") double fn4(double x);
293 @@optimize("tree-vectorize") double fn5(double x);
294 @@optimize("-ftree-vectorize") double fn6(double x);
295 @@optimize("no-finite-math-only", 3) double fn7(double x);
298 @cindex @code{register} variable attribute
299 @item @@(gcc.attributes.register ("@var{registerName}"))
301 The @code{@@register} attribute specifies that a local or @code{__gshared}
302 variable is to be given a register storage-class in the C99 sense of the term,
303 and will be placed into a register named @var{registerName}.
305 The variable needs to boiled down to a data type that fits the target register.
306 It also cannot have either thread-local or @code{extern} storage. It is an
307 error to take the address of a register variable.
310 @@register("ebx") __gshared int ebx = void;
311 void func() @{ @@register("r10") long r10 = 0x2a; @}
314 @cindex @code{restrict} parameter attribute
315 @item @@(gcc.attributes.restrict)
317 The @code{@@restrict} attribute specifies that a function parameter is to be
318 restrict-qualified in the C99 sense of the term. The parameter needs to boil
319 down to either a pointer or reference type, such as a D pointer, class
320 reference, or a @code{ref} parameter.
323 void func(@@restrict ref const float[16] array);
326 @cindex @code{section} function attribute
327 @cindex @code{section} variable attribute
328 @item @@(gcc.attributes.section ("@var{sectionName}"))
330 The @code{@@section} attribute specifies that a function or variable lives in a
331 particular section. For when you need certain particular functions to appear
334 Some file formats do not support arbitrary sections so the section attribute is
335 not available on all platforms. If you need to map the entire contents of a
336 module to a particular section, consider using the facilities of the linker
340 @@section("bar") extern void func();
341 @@section("stack") ubyte[10000] stack;
344 @cindex @code{simd} function attribute
345 @item @@(gcc.attributes.simd)
347 The @code{@@simd} attribute enables creation of one or more function versions
348 that can process multiple arguments using SIMD instructions from a single
349 invocation. Specifying this attribute allows compiler to assume that such
350 versions are available at link time (provided in the same or another module).
351 Generated versions are target-dependent and described in the corresponding
355 @@simd double sqrt(double x);
358 @cindex @code{simd_clones} function attribute
359 @item @@(gcc.attributes.simd_clones ("@var{mask}"))
361 The @code{@@simd_clones} attribute is the same as @code{@@simd}, but also
362 includes a @var{mask} argument. Valid masks values are @code{notinbranch} or
363 @code{inbranch}, and instructs the compiler to generate non-masked or masked
364 clones correspondingly.
367 @@simd_clones("notinbranch") double atan2(double y, double x);
370 @cindex @code{symver} function attribute
371 @item @@(gcc.attributes.symver ("@var{arguments}"))
373 The @code{@@symver} attribute creates a symbol version on ELF targets.
374 The syntax of the string parameter is @code{"@var{name}@@@var{nodename}"}.
375 The @var{name} part of the parameter is the actual name of the symbol by which
376 it will be externally referenced. The @var{nodename} portion should be the
377 name of a node specified in the version script supplied to the linker when
378 building a shared library. Versioned symbol must be defined and must be
379 exported with default visibility.
381 Finally if the parameter is @code{"@var{name}@@@@@var{nodename}"} then in
382 addition to creating a symbol version (as if
383 @code{"@var{name}@@@var{nodename}"} was used) the version will be also used to
384 resolve @var{name} by the linker.
387 @@symver("foo@@VERS_1") int foo_v1();
390 @cindex @code{target} function attribute
391 @item @@(gcc.attributes.target ("@var{options}"))
393 The @code{@@target} attribute is used to specify that a function is to be
394 compiled with different target options than specified on the command line. One
395 or more strings can be provided as arguments, separated by commas to specify
396 multiple options. Each string consists of one or more comma-separated suffixes
397 to the @option{-m} prefix jointly forming the name of a machine-dependent
400 The target attribute can be used for instance to have a function compiled with
401 a different ISA (instruction set architecture) than the default.
403 The options supported are specific to each target.
406 @@target("arch=core2") void core2_func();
407 @@target("sse3") void sse3_func();
410 @cindex @code{target_clones} function attribute
411 @item @@(gcc.attributes.target_clones ("@var{options}"))
413 The @code{@@target_clones} attribute is used to specify that a function be
414 cloned into multiple versions compiled with different target @var{options} than
415 specified on the command line. The supported options and restrictions are the
416 same as for @code{@@target} attribute.
418 It also creates a resolver function that dynamically selects a clone suitable
419 for current architecture. The resolver is created only if there is a usage of
420 a function with @code{@@target_clones} attribute.
423 @@target_clones("sse4.1,avx,default") double func(double x);
426 @cindex @code{used} function attribute
427 @cindex @code{used} variable attribute
428 @item @@(gcc.attributes.used)
430 The @code{@@used} attribute, annotated to a function or variable, means that
431 code must be emitted for the function even if it appears that the function is
432 not referenced. This is useful, for example, when the function is referenced
433 only in inline assembly.
436 @@used __gshared int var = 0x1000;
439 @cindex @code{visibility} function attribute
440 @cindex @code{visibility} variable attribute
441 @item @@(gcc.attributes.visibility ("@var{visibilityName}"))
443 The @code{@@visibility} attribute affects the linkage of the declaration to
444 which it is attached. It can be applied to variables, types, and functions.
446 There are four supported visibility_type values: @code{default}, @code{hidden},
447 @code{protected}, or @code{internal} visibility.
450 @@visibility("protected") void func() @{ @}
453 @cindex @code{weak} function attribute
454 @cindex @code{weak} variable attribute
455 @item @@(gcc.attributes.weak)
457 The @code{@@weak} attribute causes a declaration of an external symbol to be
458 emitted as a weak symbol rather than a global. This is primarily useful in
459 defining library functions that can be overridden in user code, though it can
460 also be used with non-function declarations. The overriding symbol must have
461 the same type as the weak symbol. In addition, if it designates a variable it
462 must also have the same size and alignment as the weak symbol.
464 Weak symbols are supported for ELF targets, and also for a.out targets when
465 using the GNU assembler and linker.
468 @@weak int func() @{ return 1; @}
473 @c --------------------------------------------------------
475 @node Other Attributes
476 @subsection Other Attributes
478 The following attributes are defined for compatibility with other compilers.
482 @cindex @code{allocSize} function attribute
483 @item @@(gcc.attributes.allocSize (@var{sizeArgIdx}))
484 @itemx @@(gcc.attributes.allocSize (@var{sizeArgIdx}, @var{numArgIdx}))
485 @item @@(gcc.attributes.allocSize (@var{sizeArgIdx}))
487 These attributes are a synonym for
488 @code{@@alloc_size(@var{sizeArgIdx}, @var{numArgIdx}, true)}.
489 Unlike @code{@@alloc_size}, it uses 0-based index of the function arguments.
491 @cindex @code{assumeUsed} function attribute
492 @cindex @code{assumeUsed} variable attribute
493 @item @@(gcc.attributes.assumeUsed)
495 This attribute is a synonym for @code{@@used}.
497 @cindex @code{dynamicCompile} function attribute
498 @item @@(gcc.attributes.dynamicCompile)
499 @itemx @@(gcc.attributes.dynamicCompileConst)
500 @itemx @@(gcc.attributes.dynamicCompileEmit)
502 These attributes are accepted, but have no effect.
504 @cindex @code{fastmath} function attribute
505 @item @@(gcc.attributes.fastmath)
507 This attribute is a synonym for @code{@@optimize("Ofast")}. Explicitly sets
508 "fast-math" for a function, enabling aggressive math optimizations.
510 @cindex @code{hidden} function attribute
511 @cindex @code{hidden} variable attribute
512 @item @@(gcc.attributes.hidden)
514 This attribute is a synonym for @code{@@visibility("hidden")}. Sets the
515 visibility of a function or global variable to "hidden".
517 @cindex @code{naked} function attribute
518 @item @@(gcc.attributes.naked)
520 This attribute is a synonym for @code{@@attribute("naked")}. Adds GCC's
521 "naked" attribute to a function, disabling function prologue / epilogue
522 emission. Intended to be used in combination with basic @code{asm} statements.
523 While using extended @code{asm} or a mixture of basic @code{asm} and D code may
524 appear to work, they cannot be depended upon to work reliably and are not
527 @cindex @code{noSanitize} function attribute
528 @item @@(gcc.attributes.noSanitize ("@var{sanitize_option}"))
530 This attribute is a synonym for @code{@@no_sanitize("sanitize_option")}.
533 @cindex @code{optStrategy} function attribute
534 @item @@(gcc.attributes.optStrategy ("@var{strategy}"))
536 This attribute is a synonym for @code{@@optimize("O0")} and
537 @code{@@optimize("Os")}. Sets the optimization strategy for a function. Valid
538 strategies are "none", "optsize", "minsize". The strategies are mutually
541 @item @@(gcc.attributes.polly)
543 This attribute is a synonym for
544 @code{@@optimize("loop-parallelize-all", "loop-nest-optimize")}.
545 Only effective when GDC was built with ISL included.
549 @c --------------------------------------------------------
551 @node Target Attributes
552 @subsection Target-specific Attributes
554 Many targets have their own target-specific attributes. These are also exposed
555 via the @code{gcc.attributes} module with use of the generic
556 @code{@@(gcc.attributes.attribute)} UDA function.
558 @xref{Attribute Syntax}, for details of the exact syntax for using attributes.
560 See the function and variable attribute documentation in the GCC manual for
561 more information about what attributes are available on each target.
563 Examples of using x86-specific target attributes are shown as follows:
566 import gcc.attributes;
569 @@attribute("fastcall")
570 @@attribute("ms_abi")
571 @@attribute("sysv_abi")
572 @@attribute("callee_pop_aggregate_return", 1)
573 @@attribute("ms_hook_prologue")
575 @@attribute("regparm", 2)
576 @@attribute("sseregparm")
577 @@attribute("force_align_arg_pointer")
578 @@attribute("stdcall")
579 @@attribute("no_caller_saved_registers")
580 @@attribute("interrupt")
581 @@attribute("indirect_branch", "thunk")
582 @@attribute("function_return", "keep"))
583 @@attribute("nocf_check")
584 @@attribute("cf_check")
585 @@attribute("indirect_return")
586 @@attribute("fentry_name", "nop")
587 @@attribute("fentry_section", "__entry_loc")
588 @@attribute("nodirect_extern_access")
593 @c --------------------------------------------------------
595 @node Builtin Functions
596 @section Built-in Functions
597 @cindex built-in functions
599 GCC provides a large number of built-in functions that are made available in
600 GNU D by importing the @code{gcc.builtins} module. Declarations in this module
601 are automatically created by the compiler. All declarations start with
602 @code{__builtin_}. Refer to the built-in function documentation in the GCC
603 manual for a full list of functions that are available.
611 @c --------------------------------------------------------
614 @subsection Built-in Types
615 @cindex built-in types
617 In addition to built-in functions, the following types are defined in the
618 @code{gcc.builtins} module.
621 @item ___builtin_clong
622 The D equivalent of the target's C @code{long} type.
624 @item ___builtin_clonglong
625 The D equivalent of the target's C @code{long long} type.
627 @item ___builtin_culong
628 The D equivalent of the target's C @code{unsigned long} type.
630 @item ___builtin_culonglong
631 The D equivalent of the target's C @code{unsigned long long} type.
633 @item ___builtin_machine_byte
634 Signed unit-sized integer type.
636 @item ___builtin_machine_int
637 Signed word-sized integer type.
639 @item ___builtin_machine_ubyte
640 Unsigned unit-sized integer type.
642 @item ___builtin_machine_uint
643 Unsigned word-sized integer type.
645 @item ___builtin_pointer_int
646 Signed pointer-sized integer type.
648 @item ___builtin_pointer_uint
649 Unsigned pointer-sized integer type.
651 @item ___builtin_unwind_int
652 The D equivalent of the target's C @code{_Unwind_Sword} type.
654 @item ___builtin_unwind_uint
655 The D equivalent of the target's C @code{_Unwind_Word} type.
657 @item ___builtin_va_list
658 The target's @code{va_list} type.
661 @c --------------------------------------------------------
664 @subsection Querying Available Built-ins
665 @cindex built-in functions
667 Not all of the functions are supported, and some target-specific functions may
668 only be available when compiling for a particular ISA. One way of finding out
669 what is exposed by the built-ins module is by generating a D interface file.
670 Assuming you have no file @file{builtins.d}, the command
672 echo "module gcc.builtins;" > builtins.d; gdc -H -fsyntax-only builtins.d
675 will save all built-in declarations to the file @file{builtins.di}.
677 Another way to determine whether a specific built-in is available is by using
678 compile-time reflection.
680 enum X86_HAVE_SSE3 = __traits(compiles, __builtin_ia32_haddps);
681 enum X86_HAVE_SSSE3 = __traits(compiles, __builtin_ia32_pmulhrsw128);
682 enum X86_HAVE_SSE41 = __traits(compiles, __builtin_ia32_dpps);
683 enum X86_HAVE_SSE42 = __traits(compiles, __builtin_ia32_pcmpgtq);
684 enum X86_HAVE_AVX = __traits(compiles, __builtin_ia32_vbroadcastf128_pd256);
685 enum X86_HAVE_AVX2 = __traits(compiles, __builtin_ia32_gathersiv2df);
686 enum X86_HAVE_BMI2 = __traits(compiles, __builtin_ia32_pext_si);
689 @c --------------------------------------------------------
692 @subsection Other Built-in Functions
693 @cindex built-in functions
696 As well as built-ins being available from the @code{gcc.builtins} module, GNU D
697 will also recognize when an @code{extern(C)} library function is a GCC
698 built-in. Many of these functions are only optimized in certain cases; if they
699 are not optimized in a particular case, a call to the library function is
700 emitted. This optimization can be disabled with the @option{-fno-builtin}
701 option (@pxref{Runtime Options}).
703 In the @code{core.stdc.complex} module, the functions
704 @code{cabs}, @code{cabsf}, @code{cabsl}, @code{cacos}, @code{cacosf},
705 @code{cacosh}, @code{cacoshf}, @code{cacoshl}, @code{cacosl}, @code{carg},
706 @code{cargf}, @code{cargl}, @code{casin}, @code{casinf}, @code{casinh},
707 @code{casinhf}, @code{casinhl}, @code{casinl}, @code{catan}, @code{catanf},
708 @code{catanh}, @code{catanhf}, @code{catanhl}, @code{catanl}, @code{ccos},
709 @code{ccosf}, @code{ccosh}, @code{ccoshf}, @code{ccoshl}, @code{ccosl},
710 @code{cexp}, @code{cexpf}, @code{cexpl}, @code{clog}, @code{clogf},
711 @code{clogl}, @code{conj}, @code{conjf}, @code{conjl}, @code{cpow},
712 @code{cpowf}, @code{cpowl}, @code{cproj}, @code{cprojf}, @code{cprojl},
713 @code{csin}, @code{csinf}, @code{csinh}, @code{csinhf}, @code{csinhl},
714 @code{csinl}, @code{csqrt}, @code{csqrtf}, @code{csqrtl}, @code{ctan},
715 @code{ctanf}, @code{ctanh}, @code{ctanhf}, @code{ctanhl}, @code{ctanl}
716 may be handled as built-in functions. All these functions have corresponding
717 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
719 In the @code{core.stdc.ctype} module, the functions
720 @code{isalnum}, @code{isalpha}, @code{isblank}, @code{iscntrl}, @code{isdigit},
721 @code{isgraph}, @code{islower}, @code{isprint}, @code{ispunct}, @code{isspace},
722 @code{isupper}, @code{isxdigit}, @code{tolower}, @code{toupper}
723 may be handled as built-in functions. All these functions have corresponding
724 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
726 In the @code{core.stdc.fenv} module, the functions
727 @code{feclearexcept}, @code{fegetenv}, @code{fegetexceptflag},
728 @code{fegetround}, @code{feholdexcept}, @code{feraiseexcept}, @code{fesetenv},
729 @code{fesetexceptflag}, @code{fesetround}, @code{fetestexcept},
731 may be handled as built-in functions. All these functions have corresponding
732 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
734 In the @code{core.stdc.inttypes} module, the function @code{imaxabs} may be
735 handled as a built-in function. All these functions have corresponding
736 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
738 In the @code{core.stdc.math} module, the functions
739 @code{acos}, @code{acosf}, @code{acosh}, @code{acoshf}, @code{acoshl},
740 @code{acosl}, @code{asin}, @code{asinf}, @code{asinh}, @code{asinhf},
741 @code{asinhl}, @code{asinl}, @code{atan}, @code{atan2}, @code{atan2f},
742 @code{atan2l}, @code{atanf}, @code{atanh}, @code{atanhf}, @code{atanhl},
743 @code{atanl}, @code{cbrt}, @code{cbrtf}, @code{cbrtl}, @code{ceil},
744 @code{ceilf}, @code{ceill}, @code{copysign}, @code{copysignf},
745 @code{copysignl}, @code{cos}, @code{cosf}, @code{cosh}, @code{coshf},
746 @code{coshl}, @code{cosl}, @code{erf}, @code{erfc}, @code{erfcf}, @code{erfcl},
747 @code{erff}, @code{erfl}, @code{exp}, @code{exp2}, @code{exp2f}, @code{exp2l},
748 @code{expf}, @code{expl}, @code{expm1}, @code{expm1f}, @code{expm1l},
749 @code{fabs}, @code{fabsf}, @code{fabsl}, @code{fdim}, @code{fdimf},
750 @code{fdiml}, @code{floor}, @code{floorf}, @code{floorl}, @code{fma},
751 @code{fmaf}, @code{fmal}, @code{fmax}, @code{fmaxf}, @code{fmaxl}, @code{fmin},
752 @code{fminf}, @code{fminl}, @code{fmod}, @code{fmodf}, @code{fmodl},
753 @code{frexp}, @code{frexpf}, @code{frexpl}, @code{hypot}, @code{hypotf},
754 @code{hypotl}, @code{ilogb}, @code{ilogbf}, @code{ilogbl}, @code{isinf},
755 @code{isnan}, @code{ldexp}, @code{ldexpf}, @code{ldexpl}, @code{lgamma},
756 @code{lgammaf}, @code{lgammal}, @code{llrint}, @code{llrintf}, @code{llrintl},
757 @code{llround}, @code{llroundf}, @code{llroundl}, @code{log}, @code{log10},
758 @code{log10f}, @code{log10l}, @code{log1p}, @code{log1pf}, @code{log1pl},
759 @code{log2}, @code{log2f}, @code{log2l}, @code{logb}, @code{logbf},
760 @code{logbl}, @code{logf}, @code{logl}, @code{lrint}, @code{lrintf},
761 @code{lrintl}, @code{lround}, @code{lroundf}, @code{lroundl}, @code{modf},
762 @code{modff}, @code{modfl}, @code{nan}, @code{nanf}, @code{nanl},
763 @code{nearbyint}, @code{nearbyintf}, @code{nearbyintl}, @code{nextafter},
764 @code{nextafterf}, @code{nextafterl}, @code{nexttoward}, @code{nexttowardf},
765 @code{nexttowardl}, @code{pow}, @code{powf}, @code{powl}, @code{remainder},
766 @code{remainderf}, @code{remainderl}, @code{remquo}, @code{remquof},
767 @code{remquol}, @code{rint}, @code{rintf}, @code{rintl}, @code{round},
768 @code{roundf}, @code{roundl}, @code{scalbln}, @code{scalblnf}, @code{scalblnl},
769 @code{scalbn}, @code{scalbnf}, @code{scalbnl}, @code{signbit}, @code{sin},
770 @code{sinf}, @code{sinh}, @code{sinhf}, @code{sinhl}, @code{sinl}, @code{sqrt},
771 @code{sqrtf}, @code{sqrtl}, @code{tan}, @code{tanf}, @code{tanh}, @code{tanhf},
772 @code{tanhl}, @code{tanl}, @code{tgamma}, @code{tgammaf}, @code{tgammal},
773 @code{trunc}, @code{truncf}, @code{truncl}
774 may be handled as built-in functions. All these functions have corresponding
775 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
777 In the @code{core.stdc.stdio} module, the functions
778 @code{fprintf}, @code{fputc}, @code{fputc_unlocked}, @code{fputs},
779 @code{fwrite}, @code{printf}, @code{puts}, @code{snprintf}, @code{sprintf},
780 @code{vfprintf}, @code{vprintf}, @code{vsnprintf}, @code{vsprintf}
781 may be handled as built-in functions. All these functions have corresponding
782 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
784 In the @code{core.stdc.stdlib} module, the functions
785 @code{abort}, @code{abs}, @code{aligned_alloc}, @code{alloca}, @code{calloc},
786 @code{exit}, @code{_Exit}, @code{free}, @code{labs}, @code{llabs},
787 @code{malloc}, @code{realloc}
788 may be handled as built-in functions. All these functions have corresponding
789 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
791 In the @code{core.stdc.string} module, the functions
792 @code{memchr}, @code{memcmp}, @code{memcpy}, @code{memmove}, @code{memset},
793 @code{strcat}, @code{strchr}, @code{strcmp}, @code{strcpy}, @code{strcspn},
794 @code{strdup}, @code{strlen}, @code{strncat}, @code{strncmp}, @code{strncpy},
795 @code{strpbrk}, @code{strrchr}, @code{strspn}, @code{strstr}
796 may be handled as built-in functions. All these functions have corresponding
797 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
799 In the @code{core.stdc.time} module, the function @code{strftime} may be
800 handled as a built-in function. All these functions have corresponding
801 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
803 In the @code{core.stdc.wctype} module, the functions
804 @code{iswalnum}, @code{iswalpha}, @code{iswblank}, @code{iswcntrl},
805 @code{iswdigit}, @code{iswgraph}, @code{iswlower}, @code{iswprint},
806 @code{iswpunct}, @code{iswspace}, @code{iswupper}, @code{iswxdigit},
807 @code{towlower}, @code{towupper}
808 may be handled as built-in functions. All these functions have corresponding
809 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
811 Within the @code{core.sys} package for POSIX and platform definitions, the
813 @code{putchar_unlocked}, @code{putc_unlocked}, @code{posix_memalign},
814 @code{ffs}, @code{strcasecmp}, @code{strncasecmp}, @code{stpcpy},
815 @code{stpncpy}, @code{strndup}, @code{strnlen}, @code{execl}, @code{execle},
816 @code{execlp}, @code{execv}, @code{execve}, @code{execvp}, @code{_exit},
818 may be handled as built-in functions. All these functions have corresponding
819 versions prefixed with @code{__builtin_} in the @code{gcc.builtins} module.
822 @c --------------------------------------------------------
825 @section Importing C Sources into D
828 ImportC is a C preprocessor and parser embedded into the GNU D implementation.
829 It enables direct importation of C files, without needing to manually prepare a
830 D file corresponding to the declarations in the C file.
832 ImportC is an implementation of ISO/IEC 9899:2011, which will be referred to as
833 C11. Prior versions, such as C99, C89, and K+R C, are not supported.
835 Assuming you have no file @file{cstdio.c} or @file{main.d}, the commands
837 cat > cstdio.c << @@EOC
838 int printf(const char*, ...);
840 cat > main.d << @@EOD
842 void main() @{ printf("Hello ImportC\n"); @}
844 gdc main.d -o main; ./main
846 will generate a program which will print @samp{Hello ImportC}.
848 ImportC does not have a preprocessor. It is designed to compile C files after
849 they have been first run through the C preprocessor. If the C file has a
850 @samp{.i} extension, the file is presumed to be already preprocessed.
851 Preprocessing can be run manually:
853 gcc -E file.c > file.i
857 ImportC collects all the @code{#define} macros from the preprocessor run when
858 it is run automatically. The macros that look like manifest constants, such as:
860 #define COLOR 0x123456
862 are interpreted as D manifest constant declarations of the form:
864 enum COLOR = 0x123456;
868 The variety of macros that can be interpreted as D declarations may be
869 expanded, but will never encompass all the metaprogramming uses of C macros.
871 GNU D does not directly compile C files into modules that can be linked in with
872 D code to form an executable. When given a source file with the suffix
873 @samp{.c}, the compiler driver program @command{gdc} instead runs the
874 subprogram @command{cc1}.
877 gdc file1.d file2.c // d21 file1.d -o file1.s
878 // cc1 file2.c -o file2.s
879 // as file1.s -o file1.o
880 // as file2.s -o file2.o
881 // ld file1.o file2.o
885 @c --------------------------------------------------------
887 @node Inline Assembly
888 @section Inline Assembly
889 @cindex assembly language in D
891 The @code{asm} keyword allows you to embed assembler instructions within D
892 code. GNU D provides two forms of inline @code{asm} statements. A @dfn{basic
893 @code{asm}} statement is one with no operands, while an @dfn{extended
894 @code{asm}} statement includes one or more operands.
897 asm @var{FunctionAttributes} @{
898 @var{AssemblerInstruction} ;
901 asm @var{FunctionAttributes} @{
902 @var{AssemblerTemplate}
903 : @var{OutputOperands}
904 @r{[} : @var{InputOperands}
905 @r{[} : @var{Clobbers}
906 @r{[} : @var{GotoLabels} @r{]} @r{]} @r{]} ;
911 The extended form is preferred for mixing D and assembly language within a
912 function, but to include assembly language in a function declared with the
913 @code{naked} attribute you must use basic @code{asm}.
916 uint incr (uint value)
928 Multiple assembler instructions can appear within an @code{asm} block, or the
929 instruction template can be a multi-line or concatenated string. In both
930 cases, GCC's optimizers won't discard or move any instruction within the
936 asm nothrow @@nogc @{
939 "xorl %0, (%%esp)" :: "i" (0x00200000);
942 "popl %0" : "=a" (flags);
943 "xorl (%%esp), %0" : "=a" (flags);
946 return (flags & 0x0020_0000) != 0;
951 The instruction templates for both basic and extended @code{asm} can be any
952 expression that can be evaluated at compile-time to a string, not just string
959 asm @@safe @@nogc nothrow pure @{
961 : [res] `=r` (result)
970 The total number of input + output + goto operands is limited to 30.
973 @c --------------------------------------------------------
979 The D language specification itself does not define any intrinsics that a
980 compatible compiler must implement. Rather, within the D core library there
981 are a number of modules that define primitives with generic implementations.
982 While the generic versions of these functions are computationally expensive
983 relative to the cost of the operation itself, compiler implementations are free
984 to recognize them and generate equivalent and faster code.
986 The following are the kinds of intrinsics recognized by GNU D.
989 * Bit Operation Intrinsics::
990 * Integer Overflow Intrinsics::
992 * Variadic Intrinsics::
993 * Volatile Intrinsics::
997 @c --------------------------------------------------------
999 @node Bit Operation Intrinsics
1000 @subsection Bit Operation Intrinsics
1001 @cindex intrinsics, bitop
1003 The following functions are a collection of intrinsics that do bit-level
1004 operations, available by importing the @code{core.bitop} module.
1006 Although most are named after x86 hardware instructions, it is not guaranteed
1007 that they will result in generating equivalent assembly on x86. If the
1008 compiler determines there is a better way to get the same result in hardware,
1009 then that will be used instead.
1011 @deftypefn {Function} {int} core.bitop.bsf (uint @var{v})
1012 @deftypefnx {Function} {int} core.bitop.bsf (ulong @var{v})
1014 Scans the bits in @var{v} starting with bit @code{0}, looking for the first set
1015 bit. Returns the bit number of the first bit set. The return value is
1016 undefined if @var{v} is zero.
1018 This intrinsic is the same as the GCC built-in function @code{__builtin_ctz}.
1021 @deftypefn {Function} {int} core.bitop.bsr (uint @var{v})
1022 @deftypefnx {Function} {int} core.bitop.bsr (ulong @var{v})
1024 Scans the bits in @var{v} from the most significant bit to the least
1025 significant bit, looking for the first set bit. Returns the bit number of the
1026 first bit set. The return value is undefined if @var{v} is zero.
1028 This intrinsic is equivalent to writing the following:
1030 result = __builtin_clz(v) ^ (v.sizeof * 8 - 1)
1034 @deftypefn {Function} {int} core.bitop.bt (scope const(uint*) @var{p}, uint @var{bitnum})
1035 @deftypefnx {Function} {int} core.bitop.bt (scope const(uint*) @var{p}, uint @var{bitnum})
1037 Tests the bit @var{bitnum} in the input parameter @var{p}. Returns a non-zero
1038 value if the bit was set, and a zero if it was clear.
1040 This intrinsic is equivalent to writing the following:
1042 immutable bits_per_unit = (*p).sizeof * 8;
1043 immutable bit_mask = size_t(1) << (bitnum % bits_per_unit);
1045 result = (p[bitnum / bits_per_unit] & bit_mask) != 0;
1049 @deftypefn {Function} {int} core.bitop.btc (uint* @var{p}, uint @var{bitnum})
1050 @deftypefnx {Function} {int} core.bitop.btc (ulong* @var{p}, ulong @var{bitnum})
1052 Tests and complements the bit @var{bitnum} in the input parameter @var{p}.
1053 Returns a non-zero value if the bit was set, and a zero if it was clear.
1055 This intrinsic is equivalent to writing the following:
1057 immutable bits_per_unit = (*p).sizeof * 8;
1058 immutable bit_mask = size_t(1) << (bitnum % bits_per_unit);
1060 result = (p[bitnum / bits_per_unit] & bit_mask) != 0;
1062 p[bitnum / bits_per_unit] ^= bit_mask;
1066 @deftypefn {Function} {int} core.bitop.btr (uint* @var{p}, uint @var{bitnum})
1067 @deftypefnx {Function} {int} core.bitop.btr (ulong* @var{p}, ulong @var{bitnum})
1069 Tests and resets (sets to 0) the bit @var{bitnum} in the input parameter
1070 @var{p}. Returns a non-zero value if the bit was set, and a zero if it was
1073 This intrinsic is equivalent to writing the following:
1075 immutable bits_per_unit = (*p).sizeof * 8;
1076 immutable bit_mask = size_t(1) << (bitnum % bits_per_unit);
1078 result = (p[bitnum / bits_per_unit] & bit_mask) != 0;
1080 p[bitnum / bits_per_unit] &= ~bit_mask;
1084 @deftypefn {Function} {int} core.bitop.bts (uint* @var{p}, uint @var{bitnum})
1085 @deftypefnx {Function} {int} core.bitop.bts (ulong* @var{p}, ulong @var{bitnum})
1087 Tests and sets the bit @var{bitnum} in the input parameter @var{p}. Returns a
1088 non-zero value if the bit was set, and a zero if it was clear.
1090 This intrinsic is equivalent to writing the following:
1092 immutable bits_per_unit = (*p).sizeof * 8;
1093 immutable bit_mask = size_t(1) << (bitnum % bits_per_unit);
1095 result = (p[bitnum / bits_per_unit] & bit_mask) != 0;
1097 p[bitnum / bits_per_unit] |= bit_mask;
1102 @deftypefn {Function} {ushort} core.bitop.byteswap (ushort @var{x})
1103 @deftypefnx {Function} {uint} core.bitop.bswap (uint @var{x})
1104 @deftypefnx {Function} {ulong} core.bitop.bswap (ulong @var{x})
1106 Swaps the bytes in @var{x} end-to-end; for example, in a 4-byte @code{uint},
1107 byte @code{0} becomes byte @code{3}, byte @code{1} becomes byte @code{2}, etc.
1109 This intrinsic is the same as the GCC built-in function @code{__builtin_bswap}.
1112 @deftypefn {Function} {int} core.bitop.popcnt (uint @var{x})
1113 @deftypefnx {Function} {int} core.bitop.popcnt (ulong @var{x})
1115 Calculates the number of set bits in @var{x}.
1117 This intrinsic is the same as the GCC built-in function
1118 @code{__builtin_popcount}.
1121 @deftypefn {Template} {T} core.bitop.rol (T)(const T @var{value}, const uint @var{count})
1122 @deftypefnx {Template} {T} core.bitop.rol (uint @var{count}, T)(const T @var{value})
1124 Bitwise rotate @var{value} left by @var{count} bit positions.
1126 This intrinsic is equivalent to writing the following:
1128 result = cast(T) ((value << count) | (value >> (T.sizeof * 8 - count)));
1132 @deftypefn {Template} {T} core.bitop.ror (T)(const T @var{value}, const uint @var{count})
1133 @deftypefnx {Template} {T} core.bitop.ror (uint @var{count}, T)(const T @var{value})
1135 Bitwise rotate @var{value} right by @var{count} bit positions.
1137 This intrinsic is equivalent to writing the following:
1139 result = cast(T) ((value >> count) | (value << (T.sizeof * 8 - count)));
1143 @c --------------------------------------------------------
1145 @node Integer Overflow Intrinsics
1146 @subsection Integer Overflow Intrinsics
1147 @cindex intrinsics, checkedint
1149 The following functions are a collection of intrinsics that implement integral
1150 arithmetic primitives that check for out-of-range results, available by
1151 importing the @code{core.checkedint} module.
1153 In all intrinsics, the overflow is sticky, meaning a sequence of operations can
1154 be done and overflow need only be checked at the end.
1156 @deftypefn {Function} {int} core.checkedint.adds (int @var{x}, int @var{y}, @
1157 ref bool @var{overflow})
1158 @deftypefnx {Function} {long} core.checkedint.adds (long @var{x}, long @var{y}, @
1159 ref bool @var{overflow})
1161 Add two signed integers, checking for overflow.
1163 This intrinsic is the same as the GCC built-in function
1164 @code{__builtin_sadd_overflow}.
1167 @deftypefn {Function} {int} core.checkedint.addu (int @var{x}, int @var{y}, @
1168 ref bool @var{overflow})
1169 @deftypefnx {Function} {long} core.checkedint.addu (long @var{x}, long @var{y}, @
1170 ref bool @var{overflow})
1172 Add two unsigned integers, checking for overflow.
1174 This intrinsic is the same as the GCC built-in function
1175 @code{__builtin_uadd_overflow}.
1178 @deftypefn {Function} {int} core.checkedint.muls (int @var{x}, int @var{y}, @
1179 ref bool @var{overflow})
1180 @deftypefnx {Function} {long} core.checkedint.muls (long @var{x}, long @var{y}, @
1181 ref bool @var{overflow})
1183 Multiply two signed integers, checking for overflow.
1185 This intrinsic is the same as the GCC built-in function
1186 @code{__builtin_smul_overflow}.
1189 @deftypefn {Function} {int} core.checkedint.mulu (int @var{x}, int @var{y}, @
1190 ref bool @var{overflow})
1191 @deftypefnx {Function} {long} core.checkedint.mulu (long @var{x}, long @var{y}, @
1192 ref bool @var{overflow})
1194 Multiply two unsigned integers, checking for overflow.
1196 This intrinsic is the same as the GCC built-in function
1197 @code{__builtin_umul_overflow}.
1200 @deftypefn {Function} {int} core.checkedint.negs (int @var{x}, @
1201 ref bool @var{overflow})
1202 @deftypefnx {Function} {long} core.checkedint.negs (long @var{x}, @
1203 ref bool @var{overflow})
1207 This intrinsic is equivalent to writing the following:
1209 result = __builtin_ssub (0, x, overflow);
1213 @deftypefn {Function} {int} core.checkedint.subs (int @var{x}, int @var{y}, @
1214 ref bool @var{overflow})
1215 @deftypefnx {Function} {long} core.checkedint.subs (long @var{x}, long @var{y}, @
1216 ref bool @var{overflow})
1218 Substract two signed integers, checking for overflow.
1220 This intrinsic is the same as the GCC built-in function
1221 @code{__builtin_ssub_overflow}.
1224 @deftypefn {Function} {int} core.checkedint.subu (int @var{x}, int @var{y}, @
1225 ref bool @var{overflow})
1226 @deftypefnx {Function} {long} core.checkedint.subu (long @var{x}, long @var{y}, @
1227 ref bool @var{overflow})
1229 Substract two unsigned integers, checking for overflow.
1231 This intrinsic is the same as the GCC built-in function
1232 @code{__builtin_usub_overflow}.
1235 @c --------------------------------------------------------
1237 @node Math Intrinsics
1238 @subsection Math Intrinsics
1239 @cindex intrinsics, math
1241 The following functions are a collection of mathematical intrinsics, available
1242 by importing the @code{core.math} module.
1244 @deftypefn {Function} {float} core.math.cos (float x)
1245 @deftypefnx {Function} {double} core.math.cos (double x)
1246 @deftypefnx {Function} {real} core.math.cos (real x)
1248 Returns cosine of @var{x}, where @var{x} is in radians. The return value is
1249 undefined if @var{x} is greater than @math{2^{64}}.
1251 This intrinsic is the same as the GCC built-in function @code{__builtin_cos}.
1254 @deftypefn {Function} {float} core.math.fabs (float x)
1255 @deftypefnx {Function} {double} core.math.fabs (double x)
1256 @deftypefnx {Function} {real} core.math.fabs (real x)
1258 Compute the absolute value of @var{x}.
1260 This intrinsic is the same as the GCC built-in function @code{__builtin_fabs}.
1263 @deftypefn {Function} {float} core.math.ldexp (float n, int exp)
1264 @deftypefnx {Function} {double} core.math.ldexp (double n, int exp)
1265 @deftypefnx {Function} {real} core.math.ldexp (real n, int exp)
1267 Compute @math{n * 2^{exp}}.
1269 This intrinsic is the same as the GCC built-in function @code{__builtin_ldexp}.
1272 @deftypefn {Function} {float} core.math.rint (float x)
1273 @deftypefnx {Function} {double} core.math.rint (double x)
1274 @deftypefnx {Function} {real} core.math.rint (real x)
1276 Rounds @var{x} to the nearest integer value, using the current rounding mode.
1277 If the return value is not equal to @var{x}, the @code{FE_INEXACT} exception is
1278 raised. @code{nearbyint} performs the same operation, but does not set the
1279 @code{FE_INEXACT} exception.
1281 This intrinsic is the same as the GCC built-in function @code{__builtin_rint}.
1284 @deftypefn {Function} {float} core.math.rndtol (float x)
1285 @deftypefnx {Function} {double} core.math.rndtol (double x)
1286 @deftypefnx {Function} {real} core.math.rndtol (real x)
1288 Returns @var{x} rounded to a long value using the current rounding mode.
1289 If the integer value of @var{x} is greater than @code{long.max}, the result
1292 This intrinsic is the same as the GCC built-in function
1293 @code{__builtin_llround}.
1296 @deftypefn {Function} {float} core.math.sin (float x)
1297 @deftypefnx {Function} {double} core.math.sin (double x)
1298 @deftypefnx {Function} {real} core.math.sin (real x)
1300 Returns sine of @var{x}, where @var{x} is in radians. The return value is
1301 undefined if @var{x} is greater than @math{2^{64}}.
1303 This intrinsic is the same as the GCC built-in function @code{__builtin_sin}.
1306 @deftypefn {Function} {float} core.math.sqrt (float x)
1307 @deftypefnx {Function} {double} core.math.sqrt (double x)
1308 @deftypefnx {Function} {real} core.math.sqrt (real x)
1310 Compute the sqrt of @var{x}.
1312 This intrinsic is the same as the GCC built-in function @code{__builtin_sqrt}.
1315 @deftypefn {Template} {T} core.math.toPrec (T)(float f)
1316 @deftypefnx {Template} {T} core.math.toPrec (T)(double f)
1317 @deftypefnx {Template} {T} core.math.toPrec (T)(real f)
1319 Round @var{f} to a specific precision.
1321 In floating-point operations, D language types specify only a minimum
1322 precision, not a maximum. The @code{toPrec} function forces rounding of the
1323 argument @var{f} to the precision of the specified floating point type
1324 @code{T}. The rounding mode used is inevitably target-dependent, but will be
1325 done in a way to maximize accuracy. In most cases, the default is
1329 @c --------------------------------------------------------
1331 @node Variadic Intrinsics
1332 @subsection Variadic Intrinsics
1333 @cindex intrinsics, stdarg
1335 The following functions are a collection of variadic intrinsics, available by
1336 importing the @code{core.stdc.stdarg} module.
1338 @deftypefn {Template} {void} core.stdc.stdarg.va_arg (T)(ref va_list ap, ref T parmn)
1340 Retrieve and store in @var{parmn} the next value from the @code{va_list}
1341 @var{ap} that is of type @code{T}.
1343 This intrinsic is equivalent to writing the following:
1345 parmn = __builtin_va_arg (ap, T);
1349 @deftypefn {Template} {T} core.stdc.stdarg.va_arg (T)(ref va_list ap)
1351 Retrieve and return the next value from the @code{va_list} @var{ap} that is of
1354 This intrinsic is equivalent to writing the following:
1356 result = __builtin_va_arg (ap, T);
1360 @deftypefn {Function} {void} core.stdc.stdarg.va_copy (out va_list dest, va_list src)
1362 Make a copy of @var{src} in its current state and store to @var{dest}.
1364 This intrinsic is the same as the GCC built-in function @code{__builtin_va_copy}.
1367 @deftypefn {Function} {void} core.stdc.stdarg.va_end (va_list ap)
1369 Destroy @var{ap} so that it is no longer useable.
1371 This intrinsic is the same as the GCC built-in function @code{__builtin_va_end}.
1374 @deftypefn {Template} {void} core.stdc.stdarg.va_start (T)(out va_list ap, ref T parmn)
1376 Initialize @var{ap} so that it can be used to access the variable arguments
1377 that follow the named argument @var{parmn}.
1379 This intrinsic is the same as the GCC built-in function @code{__builtin_va_start}.
1382 @c --------------------------------------------------------
1384 @node Volatile Intrinsics
1385 @subsection Volatile Intrinsics
1386 @cindex intrinsics, volatile
1388 The following functions are a collection of intrinsics for volatile operations,
1389 available by importing the @code{core.volatile} module.
1391 Calls to them are guaranteed to not be removed (as dead assignment elimination
1392 or presumed to have no effect) or reordered in the same thread.
1394 These reordering guarantees are only made with regards to other operations done
1395 through these functions; the compiler is free to reorder regular loads/stores
1396 with regards to loads/stores done through these functions.
1398 This is useful when dealing with memory-mapped I/O (MMIO) where a store can
1399 have an effect other than just writing a value, or where sequential loads with
1400 no intervening stores can retrieve different values from the same location due
1401 to external stores to the location.
1403 These functions will, when possible, do the load/store as a single operation.
1404 In general, this is possible when the size of the operation is less than or
1405 equal to @code{(void*).sizeof}, although some targets may support larger
1406 operations. If the load/store cannot be done as a single operation, multiple
1407 smaller operations will be used.
1409 These are not to be conflated with atomic operations. They do not guarantee
1410 any atomicity. This may be provided by coincidence as a result of the
1411 instructions used on the target, but this should not be relied on for portable
1412 programs. Further, no memory fences are implied by these functions. They
1413 should not be used for communication between threads. They may be used to
1414 guarantee a write or read cycle occurs at a specified address.
1416 @deftypefn {Function} {ubyte} core.volatile.volatileLoad (ubyte* ptr)
1417 @deftypefnx {Function} {ushort} core.volatile.volatileLoad (ushort* ptr)
1418 @deftypefnx {Function} {uint} core.volatile.volatileLoad (uint* ptr)
1419 @deftypefnx {Function} {ulong} core.volatile.volatileLoad (ulong* ptr)
1421 Read value from the memory location indicated by @var{ptr}.
1424 @deftypefn {Function} {ubyte} core.volatile.volatileStore (ubyte* ptr, ubyte value)
1425 @deftypefnx {Function} {ushort} core.volatile.volatileStore (ushort* ptr, ushort value)
1426 @deftypefnx {Function} {uint} core.volatile.volatileStore (uint* ptr, uint value)
1427 @deftypefnx {Function} {ulong} core.volatile.volatileStore (ulong* ptr, ulong value)
1429 Write @var{value} to the memory location indicated by @var{ptr}.
1432 @c --------------------------------------------------------
1434 @node CTFE Intrinsics
1435 @subsection CTFE Intrinsics
1436 @cindex intrinsics, ctfe
1438 The following functions are only treated as intrinsics during compile-time
1439 function execution (CTFE) phase of compilation to allow more functions to be
1440 computable at compile-time, either because their generic implementations are
1441 too complex, or do some low-level bit manipulation of floating point types.
1443 Calls to these functions that exist after CTFE has finished will get standard
1444 code-generation without any special compiler intrinsic suppport.
1446 @deftypefn {Function} {float} std.math.exponential.exp (float x)
1447 @deftypefnx {Function} {double} std.math.exponential.exp (double x)
1448 @deftypefnx {Function} {real} std.math.exponential.exp (real x)
1450 Calculates @math{e^x}.
1452 This function is evaluated during CTFE as the GCC built-in function
1453 @code{__builtin_exp}.
1456 @deftypefn {Function} {float} std.math.exponential.expm1 (float x)
1457 @deftypefnx {Function} {double} std.math.exponential.expm1 (double x)
1458 @deftypefnx {Function} {real} std.math.exponential.expm1 (real x)
1460 Calculates @math{e^x-1.0}.
1462 This function is evaluated during CTFE as the GCC built-in function
1463 @code{__builtin_expm1}.
1466 @deftypefn {Function} {float} std.math.exponential.exp2 (float x)
1467 @deftypefnx {Function} {double} std.math.exponential.exp2 (double x)
1468 @deftypefnx {Function} {real} std.math.exponential.exp2 (real x)
1470 Calculates @math{2^x}.
1472 This function is evaluated during CTFE as the GCC built-in function
1473 @code{__builtin_exp2}.
1476 @deftypefn {Function} {float} std.math.exponential.log (float x)
1477 @deftypefnx {Function} {double} std.math.exponential.log (double x)
1478 @deftypefnx {Function} {real} std.math.exponential.log (real x)
1480 Calculate the natural logarithm of @var{x}.
1482 This function is evaluated during CTFE as the GCC built-in function
1483 @code{__builtin_log}.
1486 @deftypefn {Function} {float} std.math.exponential.log10 (float x)
1487 @deftypefnx {Function} {double} std.math.exponential.log10 (double x)
1488 @deftypefnx {Function} {real} std.math.exponential.log10 (real x)
1490 Calculates the base-10 logarithm of @var{x}.
1492 This function is evaluated during CTFE as the GCC built-in function
1493 @code{__builtin_log10}.
1496 @deftypefn {Function} {float} std.math.exponential.log2 (float x)
1497 @deftypefnx {Function} {double} std.math.exponential.log2 (double x)
1498 @deftypefnx {Function} {real} std.math.exponential.log2 (real x)
1500 Calculates the base-2 logarithm of @var{x}.
1502 This function is evaluated during CTFE as the GCC built-in function
1503 @code{__builtin_log2}.
1506 @deftypefn {Template} {Largest!(F, G)} std.math.exponential.pow (F, G) (F x, G y)
1507 @deftypefnx {Template} {real} std.math.exponential.pow (I, F)(I x, F y)
1509 Calculates @math{x^y}, where @var{y} is a float.
1511 This function is evaluated during CTFE as the GCC built-in function
1512 @code{__builtin_pow}.
1515 @deftypefn {Template} {F} std.math.exponential.pow (F, G) (F x, G n)
1517 Calculates @math{x^n}, where @var{n} is an integer.
1519 This function is evaluated during CTFE as the GCC built-in function
1520 @code{__builtin_powi}.
1523 @deftypefn {Function} {real} std.math.operations.fma (real x, real y, real z)
1525 Returns @code{(x * y) + z}, rounding only once according to the current
1528 This function is evaluated during CTFE as the GCC built-in function
1529 @code{__builtin_fma}.
1532 @deftypefn {Template} {F} std.math.operations.fmax (F)(const F x, const F y)
1534 Returns the larger of @var{x} and @var{y}.
1536 This function is evaluated during CTFE as the GCC built-in function
1537 @code{__builtin_fmax}.
1540 @deftypefn {Template} {F} std.math.operations.fmin (F)(const F x, const F y)
1542 Returns the smaller of @var{x} and @var{y}.
1544 This function is evaluated during CTFE as the GCC built-in function
1545 @code{__builtin_fmin}.
1548 @deftypefn {Function} {float} std.math.rounding.ceil (float x)
1549 @deftypefnx {Function} {double} std.math.rounding.ceil (double x)
1550 @deftypefnx {Function} {real} std.math.rounding.ceil (real x)
1552 Returns the value of @var{x} rounded upward to the next integer (toward
1555 This function is evaluated during CTFE as the GCC built-in function
1556 @code{__builtin_ceil}.
1559 @deftypefn {Function} {float} std.math.rounding.floor (float x)
1560 @deftypefnx {Function} {double} std.math.rounding.floor (double x)
1561 @deftypefnx {Function} {real} std.math.rounding.floor (real x)
1563 Returns the value of @var{x} rounded downward to the next integer (toward
1566 This function is evaluated during CTFE as the GCC built-in function
1567 @code{__builtin_floor}.
1570 @deftypefn {Function} {real} std.math.rounding.round (real x)
1572 Return the value of @var{x} rounded to the nearest integer. If the fractional
1573 part of @var{x} is exactly 0.5, the return value is rounded away from zero.
1575 This function is evaluated during CTFE as the GCC built-in function
1576 @code{__builtin_round}.
1579 @deftypefn {Function} {real} std.math.rounding.trunc (real x)
1581 Returns the integer portion of @var{x}, dropping the fractional portion.
1583 This function is evaluated during CTFE as the GCC built-in function
1584 @code{__builtin_trunc}.
1587 @deftypefn {Template} {R} std.math.traits.copysign (R, X)(R to, X from)
1589 Returns a value composed of @var{to} with @var{from}'s sign bit.
1591 This function is evaluated during CTFE as the GCC built-in function
1592 @code{__builtin_copysign}.
1595 @deftypefn {Template} {bool} std.math.traits.isFinite (X)(X x)
1597 Returns true if @var{x} is finite.
1599 This function is evaluated during CTFE as the GCC built-in function
1600 @code{__builtin_isfinite}.
1603 @deftypefn {Template} {bool} std.math.traits.isInfinity (X)(X x)
1605 Returns true if @var{x} is infinite.
1607 This function is evaluated during CTFE as the GCC built-in function
1608 @code{__builtin_isinf}.
1611 @deftypefn {Template} {bool} std.math.traits.isNaN (X)(X x)
1613 Returns true if @var{x} is NaN.
1615 This function is evaluated during CTFE as the GCC built-in function
1616 @code{__builtin_isnan}.
1619 @deftypefn {Function} {float} std.math.trigoometry.tan (float x)
1620 @deftypefnx {Function} {double} std.math.trigoometry.tan (double x)
1621 @deftypefnx {Function} {real} std.math.trigonometry.tan (real x)
1623 Returns tangent of @var{x}, where @var{x} is in radians.
1625 This intrinsic is the same as the GCC built-in function @code{__builtin_tan}.
1629 @c --------------------------------------------------------
1631 @node Predefined Pragmas
1632 @section Predefined Pragmas
1633 @cindex predefined pragmas
1634 @cindex @code{pragma}
1636 The @code{@w{pragma}} operator is used as a way to pass special information to the
1637 implementation and allow the addition of vendor specific extensions. The
1638 standard predefined pragmas are documented by the D language specification
1639 hosted at @uref{https://dlang.org/spec/pragma.html#predefined-pragmas}. A D
1640 compiler must recognize, but is free to ignore any pragma in this list.
1642 Where a pragma is ignored, the GNU D compiler will emit a warning when the
1643 @option{-Wunknown-pragmas} option is seen on the command-line.
1646 @item pragma(crt_constructor)
1647 @code{pragma(crt_constructor)} annotates a function so it is run after the C
1648 runtime library is initialized and before the D runtime library is initialized.
1649 Functions with this pragma must return @code{void}.
1651 pragma(crt_constructor) void init() @{ @}
1654 @item pragma(crt_destructor)
1655 @code{pragma(crt_destructor)} annotates a function so it is run after the D
1656 runtime library is terminated and before the C runtime library is terminated.
1657 Calling @code{exit} function also causes the annotated functions to run.
1658 Functions with this pragma must return @code{void}.
1660 pragma(crt_destructor) void init() @{ @}
1663 @item pragma(inline)
1664 @itemx pragma(inline, false)
1665 @itemx pragma(inline, true)
1666 @code{pragma(inline)} affects whether functions are declared inlined or not.
1667 The pragma takes two forms. In the first form, inlining is controlled by the
1668 command-line options for inlining.
1670 Functions annotated with @code{pragma(inline, false)} are marked uninlinable.
1671 Functions annotated with @code{pragma(inline, true)} are always inlined.
1674 This pragma is accepted, but has no effect.
1676 pragma(lib, "advapi32");
1679 @item pragma(linkerDirective)
1680 This pragma is accepted, but has no effect.
1682 pragma(linkerDirective, "/FAILIFMISMATCH:_ITERATOR_DEBUG_LEVEL=2");
1685 @item pragma(mangle)
1686 @code{pragma(mangle, "symbol_name")} overrides the default mangling for a
1687 function or variable symbol. The symbol name can be any expression that must
1688 evaluate at compile time to a string literal. This enables linking to a symbol
1689 which is a D keyword, since an identifier cannot be a keyword.
1691 Targets are free to apply a prefix to the user label of the symbol name in
1692 assembly. For example, on @code{x86_64-apple-darwin}, @samp{symbol_name} would
1693 produce @samp{_symbol_name}. If the mangle string begins with @samp{*}, then
1694 @code{pragma(mangle)} will output the rest of the string unchanged.
1697 pragma(mangle, "body")
1698 extern(C) void body_func();
1700 pragma(mangle, "function")
1701 extern(C++) struct _function @{@}
1705 @code{pragma(msg, "message")} causes the compiler to print an informational
1706 message with the text @samp{message}. The pragma accepts multiple arguments,
1707 each to which is evaluated at compile time and then all are combined into one
1708 concatenated message.
1710 pragma(msg, "compiling...", 6, 1.0); // prints "compiling...61.0"
1713 @item pragma(printf)
1714 @itemx pragma(scanf)
1716 @code{pragma(printf)} and @code{pragma(scanf)} specifies that a function
1717 declaration with @code{printf} or @code{scanf} style arguments that should be
1718 type-checked against a format string.
1720 A printf-like or scanf-like function can either be an @code{extern(C)} or
1721 @code{extern(C++)} function with a @var{format} parameter accepting a pointer
1722 to a 0-terminated @code{char} string, immediately followed by either a
1723 @code{...} variadic argument list or a parameter of type @code{va_list} as the
1729 int printf(scope const char* format, scope const ...);
1732 int vscanf(scope const char* format, va_list arg);
1735 @item pragma(startaddress)
1736 This pragma is accepted, but has no effect.
1739 pragma(startaddress, foo);
1745 @c --------------------------------------------------------
1747 @node Predefined Versions
1748 @section Predefined Versions
1749 @cindex predefined versions
1750 @cindex @code{version}
1752 Several conditional version identifiers are predefined; you use them without
1753 supplying their definitions. They fall into three classes: standard, common,
1754 and target-specific.
1756 Predefined version identifiers from this list cannot be set from the command
1757 line or from version statements. This prevents things like both @code{Windows}
1758 and @code{linux} being simultaneously set.
1761 * Standard Predefined Versions::
1762 * Common Predefined Versions::
1763 * Target Predefined Versions::
1766 @c --------------------------------------------------------
1768 @node Standard Predefined Versions
1769 @subsection Standard Predefined Versions
1770 @cindex standard predefined versions
1772 The standard predefined versions are documented by the D language specification
1773 hosted at @uref{https://dlang.org/spec/version.html#predefined-versions}.
1778 Version @code{none} is never defined; used to just disable a section of code.
1779 Version @code{all} is always defined; used as the opposite of @code{none}.
1783 These versions reflect the byte order of multi-byte data in memory.
1784 @code{LittleEndian} is set when the least significant byte is first.
1785 @code{BigEndian} is set when the most significant byte is first.
1787 @item CRuntime_Bionic
1788 @itemx CRuntime_Glibc
1789 @itemx CRuntime_Microsoft
1790 @itemx CRuntime_Musl
1791 @itemx CRuntime_Newlib
1792 @itemx CRuntime_UClibc
1794 These versions reflect which standard C library is being linked in.
1795 @code{CRuntime_Bionic} is set when Bionic is the default C library.
1796 @code{CRuntime_Glibc} is set when GLIBC is the default C library.
1797 @code{CRuntime_Microsoft} is set when MSVCRT is the default C library.
1798 @code{CRuntime_Musl} is set when musl is the default C library.
1799 @code{CRuntime_Newlib} is set when Newlib is the default C library.
1800 @code{CRuntime_UClibc} is set when uClibc is the default C library.
1802 @item CppRuntime_Gcc
1803 This version is defined when the standard C++ library being linked in is @file{libstdc++}.
1806 This version is defined when the standard D libraries are not being implicitly
1807 linked in. This also implies that features of the D language that rely on
1808 exceptions, module information, or run-time type information are disabled as
1809 well. Enabled by @option{-fno-druntime}.
1812 This version is defined when code coverage analysis instrumentation is being
1813 generated. Enabled by @option{-ftest-coverage}.
1816 This version is defined when Ddoc documentation is being generated. Enabled by
1820 This version is defined when exception handling is supported. Disabled by
1821 @option{-fno-exceptions}.
1825 These versions reflect the floating-point ABI in use by the target.
1826 @code{D_HardFloat} is set when the target hardware has a floating-point unit.
1827 @code{D_SoftFloat} is set when the target hardware does not have a
1828 floating-point unit.
1831 This version is defined when checks are being emitted for class invariants and
1832 struct invariants. Enabled by @option{-finvariants}.
1835 This version is defined when pointers are 64-bits. Not to be confused with
1836 with C's @code{__LP64__} model.
1839 This version is defined when run-time module information (also known as
1840 @code{ModuleInfo}) is supported. Disabled by @option{-fno-moduleinfo}.
1842 @item D_NoBoundsChecks
1843 This version is defined when array bounds checks are disabled. Enabled by
1844 @option{-fno-bounds-checks}.
1847 This version is defined in all optimizing compilations.
1850 This version is defined when position-independent code is being generated.
1851 Enabled by @option{-fPIC}.
1854 This version is defined when position-independent code that can be only linked
1855 into executables is being generated. Enabled by @option{-fPIE}.
1857 @item D_PreConditions
1858 This version is defined when checks are being emitted for @code{in} contracts.
1859 Disabled by @option{-fno-preconditions}.
1861 @item D_PostConditions
1862 This version is defined when checks are being emitted for @code{out} contracts.
1863 Disabled by @option{-fno-postconditions}.
1866 This version is defined when run-time type information (also known as
1867 @code{TypeInfo}) is supported. Disabled by @option{-fno-rtti}.
1870 This version defined when this is a D version 2 compiler.
1873 This version is defined when the @code{unittest} code is being compiled in.
1874 Enabled by @option{-funittest}.
1878 @c --------------------------------------------------------
1880 @node Common Predefined Versions
1881 @subsection Common Predefined Versions
1882 @cindex common predefined versions
1884 The common predefined macros are GNU D extensions. They are available
1885 with the same meanings regardless of the machine or operating system on
1886 which you are using GNU D. Their names all start with @code{GNU}.
1891 This version is defined by the GNU D compiler. If all you need to know is
1892 whether or not your D program is being compiled by GDC, or a non-GDC compiler,
1893 you can simply test @code{version(GNU)}.
1895 @item GNU_DWARF2_Exceptions
1896 @itemx GNU_SEH_Exceptions
1897 @itemx GNU_SjLj_Exceptions
1898 These versions reflect the mechanism that will be used for exception handling
1899 by the target. @code{GNU_DWARF2_Exceptions} is defined when the target uses
1900 DWARF 2 exceptions. @code{GNU_SEH_Exceptions} is defined when the target uses
1901 SEH exceptions. @code{GNU_SjLj_Exceptions} is defined when the target uses the
1902 @code{setjmp}/@code{longjmp}-based exception handling scheme.
1905 This version is defined if the target does not support thread-local storage,
1906 and an emulation layer is used instead.
1909 This version is defined when @code{asm} statements use GNU D style syntax.
1910 (@pxref{Inline Assembly})
1912 @item GNU_StackGrowsDown
1913 This version is defined if pushing a word onto the stack moves the stack
1914 pointer to a smaller address, and is undefined otherwise.
1918 @c --------------------------------------------------------
1920 @node Target Predefined Versions
1921 @subsection Target-specific Predefined Versions
1922 @cindex target-specific predefined versions
1924 The D compiler normally predefines several versions that indicate what type of
1925 system and machine is in use. They are obviously different on each target
1930 Version relating to the AArch64 family of processors.
1933 Version relating to the Android platform.
1936 @itemx ARM_HardFloat
1937 @itemx ARM_SoftFloat
1940 Versions relating to the ARM family of processors.
1943 Version relating to the Cygwin environment.
1946 Deprecated; use @code{OSX} instead.
1949 Versions relating to DragonFlyBSD systems.
1956 Versions relating to FreeBSD systems. The FreeBSD major version number is
1957 inferred from the target triplet.
1961 Versions relating to the HPPA family of processors.
1964 Version relating to GNU Hurd systems.
1967 Version relating to Linux systems.
1970 Version relating to the MinGW environment.
1975 @itemx MIPS_HardFloat
1980 @itemx MIPS_SoftFloat
1981 Versions relating to the MIPS family of processors.
1984 Version relating to NetBSD systems.
1987 Version relating to OpenBSD systems.
1990 Version relating to OSX systems.
1993 Version relating to POSIX systems (includes Linux, FreeBSD, OSX, Solaris, etc).
1997 @itemx PPC_HardFloat
1998 @itemx PPC_SoftFloat
1999 Versions relating to the PowerPC family of processors.
2003 Versions relating to the RISC-V family of processors.
2007 Versions relating to the S/390 and System Z family of processors.
2010 Deprecated; use @code{SystemZ} instead.
2013 Versions relating to Solaris systems.
2017 @itemx SPARC_HardFloat
2018 @itemx SPARC_SoftFloat
2020 Versions relating to the SPARC family of processors.
2023 Deprecated; use @code{ARM_Thumb} instead.
2028 Versions relating to the x86-32 and x86-64 family of processors.
2033 Versions relating to Microsoft Windows systems.
2038 @c --------------------------------------------------------
2041 @section Special Enums
2042 @cindex special enums
2044 Special @code{enum} names are used to represent types that do not have an
2045 equivalent basic D type. For example, C++ types used by the C++ name mangler.
2047 Special enums are declared opaque, with a base type explicitly set. Unlike
2048 regular opaque enums, special enums can be used as any other value type. They
2049 have a default @code{.init} value, as well as other enum properties available
2050 (@code{.min}, @code{.max}). Special enums can be declared in any module, and
2051 will be recognized by the compiler.
2054 import gcc.builtins;
2055 enum __c_long : __builtin_clong;
2056 __c_long var = 0x800A;
2060 The following identifiers are recognized by GNU D.
2063 @item __c_complex_double
2064 C @code{_Complex double} type.
2065 @item __c_complex_float
2066 C @code{_Complex float} type.
2067 @item __c_complex_real
2068 C @code{_Complex long double} type.
2070 C++ @code{long} type.
2072 C++ @code{long long} type.
2073 @item __c_long_double
2074 C @code{long double} type.
2076 C++ @code{unsigned long} type.
2078 C++ @code{unsigned long long} type.
2080 C++ @code{wchar_t} type.
2083 The @code{core.stdc.config} module declares the following shorthand alias types
2084 for convenience: @code{c_complex_double}, @code{c_complex_float},
2085 @code{c_complex_real}, @code{cpp_long}, @code{cpp_longlong},
2086 @code{c_long_double}, @code{cpp_ulong}, @code{cpp_ulonglong}.
2088 It may cause undefined behavior at runtime if a special enum is declared with a
2089 base type that has a different size to the target C/C++ type it is
2090 representing. The GNU D compiler will catch such declarations and emit a
2091 warning when the @option{-Wmismatched-special-enum} option is seen on the
2094 @c --------------------------------------------------------
2100 Traits are extensions to the D programming language to enable programs, at
2101 compile time, to get at information internal to the compiler. This is also
2102 known as compile time reflection.
2104 GNU D implements a @code{__traits(getTargetInfo)} trait that receives a string
2105 key as its argument. The result is an expression describing the requested
2111 static assert(__traits(getTargetInfo, "objectFormat") == "macho");
2116 Keys for the trait are implementation defined, allowing target-specific data
2117 for exotic targets. A reliable subset exists which a D compiler must
2118 recognize. These are documented by the D language specification hosted at
2119 @uref{https://dlang.org/spec/traits.html#getTargetInfo}.
2121 The following keys are recognized by GNU D.
2124 @item cppRuntimeLibrary
2125 The C++ runtime library affinity for this toolchain.
2128 The version of the C++ standard supported by @code{extern(C++)} code,
2129 equivalent to the @code{__cplusplus} macro in a C++ compiler.
2132 Floating point ABI; may be @samp{hard}, @samp{soft}, or @samp{softfp}.
2135 Target object format.
2140 @c --------------------------------------------------------
2142 @node Vector Extensions
2143 @section Vector Extensions
2144 @cindex vector extensions
2147 CPUs often support specialized vector types and vector operations (aka media
2148 instructions). Vector types are a fixed array of floating or integer types,
2149 and vector operations operate simultaneously on them.
2152 alias int4 = __vector(int[4]);
2156 All the basic integer types can be used as base types, both as signed and as
2157 unsigned: @code{byte}, @code{short}, @code{int}, @code{long}. In addition,
2158 @code{float} and @code{double} can be used to build floating-point vector
2159 types, and @code{void} to build vectors of untyped data. Only sizes that are
2160 positive power-of-two multiples of the base type size are currently allowed.
2163 The @code{core.simd} module has the following shorthand aliases for commonly
2164 supported vector types:
2165 @code{byte8}, @code{byte16}, @code{byte32}, @code{byte64},
2166 @code{double1}, @code{double2}, @code{double4}, @code{double8},
2167 @code{float2}, @code{float4}, @code{float8}, @code{float16},
2168 @code{int2}, @code{int4}, @code{int8}, @code{int16},
2169 @code{long1}, @code{long2}, @code{long4}, @code{long8},
2170 @code{short4}, @code{short8}, @code{short16}, @code{short32},
2171 @code{ubyte8}, @code{ubyte16}, @code{ubyte32}, @code{ubyte64},
2172 @code{uint2}, @code{uint4}, @code{uint8}, @code{uint16},
2173 @code{ulong1}, @code{ulong2}, @code{ulong4}, @code{ulong8},
2174 @code{ushort4}, @code{ushort8}, @code{ushort16}, @code{ushort32},
2175 @code{void8}, @code{void16}, @code{void32}, @code{void64}.
2176 All these aliases correspond to @code{__vector(type[N])}.
2178 Which vector types are supported depends on the target. Only vector types that
2179 are implemented for the current architecture are supported at compile-time.
2180 Vector operations that are not supported in hardware cause GNU D to synthesize
2181 the instructions using a narrower mode.
2184 alias v4i = __vector(int[4]);
2185 alias v128f = __vector(float[128]); // Error: not supported on this platform
2189 c = a * b; // Natively supported on x86 with SSE4
2190 c = a / b; // Always synthesized
2194 Vector types can be used with a subset of normal D operations. Currently, GNU
2195 D allows using the following operators on these types: @code{+, -, *, /,
2199 alias int4 = __vector(int[4]);
2207 It is also possible to use shifting operators @code{<<}, @code{>>}, the modulus
2208 operator @code{%}, logical operations @code{&, |, ^}, and the complement
2209 operator @code{unary~} on integer-type vectors.
2211 For convenience, it is allowed to use a binary vector operation where one
2212 operand is a scalar. In that case the compiler transforms the scalar operand
2213 into a vector where each element is the scalar from the operation. The
2214 transformation happens only if the scalar could be safely converted to the
2215 vector-element type. Consider the following code.
2218 alias int4 = __vector(int[4]);
2223 a = b + 1; // a = b + [1,1,1,1];
2224 a = 2 * b; // a = [2,2,2,2] * b;
2226 a = l + a; // Error, incompatible types.
2230 Vector comparison is supported with standard comparison operators:
2231 @code{==, !=, <, <=, >, >=}. Comparison operands can be vector expressions of
2232 integer-type or real-type. Comparison between integer-type vectors and
2233 real-type vectors are not supported. The result of the comparison is a vector
2234 of the same width and number of elements as the comparison operands with a
2235 signed integral element type.
2237 Vectors are compared element-wise producing 0 when comparison is false
2238 and -1 (constant of the appropriate type where all bits are set)
2239 otherwise. Consider the following example.
2242 alias int4 = __vector(int[4]);
2248 c = a > b; // The result would be [0, 0,-1, 0]
2249 c = a == b; // The result would be [0,-1, 0,-1]
2253 @c --------------------------------------------------------
2255 @node Vector Intrinsics
2256 @section Vector Intrinsics
2257 @cindex intrinsics, vector
2259 The following functions are a collection of vector operation intrinsics,
2260 available by importing the @code{gcc.simd} module.
2262 @deftypefn {Template} {void} gcc.simd.prefetch (bool @var{rw}, @
2263 ubyte @var{locality}) @
2264 (const(void)* @var{addr})
2266 Emit the prefetch instruction. The value of @var{addr} is the address of the
2267 memory to prefetch. The value of @var{rw} is a compile-time constant one or
2268 zero; one means that the prefetch is preparing for a write to the memory
2269 address and zero, the default, means that the prefetch is preparing for a read.
2270 The value @var{locality} must be a compile-time constant integer between zero
2273 This intrinsic is the same as the GCC built-in function
2274 @code{__builtin_prefetch}.
2277 for (i = 0; i < n; i++)
2279 import gcc.simd : prefetch;
2281 prefetch!(true, 1)(&a[i+j]);
2282 prefetch!(false, 1)(&b[i+j]);
2288 @deftypefn {Template} {V} gcc.simd.loadUnaligned (V)(const V* @var{p})
2290 Load unaligned vector from the address @var{p}.
2296 v = loadUnaligned(cast(float4*)arr.ptr);
2300 @deftypefn {Template} {V} gcc.simd.storeUnaligned (V)(V* @var{p}, V @var{value})
2302 Store vector @var{value} to unaligned address @var{p}.
2308 storeUnaligned(cast(float4*)arr.ptr, v);
2312 @deftypefn {Template} {V0} gcc.simd.shuffle (V0, V1, M)(V0 @var{op1}, @
2315 @deftypefnx {Template} {V} gcc.simd.shuffle (V, M)(V @var{op1}, M @var{mask})
2317 Construct a permutation of elements from one or two vectors, returning a vector
2318 of the same type as the input vector(s). The @var{mask} is an integral vector
2319 with the same width and element count as the output vector.
2321 This intrinsic is the same as the GCC built-in function
2322 @code{__builtin_shuffle}.
2325 int4 a = [1, 2, 3, 4];
2326 int4 b = [5, 6, 7, 8];
2327 int4 mask1 = [0, 1, 1, 3];
2328 int4 mask2 = [0, 4, 2, 5];
2331 res = shuffle(a, mask1); // res is [1,2,2,4]
2332 res = shuffle(a, b, mask2); // res is [1,5,3,6]
2336 @deftypefn {Template} {V} gcc.simd.shufflevector (V1, V2, M...)(V1 @var{op1}, @
2337 V2 @var{op2}, M @var{mask})
2338 @deftypefnx {Template} {V} gcc.simd.shufflevector (V, @var{mask}...)(V @
2339 @var{op1}, V @var{op2})
2341 Construct a permutation of elements from two vectors, returning a vector with
2342 the same element type as the input vector(s), and same length as the
2345 This intrinsic is the same as the GCC built-in function
2346 @code{__builtin_shufflevector}.
2349 int8 a = [1, -2, 3, -4, 5, -6, 7, -8];
2350 int4 b = shufflevector(a, a, 0, 2, 4, 6); // b is [1,3,5,7]
2351 int4 c = [-2, -4, -6, -8];
2352 int8 d = shufflevector!(int8, 4, 0, 5, 1, 6, 2, 7, 3)(c, b); // d is a
2356 @deftypefn {Template} {E} gcc.simd.extractelement (V, int idx)(V @var{val})
2357 Extracts a single scalar element from a vector @var{val} at a specified index
2361 int4 a = [0, 10, 20, 30];
2362 int k = extractelement!(int4, 2)(a); // a is 20
2366 @deftypefn {Template} {V} gcc.simd.insertelement (V, int idx)(V val, B @var{e})
2367 Inserts a scalar element @var{e} into a vector @var{val} at a specified index
2371 int4 a = [0, 10, 20, 30];
2372 int4 b = insertelement!(int4, 2)(a, 50); // b is [0,10,50,30]
2376 @deftypefn {Template} {V} gcc.simd.convertvector (V, T)(T val)
2377 Convert a vector @var{val} from one integral or floating vector type to
2378 another. The result is an integral or floating vector that has had every
2379 element cast to the element type of the return type.
2381 This intrinsic is the same as the GCC built-in function
2382 @code{__builtin_convertvector}.
2385 int4 a = [1, -2, 3, -4];
2386 float4 b = [1.5, -2.5, 3, 7];
2387 float4 c = convertvector!float4(a); // c is [1,-2,3,-4]
2388 double4 d = convertvector!double4(a); // d is [1,-2,3,-4]
2389 double4 e = convertvector!double4(b); // e is [1.5,-2.5,3,7]
2390 int4 f = convertvector!int4(b); // f is [1,-2,3,7]
2394 @deftypefn {Template} {V0} gcc.simd.blendvector (V0, V1, M)(V0 @var{op0}, @
2398 Construct a conditional merge of elements from two vectors, returning a vector
2399 of the same type as the input vector(s). The @var{mask} is an integral vector
2400 with the same width and element count as the output vector.
2403 int4 a = [1, 2, 3, 4];
2404 int4 b = [3, 2, 1, 4];
2405 auto c = blendvector(a, b, a > b); // c is [3,2,3,4]
2406 auto d = blendvector(a, b, a < b); // d is [1,2,1,4]
2411 @c --------------------------------------------------------
2413 @node Missing Features
2414 @section Missing Features and Deviations
2415 @cindex missing features
2416 @cindex D spec deviations
2418 Some parts of the D specification are hard or impossible to implement with
2419 GCC, they should be listed here.
2422 @item Bit Operation Intrinsics
2423 The Digital Mars D compiler implements the @code{core.bitop} intrinsics
2424 @code{inp}, @code{inpw}, @code{inpl}, @code{outp}, @code{outpw}, and
2425 @code{outpl}. These are not recognized by GNU D. On most targets, equivalent
2426 intrinsics that have the same effect would be @code{core.volatile.loadVolatile}
2427 and @code{core.volatile.storeVolatile} respectively
2428 (@pxref{Volatile Intrinsics}).
2430 On x86 targets, if an @code{in} or @code{out} instruction is specifically
2431 required, that can be achieved using assembler statements instead.
2433 ubyte inp(uint port)
2436 asm @{ "inb %w1, %b0" : "=a" (value) : "Nd" (port); @}
2440 void outp(uint port, ushort value)
2442 asm @{ "outb %b0, %w1" : : "a" (value), "Nd" (port); @}
2446 @item Floating-Point Intermediate Values
2448 GNU D uses a software compile-time floating-point type that assists in
2449 cross-compilation and support for arbitrary target @code{real} precisions wider
2450 than 80 bits. Because of this, the result of floating-point CTFE operations
2451 may have different results in GNU D compared with other D compilers that use
2452 the host's native floating-point type for storage and CTFE. In particular, GNU
2453 D won't overflow or underflow when a target real features a higher precision
2454 than the host. Differences also extend to @code{.stringof} representations of
2455 intermediate values due to formatting differences with @code{sprintf("%Lg")}.
2458 assert((25.5).stringof ~ (3.01).stringof == "2.55e+13.01e+0");
2460 assert((25.5).stringof ~ (3.01).stringof == "25.53.01");
2463 @item Function Calling Conventions
2464 GNU D does not implement the @code{extern(D)} calling convention for x86 as
2465 described in the D specification hosted at
2466 @uref{https://dlang.org/spec/abi.html#function_calling_conventions}.
2468 Instead, there is no distinction between @code{extern(C)} and @code{extern(D)}
2469 other than name mangling.
2471 @item ImportC Limitations
2472 GNU D does not run the preprocessor automatically for any ImportC sources.
2473 Instead all C files are expected to be manually preprocessed before they are
2474 imported into the compilation.
2476 @item Inline Assembler
2477 GNU D does not implement the D inline assembler for x86 and x86_64 as described
2478 in the D specification hosted at @uref{https://dlang.org/spec/iasm.html}. Nor
2479 does GNU D predefine the @code{D_InlineAsm_X86} and @code{D_InlineAsm_X86_64}
2480 version identifiers to indicate support.
2482 The GNU D compiler uses an alternative, GCC-based syntax for inline assembler
2483 (@pxref{Inline Assembly}).
2485 @item Interfacing to Objective-C
2486 GNU D does not support interfacing with Objective-C, nor its protocols,
2487 classes, subclasses, instance variables, instance methods and class methods.
2488 The @code{extern(Objective-C)} linkage is ignored, as are the @code{@@optional}
2489 and @code{@@selector} attributes. The @code{D_ObjectiveC} version identifier
2490 is not predefined for compilations.
2492 @item Pragma Directives
2493 Pragmas that are designed to embed information into object files or otherwise
2494 pass options to the linker are not supported by GNU D. These include
2495 @code{pragma(lib)}, @code{pragma(linkerDirective)}, and
2496 @code{pragma(startaddress)}.
2498 @item SIMD Intrinsics
2499 The Digital Mars D compiler implements the @code{core.simd} intrinsics
2500 @code{__simd}, @code{__simd_ib}, @code{__simd_sto}. These are not recognized
2501 by GNU D, nor does GNU D predefine the @code{D_SIMD} version identifier to
2504 On x86 targets, all intrinsics are available as functions in the
2505 @code{gcc.builtins} module, and have predictable equivalents.
2507 version (DigitalMars)
2509 __simd(XMM.PSLLW, op1, op2);
2510 __simd_ib(XMM.PSLLW, op1, imm8);
2514 __builtin_ia32_psllw(op1, op2);
2515 __builtin_ia32_psllwi(op1, imm8);
2519 @item TypeInfo-based va_arg
2520 The Digital Mars D compiler implements a version of @code{core.vararg.va_arg}
2521 that accepts a run-time @code{TypeInfo} argument for use when the static type
2522 is not known. This function is not implemented by GNU D. It is more portable
2523 to use variadic template functions instead.