d: Merge upstream dmd, druntime 4c18eed967, phobos d945686a4.
[official-gcc.git] / gcc / d / decl.cc
blobc80bb8aebd7b04bd90d146c06a755086b7ba99dc
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2 Copyright (C) 2006-2023 Free Software Foundation, Inc.
4 GCC is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
7 any later version.
9 GCC is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with GCC; see the file COPYING3. If not see
16 <http://www.gnu.org/licenses/>. */
18 #include "config.h"
19 #include "system.h"
20 #include "coretypes.h"
22 #include "dmd/aggregate.h"
23 #include "dmd/attrib.h"
24 #include "dmd/cond.h"
25 #include "dmd/ctfe.h"
26 #include "dmd/declaration.h"
27 #include "dmd/enum.h"
28 #include "dmd/errors.h"
29 #include "dmd/globals.h"
30 #include "dmd/hdrgen.h"
31 #include "dmd/identifier.h"
32 #include "dmd/import.h"
33 #include "dmd/init.h"
34 #include "dmd/mangle.h"
35 #include "dmd/module.h"
36 #include "dmd/nspace.h"
37 #include "dmd/target.h"
38 #include "dmd/template.h"
40 #include "tree.h"
41 #include "tree-iterator.h"
42 #include "fold-const.h"
43 #include "diagnostic.h"
44 #include "langhooks.h"
45 #include "target.h"
46 #include "common/common-target.h"
47 #include "cgraph.h"
48 #include "toplev.h"
49 #include "stringpool.h"
50 #include "varasm.h"
51 #include "stor-layout.h"
52 #include "attribs.h"
53 #include "function.h"
54 #include "debug.h"
55 #include "tree-pretty-print.h"
56 #include "tree-nested.h"
57 #include "alloc-pool.h"
58 #include "symbol-summary.h"
59 #include "symtab-thunks.h"
60 #include "gimple-expr.h"
62 #include "d-tree.h"
63 #include "d-target.h"
66 /* Return identifier for the external mangled name of DECL. */
68 const char *
69 d_mangle_decl (Dsymbol *decl)
71 if (decl->isFuncDeclaration ())
72 return mangleExact ((FuncDeclaration *) decl);
73 else
75 OutBuffer buf;
76 mangleToBuffer (decl, buf);
77 return buf.extractChars ();
81 /* Generate a mangled identifier using NAME and SUFFIX, prefixed by the
82 assembler name for DECL. */
84 tree
85 mangle_internal_decl (Dsymbol *decl, const char *name, const char *suffix)
87 const char *prefix = d_mangle_decl (decl);
88 unsigned namelen = strlen (name);
89 unsigned buflen = (2 + strlen (prefix) + namelen + strlen (suffix)) * 2;
90 char *buf = (char *) alloca (buflen);
92 snprintf (buf, buflen, "_D%s%u%s%s", prefix, namelen, name, suffix);
93 tree ident = get_identifier (buf);
95 /* Symbol is not found in user code, but generate a readable name for it
96 anyway for debug and diagnostic reporting. */
97 snprintf (buf, buflen, "%s.%s", decl->toPrettyChars (), name);
98 IDENTIFIER_PRETTY_NAME (ident) = get_identifier (buf);
100 return ident;
103 /* Returns true if DECL is from the gcc.attributes module. */
105 static bool
106 gcc_attribute_p (Dsymbol *decl)
108 ModuleDeclaration *md = decl->getModule ()->md;
110 if (md && md->packages.length == 1)
112 if (!strcmp (md->packages.ptr[0]->toChars (), "gcc")
113 && !strcmp (md->id->toChars (), "attributes"))
114 return true;
117 return false;
120 /* Return the DECL_RESULT for the function declaration DECL, create it if it
121 doesn't already exist. */
123 static tree
124 get_fndecl_result (FuncDeclaration *decl)
126 tree fndecl = get_symbol_decl (decl);
127 tree resdecl = DECL_RESULT (fndecl);
129 if (resdecl != NULL_TREE)
130 return resdecl;
132 resdecl = build_decl (make_location_t (decl->loc), RESULT_DECL,
133 NULL_TREE, TREE_TYPE (TREE_TYPE (fndecl)));
135 DECL_ARTIFICIAL (resdecl) = 1;
136 DECL_IGNORED_P (resdecl) = 1;
137 DECL_CONTEXT (resdecl) = fndecl;
138 DECL_RESULT (fndecl) = resdecl;
139 return resdecl;
142 /* Return the list of PARAM_DECLs for the function declaration DECL, create it
143 if it doesn't already exist. */
145 static tree
146 get_fndecl_arguments (FuncDeclaration *decl)
148 tree fndecl = get_symbol_decl (decl);
149 tree param_list = DECL_ARGUMENTS (fndecl);
151 if (param_list != NULL_TREE)
152 return param_list;
154 if (decl->fbody)
156 /* Handle special arguments first. */
158 /* `this' parameter:
159 For nested functions, D still generates a vthis, but it
160 should not be referenced in any expression. */
161 if (decl->vthis)
163 tree parm_decl = get_symbol_decl (decl->vthis);
164 DECL_ARTIFICIAL (parm_decl) = 1;
165 TREE_READONLY (parm_decl) = 1;
167 if (decl->vthis->type == Type::tvoidptr)
169 /* Replace generic pointer with back-end closure type
170 (this wins for gdb). */
171 tree frame_type = FRAMEINFO_TYPE (get_frameinfo (decl));
172 gcc_assert (frame_type != NULL_TREE);
173 TREE_TYPE (parm_decl) = build_pointer_type (frame_type);
176 param_list = chainon (param_list, parm_decl);
179 /* `_arguments' parameter. */
180 if (decl->v_arguments)
182 tree parm_decl = get_symbol_decl (decl->v_arguments);
183 param_list = chainon (param_list, parm_decl);
186 /* Now add on formal function parameters. */
187 size_t n_parameters = decl->parameters ? decl->parameters->length : 0;
189 for (size_t i = 0; i < n_parameters; i++)
191 VarDeclaration *param = (*decl->parameters)[i];
192 tree parm_decl = get_symbol_decl (param);
194 /* Type `noreturn` is a terminator, as no other arguments can possibly
195 be evaluated after it. */
196 if (TREE_TYPE (parm_decl) == noreturn_type_node)
197 break;
199 /* Chain them in the correct order. */
200 param_list = chainon (param_list, parm_decl);
203 else
205 /* Build parameters from the function type. */
206 tree fntype = TREE_TYPE (fndecl);
208 for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
210 if (t == void_list_node)
211 break;
213 tree param = build_decl (DECL_SOURCE_LOCATION (fndecl),
214 PARM_DECL, NULL_TREE, TREE_VALUE (t));
215 DECL_ARG_TYPE (param) = TREE_TYPE (param);
216 DECL_ARTIFICIAL (param) = 1;
217 DECL_IGNORED_P (param) = 1;
218 DECL_CONTEXT (param) = fndecl;
219 param_list = chainon (param_list, param);
223 DECL_ARGUMENTS (fndecl) = param_list;
224 return param_list;
227 /* Implements the visitor interface to lower all Declaration AST classes
228 emitted from the D Front-end to GCC trees.
229 All visit methods accept one parameter D, which holds the frontend AST
230 of the declaration to compile. These also don't return any value, instead
231 generated code are appened to global_declarations or added to the
232 current_binding_level by d_pushdecl(). */
234 class DeclVisitor : public Visitor
236 using Visitor::visit;
238 /* If we're lowering the body of a version(unittest) condition. */
239 bool in_version_unittest_;
241 public:
242 DeclVisitor (void)
244 this->in_version_unittest_ = false;
247 /* Helper for generating code for the dsymbol AST class D.
248 Sets up the location of the symbol before lowering. */
250 void build_dsymbol (Dsymbol *d)
252 location_t saved_location = input_location;
253 input_location = make_location_t (d->loc);
254 d->accept (this);
255 input_location = saved_location;
258 /* This should be overridden by each declaration class. */
260 void visit (Dsymbol *) final override
264 /* Compile a D module, and all members of it. */
266 void visit (Module *d) final override
268 if (d->semanticRun >= PASS::obj)
269 return;
271 build_module_tree (d);
272 d->semanticRun = PASS::obj;
275 /* Write the imported symbol to debug. */
277 void visit (Import *d) final override
279 if (d->semanticRun >= PASS::obj)
280 return;
282 /* Implements import declarations by telling the debug back-end we are
283 importing the NAMESPACE_DECL of the module or IMPORTED_DECL of the
284 declaration into the current lexical scope CONTEXT. NAME is set if
285 this is a renamed import. */
286 if (d->isstatic)
287 return;
289 /* Get the context of this import, this should never be null. */
290 tree context = d_module_context ();
292 if (d->ident == NULL)
294 /* Importing declaration list. */
295 for (size_t i = 0; i < d->names.length; i++)
297 AliasDeclaration *aliasdecl = d->aliasdecls[i];
298 tree decl = build_import_decl (aliasdecl);
300 /* Skip over unhandled imports. */
301 if (decl == NULL_TREE)
302 continue;
304 Identifier *alias = d->aliases[i];
305 tree name = (alias != NULL)
306 ? get_identifier (alias->toChars ()) : NULL_TREE;
308 if (TREE_CODE (decl) != TREE_LIST)
309 debug_hooks->imported_module_or_decl (decl, name, context,
310 false, false);
311 else
313 /* Overload sets return a list of imported decls. */
314 for (; decl != NULL_TREE; decl = TREE_CHAIN (decl))
315 debug_hooks->imported_module_or_decl (TREE_VALUE (decl), name,
316 context, false, false);
320 else
322 /* Importing the entire module. */
323 tree decl = build_import_decl (d->mod);
325 tree name = (d->aliasId != NULL)
326 ? get_identifier (d->aliasId->toChars ()) : NULL_TREE;
328 debug_hooks->imported_module_or_decl (decl, name, context,
329 false, false);
332 d->semanticRun = PASS::obj;
335 /* Expand any local variables found in tuples. */
337 void visit (TupleDeclaration *d) final override
339 for (size_t i = 0; i < d->objects->length; i++)
341 RootObject *o = (*d->objects)[i];
342 if (o->dyncast () == DYNCAST_EXPRESSION)
344 VarExp *ve = ((Expression *) o)->isVarExp ();
345 if (ve)
346 this->build_dsymbol (ve->var);
351 /* Walk over all declarations in the attribute scope. */
353 void visit (AttribDeclaration *d) final override
355 Dsymbols *ds = d->include (NULL);
357 if (!ds)
358 return;
360 for (size_t i = 0; i < ds->length; i++)
361 this->build_dsymbol ((*ds)[i]);
364 /* Pragmas are a way to pass special information to the compiler and to add
365 vendor specific extensions to D. */
367 void visit (PragmaDeclaration *d) final override
369 if (d->ident == Identifier::idPool ("lib")
370 || d->ident == Identifier::idPool ("startaddress"))
372 if (!global.params.ignoreUnsupportedPragmas)
374 warning_at (make_location_t (d->loc), OPT_Wunknown_pragmas,
375 "pragma(%s) not implemented", d->ident->toChars ());
379 visit ((AttribDeclaration *) d);
382 /* Conditional compilation is the process of selecting which code to compile
383 and which code to not compile. Look for version conditions that may */
385 void visit (ConditionalDeclaration *d) final override
387 bool old_condition = this->in_version_unittest_;
389 if (global.params.useUnitTests)
391 VersionCondition *vc = d->condition->isVersionCondition ();
392 if (vc && vc->ident == Identifier::idPool ("unittest"))
393 this->in_version_unittest_ = true;
396 visit ((AttribDeclaration *) d);
398 this->in_version_unittest_ = old_condition;
401 /* Walk over all members in the namespace scope. */
403 void visit (Nspace *d) final override
405 if (isError (d) || !d->members)
406 return;
408 for (size_t i = 0; i < d->members->length; i++)
409 this->build_dsymbol ((*d->members)[i]);
412 /* Templates are D's approach to generic programming. They have no members
413 that can be emitted, however if the template is nested and used as a
414 voldemort type, then it's members must be compiled before the parent
415 function finishes. */
417 void visit (TemplateDeclaration *d) final override
419 /* Type cannot be directly named outside of the scope it's declared in, so
420 the only way it can be escaped is if the function has auto return. */
421 FuncDeclaration *fd = d_function_chain ? d_function_chain->function : NULL;
423 if (!fd || !fd->isAuto ())
424 return;
426 /* Check if the function returns an instantiated type that may contain
427 nested members. Only applies to classes or structs. */
428 Type *tb = fd->type->nextOf ()->baseElemOf ();
430 while (tb->ty == TY::Tarray || tb->ty == TY::Tpointer)
431 tb = tb->nextOf ()->baseElemOf ();
433 TemplateInstance *ti = NULL;
435 if (tb->ty == TY::Tstruct)
436 ti = tb->isTypeStruct ()->sym->isInstantiated ();
437 else if (tb->ty == TY::Tclass)
438 ti = tb->isTypeClass ()->sym->isInstantiated ();
440 /* Return type is instantiated from this template declaration, walk over
441 all members of the instance. */
442 if (ti && ti->tempdecl == d)
443 this->build_dsymbol (ti);
446 /* Walk over all members in the instantiated template. */
448 void visit (TemplateInstance *d) final override
450 if (isError (d)|| !d->members)
451 return;
453 if (!d->needsCodegen ())
454 return;
456 for (size_t i = 0; i < d->members->length; i++)
457 this->build_dsymbol ((*d->members)[i]);
460 /* Walk over all members in the mixin template scope. */
462 void visit (TemplateMixin *d) final override
464 if (isError (d)|| !d->members)
465 return;
467 for (size_t i = 0; i < d->members->length; i++)
468 this->build_dsymbol ((*d->members)[i]);
471 /* Write out compiler generated TypeInfo, initializer and functions for the
472 given struct declaration, walking over all static members. */
474 void visit (StructDeclaration *d) final override
476 if (d->semanticRun >= PASS::obj)
477 return;
479 if (d->type->ty == TY::Terror)
481 error_at (make_location_t (d->loc),
482 "had semantic errors when compiling");
483 return;
486 /* Don't emit any symbols from gcc.attributes module. */
487 if (gcc_attribute_p (d))
488 return;
490 /* Add this decl to the current binding level. */
491 tree ctype = build_ctype (d->type);
492 if (TYPE_NAME (ctype))
493 d_pushdecl (TYPE_NAME (ctype));
495 /* Anonymous structs/unions only exist as part of others,
496 do not output forward referenced structs. */
497 if (d->isAnonymous () || !d->members)
498 return;
500 /* Generate TypeInfo. */
501 if (have_typeinfo_p (Type::dtypeinfo))
502 create_typeinfo (d->type, NULL);
504 /* Generate static initializer. */
505 tree sinit = aggregate_initializer_decl (d);
506 DECL_INITIAL (sinit) = layout_struct_initializer (d);
507 d_finish_decl (sinit);
509 /* Put out the members. There might be static constructors in the members
510 list, and they cannot be put in separate object files. */
511 for (size_t i = 0; i < d->members->length; i++)
512 this->build_dsymbol ((*d->members)[i]);
514 /* Put out xopEquals, xopCmp and xopHash. */
515 if (d->xeq && d->xeq != d->xerreq)
516 this->build_dsymbol (d->xeq);
518 if (d->xcmp && d->xcmp != d->xerrcmp)
519 this->build_dsymbol (d->xcmp);
521 if (d->xhash)
522 this->build_dsymbol (d->xhash);
524 d->semanticRun = PASS::obj;
527 /* Finish semantic analysis of functions in vtbl for class CD. */
529 bool finish_vtable (ClassDeclaration *d)
531 bool has_errors = false;
533 /* Finish semantic analysis of functions in vtbl[]. */
534 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
536 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
538 if (!fd || (!fd->fbody && d->isAbstract ()))
539 continue;
541 /* Ensure function has a return value. */
542 if (!fd->functionSemantic ())
543 has_errors = true;
545 /* No name hiding to check for. */
546 if (!d->isFuncHidden (fd) || fd->isFuture ())
547 continue;
549 /* The function fd is hidden from the view of the class.
550 If it overlaps with any function in the vtbl[], then
551 issue an error. */
552 for (size_t j = 1; j < d->vtbl.length; j++)
554 if (j == i)
555 continue;
557 FuncDeclaration *fd2 = d->vtbl[j]->isFuncDeclaration ();
558 if (!fd2->ident->equals (fd->ident))
559 continue;
561 /* The function is marked as @__future, a deprecation has
562 already been given by the frontend. */
563 if (fd2->isFuture ())
564 continue;
566 if (fd->leastAsSpecialized (fd2, NULL) != MATCH::nomatch
567 || fd2->leastAsSpecialized (fd, NULL) != MATCH::nomatch)
569 error_at (make_location_t (fd->loc), "use of %qs",
570 fd->toPrettyChars ());
571 inform (make_location_t (fd2->loc), "is hidden by %qs",
572 fd2->toPrettyChars ());
573 inform (make_location_t (d->loc),
574 "use %<alias %s = %s.%s;%> to introduce base class "
575 "overload set", fd->toChars (),
576 fd->parent->toChars (), fd->toChars ());
577 has_errors = true;
578 break;
583 return !has_errors;
586 /* Write out compiler generated TypeInfo, initializer and vtables for the
587 given class declaration, walking over all static members. */
589 void visit (ClassDeclaration *d) final override
591 if (d->semanticRun >= PASS::obj)
592 return;
594 if (d->type->ty == TY::Terror)
596 error_at (make_location_t (d->loc),
597 "had semantic errors when compiling");
598 return;
601 /* Add this decl to the current binding level. */
602 tree ctype = TREE_TYPE (build_ctype (d->type));
603 if (TYPE_NAME (ctype))
604 d_pushdecl (TYPE_NAME (ctype));
606 if (!d->members)
607 return;
609 /* Put out the members. */
610 for (size_t i = 0; i < d->members->length; i++)
611 this->build_dsymbol ((*d->members)[i]);
613 /* If something goes wrong during final semantic pass, don't bother with
614 the rest as we may have incomplete info. */
615 if (!this->finish_vtable (d))
616 return;
618 /* Generate C symbols. */
619 d->csym = get_classinfo_decl (d);
620 Dsymbol *vtblsym = d->vtblSymbol ();
621 vtblsym->csym = get_vtable_decl (d);
622 tree sinit = aggregate_initializer_decl (d);
624 /* Generate static initializer. */
625 DECL_INITIAL (sinit) = layout_class_initializer (d);
626 d_finish_decl (sinit);
628 /* Put out the TypeInfo. */
629 if (have_typeinfo_p (Type::dtypeinfo))
630 create_typeinfo (d->type, NULL);
632 DECL_INITIAL (d->csym) = layout_classinfo (d);
633 d_finish_decl (d->csym);
635 /* Put out the vtbl[]. */
636 vec <constructor_elt, va_gc> *elms = NULL;
638 /* First entry is ClassInfo reference. */
639 if (d->vtblOffset ())
640 CONSTRUCTOR_APPEND_ELT (elms, size_zero_node, build_address (d->csym));
642 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
644 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
646 if (fd && (fd->fbody || !d->isAbstract ()))
648 CONSTRUCTOR_APPEND_ELT (elms, size_int (i),
649 build_address (get_symbol_decl (fd)));
653 DECL_INITIAL (vtblsym->csym)
654 = build_constructor (TREE_TYPE (vtblsym->csym), elms);
655 d_finish_decl (vtblsym->csym);
657 d->semanticRun = PASS::obj;
660 /* Write out compiler generated TypeInfo and vtables for the given interface
661 declaration, walking over all static members. */
663 void visit (InterfaceDeclaration *d) final override
665 if (d->semanticRun >= PASS::obj)
666 return;
668 if (d->type->ty == TY::Terror)
670 error_at (make_location_t (d->loc),
671 "had semantic errors when compiling");
672 return;
675 /* Add this decl to the current binding level. */
676 tree ctype = TREE_TYPE (build_ctype (d->type));
677 if (TYPE_NAME (ctype))
678 d_pushdecl (TYPE_NAME (ctype));
680 if (!d->members)
681 return;
683 /* Put out the members. */
684 for (size_t i = 0; i < d->members->length; i++)
685 this->build_dsymbol ((*d->members)[i]);
687 /* Generate C symbols. */
688 d->csym = get_classinfo_decl (d);
690 /* Put out the TypeInfo. */
691 if (have_typeinfo_p (Type::dtypeinfo))
693 create_typeinfo (d->type, NULL);
694 this->build_dsymbol (d->type->vtinfo);
697 DECL_INITIAL (d->csym) = layout_classinfo (d);
698 d_finish_decl (d->csym);
700 d->semanticRun = PASS::obj;
703 /* Write out compiler generated TypeInfo and initializer for the given
704 enum declaration. */
706 void visit (EnumDeclaration *d) final override
708 if (d->semanticRun >= PASS::obj)
709 return;
711 if (d->errors || d->type->ty == TY::Terror)
713 error_at (make_location_t (d->loc),
714 "had semantic errors when compiling");
715 return;
718 /* Add this decl to the current binding level. */
719 tree ctype = build_ctype (d->type);
720 if (TREE_CODE (ctype) == ENUMERAL_TYPE && TYPE_NAME (ctype))
721 d_pushdecl (TYPE_NAME (ctype));
723 if (d->isAnonymous ())
724 return;
726 /* Generate TypeInfo. */
727 if (have_typeinfo_p (Type::dtypeinfo))
728 create_typeinfo (d->type, NULL);
730 TypeEnum *tc = d->type->isTypeEnum ();
731 if (tc->sym->members && !d->type->isZeroInit ())
733 /* Generate static initializer. */
734 d->sinit = enum_initializer_decl (d);
735 DECL_INITIAL (d->sinit) = build_expr (tc->sym->defaultval, true);
736 d_finish_decl (d->sinit);
739 d->semanticRun = PASS::obj;
742 /* Finish up a variable declaration and push it into the current scope.
743 This can either be a static, local or manifest constant. */
745 void visit (VarDeclaration *d) final override
747 if (d->semanticRun >= PASS::obj)
748 return;
750 if (d->type->ty == TY::Terror)
752 error_at (make_location_t (d->loc),
753 "had semantic errors when compiling");
754 return;
757 /* Variables of type `noreturn` are just placeholders, and evaluate to
758 `assert(0)` if ever read. */
759 if (d->type->isTypeNoreturn ())
761 if (!d->isDataseg () && !d->isMember ()
762 && d->_init && !d->_init->isVoidInitializer ())
764 /* Evaluate RHS for side effects first. */
765 Expression *ie = initializerToExpression (d->_init);
766 add_stmt (build_expr (ie));
768 Expression *e = d->type->defaultInitLiteral (d->loc);
769 add_stmt (build_expr (e));
772 return;
775 if (d->aliasTuple)
777 this->build_dsymbol (d->toAlias ());
778 return;
781 if (!d->canTakeAddressOf ())
783 /* Do not store variables we cannot take the address of,
784 but keep the values for purposes of debugging. */
785 if (d->type->isscalar () && !d->type->hasPointers ())
787 tree decl = get_symbol_decl (d);
788 d_pushdecl (decl);
789 rest_of_decl_compilation (decl, 1, 0);
792 else if (d->isDataseg ())
794 tree decl = get_symbol_decl (d);
796 /* Only need to build the VAR_DECL for extern declarations. */
797 if (d->storage_class & STCextern)
798 return;
800 /* Duplicated VarDeclarations map to the same symbol. Check if this
801 is the one declaration which will be emitted. */
802 tree ident = DECL_ASSEMBLER_NAME (decl);
803 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
804 return;
806 /* How big a symbol can be should depend on back-end. */
807 tree size = build_integer_cst (d->type->size (d->loc),
808 build_ctype (Type::tsize_t));
809 if (!valid_constant_size_p (size))
811 error_at (make_location_t (d->loc), "size is too large");
812 return;
815 if (d->_init)
817 /* Use the explicit initializer, this includes `void`. */
818 if (!d->_init->isVoidInitializer ())
820 Expression *e = initializerToExpression (d->_init, d->type);
821 DECL_INITIAL (decl) = build_expr (e, true);
824 else if (!d->type->isZeroInit ())
826 /* Use default initializer for the type. */
827 if (TypeStruct *ts = d->type->isTypeStruct ())
828 DECL_INITIAL (decl) = layout_struct_initializer (ts->sym);
829 else
831 Expression *e = d->type->defaultInitLiteral (d->loc);
832 DECL_INITIAL (decl) = build_expr (e, true);
836 /* Frontend should have already caught this. */
837 gcc_assert (!integer_zerop (size)
838 || d->type->toBasetype ()->isTypeSArray ());
840 d_finish_decl (decl);
842 /* Maybe record the var against the current module. */
843 register_module_decl (d);
845 else if (!d->isDataseg () && !d->isMember ())
847 /* This is needed for VarDeclarations in mixins that are to be local
848 variables of a function. Otherwise, it would be enough to make
849 a check for isVarDeclaration() in DeclarationExp codegen. */
850 declare_local_var (d);
852 if (d->_init && !d->_init->isVoidInitializer ())
854 tree decl = get_symbol_decl (d);
856 ExpInitializer *vinit = d->_init->isExpInitializer ();
857 Expression *ie = initializerToExpression (vinit);
858 tree exp = build_expr (ie);
860 /* Maybe put variable on list of things needing destruction. */
861 if (d->needsScopeDtor ())
863 vec_safe_push (d_function_chain->vars_in_scope, decl);
864 /* Force a TARGET_EXPR to add the corresponding cleanup. */
865 exp = force_target_expr (compound_expr (exp, decl));
866 TARGET_EXPR_CLEANUP (exp) = build_expr (d->edtor);
869 add_stmt (exp);
873 d->semanticRun = PASS::obj;
876 /* Generate and compile a static TypeInfo declaration, but only if it is
877 needed in the current compilation. */
879 void visit (TypeInfoDeclaration *d) final override
881 if (d->semanticRun >= PASS::obj)
882 return;
884 if (speculative_type_p (d->tinfo))
885 return;
887 tree t = get_typeinfo_decl (d);
888 DECL_INITIAL (t) = layout_typeinfo (d);
889 d_finish_decl (t);
890 d->semanticRun = PASS::obj;
893 /* Finish up a function declaration and compile it all the way
894 down to assembler language output. */
896 void visit (FuncDeclaration *d) final override
898 /* Already generated the function. */
899 if (d->semanticRun >= PASS::obj)
900 return;
902 /* Don't emit any symbols from gcc.attributes module. */
903 if (gcc_attribute_p (d))
904 return;
906 /* Front-end decided this function doesn't require code generation. */
907 if (d->skipCodegen ())
908 return;
910 /* Not emitting unittest functions. */
911 if (!global.params.useUnitTests && d->isUnitTestDeclaration ())
912 return;
914 /* Check if any errors occurred when running semantic. */
915 if (TypeFunction *tf = d->type->isTypeFunction ())
917 if (tf->next == NULL || tf->next->ty == TY::Terror)
918 return;
921 if (d->hasSemantic3Errors ())
922 return;
924 if (d->isNested ())
926 FuncDeclaration *fdp = d;
927 while (fdp && fdp->isNested ())
929 fdp = fdp->toParent2 ()->isFuncDeclaration ();
931 if (fdp == NULL)
932 break;
934 /* Parent failed to compile, but errors were gagged. */
935 if (fdp->hasSemantic3Errors ())
936 return;
940 /* Ensure all semantic passes have run. */
941 if (d->semanticRun < PASS::semantic3)
943 gcc_assert (!doing_semantic_analysis_p);
945 doing_semantic_analysis_p = true;
946 d->functionSemantic3 ();
947 Module::runDeferredSemantic3 ();
948 doing_semantic_analysis_p = false;
951 if (global.errors)
952 return;
954 /* Start generating code for this function. */
955 gcc_assert (d->semanticRun == PASS::semantic3done);
956 d->semanticRun = PASS::obj;
958 /* Duplicated FuncDeclarations map to the same symbol. Check if this
959 is the one declaration which will be emitted. */
960 tree fndecl = get_symbol_decl (d);
961 tree ident = DECL_ASSEMBLER_NAME (fndecl);
962 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
963 return;
965 if (!d->fbody)
967 rest_of_decl_compilation (fndecl, 1, 0);
968 return;
971 if (global.params.v.verbose)
972 message ("function %s", d->toPrettyChars ());
974 tree old_context = start_function (d);
975 tree param_list = get_fndecl_arguments (d);
977 DECL_IN_UNITTEST_CONDITION_P (fndecl) = this->in_version_unittest_;
978 rest_of_decl_compilation (fndecl, 1, 0);
980 /* If this is a member function that nested (possibly indirectly) in another
981 function, construct an expession for this member function's static chain
982 by going through parent link of nested classes. */
983 if (d->vthis)
984 d_function_chain->static_chain = get_symbol_decl (d->vthis);
986 if (d->isThis ())
988 AggregateDeclaration *ad = d->isThis ();
989 tree this_tree = get_symbol_decl (d->vthis);
991 while (ad->isNested ())
993 Dsymbol *pd = ad->toParent2 ();
994 tree vthis_field = get_symbol_decl (ad->vthis);
995 this_tree = component_ref (build_deref (this_tree), vthis_field);
997 ad = pd->isAggregateDeclaration ();
998 if (ad == NULL)
1000 d_function_chain->static_chain = this_tree;
1001 break;
1006 /* Named return value optimisation support for D.
1007 Implemented by overriding all the RETURN_EXPRs and replacing all
1008 occurrences of VAR with the RESULT_DECL for the function.
1009 This is only worth doing for functions that can return in memory. */
1010 tree resdecl = DECL_RESULT (fndecl);
1012 if (TREE_ADDRESSABLE (TREE_TYPE (resdecl))
1013 || aggregate_value_p (TREE_TYPE (resdecl), fndecl))
1015 /* Return non-trivial structs by invisible reference. */
1016 if (TREE_ADDRESSABLE (TREE_TYPE (resdecl)))
1018 TREE_TYPE (resdecl) = build_reference_type (TREE_TYPE (resdecl));
1019 DECL_BY_REFERENCE (resdecl) = 1;
1020 TREE_ADDRESSABLE (resdecl) = 0;
1021 relayout_decl (resdecl);
1022 d->shidden = build_deref (resdecl);
1024 else
1025 d->shidden = resdecl;
1027 if (d->isNRVO () && d->nrvo_var)
1029 tree var = get_symbol_decl (d->nrvo_var);
1031 /* Copy name from VAR to RESULT. */
1032 DECL_NAME (resdecl) = DECL_NAME (var);
1033 /* Don't forget that we take its address. */
1034 TREE_ADDRESSABLE (var) = 1;
1036 SET_DECL_VALUE_EXPR (var, resdecl);
1037 DECL_HAS_VALUE_EXPR_P (var) = 1;
1038 SET_DECL_LANG_NRVO (var, d->shidden);
1042 /* May change cfun->static_chain. */
1043 build_closure (d);
1045 if (d->vresult)
1046 declare_local_var (d->vresult);
1048 if (d->v_argptr)
1049 push_stmt_list ();
1051 build_function_body (d);
1053 /* Initialize the _argptr variable. */
1054 if (d->v_argptr)
1056 tree body = pop_stmt_list ();
1057 tree var = get_decl_tree (d->v_argptr);
1058 var = build_address (var);
1060 tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
1061 2, var, tree_last (param_list));
1062 declare_local_var (d->v_argptr);
1063 add_stmt (init);
1065 tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
1066 1, var);
1067 add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
1070 finish_function (old_context);
1072 /* Maybe record the function against the current module. */
1073 register_module_decl (d);
1077 /* Main entry point for the DeclVisitor interface to send
1078 the Declaration AST class D to GCC back-end. */
1080 void
1081 build_decl_tree (Dsymbol *d)
1083 location_t saved_location = input_location;
1085 /* Set input location, empty DECL_SOURCE_FILE can crash debug generator. */
1086 if (d->loc.filename ())
1087 input_location = make_location_t (d->loc);
1088 else
1089 input_location = make_location_t (Loc ("<no_file>", 1, 0));
1091 DeclVisitor v = DeclVisitor ();
1092 v.build_dsymbol (d);
1094 input_location = saved_location;
1097 /* Returns true if function FD always needs to be implicitly defined, such as
1098 it was declared `pragma(inline)'. */
1100 static bool
1101 function_needs_inline_definition_p (FuncDeclaration *fd)
1103 /* Function has already been defined. */
1104 if (!DECL_EXTERNAL (fd->csym))
1105 return false;
1107 /* No function body available for inlining. */
1108 if (!fd->fbody)
1109 return false;
1111 /* These functions are tied to the module they are defined in. */
1112 if (fd->isFuncLiteralDeclaration ()
1113 || fd->isUnitTestDeclaration ()
1114 || fd->isFuncAliasDeclaration ()
1115 || fd->isInvariantDeclaration ())
1116 return false;
1118 /* Check whether function will be regularly defined later in the current
1119 translation unit. */
1120 Module *md = fd->getModule ();
1121 if (md && md->isRoot ())
1122 return false;
1124 /* Non-inlineable functions are always external. */
1125 if (DECL_UNINLINABLE (fd->csym))
1126 return false;
1128 /* Ignore functions that aren't decorated with `pragma(inline)'. */
1129 if (!DECL_DECLARED_INLINE_P (fd->csym))
1130 return false;
1132 /* Weak functions cannot be inlined. */
1133 if (lookup_attribute ("weak", DECL_ATTRIBUTES (fd->csym)))
1134 return false;
1136 /* Naked functions cannot be inlined. */
1137 if (lookup_attribute ("naked", DECL_ATTRIBUTES (fd->csym)))
1138 return false;
1140 return true;
1143 /* If the variable or function declaration in DECL needs to be defined, add it
1144 to the list of deferred declarations to build later. */
1146 static tree
1147 maybe_build_decl_tree (Declaration *decl)
1149 gcc_assert (decl->csym != NULL_TREE);
1151 /* Still running semantic analysis on declaration, or it has already had its
1152 code generated. */
1153 if (doing_semantic_analysis_p || decl->semanticRun >= PASS::obj)
1154 return decl->csym;
1156 if (error_operand_p (decl->csym))
1157 return decl->csym;
1159 if (FuncDeclaration *fd = decl->isFuncDeclaration ())
1161 /* Externally defined inline functions need to be emitted. */
1162 if (function_needs_inline_definition_p (fd))
1164 DECL_EXTERNAL (fd->csym) = 0;
1165 d_defer_declaration (fd);
1169 return decl->csym;
1172 /* Return the decl for the symbol, create it if it doesn't already exist. */
1174 tree
1175 get_symbol_decl (Declaration *decl)
1177 if (decl->csym)
1178 return maybe_build_decl_tree (decl);
1180 /* Deal with placeholder symbols immediately:
1181 SymbolDeclaration is used as a shell around an initializer symbol. */
1182 SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1183 if (sd)
1185 decl->csym = aggregate_initializer_decl (sd->dsym);
1186 return decl->csym;
1189 /* Global static TypeInfo declaration. */
1190 if (decl->isTypeInfoDeclaration ())
1191 return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1193 /* FuncAliasDeclaration is used to import functions from another scope. */
1194 FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1195 if (fad)
1197 decl->csym = get_symbol_decl (fad->funcalias);
1198 return decl->csym;
1201 /* It is possible for a field declaration symbol to be requested
1202 before the parent type has been built. */
1203 if (decl->isField ())
1205 AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1206 gcc_assert (ad != NULL);
1208 /* Finishing off the type should create the associated FIELD_DECL. */
1209 build_ctype (ad->type);
1210 gcc_assert (decl->csym != NULL);
1212 return decl->csym;
1215 if (VarDeclaration *vd = decl->isVarDeclaration ())
1217 /* CONST_DECL was initially intended for enumerals and may be used for
1218 scalars in general, but not for aggregates. Here a non-constant
1219 value is generated anyway so as its value can be used. */
1220 if (!vd->canTakeAddressOf () && !vd->type->isscalar ())
1222 gcc_assert (vd->_init && !vd->_init->isVoidInitializer ());
1223 Expression *ie = initializerToExpression (vd->_init);
1224 decl->csym = build_expr (ie, false);
1225 return decl->csym;
1229 /* Build the tree for the symbol. */
1230 FuncDeclaration *fd = decl->isFuncDeclaration ();
1231 if (fd)
1233 /* Run full semantic on functions we need to know about. */
1234 if (!fd->functionSemantic ())
1236 decl->csym = error_mark_node;
1237 return decl->csym;
1240 decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1241 get_identifier (decl->ident->toChars ()),
1242 NULL_TREE);
1244 /* Set function type afterwards as there could be self references. */
1245 TREE_TYPE (decl->csym) = build_ctype (fd->type);
1247 /* Set DECL_INITIAL now if the function has a definition. */
1248 if (fd->fbody)
1249 DECL_INITIAL (decl->csym) = error_mark_node;
1250 else
1251 DECL_EXTERNAL (decl->csym) = 1;
1253 else
1255 /* Build the variable declaration. */
1256 VarDeclaration *vd = decl->isVarDeclaration ();
1257 gcc_assert (vd != NULL);
1259 tree_code code = vd->isParameter () ? PARM_DECL
1260 : !vd->canTakeAddressOf () ? CONST_DECL
1261 : VAR_DECL;
1262 decl->csym = build_decl (make_location_t (decl->loc), code,
1263 get_identifier (decl->ident->toChars ()),
1264 declaration_type (vd));
1266 /* If any alignment was set on the declaration. */
1267 if (!vd->alignment.isDefault ())
1269 SET_DECL_ALIGN (decl->csym, vd->alignment.get () * BITS_PER_UNIT);
1270 DECL_USER_ALIGN (decl->csym) = 1;
1273 if (vd->storage_class & STCextern)
1274 DECL_EXTERNAL (decl->csym) = 1;
1276 if (!vd->canTakeAddressOf ())
1278 /* Cannot make an expression out of a void initializer. */
1279 gcc_assert (vd->_init && !vd->_init->isVoidInitializer ());
1280 /* Non-scalar manifest constants have already been dealt with. */
1281 gcc_assert (vd->type->isscalar ());
1283 Expression *ie = initializerToExpression (vd->_init);
1284 DECL_INITIAL (decl->csym) = build_expr (ie, true);
1287 /* [type-qualifiers/const-and-immutable]
1289 `immutable` applies to data that cannot change. Immutable data values,
1290 once constructed, remain the same for the duration of the program's
1291 execution. */
1292 if (vd->isImmutable () && !vd->setInCtorOnly ())
1293 TREE_READONLY (decl->csym) = 1;
1295 /* `const` applies to data that cannot be changed by the const reference
1296 to that data. It may, however, be changed by another reference to that
1297 same data. */
1298 if (vd->isConst () && !vd->isDataseg ())
1299 TREE_READONLY (decl->csym) = 1;
1302 /* Set the declaration mangled identifier if static. */
1303 if (decl->isCodeseg () || decl->isDataseg ())
1305 tree mangled_name;
1307 if (decl->mangleOverride.length)
1309 mangled_name =
1310 get_identifier_with_length (decl->mangleOverride.ptr,
1311 decl->mangleOverride.length);
1313 else
1314 mangled_name = get_identifier (d_mangle_decl (decl));
1316 mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1317 mangled_name);
1318 /* The frontend doesn't handle duplicate definitions of unused symbols
1319 with the same mangle. So a check is done here instead. */
1320 if (IDENTIFIER_DSYMBOL (mangled_name))
1322 Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1323 tree olddecl = decl->csym;
1324 decl->csym = get_symbol_decl (other);
1326 /* Update the symbol location to the current definition. */
1327 if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1328 DECL_SOURCE_LOCATION (decl->csym) = DECL_SOURCE_LOCATION (olddecl);
1330 /* The current declaration is a prototype or marked extern, merge
1331 applied user attributes and return. */
1332 if (DECL_EXTERNAL (olddecl) && !DECL_INITIAL (olddecl))
1334 apply_user_attributes (decl, decl->csym);
1335 return decl->csym;
1337 /* The previous declaration is a prototype or marked extern, set the
1338 current declaration as the main reference of the symbol. */
1339 else if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1341 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1342 DECL_EXTERNAL (decl->csym) = 0;
1344 /* Non-extern, non-templated decls shouldn't be defined twice. */
1345 else if (!decl->isInstantiated ())
1346 ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1348 else
1350 IDENTIFIER_PRETTY_NAME (mangled_name)
1351 = get_identifier (decl->toPrettyChars (true));
1352 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1354 SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1358 DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1359 DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1361 if (TREE_CODE (decl->csym) == PARM_DECL)
1363 /* Pass non-trivial structs by invisible reference. */
1364 if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1366 tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1367 argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1368 gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1369 TREE_TYPE (decl->csym) = argtype;
1370 DECL_BY_REFERENCE (decl->csym) = 1;
1371 TREE_ADDRESSABLE (decl->csym) = 0;
1372 relayout_decl (decl->csym);
1373 decl->storage_class |= STCref;
1376 DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1377 gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1379 else if (TREE_CODE (decl->csym) == CONST_DECL)
1381 /* Manifest constants have no address in memory. */
1382 TREE_CONSTANT (decl->csym) = 1;
1383 TREE_READONLY (decl->csym) = 1;
1385 else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1387 /* Dual-context functions require the code generation to build an array
1388 for the context pointer of the function, making the delicate task of
1389 tracking which context to follow when encountering a non-local symbol,
1390 and so are a not planned to be supported. */
1391 if (fd->needThis () && !fd->isMember2 ())
1393 fatal_error (make_location_t (fd->loc),
1394 "function requires a dual-context, which is not yet "
1395 "supported by GDC");
1398 /* The real function type may differ from its declaration. */
1399 tree fntype = TREE_TYPE (decl->csym);
1400 tree newfntype = NULL_TREE;
1402 if (fd->isNested ())
1404 /* Add an extra argument for the frame/closure pointer, this is also
1405 required to be compatible with D delegates. */
1406 newfntype = build_vthis_function (void_type_node, fntype);
1408 else if (fd->isThis ())
1410 /* Add an extra argument for the `this' parameter. The handle type is
1411 used even if there is no debug info. It is needed to make sure
1412 virtual member functions are not called statically. */
1413 AggregateDeclaration *ad = fd->isMember2 ();
1414 tree handle = build_ctype (ad->handleType ());
1416 /* If handle is a pointer type, get record type. */
1417 if (!ad->isStructDeclaration ())
1418 handle = TREE_TYPE (handle);
1420 newfntype = build_vthis_function (handle, fntype);
1422 /* Set the vindex on virtual functions. */
1423 if (fd->isVirtual () && fd->vtblIndex != -1)
1425 DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1426 DECL_VIRTUAL_P (decl->csym) = 1;
1429 /* Align method to the minimum boundary for target. */
1430 SET_DECL_ALIGN (decl->csym, MINIMUM_METHOD_BOUNDARY);
1432 else if (fd->isMain () || fd->isCMain ())
1434 /* The main function is named `D main' to distinguish from C main. */
1435 if (fd->isMain ())
1436 DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1438 /* `void main' is implicitly converted to returning an int. */
1439 newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1442 if (newfntype != NULL_TREE)
1444 /* Copy the old attributes from the original type. */
1445 TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1446 TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1447 TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1448 TREE_TYPE (decl->csym) = newfntype;
1449 d_keep (newfntype);
1452 /* Miscellaneous function flags. */
1454 /* In [pragma/inline], functions decorated with `pragma(inline)' affects
1455 whether they are inlined or not. */
1456 if (fd->inlining == PINLINE::always)
1457 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1458 else if (fd->inlining == PINLINE::never)
1459 DECL_UNINLINABLE (decl->csym) = 1;
1461 /* In [pragma/crtctor], Annotates a function so it is run after the C
1462 runtime library is initialized and before the D runtime library is
1463 initialized. */
1464 if (fd->isCrtCtor ())
1466 DECL_STATIC_CONSTRUCTOR (decl->csym) = 1;
1467 decl_init_priority_insert (decl->csym, DEFAULT_INIT_PRIORITY);
1469 else if (fd->isCrtDtor ())
1471 DECL_STATIC_DESTRUCTOR (decl->csym) = 1;
1472 decl_fini_priority_insert (decl->csym, DEFAULT_INIT_PRIORITY);
1475 /* Function was declared `naked'. */
1476 if (fd->isNaked ())
1478 insert_decl_attribute (decl->csym, "naked");
1479 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1482 /* In [expression/function_literals], function literals (aka lambdas)
1483 enable embedding anonymous functions and anonymous delegates directly
1484 into expressions. They are defined in each referencing module. */
1485 if (fd->isFuncLiteralDeclaration ())
1486 DECL_SET_LAMBDA_FUNCTION (decl->csym, true);
1488 /* Mark compiler generated functions as artificial. */
1489 if (fd->isGenerated ())
1490 DECL_ARTIFICIAL (decl->csym) = 1;
1492 /* Ensure and require contracts are lexically nested in the function they
1493 part of, but are always publicly callable. */
1494 if (fd->ident == Identifier::idPool ("ensure")
1495 || fd->ident == Identifier::idPool ("require"))
1496 TREE_PUBLIC (decl->csym) = 1;
1498 if (decl->storage_class & STCfinal)
1499 DECL_FINAL_P (decl->csym) = 1;
1501 /* Function is of type `noreturn' or `typeof(*null)'. */
1502 if (fd->type->nextOf ()->isTypeNoreturn ())
1503 TREE_THIS_VOLATILE (decl->csym) = 1;
1505 /* Check whether this function is expanded by the frontend. */
1506 DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1507 maybe_set_intrinsic (fd);
1509 /* For nested functions in particular, unnest fndecl in the cgraph, as
1510 all static chain passing is handled by the front-end. Do this even
1511 if we are not emitting the body. */
1512 struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1513 if (nested_function_origin (node))
1514 unnest_function (node);
1517 /* Mark compiler generated temporaries as artificial. */
1518 if (decl->storage_class & STCtemp)
1519 DECL_ARTIFICIAL (decl->csym) = 1;
1521 /* Propagate shared on the decl. */
1522 if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1523 TREE_ADDRESSABLE (decl->csym) = 1;
1525 /* Symbol was marked volatile. */
1526 if (decl->storage_class & STCvolatile)
1527 TREE_THIS_VOLATILE (decl->csym) = 1;
1529 /* Symbol was marked register. */
1530 if (decl->storage_class & STCregister)
1531 DECL_REGISTER (decl->csym) = 1;
1533 /* Symbol was declared with deprecated attribute. */
1534 if (decl->storage_class & STCdeprecated)
1535 TREE_DEPRECATED (decl->csym) = 1;
1537 if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1539 /* Set TREE_PUBLIC by default, but allow private template to override. */
1540 if (!fd || !fd->isNested ())
1541 TREE_PUBLIC (decl->csym) = 1;
1543 TREE_STATIC (decl->csym) = 1;
1544 /* The decl has not been defined -- yet. */
1545 DECL_EXTERNAL (decl->csym) = 1;
1547 /* Visibility attributes are used by the debugger. */
1548 set_visibility_for_decl (decl->csym, decl);
1550 DECL_INSTANTIATED (decl->csym) = (decl->isInstantiated () != NULL);
1551 set_linkage_for_decl (decl->csym);
1554 /* Symbol is going in thread local storage. */
1555 if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1557 if (global.params.v.tls)
1558 message (decl->loc, "`%s` is thread local", decl->toChars ());
1560 set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1563 /* Apply any user attributes that may affect semantic meaning. */
1564 apply_user_attributes (decl, decl->csym);
1566 /* Handle any conflicts between D language attributes and compiler-recognized
1567 * user attributes. */
1568 if (VAR_P (decl->csym) && DECL_HARD_REGISTER (decl->csym))
1570 if (decl->storage_class & STCextern)
1571 error_at (make_location_t (decl->loc), "explicit register variable "
1572 "%qs declared %<extern%>", decl->toChars ());
1573 else if (decl->isThreadlocal ())
1574 error_at (make_location_t (decl->loc), "explicit register variable "
1575 "%qs declared thread local", decl->toChars ());
1578 /* %% Probably should be a little more intelligent about setting this. */
1579 TREE_USED (decl->csym) = 1;
1580 d_keep (decl->csym);
1582 return maybe_build_decl_tree (decl);
1585 /* Returns a declaration for a VAR_DECL. Used to create compiler-generated
1586 global variables. */
1588 tree
1589 declare_extern_var (tree ident, tree type)
1591 /* If the VAR_DECL has already been declared, return it. */
1592 if (IDENTIFIER_DECL_TREE (ident))
1593 return IDENTIFIER_DECL_TREE (ident);
1595 tree name = IDENTIFIER_PRETTY_NAME (ident)
1596 ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1597 tree decl = build_decl (input_location, VAR_DECL, name, type);
1599 IDENTIFIER_DECL_TREE (ident) = decl;
1600 d_keep (decl);
1602 SET_DECL_ASSEMBLER_NAME (decl, ident);
1603 DECL_ARTIFICIAL (decl) = 1;
1604 TREE_STATIC (decl) = 1;
1605 TREE_PUBLIC (decl) = 1;
1607 /* The decl has not been defined -- yet. */
1608 DECL_EXTERNAL (decl) = 1;
1610 set_linkage_for_decl (decl);
1612 return decl;
1615 /* Add local variable VAR into the current function body. */
1617 void
1618 declare_local_var (VarDeclaration *var)
1620 gcc_assert (!var->isDataseg () && !var->isMember ());
1621 gcc_assert (current_function_decl != NULL_TREE);
1623 FuncDeclaration *fd = cfun->language->function;
1624 tree decl = get_symbol_decl (var);
1626 gcc_assert (!TREE_STATIC (decl));
1627 d_pushdecl (decl);
1628 DECL_CONTEXT (decl) = current_function_decl;
1630 /* Compiler generated symbols. */
1631 if (var == fd->vresult || var == fd->v_argptr)
1632 DECL_ARTIFICIAL (decl) = 1;
1634 if (DECL_LANG_FRAME_FIELD (decl))
1636 /* Fixes debugging local variables. */
1637 SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1638 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1642 /* Return an unnamed local temporary of type TYPE. */
1644 tree
1645 build_local_temp (tree type)
1647 tree decl = create_tmp_var_raw (type);
1648 d_pushdecl (decl);
1650 return decl;
1653 /* Return the correct decl to be used for DECL. For VAR_DECLs, this could
1654 instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1655 value. For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1656 For all other kinds of decls, this just returns the result of
1657 get_symbol_decl(). */
1659 tree
1660 get_decl_tree (Declaration *decl)
1662 tree t = get_symbol_decl (decl);
1663 FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1664 VarDeclaration *vd = decl->isVarDeclaration ();
1666 /* If cfun is NULL, then this is a global static. */
1667 if (vd == NULL || fd == NULL)
1668 return t;
1670 /* Get the closure holding the var decl. */
1671 if (DECL_LANG_FRAME_FIELD (t))
1673 FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1674 tree frame_ref = get_framedecl (fd, parent);
1676 tree field = component_ref (build_deref (frame_ref),
1677 DECL_LANG_FRAME_FIELD (t));
1678 /* Frame field can also be a reference to the DECL_RESULT of a function.
1679 Dereference it to get the value. */
1680 if (DECL_LANG_NRVO (t))
1681 field = build_deref (field);
1683 return field;
1686 /* Get the named return value. */
1687 if (DECL_LANG_NRVO (t))
1688 return DECL_LANG_NRVO (t);
1690 /* Get the non-local `this' value by going through parent link
1691 of nested classes, this routine pretty much undoes what
1692 getRightThis in the frontend removes from codegen. */
1693 if (vd->parent != fd && vd->isThisDeclaration ())
1695 /* Find the first parent that is a member function. */
1696 while (!fd->isMember2 ())
1698 gcc_assert (fd->vthis);
1699 fd = fd->toParent2 ()->isFuncDeclaration ();
1700 gcc_assert (fd != NULL);
1703 AggregateDeclaration *ad = fd->isThis ();
1704 gcc_assert (ad != NULL);
1706 /* The parent function is for the same `this' declaration we are
1707 building a chain to. Non-local declaration is inaccessible. */
1708 if (fd->vthis == vd)
1709 return error_no_frame_access (fd);
1711 t = get_decl_tree (fd->vthis);
1712 Dsymbol *outer = fd;
1714 while (outer != vd->parent)
1716 gcc_assert (ad != NULL);
1717 outer = ad->toParent2 ();
1719 /* Get the this->this parent link. */
1720 tree vfield = get_symbol_decl (ad->vthis);
1721 t = component_ref (build_deref (t), vfield);
1723 ad = outer->isAggregateDeclaration ();
1724 if (ad != NULL)
1725 continue;
1727 fd = outer->isFuncDeclaration ();
1728 while (fd != NULL)
1730 /* If outer function creates a closure, then the `this'
1731 value would be the closure pointer, and the real
1732 `this' the first field of that closure. */
1733 tree ff = get_frameinfo (fd);
1734 if (FRAMEINFO_CREATES_FRAME (ff))
1736 t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1737 t = indirect_ref (build_ctype (fd->vthis->type), t);
1740 if (fd == vd->parent)
1741 break;
1743 /* Continue looking for the right `this'. */
1744 outer = outer->toParent2 ();
1745 fd = outer->isFuncDeclaration ();
1748 ad = outer->isAggregateDeclaration ();
1751 return t;
1754 /* Auto variable that the back end will handle for us. */
1755 return t;
1758 /* Finish up a variable declaration and compile it all the way to
1759 the assembler language output. */
1761 void
1762 d_finish_decl (tree decl)
1764 gcc_assert (!error_operand_p (decl));
1766 /* We are sending this symbol to object file, can't be extern. */
1767 TREE_STATIC (decl) = 1;
1768 DECL_EXTERNAL (decl) = 0;
1770 /* Update the TLS model as the linkage has been modified. */
1771 if (DECL_THREAD_LOCAL_P (decl))
1772 set_decl_tls_model (decl, decl_default_tls_model (decl));
1774 relayout_decl (decl);
1776 if (flag_checking && DECL_INITIAL (decl))
1778 /* Initializer must never be bigger than symbol size. */
1779 HOST_WIDE_INT tsize = int_size_in_bytes (TREE_TYPE (decl));
1780 HOST_WIDE_INT dtsize =
1781 int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1783 if (tsize < dtsize)
1785 tree name = DECL_ASSEMBLER_NAME (decl);
1787 internal_error ("mismatch between declaration %qE size (%wd) and "
1788 "its initializer size (%wd)",
1789 IDENTIFIER_PRETTY_NAME (name)
1790 ? IDENTIFIER_PRETTY_NAME (name) : name,
1791 tsize, dtsize);
1795 /* Without weak symbols, symbol should be put in .common, but that can't
1796 be done if there is a nonzero initializer. */
1797 if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1798 && initializer_zerop (DECL_INITIAL (decl)))
1799 DECL_INITIAL (decl) = error_mark_node;
1801 /* Add this decl to the current binding level. */
1802 d_pushdecl (decl);
1804 rest_of_decl_compilation (decl, 1, 0);
1807 /* Thunk code is based on g++. */
1809 static int thunk_labelno;
1811 /* Create a static alias to function. */
1813 static tree
1814 make_alias_for_thunk (tree function)
1816 tree alias;
1817 char buf[256];
1819 /* Thunks may reference extern functions which cannot be aliased. */
1820 if (DECL_EXTERNAL (function))
1821 return function;
1823 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1824 thunk_labelno++;
1826 alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1827 get_identifier (buf), TREE_TYPE (function));
1828 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1829 lang_hooks.dup_lang_specific_decl (alias);
1830 DECL_CONTEXT (alias) = NULL_TREE;
1831 TREE_READONLY (alias) = TREE_READONLY (function);
1832 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1833 TREE_PUBLIC (alias) = 0;
1835 DECL_EXTERNAL (alias) = 0;
1836 DECL_ARTIFICIAL (alias) = 1;
1838 DECL_DECLARED_INLINE_P (alias) = 0;
1839 DECL_INITIAL (alias) = error_mark_node;
1840 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1842 TREE_ADDRESSABLE (alias) = 1;
1843 TREE_USED (alias) = 1;
1844 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1846 if (!flag_syntax_only)
1848 cgraph_node *aliasn;
1849 aliasn = cgraph_node::create_same_body_alias (alias, function);
1850 gcc_assert (aliasn != NULL);
1852 return alias;
1855 /* Emit the definition of a D vtable thunk. */
1857 static void
1858 finish_thunk (tree thunk, tree function)
1860 /* Setup how D thunks are outputted. */
1861 int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1862 bool this_adjusting = true;
1863 tree alias;
1865 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1866 alias = make_alias_for_thunk (function);
1867 else
1868 alias = function;
1870 TREE_ADDRESSABLE (function) = 1;
1871 TREE_USED (function) = 1;
1872 DECL_EXTERNAL (thunk) = 0;
1874 if (flag_syntax_only)
1876 TREE_ASM_WRITTEN (thunk) = 1;
1877 return;
1880 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1881 && targetm_common.have_named_sections)
1883 tree fn = function;
1884 symtab_node *symbol = symtab_node::get (function);
1886 if (symbol != NULL && symbol->alias)
1888 if (symbol->analyzed)
1889 fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1890 else
1891 fn = symtab_node::get (function)->alias_target;
1893 resolve_unique_section (fn, 0, flag_function_sections);
1895 if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1897 resolve_unique_section (thunk, 0, flag_function_sections);
1899 /* Output the thunk into the same section as function. */
1900 set_decl_section_name (thunk, fn);
1901 symtab_node::get (thunk)->implicit_section
1902 = symtab_node::get (fn)->implicit_section;
1906 /* Set up cloned argument trees for the thunk. */
1907 tree t = NULL_TREE;
1908 for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1910 tree x = copy_node (a);
1911 DECL_CHAIN (x) = t;
1912 DECL_CONTEXT (x) = thunk;
1913 SET_DECL_RTL (x, NULL);
1914 DECL_HAS_VALUE_EXPR_P (x) = 0;
1915 TREE_ADDRESSABLE (x) = 0;
1916 t = x;
1918 DECL_ARGUMENTS (thunk) = nreverse (t);
1919 TREE_ASM_WRITTEN (thunk) = 1;
1921 cgraph_node *funcn, *thunk_node;
1923 funcn = cgraph_node::get_create (function);
1924 gcc_assert (funcn);
1925 thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1926 fixed_offset, 0, 0, 0, alias);
1928 if (DECL_ONE_ONLY (function))
1929 thunk_node->add_to_same_comdat_group (funcn);
1932 /* Return a thunk to DECL. Thunks adjust the incoming `this' pointer by OFFSET.
1933 Adjustor thunks are created and pointers to them stored in the method entries
1934 in the vtable in order to set the this pointer to the start of the object
1935 instance corresponding to the implementing method. */
1937 tree
1938 make_thunk (FuncDeclaration *decl, int offset)
1940 tree function = get_symbol_decl (decl);
1942 if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1944 /* Build parameters for functions that are not being compiled,
1945 so that they can be correctly cloned in finish_thunk. */
1946 tree function = get_symbol_decl (decl);
1947 DECL_ARGUMENTS (function) = get_fndecl_arguments (decl);
1949 /* Also build the result decl, which is needed when force creating
1950 the thunk in gimple inside cgraph_node::expand_thunk. */
1951 DECL_RESULT (function) = get_fndecl_result (decl);
1954 /* Don't build the thunk if the compilation step failed. */
1955 if (global.errors)
1956 return error_mark_node;
1958 /* See if we already have the thunk in question. */
1959 for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1961 if (THUNK_LANG_OFFSET (t) == offset)
1962 return t;
1965 tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1966 FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1967 DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1968 lang_hooks.dup_lang_specific_decl (thunk);
1969 THUNK_LANG_OFFSET (thunk) = offset;
1971 TREE_READONLY (thunk) = TREE_READONLY (function);
1972 TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
1973 TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
1975 DECL_CONTEXT (thunk) = d_decl_context (decl);
1977 /* Thunks inherit the public access of the function they are targeting. */
1978 TREE_PUBLIC (thunk) = TREE_PUBLIC (function);
1979 /* The thunk has not been defined -- yet. */
1980 DECL_EXTERNAL (thunk) = 1;
1982 /* Thunks are always addressable. */
1983 TREE_ADDRESSABLE (thunk) = 1;
1984 TREE_USED (thunk) = 1;
1985 DECL_ARTIFICIAL (thunk) = 1;
1986 DECL_DECLARED_INLINE_P (thunk) = 0;
1988 if (TREE_PUBLIC (thunk))
1990 DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
1991 DECL_COMDAT (thunk) = DECL_COMDAT (function);
1992 DECL_WEAK (thunk) = DECL_WEAK (function);
1995 /* When the thunk is for an extern C++ function, let C++ do the thunk
1996 generation and just reference the symbol as extern, instead of
1997 forcing a D local thunk to be emitted. */
1998 const char *ident;
2000 if (decl->resolvedLinkage () == LINK::cpp)
2001 ident = target.cpp.thunkMangle (decl, offset);
2002 else
2004 tree target_name = DECL_ASSEMBLER_NAME (function);
2005 unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
2006 ident = XNEWVEC (const char, identlen);
2008 snprintf (CONST_CAST (char *, ident), identlen,
2009 "_DTi%u%s", offset, IDENTIFIER_POINTER (target_name));
2012 DECL_NAME (thunk) = get_identifier (ident);
2013 SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
2015 d_keep (thunk);
2017 if (decl->resolvedLinkage () != LINK::cpp)
2018 free (CONST_CAST (char *, ident));
2020 /* Thunks are connected to the definitions of the functions, so thunks are
2021 not produced for external functions. */
2022 if (!DECL_EXTERNAL (function))
2023 finish_thunk (thunk, function);
2025 /* Add it to the list of thunks associated with the function. */
2026 DECL_LANG_THUNKS (thunk) = NULL_TREE;
2027 DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
2028 DECL_LANG_THUNKS (function) = thunk;
2030 return thunk;
2033 /* Create the FUNCTION_DECL for a function definition.
2034 This function creates a binding context for the function body
2035 as well as setting up the FUNCTION_DECL in current_function_decl.
2036 Returns the previous function context if it was already set. */
2038 tree
2039 start_function (FuncDeclaration *fd)
2041 tree fndecl = get_symbol_decl (fd);
2043 /* Function has been defined. Whether we intend to send it to object file, or
2044 discard it has already been determined by set_linkage_for_decl. */
2045 DECL_EXTERNAL (fndecl) = 0;
2046 DECL_INITIAL (fndecl) = error_mark_node;
2048 /* Add this decl to the current binding level. */
2049 d_pushdecl (fndecl);
2051 /* Save the current function context. */
2052 tree old_context = current_function_decl;
2054 if (old_context)
2055 push_function_context ();
2057 /* Let GCC know the current scope is this function. */
2058 current_function_decl = fndecl;
2060 /* Build the result decl before calling allocate_struct_function. */
2061 DECL_RESULT (fndecl) = get_fndecl_result (fd);
2063 /* Initialize the RTL code for the function. */
2064 allocate_struct_function (fndecl, false);
2066 /* Store the end of the function. */
2067 if (fd->endloc.filename ())
2068 cfun->function_end_locus = make_location_t (fd->endloc);
2069 else
2070 cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
2072 cfun->language = ggc_cleared_alloc <language_function> ();
2073 cfun->language->function = fd;
2075 /* Default chain value is `null' unless parent found. */
2076 cfun->language->static_chain = null_pointer_node;
2078 /* Find module for this function. */
2079 for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
2081 cfun->language->module = p->isModule ();
2082 if (cfun->language->module)
2083 break;
2085 gcc_assert (cfun->language->module != NULL);
2087 /* Begin the statement tree for this function. */
2088 push_stmt_list ();
2089 push_binding_level (level_function);
2091 return old_context;
2094 /* Finish up a function declaration and compile that function all
2095 the way to assembler language output. The free the storage for
2096 the function definition. Restores the previous function context. */
2098 void
2099 finish_function (tree old_context)
2101 tree fndecl = current_function_decl;
2103 /* Tie off the statement tree for this function. */
2104 tree block = pop_binding_level ();
2105 tree body = pop_stmt_list ();
2106 tree bind = build3 (BIND_EXPR, void_type_node,
2107 BLOCK_VARS (block), body, block);
2109 gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
2111 /* Back-end expects a statement list to come from somewhere, however
2112 pop_stmt_list returns expressions when there is a single statement.
2113 So here we create a statement list unconditionally. */
2114 if (TREE_CODE (body) != STATEMENT_LIST)
2116 tree stmtlist = alloc_stmt_list ();
2117 append_to_statement_list_force (body, &stmtlist);
2118 BIND_EXPR_BODY (bind) = stmtlist;
2120 else if (!STATEMENT_LIST_HEAD (body))
2122 /* For empty functions add a void return. */
2123 append_to_statement_list_force (return_expr (NULL_TREE), &body);
2126 DECL_SAVED_TREE (fndecl) = bind;
2128 /* Finish any forward referenced thunks for the function. */
2129 for (tree t = DECL_LANG_THUNKS (fndecl); t; t = DECL_CHAIN (t))
2130 finish_thunk (t, fndecl);
2132 if (!errorcount && !global.errors)
2134 /* Dump the D-specific tree IR. */
2135 dump_function (TDI_original, fndecl);
2137 cgraph_node::finalize_function (fndecl, true);
2140 /* We're leaving the context of this function, so free it. */
2141 ggc_free (cfun->language);
2142 cfun->language = NULL;
2143 set_cfun (NULL);
2145 if (old_context)
2146 pop_function_context ();
2148 current_function_decl = old_context;
2151 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
2152 must be emitted in this, output module. */
2154 static void
2155 d_mark_needed (tree decl)
2157 TREE_USED (decl) = 1;
2159 if (TREE_CODE (decl) == FUNCTION_DECL)
2161 struct cgraph_node *node = cgraph_node::get_create (decl);
2162 node->forced_by_abi = true;
2164 else if (VAR_P (decl))
2166 struct varpool_node *node = varpool_node::get_create (decl);
2167 node->forced_by_abi = true;
2171 /* Get the VAR_DECL of the vtable symbol for DECL. If this does not yet exist,
2172 create it. The vtable is accessible via ClassInfo, but since it is needed
2173 frequently (like for rtti comparisons), make it directly accessible. */
2175 tree
2176 get_vtable_decl (ClassDeclaration *decl)
2178 if (decl->vtblsym && decl->vtblsym->csym)
2179 return decl->vtblsym->csym;
2181 tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
2182 /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
2183 will have a different type. However the back-end seems to accept this. */
2184 tree type = build_ctype (Type::tvoidptr->sarrayOf (decl->vtbl.length));
2186 Dsymbol *vtblsym = decl->vtblSymbol ();
2187 vtblsym->csym = declare_extern_var (ident, type);
2188 DECL_LANG_SPECIFIC (vtblsym->csym) = build_lang_decl (NULL);
2190 /* Class is a reference, want the record type. */
2191 DECL_CONTEXT (vtblsym->csym) = TREE_TYPE (build_ctype (decl->type));
2192 TREE_READONLY (vtblsym->csym) = 1;
2193 DECL_VIRTUAL_P (vtblsym->csym) = 1;
2195 SET_DECL_ALIGN (vtblsym->csym, TARGET_VTABLE_ENTRY_ALIGN);
2196 DECL_USER_ALIGN (vtblsym->csym) = true;
2198 return vtblsym->csym;
2201 /* Helper function of build_class_instance. Find the field inside aggregate
2202 TYPE identified by IDENT at field OFFSET. */
2204 static tree
2205 find_aggregate_field (tree type, tree ident, tree offset)
2207 tree fields = TYPE_FIELDS (type);
2209 for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2211 if (DECL_NAME (field) == NULL_TREE
2212 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2213 && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2215 /* Search nesting anonymous structs and unions. */
2216 tree vfield = find_aggregate_field (TREE_TYPE (field),
2217 ident, offset);
2218 if (vfield != NULL_TREE)
2219 return vfield;
2221 else if (DECL_NAME (field) == ident
2222 && (offset == NULL_TREE
2223 || DECL_FIELD_OFFSET (field) == offset))
2225 /* Found matching field at offset. */
2226 return field;
2230 return NULL_TREE;
2233 /* Helper function of build_new_class_expr. Return a constructor that matches
2234 the layout of the class expression EXP. */
2236 static tree
2237 build_class_instance (ClassReferenceExp *exp)
2239 ClassDeclaration *cd = exp->originalClass ();
2240 tree type = TREE_TYPE (build_ctype (exp->value->stype));
2241 vec <constructor_elt, va_gc> *ve = NULL;
2243 /* The set base vtable field. */
2244 tree vptr = build_address (get_vtable_decl (cd));
2245 CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2247 /* Go through the inheritance graph from top to bottom. This will add all
2248 values to the constructor out of order, however build_struct_literal
2249 will re-order all values before returning the finished literal. */
2250 for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2252 /* Anonymous vtable interface fields are laid out before the fields of
2253 each class. The interface offset is used to determine where to put
2254 the classinfo offset reference. */
2255 for (size_t i = 0; i < bcd->vtblInterfaces->length; i++)
2257 BaseClass *bc = (*bcd->vtblInterfaces)[i];
2259 for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2261 gcc_assert (cd2 != NULL);
2263 unsigned csymoffset = base_vtable_offset (cd2, bc);
2264 /* If the base class vtable was found. */
2265 if (csymoffset != ~0u)
2267 tree csym = build_address (get_classinfo_decl (cd2));
2268 csym = build_offset (csym, size_int (csymoffset));
2270 tree field = find_aggregate_field (type, NULL_TREE,
2271 size_int (bc->offset));
2272 gcc_assert (field != NULL_TREE);
2274 CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2275 break;
2280 /* Generate initial values of all fields owned by current class.
2281 Use both the name and offset to find the right field. */
2282 for (size_t i = 0; i < bcd->fields.length; i++)
2284 VarDeclaration *vfield = bcd->fields[i];
2285 int index = exp->findFieldIndexByName (vfield);
2286 gcc_assert (index != -1);
2288 Expression *value = (*exp->value->elements)[index];
2289 if (!value)
2290 continue;
2292 /* Use find_aggregate_field to get the overridden field decl,
2293 instead of the field associated with the base class. */
2294 tree field = get_symbol_decl (bcd->fields[i]);
2295 field = find_aggregate_field (type, DECL_NAME (field),
2296 DECL_FIELD_OFFSET (field));
2297 gcc_assert (field != NULL_TREE);
2299 CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2303 return build_struct_literal (type, ve);
2306 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2307 If this does not yet exist, create it. This is used to support initializing
2308 a static variable that is of a class type using values known during CTFE.
2309 In user code, it is analogous to the following code snippet.
2311 enum E = new C(1, 2, 3);
2313 That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2314 implementation detail. The initialization of these symbols could be done at
2315 run-time using during as part of the module initialization or shared static
2316 constructors phase of run-time start-up - whichever comes after `gc_init()'.
2317 And infact that would be the better thing to do here eventually. */
2319 tree
2320 build_new_class_expr (ClassReferenceExp *expr)
2322 if (expr->value->sym)
2323 return expr->value->sym;
2325 /* Build the reference symbol. */
2326 tree type = build_ctype (expr->value->stype);
2327 expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2329 DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2330 d_pushdecl (expr->value->sym);
2331 rest_of_decl_compilation (expr->value->sym, 1, 0);
2333 return expr->value->sym;
2336 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2337 If this does not yet exist, create it. The static initializer data is
2338 accessible via TypeInfo, and is also used in `new class' and default
2339 initializing struct literals. */
2341 tree
2342 aggregate_initializer_decl (AggregateDeclaration *decl)
2344 if (decl->sinit)
2345 return (tree) decl->sinit;
2347 /* Class is a reference, want the record type. */
2348 tree type = build_ctype (decl->type);
2349 StructDeclaration *sd = decl->isStructDeclaration ();
2350 if (!sd)
2351 type = TREE_TYPE (type);
2353 tree ident = mangle_internal_decl (decl, "__init", "Z");
2355 tree sinit = declare_extern_var (ident, type);
2356 DECL_LANG_SPECIFIC (sinit) = build_lang_decl (NULL);
2358 DECL_CONTEXT (sinit) = type;
2359 TREE_READONLY (sinit) = 1;
2361 /* Honor struct alignment set by user. */
2362 if (sd && !sd->alignment.isDefault ())
2364 SET_DECL_ALIGN (sinit, sd->alignment.get () * BITS_PER_UNIT);
2365 DECL_USER_ALIGN (sinit) = true;
2368 decl->sinit = sinit;
2369 return sinit;
2372 /* Generate the data for the static initializer. */
2374 tree
2375 layout_class_initializer (ClassDeclaration *cd)
2377 NewExp *ne = NewExp::create (cd->loc, NULL, cd->type, NULL);
2378 ne->type = cd->type;
2380 Expression *e = ne->ctfeInterpret ();
2381 gcc_assert (e->op == EXP::classReference);
2383 return build_class_instance (e->isClassReferenceExp ());
2386 tree
2387 layout_struct_initializer (StructDeclaration *sd)
2389 StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2391 if (!sd->fill (sd->loc, *sle->elements, true))
2392 gcc_unreachable ();
2394 sle->type = sd->type;
2395 return build_expr (sle, true);
2398 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2399 If this does not yet exist, create it. The static initializer data is
2400 accessible via TypeInfo_Enum, but the field member type is a byte[] that
2401 requires a pointer to a symbol reference. */
2403 tree
2404 enum_initializer_decl (EnumDeclaration *decl)
2406 if (decl->sinit)
2407 return decl->sinit;
2409 gcc_assert (decl->ident);
2411 tree type = build_ctype (decl->type);
2412 tree ident = mangle_internal_decl (decl, "__init", "Z");
2414 decl->sinit = declare_extern_var (ident, type);
2415 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2417 DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2418 TREE_READONLY (decl->sinit) = 1;
2420 return decl->sinit;
2423 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2424 and optionally prefixing the name with PREFIX. */
2426 tree
2427 build_artificial_decl (tree type, tree init, const char *prefix)
2429 tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2430 const char *name = prefix ? prefix : "___s";
2431 char *label;
2433 ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2434 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2435 DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2437 TREE_PUBLIC (decl) = 0;
2438 TREE_STATIC (decl) = 1;
2439 TREE_USED (decl) = 1;
2440 DECL_IGNORED_P (decl) = 1;
2441 DECL_ARTIFICIAL (decl) = 1;
2443 /* Perhaps at some point the initializer constant should be hashed
2444 to remove duplicates. */
2445 DECL_INITIAL (decl) = init;
2447 return decl;
2450 /* Build TYPE_DECL for the declaration DSYM. */
2452 void
2453 build_type_decl (tree type, Dsymbol *dsym)
2455 if (TYPE_STUB_DECL (type))
2456 return;
2458 /* If a templated type, use the template instance name, as that includes all
2459 template parameters. */
2460 const char *name = dsym->parent->isTemplateInstance ()
2461 ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2463 tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2464 get_identifier (name), type);
2465 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (d_mangle_decl (dsym)));
2466 TREE_PUBLIC (decl) = 1;
2467 DECL_CONTEXT (decl) = d_decl_context (dsym);
2469 TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2470 TYPE_NAME (type) = decl;
2472 /* Not sure if there is a need for separate TYPE_DECLs in
2473 TYPE_NAME and TYPE_STUB_DECL. */
2474 if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2476 DECL_ARTIFICIAL (decl) = 1;
2477 TYPE_STUB_DECL (type) = decl;
2479 else if (type != TYPE_MAIN_VARIANT (type))
2480 DECL_ORIGINAL_TYPE (decl) = TYPE_MAIN_VARIANT (type);
2483 /* Create a declaration for field NAME of a given TYPE, setting the flags
2484 for whether the field is ARTIFICIAL and/or IGNORED. */
2486 tree
2487 create_field_decl (tree type, const char *name, int artificial, int ignored)
2489 tree decl = build_decl (input_location, FIELD_DECL,
2490 name ? get_identifier (name) : NULL_TREE, type);
2491 DECL_ARTIFICIAL (decl) = artificial;
2492 DECL_IGNORED_P (decl) = ignored;
2494 return decl;
2497 /* Return the COMDAT group into which DECL should be placed. */
2499 static tree
2500 d_comdat_group (tree decl)
2502 /* If already part of a comdat group, use that. */
2503 if (DECL_COMDAT_GROUP (decl))
2504 return DECL_COMDAT_GROUP (decl);
2506 return DECL_ASSEMBLER_NAME (decl);
2509 /* Set DECL up to have the closest approximation of "initialized common"
2510 linkage available. */
2512 static void
2513 d_comdat_linkage (tree decl)
2515 /* COMDAT definitions have to be public. */
2516 gcc_assert (TREE_PUBLIC (decl));
2518 if (supports_one_only ())
2519 make_decl_one_only (decl, d_comdat_group (decl));
2520 else if ((TREE_CODE (decl) == FUNCTION_DECL && DECL_INSTANTIATED (decl))
2521 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2522 /* We can just emit function and compiler-generated variables statically;
2523 having multiple copies is (for the most part) only a waste of space. */
2524 TREE_PUBLIC (decl) = 0;
2525 else if (DECL_INITIAL (decl) == NULL_TREE
2526 || DECL_INITIAL (decl) == error_mark_node)
2527 /* Fallback, cannot have multiple copies. */
2528 DECL_COMMON (decl) = 1;
2530 if (TREE_PUBLIC (decl) && DECL_INSTANTIATED (decl))
2531 DECL_COMDAT (decl) = 1;
2534 /* Set DECL up to have the closest approximation of "weak" linkage. */
2536 static void
2537 d_weak_linkage (tree decl)
2539 /* Weak definitions have to be public. */
2540 gcc_assert (TREE_PUBLIC (decl));
2542 /* Allow comdat linkage to be forced with the flag `-fno-weak-templates'. */
2543 if (!flag_weak_templates || !TARGET_SUPPORTS_WEAK)
2544 return d_comdat_linkage (decl);
2546 declare_weak (decl);
2549 /* DECL is a FUNCTION_DECL or a VAR_DECL with static storage. Set flags to
2550 reflect the linkage that DECL will receive in the object file. */
2552 void
2553 set_linkage_for_decl (tree decl)
2555 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl) && TREE_STATIC (decl));
2557 /* Non-public decls keep their internal linkage. */
2558 if (!TREE_PUBLIC (decl))
2559 return;
2561 /* Function literals and functions declared as `pragma(inline, true)' can
2562 appear in multiple translation units. */
2563 if (TREE_CODE (decl) == FUNCTION_DECL
2564 && (DECL_DECLARED_INLINE_P (decl) || DECL_LAMBDA_FUNCTION_P (decl)))
2565 return d_comdat_linkage (decl);
2567 /* Don't need to give private or protected symbols a special linkage. */
2568 if ((TREE_PRIVATE (decl) || TREE_PROTECTED (decl))
2569 && !DECL_INSTANTIATED (decl))
2570 return;
2572 /* If all instantiations must go in COMDAT, give them that linkage.
2573 This also applies to other extern declarations, so that it is possible
2574 for them to override template declarations. */
2575 if (targetdm.d_templates_always_comdat)
2577 /* Make sure that instantiations are not removed. */
2578 if (flag_weak_templates && DECL_INSTANTIATED (decl))
2579 d_mark_needed (decl);
2581 return d_comdat_linkage (decl);
2584 /* Instantiated variables and functions need to be overridable by any other
2585 symbol with the same name, so give them weak linkage. */
2586 if (DECL_INSTANTIATED (decl))
2587 return d_weak_linkage (decl);
2589 /* Compiler generated public symbols can appear in multiple contexts. */
2590 if (DECL_ARTIFICIAL (decl))
2591 return d_weak_linkage (decl);
2594 /* NODE is a FUNCTION_DECL, VAR_DECL or RECORD_TYPE for the declaration SYM.
2595 Set flags to reflect visibility that NODE will get in the object file. */
2597 void
2598 set_visibility_for_decl (tree node, Dsymbol *sym)
2600 Visibility visibility = sym->visible ();
2601 if (visibility.kind == Visibility::private_)
2602 TREE_PRIVATE (node) = 1;
2603 else if (visibility.kind == Visibility::protected_)
2604 TREE_PROTECTED (node) = 1;
2606 /* If the declaration was declared `export', append either the dllimport
2607 or dllexport attribute. */
2608 if (TARGET_DLLIMPORT_DECL_ATTRIBUTES)
2610 const char *attrname = NULL;
2612 /* Have to test for import first. */
2613 if (sym->isImportedSymbol ())
2614 attrname = "dllimport";
2615 else if (sym->isExport ())
2616 attrname = "dllexport";
2618 if (attrname != NULL)
2620 if (DECL_P (node))
2621 insert_decl_attribute (node, attrname);
2622 else if (TYPE_P (node))
2623 insert_type_attribute (node, attrname);