RISC-V: Fix rtl checking enabled failure with -msave-restore.
[official-gcc.git] / gcc / d / decl.cc
blob3824060feb9ddbc7e402a45737f26358a6ee4713
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2 Copyright (C) 2006-2020 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"
57 #include "d-tree.h"
60 /* Return identifier for the external mangled name of DECL. */
62 static const char *
63 mangle_decl (Dsymbol *decl)
65 if (decl->isFuncDeclaration ())
66 return mangleExact ((FuncDeclaration *)decl);
67 else
69 OutBuffer buf;
70 mangleToBuffer (decl, &buf);
71 return buf.extractString ();
75 /* Generate a mangled identifier using NAME and SUFFIX, prefixed by the
76 assembler name for DECL. */
78 tree
79 mangle_internal_decl (Dsymbol *decl, const char *name, const char *suffix)
81 const char *prefix = mangle_decl (decl);
82 unsigned namelen = strlen (name);
83 unsigned buflen = (2 + strlen (prefix) + namelen + strlen (suffix)) * 2;
84 char *buf = (char *) alloca (buflen);
86 snprintf (buf, buflen, "_D%s%u%s%s", prefix, namelen, name, suffix);
87 tree ident = get_identifier (buf);
89 /* Symbol is not found in user code, but generate a readable name for it
90 anyway for debug and diagnostic reporting. */
91 snprintf (buf, buflen, "%s.%s", decl->toPrettyChars (), name);
92 IDENTIFIER_PRETTY_NAME (ident) = get_identifier (buf);
94 return ident;
97 /* Returns true if DECL is from the gcc.attribute module. */
99 static bool
100 gcc_attribute_p (Dsymbol *decl)
102 ModuleDeclaration *md = decl->getModule ()->md;
104 if (md && md->packages && md->packages->dim == 1)
106 if (!strcmp ((*md->packages)[0]->toChars (), "gcc")
107 && !strcmp (md->id->toChars (), "attribute"))
108 return true;
111 return false;
114 /* Implements the visitor interface to lower all Declaration AST classes
115 emitted from the D Front-end to GCC trees.
116 All visit methods accept one parameter D, which holds the frontend AST
117 of the declaration to compile. These also don't return any value, instead
118 generated code are appened to global_declarations or added to the
119 current_binding_level by d_pushdecl(). */
121 class DeclVisitor : public Visitor
123 using Visitor::visit;
125 /* If we're lowering the body of a version(unittest) condition. */
126 bool in_version_unittest_;
128 public:
129 DeclVisitor (void)
131 this->in_version_unittest_ = false;
134 /* This should be overridden by each declaration class. */
136 void visit (Dsymbol *)
140 /* Compile a D module, and all members of it. */
142 void visit (Module *d)
144 if (d->semanticRun >= PASSobj)
145 return;
147 build_module_tree (d);
148 d->semanticRun = PASSobj;
151 /* Write the imported symbol to debug. */
153 void visit (Import *d)
155 if (d->semanticRun >= PASSobj)
156 return;
158 /* Implements import declarations by telling the debug back-end we are
159 importing the NAMESPACE_DECL of the module or IMPORTED_DECL of the
160 declaration into the current lexical scope CONTEXT. NAME is set if
161 this is a renamed import. */
162 if (d->isstatic)
163 return;
165 /* Get the context of this import, this should never be null. */
166 tree context = d_module_context ();
168 if (d->ident == NULL)
170 /* Importing declaration list. */
171 for (size_t i = 0; i < d->names.dim; i++)
173 AliasDeclaration *aliasdecl = d->aliasdecls[i];
174 tree decl = build_import_decl (aliasdecl);
176 /* Skip over unhandled imports. */
177 if (decl == NULL_TREE)
178 continue;
180 Identifier *alias = d->aliases[i];
181 tree name = (alias != NULL)
182 ? get_identifier (alias->toChars ()) : NULL_TREE;
184 debug_hooks->imported_module_or_decl (decl, name, context,
185 false, false);
188 else
190 /* Importing the entire module. */
191 tree decl = build_import_decl (d->mod);
193 tree name = (d->aliasId != NULL)
194 ? get_identifier (d->aliasId->toChars ()) : NULL_TREE;
196 debug_hooks->imported_module_or_decl (decl, name, context,
197 false, false);
200 d->semanticRun = PASSobj;
203 /* Expand any local variables found in tuples. */
205 void visit (TupleDeclaration *d)
207 for (size_t i = 0; i < d->objects->dim; i++)
209 RootObject *o = (*d->objects)[i];
210 if ((o->dyncast () == DYNCAST_EXPRESSION)
211 && ((Expression *) o)->op == TOKdsymbol)
213 Declaration *d = ((DsymbolExp *) o)->s->isDeclaration ();
214 if (d)
215 d->accept (this);
220 /* Walk over all declarations in the attribute scope. */
222 void visit (AttribDeclaration *d)
224 Dsymbols *ds = d->include (NULL, NULL);
226 if (!ds)
227 return;
229 for (size_t i = 0; i < ds->dim; i++)
231 Dsymbol *s = (*ds)[i];
232 s->accept (this);
236 /* Pragmas are a way to pass special information to the compiler and to add
237 vendor specific extensions to D. We don't do anything here, yet. */
239 void visit (PragmaDeclaration *d)
241 if (!global.params.ignoreUnsupportedPragmas)
243 if (d->ident == Identifier::idPool ("lib")
244 || d->ident == Identifier::idPool ("startaddress"))
246 warning_at (make_location_t (d->loc), OPT_Wunknown_pragmas,
247 "pragma(%s) not implemented", d->ident->toChars ());
251 visit ((AttribDeclaration *) d);
254 /* Conditional compilation is the process of selecting which code to compile
255 and which code to not compile. Look for version conditions that may */
257 void visit (ConditionalDeclaration *d)
259 bool old_condition = this->in_version_unittest_;
261 if (global.params.useUnitTests)
263 VersionCondition *vc = d->condition->isVersionCondition ();
264 if (vc && vc->ident == Identifier::idPool ("unittest"))
265 this->in_version_unittest_ = true;
268 visit ((AttribDeclaration *) d);
270 this->in_version_unittest_ = old_condition;
273 /* Walk over all members in the namespace scope. */
275 void visit (Nspace *d)
277 if (isError (d) || !d->members)
278 return;
280 for (size_t i = 0; i < d->members->dim; i++)
282 Dsymbol *s = (*d->members)[i];
283 s->accept (this);
287 /* Templates are D's approach to generic programming. They have no members
288 that can be emitted, however if the template is nested and used as a
289 voldemort type, then it's members must be compiled before the parent
290 function finishes. */
292 void visit (TemplateDeclaration *d)
294 /* Type cannot be directly named outside of the scope it's declared in, so
295 the only way it can be escaped is if the function has auto return. */
296 FuncDeclaration *fd = d_function_chain ? d_function_chain->function : NULL;
298 if (!fd || !fd->isAuto ())
299 return;
301 /* Check if the function returns an instantiated type that may contain
302 nested members. Only applies to classes or structs. */
303 Type *tb = fd->type->nextOf ()->baseElemOf ();
305 while (tb->ty == Tarray || tb->ty == Tpointer)
306 tb = tb->nextOf ()->baseElemOf ();
308 TemplateInstance *ti = NULL;
310 if (tb->ty == Tstruct)
311 ti = ((TypeStruct *) tb)->sym->isInstantiated ();
312 else if (tb->ty == Tclass)
313 ti = ((TypeClass *) tb)->sym->isInstantiated ();
315 /* Return type is instantiated from this template declaration, walk over
316 all members of the instance. */
317 if (ti && ti->tempdecl == d)
318 ti->accept (this);
321 /* Walk over all members in the instantiated template. */
323 void visit (TemplateInstance *d)
325 if (isError (d)|| !d->members)
326 return;
328 if (!d->needsCodegen ())
329 return;
331 for (size_t i = 0; i < d->members->dim; i++)
333 Dsymbol *s = (*d->members)[i];
334 s->accept (this);
338 /* Walk over all members in the mixin template scope. */
340 void visit (TemplateMixin *d)
342 if (isError (d)|| !d->members)
343 return;
345 for (size_t i = 0; i < d->members->dim; i++)
347 Dsymbol *s = (*d->members)[i];
348 s->accept (this);
352 /* Write out compiler generated TypeInfo, initializer and functions for the
353 given struct declaration, walking over all static members. */
355 void visit (StructDeclaration *d)
357 if (d->semanticRun >= PASSobj)
358 return;
360 if (d->type->ty == Terror)
362 error_at (make_location_t (d->loc),
363 "had semantic errors when compiling");
364 return;
367 /* Add this decl to the current binding level. */
368 tree ctype = build_ctype (d->type);
369 if (TYPE_NAME (ctype))
370 d_pushdecl (TYPE_NAME (ctype));
372 /* Anonymous structs/unions only exist as part of others,
373 do not output forward referenced structs. */
374 if (d->isAnonymous () || !d->members)
375 return;
377 /* Don't emit any symbols from gcc.attribute module. */
378 if (gcc_attribute_p (d))
379 return;
381 /* Generate TypeInfo. */
382 if (have_typeinfo_p (Type::dtypeinfo))
383 create_typeinfo (d->type, NULL);
385 /* Generate static initializer. */
386 d->sinit = aggregate_initializer_decl (d);
387 DECL_INITIAL (d->sinit) = layout_struct_initializer (d);
389 if (d->isInstantiated ())
390 d_linkonce_linkage (d->sinit);
392 d_finish_decl (d->sinit);
394 /* Put out the members. */
395 for (size_t i = 0; i < d->members->dim; i++)
397 Dsymbol *member = (*d->members)[i];
398 /* There might be static ctors in the members, and they cannot
399 be put in separate object files. */
400 member->accept (this);
403 /* Put out xopEquals, xopCmp and xopHash. */
404 if (d->xeq && d->xeq != d->xerreq)
405 d->xeq->accept (this);
407 if (d->xcmp && d->xcmp != d->xerrcmp)
408 d->xcmp->accept (this);
410 if (d->xhash)
411 d->xhash->accept (this);
413 d->semanticRun = PASSobj;
416 /* Finish semantic analysis of functions in vtbl for class CD. */
418 bool finish_vtable (ClassDeclaration *d)
420 bool has_errors = false;
422 /* Finish semantic analysis of functions in vtbl[]. */
423 for (size_t i = d->vtblOffset (); i < d->vtbl.dim; i++)
425 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
427 if (!fd || (!fd->fbody && d->isAbstract ()))
428 continue;
430 /* Ensure function has a return value. */
431 if (!fd->functionSemantic ())
432 has_errors = true;
434 /* No name hiding to check for. */
435 if (!d->isFuncHidden (fd) || fd->isFuture ())
436 continue;
438 /* The function fd is hidden from the view of the class.
439 If it overlaps with any function in the vtbl[], then
440 issue an error. */
441 for (size_t j = 1; j < d->vtbl.dim; j++)
443 if (j == i)
444 continue;
446 FuncDeclaration *fd2 = d->vtbl[j]->isFuncDeclaration ();
447 if (!fd2->ident->equals (fd->ident))
448 continue;
450 /* The function is marked as @__future, a deprecation has
451 already been given by the frontend. */
452 if (fd2->isFuture ())
453 continue;
455 if (fd->leastAsSpecialized (fd2) || fd2->leastAsSpecialized (fd))
457 TypeFunction *tf = (TypeFunction *) fd->type;
458 if (tf->ty == Tfunction)
460 error_at (make_location_t (fd->loc), "use of %qs",
461 fd->toPrettyChars ());
462 inform (make_location_t (fd2->loc), "is hidden by %qs",
463 fd2->toPrettyChars ());
464 inform (make_location_t (d->loc),
465 "use %<alias %s = %s.%s;%> to introduce base class "
466 "overload set", fd->toChars (),
467 fd->parent->toChars (), fd->toChars ());
469 else
471 error_at (make_location_t (fd->loc), "use of %qs",
472 fd->toPrettyChars ());
473 inform (make_location_t (fd2->loc), "is hidden by %qs",
474 fd2->toPrettyChars ());
477 has_errors = true;
478 break;
483 return !has_errors;
486 /* Write out compiler generated TypeInfo, initializer and vtables for the
487 given class declaration, walking over all static members. */
489 void visit (ClassDeclaration *d)
491 if (d->semanticRun >= PASSobj)
492 return;
494 if (d->type->ty == Terror)
496 error_at (make_location_t (d->loc),
497 "had semantic errors when compiling");
498 return;
501 if (!d->members)
502 return;
504 /* Put out the members. */
505 for (size_t i = 0; i < d->members->dim; i++)
507 Dsymbol *member = (*d->members)[i];
508 member->accept (this);
511 /* If something goes wrong during final semantic pass, don't bother with
512 the rest as we may have incomplete info. */
513 if (!this->finish_vtable (d))
514 return;
516 /* Generate C symbols. */
517 d->csym = get_classinfo_decl (d);
518 d->vtblsym = get_vtable_decl (d);
519 d->sinit = aggregate_initializer_decl (d);
521 /* Generate static initializer. */
522 DECL_INITIAL (d->sinit) = layout_class_initializer (d);
523 d_linkonce_linkage (d->sinit);
524 d_finish_decl (d->sinit);
526 /* Put out the TypeInfo. */
527 if (have_typeinfo_p (Type::dtypeinfo))
528 create_typeinfo (d->type, NULL);
530 DECL_INITIAL (d->csym) = layout_classinfo (d);
531 d_linkonce_linkage (d->csym);
532 d_finish_decl (d->csym);
534 /* Put out the vtbl[]. */
535 vec<constructor_elt, va_gc> *elms = NULL;
537 /* First entry is ClassInfo reference. */
538 if (d->vtblOffset ())
539 CONSTRUCTOR_APPEND_ELT (elms, size_zero_node, build_address (d->csym));
541 for (size_t i = d->vtblOffset (); i < d->vtbl.dim; i++)
543 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
545 if (fd && (fd->fbody || !d->isAbstract()))
547 CONSTRUCTOR_APPEND_ELT (elms, size_int (i),
548 build_address (get_symbol_decl (fd)));
552 DECL_INITIAL (d->vtblsym)
553 = build_constructor (TREE_TYPE (d->vtblsym), elms);
554 d_comdat_linkage (d->vtblsym);
555 d_finish_decl (d->vtblsym);
557 /* Add this decl to the current binding level. */
558 tree ctype = TREE_TYPE (build_ctype (d->type));
559 if (TYPE_NAME (ctype))
560 d_pushdecl (TYPE_NAME (ctype));
562 d->semanticRun = PASSobj;
565 /* Write out compiler generated TypeInfo and vtables for the given interface
566 declaration, walking over all static members. */
568 void visit (InterfaceDeclaration *d)
570 if (d->semanticRun >= PASSobj)
571 return;
573 if (d->type->ty == Terror)
575 error_at (make_location_t (d->loc),
576 "had semantic errors when compiling");
577 return;
580 if (!d->members)
581 return;
583 /* Put out the members. */
584 for (size_t i = 0; i < d->members->dim; i++)
586 Dsymbol *member = (*d->members)[i];
587 member->accept (this);
590 /* Generate C symbols. */
591 d->csym = get_classinfo_decl (d);
593 /* Put out the TypeInfo. */
594 if (have_typeinfo_p (Type::dtypeinfo))
596 create_typeinfo (d->type, NULL);
597 d->type->vtinfo->accept (this);
600 DECL_INITIAL (d->csym) = layout_classinfo (d);
601 d_linkonce_linkage (d->csym);
602 d_finish_decl (d->csym);
604 /* Add this decl to the current binding level. */
605 tree ctype = TREE_TYPE (build_ctype (d->type));
606 if (TYPE_NAME (ctype))
607 d_pushdecl (TYPE_NAME (ctype));
609 d->semanticRun = PASSobj;
612 /* Write out compiler generated TypeInfo and initializer for the given
613 enum declaration. */
615 void visit (EnumDeclaration *d)
617 if (d->semanticRun >= PASSobj)
618 return;
620 if (d->errors || d->type->ty == Terror)
622 error_at (make_location_t (d->loc),
623 "had semantic errors when compiling");
624 return;
627 if (d->isAnonymous ())
628 return;
630 /* Generate TypeInfo. */
631 if (have_typeinfo_p (Type::dtypeinfo))
632 create_typeinfo (d->type, NULL);
634 TypeEnum *tc = (TypeEnum *) d->type;
635 if (tc->sym->members && !d->type->isZeroInit ())
637 /* Generate static initializer. */
638 d->sinit = enum_initializer_decl (d);
639 DECL_INITIAL (d->sinit) = build_expr (tc->sym->defaultval, true);
641 if (d->isInstantiated ())
642 d_linkonce_linkage (d->sinit);
644 d_finish_decl (d->sinit);
646 /* Add this decl to the current binding level. */
647 tree ctype = build_ctype (d->type);
648 if (TREE_CODE (ctype) == ENUMERAL_TYPE && TYPE_NAME (ctype))
649 d_pushdecl (TYPE_NAME (ctype));
652 d->semanticRun = PASSobj;
655 /* Finish up a variable declaration and push it into the current scope.
656 This can either be a static, local or manifest constant. */
658 void visit (VarDeclaration *d)
660 if (d->semanticRun >= PASSobj)
661 return;
663 if (d->type->ty == Terror)
665 error_at (make_location_t (d->loc),
666 "had semantic errors when compiling");
667 return;
670 if (d->aliassym)
672 d->toAlias ()->accept (this);
673 return;
676 /* Do not store variables we cannot take the address of,
677 but keep the values for purposes of debugging. */
678 if (!d->canTakeAddressOf ())
680 /* Don't know if there is a good way to handle instantiations. */
681 if (d->isInstantiated ())
682 return;
684 /* Cannot make an expression out of a void initializer. */
685 if (!d->_init || d->_init->isVoidInitializer ())
686 return;
688 tree decl = get_symbol_decl (d);
689 Expression *ie = initializerToExpression (d->_init);
691 /* CONST_DECL was initially intended for enumerals and may be used for
692 scalars in general, but not for aggregates. Here a non-constant
693 value is generated anyway so as the CONST_DECL only serves as a
694 placeholder for the value, however the DECL itself should never be
695 referenced in any generated code, or passed to the back-end. */
696 if (!d->type->isscalar ())
697 DECL_INITIAL (decl) = build_expr (ie, false);
698 else
700 DECL_INITIAL (decl) = build_expr (ie, true);
701 d_pushdecl (decl);
702 rest_of_decl_compilation (decl, 1, 0);
705 else if (d->isDataseg () && !(d->storage_class & STCextern))
707 tree decl = get_symbol_decl (d);
709 /* Duplicated VarDeclarations map to the same symbol. Check if this
710 is the one declaration which will be emitted. */
711 tree ident = DECL_ASSEMBLER_NAME (decl);
712 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
713 return;
715 /* How big a symbol can be should depend on back-end. */
716 tree size = build_integer_cst (d->type->size (d->loc),
717 build_ctype (Type::tsize_t));
718 if (!valid_constant_size_p (size))
720 error_at (make_location_t (d->loc), "size is too large");
721 return;
724 if (d->_init && !d->_init->isVoidInitializer ())
726 Expression *e = initializerToExpression (d->_init, d->type);
727 DECL_INITIAL (decl) = build_expr (e, true);
729 else
731 if (d->type->ty == Tstruct)
733 StructDeclaration *sd = ((TypeStruct *) d->type)->sym;
734 DECL_INITIAL (decl) = layout_struct_initializer (sd);
736 else
738 Expression *e = d->type->defaultInitLiteral (d->loc);
739 DECL_INITIAL (decl) = build_expr (e, true);
743 /* Frontend should have already caught this. */
744 gcc_assert (!integer_zerop (size)
745 || d->type->toBasetype ()->ty == Tsarray);
747 d_finish_decl (decl);
749 /* Maybe record the var against the current module. */
750 register_module_decl (d);
752 else if (!d->isDataseg () && !d->isMember ())
754 /* This is needed for VarDeclarations in mixins that are to be local
755 variables of a function. Otherwise, it would be enough to make
756 a check for isVarDeclaration() in DeclarationExp codegen. */
757 declare_local_var (d);
759 if (d->_init)
761 tree decl = get_symbol_decl (d);
763 if (!d->_init->isVoidInitializer ())
765 ExpInitializer *vinit = d->_init->isExpInitializer ();
766 Expression *ie = initializerToExpression (vinit);
767 tree exp = build_expr (ie);
769 /* Maybe put variable on list of things needing destruction. */
770 if (d->needsScopeDtor ())
772 vec_safe_push (d_function_chain->vars_in_scope, decl);
773 /* Force a TARGET_EXPR to add the corresponding cleanup. */
774 exp = force_target_expr (compound_expr (exp, decl));
775 TARGET_EXPR_CLEANUP (exp) = build_expr (d->edtor);
778 add_stmt (exp);
780 else if (d->size (d->loc) != 0)
782 /* Zero-length arrays do not have an initializer. */
783 warning (OPT_Wuninitialized, "uninitialized variable '%s'",
784 d->ident ? d->ident->toChars () : "(no name)");
789 d->semanticRun = PASSobj;
792 /* Generate and compile a static TypeInfo declaration, but only if it is
793 needed in the current compilation. */
795 void visit (TypeInfoDeclaration *d)
797 if (d->semanticRun >= PASSobj)
798 return;
800 if (speculative_type_p (d->tinfo))
801 return;
803 tree t = get_typeinfo_decl (d);
804 DECL_INITIAL (t) = layout_typeinfo (d);
805 d_finish_decl (t);
806 d->semanticRun = PASSobj;
809 /* Finish up a function declaration and compile it all the way
810 down to assembler language output. */
812 void visit (FuncDeclaration *d)
814 /* Already generated the function. */
815 if (d->semanticRun >= PASSobj)
816 return;
818 /* Don't emit any symbols from gcc.attribute module. */
819 if (gcc_attribute_p (d))
820 return;
822 /* Not emitting unittest functions. */
823 if (!global.params.useUnitTests && d->isUnitTestDeclaration ())
824 return;
826 /* Check if any errors occurred when running semantic. */
827 if (d->type->ty == Tfunction)
829 TypeFunction *tf = (TypeFunction *) d->type;
830 if (tf->next == NULL || tf->next->ty == Terror)
831 return;
834 if (d->semantic3Errors)
835 return;
837 if (d->isNested ())
839 FuncDeclaration *fdp = d;
840 while (fdp && fdp->isNested ())
842 fdp = fdp->toParent2 ()->isFuncDeclaration ();
844 if (fdp == NULL)
845 break;
847 /* Parent failed to compile, but errors were gagged. */
848 if (fdp->semantic3Errors)
849 return;
853 /* Ensure all semantic passes have run. */
854 if (d->semanticRun < PASSsemantic3)
856 d->functionSemantic3 ();
857 Module::runDeferredSemantic3 ();
860 if (global.errors)
861 return;
863 /* Duplicated FuncDeclarations map to the same symbol. Check if this
864 is the one declaration which will be emitted. */
865 tree fndecl = get_symbol_decl (d);
866 tree ident = DECL_ASSEMBLER_NAME (fndecl);
867 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
868 return;
870 if (!d->fbody)
872 rest_of_decl_compilation (fndecl, 1, 0);
873 return;
876 if (global.params.verbose)
877 message ("function %s", d->toPrettyChars ());
879 /* Start generating code for this function. */
880 gcc_assert (d->semanticRun == PASSsemantic3done);
881 d->semanticRun = PASSobj;
883 tree old_context = start_function (d);
885 tree parm_decl = NULL_TREE;
886 tree param_list = NULL_TREE;
888 /* Special arguments... */
890 /* 'this' parameter:
891 For nested functions, D still generates a vthis, but it
892 should not be referenced in any expression. */
893 if (d->vthis)
895 parm_decl = get_symbol_decl (d->vthis);
896 DECL_ARTIFICIAL (parm_decl) = 1;
897 TREE_READONLY (parm_decl) = 1;
899 if (d->vthis->type == Type::tvoidptr)
901 /* Replace generic pointer with back-end closure type
902 (this wins for gdb). */
903 tree frame_type = FRAMEINFO_TYPE (get_frameinfo (d));
904 gcc_assert (frame_type != NULL_TREE);
905 TREE_TYPE (parm_decl) = build_pointer_type (frame_type);
908 param_list = chainon (param_list, parm_decl);
909 d_function_chain->static_chain = parm_decl;
912 /* _arguments parameter. */
913 if (d->v_arguments)
915 parm_decl = get_symbol_decl (d->v_arguments);
916 param_list = chainon (param_list, parm_decl);
919 /* formal function parameters. */
920 size_t n_parameters = d->parameters ? d->parameters->dim : 0;
922 for (size_t i = 0; i < n_parameters; i++)
924 VarDeclaration *param = (*d->parameters)[i];
925 parm_decl = get_symbol_decl (param);
926 /* Chain them in the correct order. */
927 param_list = chainon (param_list, parm_decl);
930 DECL_ARGUMENTS (fndecl) = param_list;
931 DECL_IN_UNITTEST_CONDITION_P (fndecl) = this->in_version_unittest_;
932 rest_of_decl_compilation (fndecl, 1, 0);
934 /* If this is a member function that nested (possibly indirectly) in another
935 function, construct an expession for this member function's static chain
936 by going through parent link of nested classes. */
937 if (d->isThis ())
939 AggregateDeclaration *ad = d->isThis ();
940 tree this_tree = get_symbol_decl (d->vthis);
942 while (ad->isNested ())
944 Dsymbol *pd = ad->toParent2 ();
945 tree vthis_field = get_symbol_decl (ad->vthis);
946 this_tree = component_ref (build_deref (this_tree), vthis_field);
948 ad = pd->isAggregateDeclaration ();
949 if (ad == NULL)
951 cfun->language->static_chain = this_tree;
952 break;
957 /* May change cfun->static_chain. */
958 build_closure (d);
960 if (d->vresult)
961 declare_local_var (d->vresult);
963 if (d->v_argptr)
964 push_stmt_list ();
966 /* Named return value optimisation support for D.
967 Implemented by overriding all the RETURN_EXPRs and replacing all
968 occurrences of VAR with the RESULT_DECL for the function.
969 This is only worth doing for functions that can return in memory. */
970 if (d->nrvo_can)
972 tree restype = TREE_TYPE (DECL_RESULT (fndecl));
974 if (!AGGREGATE_TYPE_P (restype))
975 d->nrvo_can = 0;
976 else
977 d->nrvo_can = aggregate_value_p (restype, fndecl);
980 if (d->nrvo_can)
982 tree resdecl = DECL_RESULT (fndecl);
984 TREE_TYPE (resdecl)
985 = build_reference_type (TREE_TYPE (resdecl));
986 DECL_BY_REFERENCE (resdecl) = 1;
987 TREE_ADDRESSABLE (resdecl) = 0;
988 relayout_decl (resdecl);
990 if (d->nrvo_var)
992 tree var = get_symbol_decl (d->nrvo_var);
994 /* Copy name from VAR to RESULT. */
995 DECL_NAME (resdecl) = DECL_NAME (var);
996 /* Don't forget that we take its address. */
997 TREE_ADDRESSABLE (var) = 1;
998 resdecl = build_deref (resdecl);
1000 SET_DECL_VALUE_EXPR (var, resdecl);
1001 DECL_HAS_VALUE_EXPR_P (var) = 1;
1002 SET_DECL_LANG_NRVO (var, resdecl);
1006 build_function_body (d);
1008 /* Initialize the _argptr variable. */
1009 if (d->v_argptr)
1011 tree body = pop_stmt_list ();
1012 tree var = get_decl_tree (d->v_argptr);
1013 var = build_address (var);
1015 tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
1016 2, var, parm_decl);
1017 declare_local_var (d->v_argptr);
1018 add_stmt (init);
1020 tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
1021 1, var);
1022 add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
1025 finish_function (old_context);
1027 /* Maybe record the function against the current module. */
1028 register_module_decl (d);
1032 /* Main entry point for the DeclVisitor interface to send
1033 the Declaration AST class D to GCC back-end. */
1035 void
1036 build_decl_tree (Dsymbol *d)
1038 location_t saved_location = input_location;
1040 /* Set input location, empty DECL_SOURCE_FILE can crash debug generator. */
1041 if (d->loc.filename)
1042 input_location = make_location_t (d->loc);
1043 else
1044 input_location = make_location_t (Loc ("<no_file>", 1, 0));
1046 DeclVisitor v = DeclVisitor ();
1047 d->accept (&v);
1049 input_location = saved_location;
1052 /* Return the decl for the symbol, create it if it doesn't already exist. */
1054 tree
1055 get_symbol_decl (Declaration *decl)
1057 if (decl->csym)
1058 return decl->csym;
1060 /* Deal with placeholder symbols immediately:
1061 SymbolDeclaration is used as a shell around an initializer symbol. */
1062 SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1063 if (sd)
1065 decl->csym = aggregate_initializer_decl (sd->dsym);
1066 return decl->csym;
1069 /* Global static TypeInfo declaration. */
1070 if (decl->isTypeInfoDeclaration ())
1071 return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1073 /* FuncAliasDeclaration is used to import functions from another scope. */
1074 FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1075 if (fad)
1077 decl->csym = get_symbol_decl (fad->funcalias);
1078 return decl->csym;
1081 /* It is possible for a field declaration symbol to be requested
1082 before the parent type has been built. */
1083 if (decl->isField ())
1085 AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1086 gcc_assert (ad != NULL);
1088 /* Finishing off the type should create the associated FIELD_DECL. */
1089 build_ctype (ad->type);
1090 gcc_assert (decl->csym != NULL);
1092 return decl->csym;
1095 /* Build the tree for the symbol. */
1096 FuncDeclaration *fd = decl->isFuncDeclaration ();
1097 if (fd)
1099 /* Run full semantic on functions we need to know about. */
1100 if (!fd->functionSemantic ())
1102 decl->csym = error_mark_node;
1103 return decl->csym;
1106 decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1107 get_identifier (decl->ident->toChars ()),
1108 NULL_TREE);
1110 /* Set function type afterwards as there could be self references. */
1111 TREE_TYPE (decl->csym) = build_ctype (fd->type);
1113 if (!fd->fbody)
1114 DECL_EXTERNAL (decl->csym) = 1;
1116 else
1118 /* Build the variable declaration. */
1119 VarDeclaration *vd = decl->isVarDeclaration ();
1120 gcc_assert (vd != NULL);
1122 tree_code code = vd->isParameter () ? PARM_DECL
1123 : !vd->canTakeAddressOf () ? CONST_DECL
1124 : VAR_DECL;
1125 decl->csym = build_decl (make_location_t (decl->loc), code,
1126 get_identifier (decl->ident->toChars ()),
1127 declaration_type (vd));
1129 /* If any alignment was set on the declaration. */
1130 if (vd->alignment != STRUCTALIGN_DEFAULT)
1132 SET_DECL_ALIGN (decl->csym, vd->alignment * BITS_PER_UNIT);
1133 DECL_USER_ALIGN (decl->csym) = 1;
1136 if (vd->storage_class & STCextern)
1137 DECL_EXTERNAL (decl->csym) = 1;
1140 /* Set the declaration mangled identifier if static. */
1141 if (decl->isCodeseg () || decl->isDataseg ())
1143 tree mangled_name;
1145 if (decl->mangleOverride)
1146 mangled_name = get_identifier (decl->mangleOverride);
1147 else
1148 mangled_name = get_identifier (mangle_decl (decl));
1150 mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1151 mangled_name);
1152 /* The frontend doesn't handle duplicate definitions of unused symbols
1153 with the same mangle. So a check is done here instead. */
1154 if (!DECL_EXTERNAL (decl->csym))
1156 if (IDENTIFIER_DSYMBOL (mangled_name))
1158 Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1160 /* Non-templated variables shouldn't be defined twice. */
1161 if (!decl->isInstantiated ())
1162 ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1164 decl->csym = get_symbol_decl (other);
1165 return decl->csym;
1168 IDENTIFIER_PRETTY_NAME (mangled_name)
1169 = get_identifier (decl->toPrettyChars (true));
1170 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1173 SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1176 DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1177 DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1179 if (TREE_CODE (decl->csym) == PARM_DECL)
1181 /* Pass non-trivial structs by invisible reference. */
1182 if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1184 tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1185 argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1186 gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1187 TREE_TYPE (decl->csym) = argtype;
1188 DECL_BY_REFERENCE (decl->csym) = 1;
1189 TREE_ADDRESSABLE (decl->csym) = 0;
1190 relayout_decl (decl->csym);
1191 decl->storage_class |= STCref;
1194 DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1195 gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1197 else if (TREE_CODE (decl->csym) == CONST_DECL)
1199 /* Manifest constants have no address in memory. */
1200 TREE_CONSTANT (decl->csym) = 1;
1201 TREE_READONLY (decl->csym) = 1;
1203 else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1205 /* The real function type may differ from its declaration. */
1206 tree fntype = TREE_TYPE (decl->csym);
1207 tree newfntype = NULL_TREE;
1209 if (fd->isNested ())
1211 /* Add an extra argument for the frame/closure pointer, this is also
1212 required to be compatible with D delegates. */
1213 newfntype = build_vthis_function (void_type_node, fntype);
1215 else if (fd->isThis ())
1217 /* Add an extra argument for the 'this' parameter. The handle type is
1218 used even if there is no debug info. It is needed to make sure
1219 virtual member functions are not called statically. */
1220 AggregateDeclaration *ad = fd->isMember2 ();
1221 tree handle = build_ctype (ad->handleType ());
1223 /* If handle is a pointer type, get record type. */
1224 if (!ad->isStructDeclaration ())
1225 handle = TREE_TYPE (handle);
1227 newfntype = build_vthis_function (handle, fntype);
1229 /* Set the vindex on virtual functions. */
1230 if (fd->isVirtual () && fd->vtblIndex != -1)
1232 DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1233 DECL_VIRTUAL_P (decl->csym) = 1;
1236 else if (fd->isMain () || fd->isCMain ())
1238 /* The main function is named 'D main' to distinguish from C main. */
1239 if (fd->isMain ())
1240 DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1242 /* 'void main' is implicitly converted to returning an int. */
1243 newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1246 if (newfntype != NULL_TREE)
1248 /* Copy the old attributes from the original type. */
1249 TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1250 TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1251 TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1252 TREE_TYPE (decl->csym) = newfntype;
1253 d_keep (newfntype);
1256 /* Miscellaneous function flags. */
1257 if (fd->isMember2 () || fd->isFuncLiteralDeclaration ())
1259 /* See grokmethod in cp/decl.c. Maybe we shouldn't be setting inline
1260 flags without reason or proper handling. */
1261 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1262 DECL_NO_INLINE_WARNING_P (decl->csym) = 1;
1265 /* Function was declared 'naked'. */
1266 if (fd->naked)
1268 insert_decl_attribute (decl->csym, "naked");
1269 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1272 /* Vector array operations are always compiler generated. */
1273 if (fd->isArrayOp)
1275 TREE_PUBLIC (decl->csym) = 1;
1276 DECL_ARTIFICIAL (decl->csym) = 1;
1277 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1278 d_comdat_linkage (decl->csym);
1281 /* And so are ensure and require contracts. */
1282 if (fd->ident == Identifier::idPool ("ensure")
1283 || fd->ident == Identifier::idPool ("require"))
1285 DECL_ARTIFICIAL (decl->csym) = 1;
1286 TREE_PUBLIC (decl->csym) = 1;
1289 if (decl->storage_class & STCfinal)
1290 DECL_FINAL_P (decl->csym) = 1;
1292 /* Check whether this function is expanded by the frontend. */
1293 DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1294 maybe_set_intrinsic (fd);
1296 /* For nested functions in particular, unnest fndecl in the cgraph, as
1297 all static chain passing is handled by the front-end. Do this even
1298 if we are not emitting the body. */
1299 struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1300 if (node->origin)
1301 node->unnest ();
1304 /* Mark compiler generated temporaries as artificial. */
1305 if (decl->storage_class & STCtemp)
1306 DECL_ARTIFICIAL (decl->csym) = 1;
1308 /* Propagate shared on the decl. */
1309 if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1310 TREE_ADDRESSABLE (decl->csym) = 1;
1312 /* Symbol was marked volatile. */
1313 if (decl->storage_class & STCvolatile)
1314 TREE_THIS_VOLATILE (decl->csym) = 1;
1316 /* Protection attributes are used by the debugger. */
1317 if (decl->protection.kind == PROTprivate)
1318 TREE_PRIVATE (decl->csym) = 1;
1319 else if (decl->protection.kind == PROTprotected)
1320 TREE_PROTECTED (decl->csym) = 1;
1322 /* Likewise, so could the deprecated attribute. */
1323 if (decl->storage_class & STCdeprecated)
1324 TREE_DEPRECATED (decl->csym) = 1;
1326 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1327 /* Have to test for import first. */
1328 if (decl->isImportedSymbol ())
1330 insert_decl_attribute (decl->csym, "dllimport");
1331 DECL_DLLIMPORT_P (decl->csym) = 1;
1333 else if (decl->isExport ())
1334 insert_decl_attribute (decl->csym, "dllexport");
1335 #endif
1337 if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1339 /* Set TREE_PUBLIC by default, but allow private template to override. */
1340 if (!fd || !fd->isNested ())
1341 TREE_PUBLIC (decl->csym) = 1;
1343 TREE_STATIC (decl->csym) = 1;
1344 /* The decl has not been defined -- yet. */
1345 DECL_EXTERNAL (decl->csym) = 1;
1347 if (decl->isInstantiated ())
1348 d_linkonce_linkage (decl->csym);
1351 /* Symbol is going in thread local storage. */
1352 if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1354 if (global.params.vtls)
1355 message (decl->loc, "`%s` is thread local", decl->toChars ());
1357 set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1360 /* Apply any user attributes that may affect semantic meaning. */
1361 if (decl->userAttribDecl)
1363 Expressions *attrs = decl->userAttribDecl->getAttributes ();
1364 decl_attributes (&decl->csym, build_attributes (attrs), 0);
1366 else if (DECL_ATTRIBUTES (decl->csym) != NULL)
1367 decl_attributes (&decl->csym, DECL_ATTRIBUTES (decl->csym), 0);
1369 /* %% Probably should be a little more intelligent about setting this. */
1370 TREE_USED (decl->csym) = 1;
1371 d_keep (decl->csym);
1373 return decl->csym;
1376 /* Returns a declaration for a VAR_DECL. Used to create compiler-generated
1377 global variables. */
1379 tree
1380 declare_extern_var (tree ident, tree type)
1382 /* If the VAR_DECL has already been declared, return it. */
1383 if (IDENTIFIER_DECL_TREE (ident))
1384 return IDENTIFIER_DECL_TREE (ident);
1386 tree name = IDENTIFIER_PRETTY_NAME (ident)
1387 ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1388 tree decl = build_decl (input_location, VAR_DECL, name, type);
1390 IDENTIFIER_DECL_TREE (ident) = decl;
1391 d_keep (decl);
1393 SET_DECL_ASSEMBLER_NAME (decl, ident);
1394 DECL_ARTIFICIAL (decl) = 1;
1395 TREE_STATIC (decl) = 1;
1396 TREE_PUBLIC (decl) = 1;
1398 /* The decl has not been defined -- yet. */
1399 DECL_EXTERNAL (decl) = 1;
1401 return decl;
1404 /* Add local variable VAR into the current function body. */
1406 void
1407 declare_local_var (VarDeclaration *var)
1409 gcc_assert (!var->isDataseg () && !var->isMember ());
1410 gcc_assert (current_function_decl != NULL_TREE);
1412 FuncDeclaration *fd = cfun->language->function;
1413 tree decl = get_symbol_decl (var);
1415 gcc_assert (!TREE_STATIC (decl));
1416 d_pushdecl (decl);
1417 DECL_CONTEXT (decl) = current_function_decl;
1419 /* Compiler generated symbols. */
1420 if (var == fd->vresult || var == fd->v_argptr)
1421 DECL_ARTIFICIAL (decl) = 1;
1423 if (DECL_LANG_FRAME_FIELD (decl))
1425 /* Fixes debugging local variables. */
1426 SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1427 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1431 /* Return an unnamed local temporary of type TYPE. */
1433 tree
1434 build_local_temp (tree type)
1436 tree decl = build_decl (input_location, VAR_DECL, NULL_TREE, type);
1438 DECL_CONTEXT (decl) = current_function_decl;
1439 DECL_ARTIFICIAL (decl) = 1;
1440 DECL_IGNORED_P (decl) = 1;
1441 d_pushdecl (decl);
1443 return decl;
1446 /* Return the correct decl to be used for DECL. For VAR_DECLs, this could
1447 instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1448 value. For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1449 For all other kinds of decls, this just returns the result of
1450 get_symbol_decl(). */
1452 tree
1453 get_decl_tree (Declaration *decl)
1455 tree t = get_symbol_decl (decl);
1456 FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1457 VarDeclaration *vd = decl->isVarDeclaration ();
1459 /* If cfun is NULL, then this is a global static. */
1460 if (vd == NULL || fd == NULL)
1461 return t;
1463 /* Get the named return value. */
1464 if (DECL_LANG_NRVO (t))
1465 return DECL_LANG_NRVO (t);
1467 /* Get the closure holding the var decl. */
1468 if (DECL_LANG_FRAME_FIELD (t))
1470 FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1471 tree frame_ref = get_framedecl (fd, parent);
1473 return component_ref (build_deref (frame_ref),
1474 DECL_LANG_FRAME_FIELD (t));
1477 /* Get the non-local 'this' value by going through parent link
1478 of nested classes, this routine pretty much undoes what
1479 getRightThis in the frontend removes from codegen. */
1480 if (vd->parent != fd && vd->isThisDeclaration ())
1482 /* Find the first parent that is a member function. */
1483 while (!fd->isMember2 ())
1485 gcc_assert (fd->vthis);
1486 fd = fd->toParent2 ()->isFuncDeclaration ();
1487 gcc_assert (fd != NULL);
1490 AggregateDeclaration *ad = fd->isThis ();
1491 gcc_assert (ad != NULL);
1493 t = get_decl_tree (fd->vthis);
1494 Dsymbol *outer = fd;
1496 while (outer != vd->parent)
1498 gcc_assert (ad != NULL);
1499 outer = ad->toParent2 ();
1501 /* Get the this->this parent link. */
1502 tree vfield = get_symbol_decl (ad->vthis);
1503 t = component_ref (build_deref (t), vfield);
1505 ad = outer->isAggregateDeclaration ();
1506 if (ad != NULL)
1507 continue;
1509 fd = outer->isFuncDeclaration ();
1510 while (fd != NULL)
1512 /* If outer function creates a closure, then the 'this'
1513 value would be the closure pointer, and the real
1514 'this' the first field of that closure. */
1515 tree ff = get_frameinfo (fd);
1516 if (FRAMEINFO_CREATES_FRAME (ff))
1518 t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1519 t = indirect_ref (build_ctype (fd->vthis->type), t);
1522 if (fd == vd->parent)
1523 break;
1525 /* Continue looking for the right `this'. */
1526 outer = outer->toParent2 ();
1527 fd = outer->isFuncDeclaration ();
1530 ad = outer->isAggregateDeclaration ();
1533 return t;
1536 /* Auto variable that the back end will handle for us. */
1537 return t;
1540 /* Finish up a variable declaration and compile it all the way to
1541 the assembler language output. */
1543 void
1544 d_finish_decl (tree decl)
1546 gcc_assert (!error_operand_p (decl));
1548 /* We are sending this symbol to object file, can't be extern. */
1549 TREE_STATIC (decl) = 1;
1550 DECL_EXTERNAL (decl) = 0;
1552 /* Update the TLS model as the linkage has been modified. */
1553 if (DECL_THREAD_LOCAL_P (decl))
1554 set_decl_tls_model (decl, decl_default_tls_model (decl));
1556 relayout_decl (decl);
1558 if (flag_checking && DECL_INITIAL (decl))
1560 /* Initializer must never be bigger than symbol size. */
1561 dinteger_t tsize = int_size_in_bytes (TREE_TYPE (decl));
1562 dinteger_t dtsize = int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1564 if (tsize < dtsize)
1566 tree name = DECL_ASSEMBLER_NAME (decl);
1568 internal_error ("Mismatch between declaration %qE size (%wd) and "
1569 "its initializer size (%wd).",
1570 IDENTIFIER_PRETTY_NAME (name)
1571 ? IDENTIFIER_PRETTY_NAME (name) : name,
1572 tsize, dtsize);
1576 /* Without weak symbols, symbol should be put in .common, but that can't
1577 be done if there is a nonzero initializer. */
1578 if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1579 && initializer_zerop (DECL_INITIAL (decl)))
1580 DECL_INITIAL (decl) = error_mark_node;
1582 /* Add this decl to the current binding level. */
1583 d_pushdecl (decl);
1585 rest_of_decl_compilation (decl, 1, 0);
1588 /* Thunk code is based on g++. */
1590 static int thunk_labelno;
1592 /* Create a static alias to function. */
1594 static tree
1595 make_alias_for_thunk (tree function)
1597 tree alias;
1598 char buf[256];
1600 /* Thunks may reference extern functions which cannot be aliased. */
1601 if (DECL_EXTERNAL (function))
1602 return function;
1604 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1605 thunk_labelno++;
1607 alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1608 get_identifier (buf), TREE_TYPE (function));
1609 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1610 lang_hooks.dup_lang_specific_decl (alias);
1611 DECL_CONTEXT (alias) = NULL_TREE;
1612 TREE_READONLY (alias) = TREE_READONLY (function);
1613 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1614 TREE_PUBLIC (alias) = 0;
1616 DECL_EXTERNAL (alias) = 0;
1617 DECL_ARTIFICIAL (alias) = 1;
1619 DECL_DECLARED_INLINE_P (alias) = 0;
1620 DECL_INITIAL (alias) = error_mark_node;
1621 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1623 TREE_ADDRESSABLE (alias) = 1;
1624 TREE_USED (alias) = 1;
1625 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1627 if (!flag_syntax_only)
1629 cgraph_node *aliasn;
1630 aliasn = cgraph_node::create_same_body_alias (alias, function);
1631 gcc_assert (aliasn != NULL);
1633 return alias;
1636 /* Emit the definition of a D vtable thunk. */
1638 static void
1639 finish_thunk (tree thunk, tree function)
1641 /* Setup how D thunks are outputted. */
1642 int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1643 bool this_adjusting = true;
1644 tree alias;
1646 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1647 alias = make_alias_for_thunk (function);
1648 else
1649 alias = function;
1651 TREE_ADDRESSABLE (function) = 1;
1652 TREE_USED (function) = 1;
1654 if (flag_syntax_only)
1656 TREE_ASM_WRITTEN (thunk) = 1;
1657 return;
1660 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1661 && targetm_common.have_named_sections)
1663 tree fn = function;
1664 symtab_node *symbol = symtab_node::get (function);
1666 if (symbol != NULL && symbol->alias)
1668 if (symbol->analyzed)
1669 fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1670 else
1671 fn = symtab_node::get (function)->alias_target;
1673 resolve_unique_section (fn, 0, flag_function_sections);
1675 if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1677 resolve_unique_section (thunk, 0, flag_function_sections);
1679 /* Output the thunk into the same section as function. */
1680 set_decl_section_name (thunk, DECL_SECTION_NAME (fn));
1681 symtab_node::get (thunk)->implicit_section
1682 = symtab_node::get (fn)->implicit_section;
1686 /* Set up cloned argument trees for the thunk. */
1687 tree t = NULL_TREE;
1688 for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1690 tree x = copy_node (a);
1691 DECL_CHAIN (x) = t;
1692 DECL_CONTEXT (x) = thunk;
1693 SET_DECL_RTL (x, NULL);
1694 DECL_HAS_VALUE_EXPR_P (x) = 0;
1695 TREE_ADDRESSABLE (x) = 0;
1696 t = x;
1698 DECL_ARGUMENTS (thunk) = nreverse (t);
1699 TREE_ASM_WRITTEN (thunk) = 1;
1701 cgraph_node *funcn, *thunk_node;
1703 funcn = cgraph_node::get_create (function);
1704 gcc_assert (funcn);
1705 thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1706 fixed_offset, 0, 0, 0, alias);
1708 if (DECL_ONE_ONLY (function))
1709 thunk_node->add_to_same_comdat_group (funcn);
1711 /* Target assemble_mi_thunk doesn't work across section boundaries
1712 on many targets, instead force thunk to be expanded in gimple. */
1713 if (DECL_EXTERNAL (function))
1715 /* cgraph::expand_thunk writes over current_function_decl, so if this
1716 could ever be in use by the codegen pass, we want to know about it. */
1717 gcc_assert (current_function_decl == NULL_TREE);
1719 if (!stdarg_p (TREE_TYPE (thunk)))
1721 thunk_node->create_edge (funcn, NULL, thunk_node->count);
1722 thunk_node->expand_thunk (false, true);
1725 /* Tell the back-end to not bother inlining the function, this is
1726 assumed not to work as it could be referencing symbols outside
1727 of the current compilation unit. */
1728 DECL_UNINLINABLE (function) = 1;
1732 /* Return a thunk to DECL. Thunks adjust the incoming `this' pointer by OFFSET.
1733 Adjustor thunks are created and pointers to them stored in the method entries
1734 in the vtable in order to set the this pointer to the start of the object
1735 instance corresponding to the implementing method. */
1737 tree
1738 make_thunk (FuncDeclaration *decl, int offset)
1740 tree function = get_symbol_decl (decl);
1742 if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1744 /* Compile the function body before generating the thunk, this is done
1745 even if the decl is external to the current module. */
1746 if (decl->fbody)
1747 build_decl_tree (decl);
1748 else
1750 /* Build parameters for functions that are not being compiled,
1751 so that they can be correctly cloned in finish_thunk. */
1752 tree fntype = TREE_TYPE (function);
1753 tree params = NULL_TREE;
1755 for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
1757 if (t == void_list_node)
1758 break;
1760 tree param = build_decl (DECL_SOURCE_LOCATION (function),
1761 PARM_DECL, NULL_TREE, TREE_VALUE (t));
1762 DECL_ARG_TYPE (param) = TREE_TYPE (param);
1763 DECL_ARTIFICIAL (param) = 1;
1764 DECL_IGNORED_P (param) = 1;
1765 DECL_CONTEXT (param) = function;
1766 params = chainon (params, param);
1769 DECL_ARGUMENTS (function) = params;
1771 /* Also build the result decl, which is needed when force creating
1772 the thunk in gimple inside cgraph_node::expand_thunk. */
1773 tree resdecl = build_decl (DECL_SOURCE_LOCATION (function),
1774 RESULT_DECL, NULL_TREE,
1775 TREE_TYPE (fntype));
1776 DECL_ARTIFICIAL (resdecl) = 1;
1777 DECL_IGNORED_P (resdecl) = 1;
1778 DECL_CONTEXT (resdecl) = function;
1779 DECL_RESULT (function) = resdecl;
1783 /* Don't build the thunk if the compilation step failed. */
1784 if (global.errors)
1785 return error_mark_node;
1787 /* See if we already have the thunk in question. */
1788 for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1790 if (THUNK_LANG_OFFSET (t) == offset)
1791 return t;
1794 tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1795 FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1796 DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1797 lang_hooks.dup_lang_specific_decl (thunk);
1798 THUNK_LANG_OFFSET (thunk) = offset;
1800 TREE_READONLY (thunk) = TREE_READONLY (function);
1801 TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
1802 TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
1804 DECL_CONTEXT (thunk) = d_decl_context (decl);
1806 /* Thunks inherit the public access of the function they are targetting. */
1807 TREE_PUBLIC (thunk) = TREE_PUBLIC (function);
1808 DECL_EXTERNAL (thunk) = 0;
1810 /* Thunks are always addressable. */
1811 TREE_ADDRESSABLE (thunk) = 1;
1812 TREE_USED (thunk) = 1;
1813 DECL_ARTIFICIAL (thunk) = 1;
1814 DECL_DECLARED_INLINE_P (thunk) = 0;
1816 DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
1817 DECL_COMDAT (thunk) = DECL_COMDAT (function);
1818 DECL_WEAK (thunk) = DECL_WEAK (function);
1820 tree target_name = DECL_ASSEMBLER_NAME (function);
1821 unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
1822 const char *ident = XNEWVEC (const char, identlen);
1823 snprintf (CONST_CAST (char *, ident), identlen,
1824 "_DT%u%s", offset, IDENTIFIER_POINTER (target_name));
1826 DECL_NAME (thunk) = get_identifier (ident);
1827 SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
1829 d_keep (thunk);
1831 finish_thunk (thunk, function);
1833 /* Add it to the list of thunks associated with the function. */
1834 DECL_LANG_THUNKS (thunk) = NULL_TREE;
1835 DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
1836 DECL_LANG_THUNKS (function) = thunk;
1838 return thunk;
1841 /* Create the FUNCTION_DECL for a function definition.
1842 This function creates a binding context for the function body
1843 as well as setting up the FUNCTION_DECL in current_function_decl.
1844 Returns the previous function context if it was already set. */
1846 tree
1847 start_function (FuncDeclaration *fd)
1849 tree fndecl = get_symbol_decl (fd);
1851 /* Function has been defined, check now whether we intend to send it to
1852 object file, or it really is extern. Such as inlinable functions from
1853 modules not in this compilation, or thunk aliases. */
1854 TemplateInstance *ti = fd->isInstantiated ();
1855 if (ti && ti->needsCodegen ())
1857 /* Warn about templates instantiated in this compilation. */
1858 if (ti == fd->parent)
1860 warning (OPT_Wtemplates, "%s %qs instantiated",
1861 ti->kind (), ti->toPrettyChars (false));
1864 DECL_EXTERNAL (fndecl) = 0;
1866 else
1868 Module *md = fd->getModule ();
1869 if (md && md->isRoot ())
1870 DECL_EXTERNAL (fndecl) = 0;
1873 DECL_INITIAL (fndecl) = error_mark_node;
1875 /* Add this decl to the current binding level. */
1876 d_pushdecl (fndecl);
1878 /* Save the current function context. */
1879 tree old_context = current_function_decl;
1881 if (old_context)
1882 push_function_context ();
1884 /* Let GCC know the current scope is this function. */
1885 current_function_decl = fndecl;
1887 tree restype = TREE_TYPE (TREE_TYPE (fndecl));
1888 tree resdecl = build_decl (make_location_t (fd->loc), RESULT_DECL,
1889 NULL_TREE, restype);
1891 DECL_RESULT (fndecl) = resdecl;
1892 DECL_CONTEXT (resdecl) = fndecl;
1893 DECL_ARTIFICIAL (resdecl) = 1;
1894 DECL_IGNORED_P (resdecl) = 1;
1896 /* Initialize the RTL code for the function. */
1897 allocate_struct_function (fndecl, false);
1899 /* Store the end of the function. */
1900 if (fd->endloc.filename)
1901 cfun->function_end_locus = make_location_t (fd->endloc);
1902 else
1903 cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
1905 cfun->language = ggc_cleared_alloc<language_function> ();
1906 cfun->language->function = fd;
1908 /* Default chain value is 'null' unless parent found. */
1909 cfun->language->static_chain = null_pointer_node;
1911 /* Find module for this function. */
1912 for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
1914 cfun->language->module = p->isModule ();
1915 if (cfun->language->module)
1916 break;
1918 gcc_assert (cfun->language->module != NULL);
1920 /* Begin the statement tree for this function. */
1921 push_stmt_list ();
1922 push_binding_level (level_function);
1924 return old_context;
1927 /* Finish up a function declaration and compile that function all
1928 the way to assembler language output. The free the storage for
1929 the function definition. Restores the previous function context. */
1931 void
1932 finish_function (tree old_context)
1934 tree fndecl = current_function_decl;
1936 /* Tie off the statement tree for this function. */
1937 tree block = pop_binding_level ();
1938 tree body = pop_stmt_list ();
1939 tree bind = build3 (BIND_EXPR, void_type_node,
1940 BLOCK_VARS (block), body, block);
1942 gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
1944 /* Back-end expects a statement list to come from somewhere, however
1945 pop_stmt_list returns expressions when there is a single statement.
1946 So here we create a statement list unconditionally. */
1947 if (TREE_CODE (body) != STATEMENT_LIST)
1949 tree stmtlist = alloc_stmt_list ();
1950 append_to_statement_list_force (body, &stmtlist);
1951 BIND_EXPR_BODY (bind) = stmtlist;
1953 else if (!STATEMENT_LIST_HEAD (body))
1955 /* For empty functions add a void return. */
1956 append_to_statement_list_force (return_expr (NULL_TREE), &body);
1959 DECL_SAVED_TREE (fndecl) = bind;
1961 if (!errorcount && !global.errors)
1963 /* Dump the D-specific tree IR. */
1964 dump_function (TDI_original, fndecl);
1966 cgraph_node::finalize_function (fndecl, true);
1969 /* We're leaving the context of this function, so free it. */
1970 ggc_free (cfun->language);
1971 cfun->language = NULL;
1972 set_cfun (NULL);
1974 if (old_context)
1975 pop_function_context ();
1977 current_function_decl = old_context;
1980 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
1981 must be emitted in this, output module. */
1983 void
1984 mark_needed (tree decl)
1986 TREE_USED (decl) = 1;
1988 if (TREE_CODE (decl) == FUNCTION_DECL)
1990 struct cgraph_node *node = cgraph_node::get_create (decl);
1991 node->forced_by_abi = true;
1993 else if (VAR_P (decl))
1995 struct varpool_node *node = varpool_node::get_create (decl);
1996 node->forced_by_abi = true;
2000 /* Get the offset to the BC's vtbl[] initializer from the start of CD.
2001 Returns "~0u" if the base class is not found in any vtable interfaces. */
2003 unsigned
2004 base_vtable_offset (ClassDeclaration *cd, BaseClass *bc)
2006 unsigned csymoffset = Target::classinfosize;
2007 unsigned interfacesize = int_size_in_bytes (vtbl_interface_type_node);
2008 csymoffset += cd->vtblInterfaces->dim * interfacesize;
2010 for (size_t i = 0; i < cd->vtblInterfaces->dim; i++)
2012 BaseClass *b = (*cd->vtblInterfaces)[i];
2013 if (b == bc)
2014 return csymoffset;
2015 csymoffset += b->sym->vtbl.dim * Target::ptrsize;
2018 /* Check all overriding interface vtbl[]s. */
2019 for (ClassDeclaration *cd2 = cd->baseClass; cd2; cd2 = cd2->baseClass)
2021 for (size_t k = 0; k < cd2->vtblInterfaces->dim; k++)
2023 BaseClass *bs = (*cd2->vtblInterfaces)[k];
2024 if (bs->fillVtbl (cd, NULL, 0))
2026 if (bc == bs)
2027 return csymoffset;
2028 csymoffset += bs->sym->vtbl.dim * Target::ptrsize;
2033 return ~0u;
2036 /* Get the VAR_DECL of the vtable symbol for DECL. If this does not yet exist,
2037 create it. The vtable is accessible via ClassInfo, but since it is needed
2038 frequently (like for rtti comparisons), make it directly accessible. */
2040 tree
2041 get_vtable_decl (ClassDeclaration *decl)
2043 if (decl->vtblsym)
2044 return decl->vtblsym;
2046 tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
2047 /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
2048 will have a different type. However the back-end seems to accept this. */
2049 tree type = build_ctype (Type::tvoidptr->sarrayOf (decl->vtbl.dim));
2051 decl->vtblsym = declare_extern_var (ident, type);
2052 DECL_LANG_SPECIFIC (decl->vtblsym) = build_lang_decl (NULL);
2054 /* Class is a reference, want the record type. */
2055 DECL_CONTEXT (decl->vtblsym) = TREE_TYPE (build_ctype (decl->type));
2056 TREE_READONLY (decl->vtblsym) = 1;
2057 DECL_VIRTUAL_P (decl->vtblsym) = 1;
2059 SET_DECL_ALIGN (decl->vtblsym, TARGET_VTABLE_ENTRY_ALIGN);
2060 DECL_USER_ALIGN (decl->vtblsym) = true;
2062 return decl->vtblsym;
2065 /* Helper function of build_class_instance. Find the field inside aggregate
2066 TYPE identified by IDENT at field OFFSET. */
2068 static tree
2069 find_aggregate_field (tree type, tree ident, tree offset)
2071 tree fields = TYPE_FIELDS (type);
2073 for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2075 if (DECL_NAME (field) == NULL_TREE
2076 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2077 && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2079 /* Search nesting anonymous structs and unions. */
2080 tree vfield = find_aggregate_field (TREE_TYPE (field),
2081 ident, offset);
2082 if (vfield != NULL_TREE)
2083 return vfield;
2085 else if (DECL_NAME (field) == ident
2086 && (offset == NULL_TREE
2087 || DECL_FIELD_OFFSET (field) == offset))
2089 /* Found matching field at offset. */
2090 return field;
2094 return NULL_TREE;
2097 /* Helper function of build_new_class_expr. Return a constructor that matches
2098 the layout of the class expression EXP. */
2100 static tree
2101 build_class_instance (ClassReferenceExp *exp)
2103 ClassDeclaration *cd = exp->originalClass ();
2104 tree type = TREE_TYPE (build_ctype (exp->value->stype));
2105 vec<constructor_elt, va_gc> *ve = NULL;
2107 /* The set base vtable field. */
2108 tree vptr = build_address (get_vtable_decl (cd));
2109 CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2111 /* Go through the inheritance graph from top to bottom. This will add all
2112 values to the constructor out of order, however build_struct_literal
2113 will re-order all values before returning the finished literal. */
2114 for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2116 /* Anonymous vtable interface fields are laid out before the fields of
2117 each class. The interface offset is used to determine where to put
2118 the classinfo offset reference. */
2119 for (size_t i = 0; i < bcd->vtblInterfaces->dim; i++)
2121 BaseClass *bc = (*bcd->vtblInterfaces)[i];
2123 for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2125 gcc_assert (cd2 != NULL);
2127 unsigned csymoffset = base_vtable_offset (cd2, bc);
2128 /* If the base class vtable was found. */
2129 if (csymoffset != ~0u)
2131 tree csym = build_address (get_classinfo_decl (cd2));
2132 csym = build_offset (csym, size_int (csymoffset));
2134 tree field = find_aggregate_field (type, NULL_TREE,
2135 size_int (bc->offset));
2136 gcc_assert (field != NULL_TREE);
2138 CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2139 break;
2144 /* Generate initial values of all fields owned by current class.
2145 Use both the name and offset to find the right field. */
2146 for (size_t i = 0; i < bcd->fields.dim; i++)
2148 VarDeclaration *vfield = bcd->fields[i];
2149 int index = exp->findFieldIndexByName (vfield);
2150 gcc_assert (index != -1);
2152 Expression *value = (*exp->value->elements)[index];
2153 if (!value)
2154 continue;
2156 /* Use find_aggregate_field to get the overridden field decl,
2157 instead of the field associated with the base class. */
2158 tree field = get_symbol_decl (bcd->fields[i]);
2159 field = find_aggregate_field (type, DECL_NAME (field),
2160 DECL_FIELD_OFFSET (field));
2161 gcc_assert (field != NULL_TREE);
2163 CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2167 return build_struct_literal (type, ve);
2170 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2171 If this does not yet exist, create it. This is used to support initializing
2172 a static variable that is of a class type using values known during CTFE.
2173 In user code, it is analogous to the following code snippet.
2175 enum E = new C(1, 2, 3);
2177 That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2178 implementation detail. The initialization of these symbols could be done at
2179 run-time using during as part of the module initialization or shared static
2180 constructors phase of run-time start-up - whichever comes after `gc_init()'.
2181 And infact that would be the better thing to do here eventually. */
2183 tree
2184 build_new_class_expr (ClassReferenceExp *expr)
2186 if (expr->value->sym)
2187 return expr->value->sym;
2189 /* Build the reference symbol. */
2190 tree type = build_ctype (expr->value->stype);
2191 expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2193 DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2194 d_pushdecl (expr->value->sym);
2195 rest_of_decl_compilation (expr->value->sym, 1, 0);
2197 return expr->value->sym;
2200 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2201 If this does not yet exist, create it. The static initializer data is
2202 accessible via TypeInfo, and is also used in 'new class' and default
2203 initializing struct literals. */
2205 tree
2206 aggregate_initializer_decl (AggregateDeclaration *decl)
2208 if (decl->sinit)
2209 return decl->sinit;
2211 /* Class is a reference, want the record type. */
2212 tree type = build_ctype (decl->type);
2213 StructDeclaration *sd = decl->isStructDeclaration ();
2214 if (!sd)
2215 type = TREE_TYPE (type);
2217 tree ident = mangle_internal_decl (decl, "__init", "Z");
2219 decl->sinit = declare_extern_var (ident, type);
2220 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2222 DECL_CONTEXT (decl->sinit) = type;
2223 TREE_READONLY (decl->sinit) = 1;
2225 /* Honor struct alignment set by user. */
2226 if (sd && sd->alignment != STRUCTALIGN_DEFAULT)
2228 SET_DECL_ALIGN (decl->sinit, sd->alignment * BITS_PER_UNIT);
2229 DECL_USER_ALIGN (decl->sinit) = true;
2232 return decl->sinit;
2235 /* Generate the data for the static initializer. */
2237 tree
2238 layout_class_initializer (ClassDeclaration *cd)
2240 NewExp *ne = NewExp::create (cd->loc, NULL, NULL, cd->type, NULL);
2241 ne->type = cd->type;
2243 Expression *e = ne->ctfeInterpret ();
2244 gcc_assert (e->op == TOKclassreference);
2246 return build_class_instance ((ClassReferenceExp *) e);
2249 tree
2250 layout_struct_initializer (StructDeclaration *sd)
2252 StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2254 if (!sd->fill (sd->loc, sle->elements, true))
2255 gcc_unreachable ();
2257 sle->type = sd->type;
2258 return build_expr (sle, true);
2261 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2262 If this does not yet exist, create it. The static initializer data is
2263 accessible via TypeInfo_Enum, but the field member type is a byte[] that
2264 requires a pointer to a symbol reference. */
2266 tree
2267 enum_initializer_decl (EnumDeclaration *decl)
2269 if (decl->sinit)
2270 return decl->sinit;
2272 tree type = build_ctype (decl->type);
2274 Identifier *ident_save = decl->ident;
2275 if (!decl->ident)
2276 decl->ident = Identifier::generateId ("__enum");
2277 tree ident = mangle_internal_decl (decl, "__init", "Z");
2278 decl->ident = ident_save;
2280 decl->sinit = declare_extern_var (ident, type);
2281 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2283 DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2284 TREE_READONLY (decl->sinit) = 1;
2286 return decl->sinit;
2289 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2290 and optionally prefixing the name with PREFIX. */
2292 tree
2293 build_artificial_decl (tree type, tree init, const char *prefix)
2295 tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2296 const char *name = prefix ? prefix : "___s";
2297 char *label;
2299 ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2300 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2301 DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2303 TREE_PUBLIC (decl) = 0;
2304 TREE_STATIC (decl) = 1;
2305 TREE_USED (decl) = 1;
2306 DECL_IGNORED_P (decl) = 1;
2307 DECL_ARTIFICIAL (decl) = 1;
2309 /* Perhaps at some point the initializer constant should be hashed
2310 to remove duplicates. */
2311 DECL_INITIAL (decl) = init;
2313 return decl;
2316 /* Build TYPE_DECL for the declaration DSYM. */
2318 void
2319 build_type_decl (tree type, Dsymbol *dsym)
2321 if (TYPE_STUB_DECL (type))
2322 return;
2324 gcc_assert (!POINTER_TYPE_P (type));
2326 /* If a templated type, use the template instance name, as that includes all
2327 template parameters. */
2328 const char *name = dsym->parent->isTemplateInstance ()
2329 ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2331 tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2332 get_identifier (name), type);
2333 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (mangle_decl (dsym)));
2334 TREE_PUBLIC (decl) = 1;
2335 DECL_ARTIFICIAL (decl) = 1;
2336 DECL_CONTEXT (decl) = d_decl_context (dsym);
2338 TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2339 TYPE_NAME (type) = decl;
2341 /* Not sure if there is a need for separate TYPE_DECLs in
2342 TYPE_NAME and TYPE_STUB_DECL. */
2343 if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2344 TYPE_STUB_DECL (type) = decl;
2346 rest_of_decl_compilation (decl, SCOPE_FILE_SCOPE_P (decl), 0);
2349 /* Create a declaration for field NAME of a given TYPE, setting the flags
2350 for whether the field is ARTIFICIAL and/or IGNORED. */
2352 tree
2353 create_field_decl (tree type, const char *name, int artificial, int ignored)
2355 tree decl = build_decl (input_location, FIELD_DECL,
2356 name ? get_identifier (name) : NULL_TREE, type);
2357 DECL_ARTIFICIAL (decl) = artificial;
2358 DECL_IGNORED_P (decl) = ignored;
2360 return decl;
2363 /* Return the COMDAT group into which DECL should be placed. */
2365 static tree
2366 d_comdat_group (tree decl)
2368 /* If already part of a comdat group, use that. */
2369 if (DECL_COMDAT_GROUP (decl))
2370 return DECL_COMDAT_GROUP (decl);
2372 return DECL_ASSEMBLER_NAME (decl);
2375 /* Set DECL up to have the closest approximation of "initialized common"
2376 linkage available. */
2378 void
2379 d_comdat_linkage (tree decl)
2381 if (flag_weak)
2382 make_decl_one_only (decl, d_comdat_group (decl));
2383 else if (TREE_CODE (decl) == FUNCTION_DECL
2384 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2385 /* We can just emit function and compiler-generated variables statically;
2386 having multiple copies is (for the most part) only a waste of space. */
2387 TREE_PUBLIC (decl) = 0;
2388 else if (DECL_INITIAL (decl) == NULL_TREE
2389 || DECL_INITIAL (decl) == error_mark_node)
2390 /* Fallback, cannot have multiple copies. */
2391 DECL_COMMON (decl) = 1;
2393 if (TREE_PUBLIC (decl))
2394 DECL_COMDAT (decl) = 1;
2397 /* Set DECL up to have the closest approximation of "linkonce" linkage. */
2399 void
2400 d_linkonce_linkage (tree decl)
2402 /* Weak definitions have to be public. */
2403 if (!TREE_PUBLIC (decl))
2404 return;
2406 /* Necessary to allow DECL_ONE_ONLY or DECL_WEAK functions to be inlined. */
2407 if (TREE_CODE (decl) == FUNCTION_DECL)
2408 DECL_DECLARED_INLINE_P (decl) = 1;
2410 /* No weak support, fallback to COMDAT linkage. */
2411 if (!flag_weak)
2412 return d_comdat_linkage (decl);
2414 make_decl_one_only (decl, d_comdat_group (decl));