d: Fix ICE in build_deref, at d/d-codegen.cc:1650 [PR111650]
[official-gcc.git] / gcc / d / decl.cc
blob0a87c85ae2e516d0100a3cb5b9d389ede789eac4
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2 Copyright (C) 2006-2024 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 dmd::mangleExact ((FuncDeclaration *) decl);
73 else
75 OutBuffer buf;
76 dmd::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;
166 param_list = chainon (param_list, parm_decl);
169 /* `_arguments' parameter. */
170 if (decl->v_arguments)
172 tree parm_decl = get_symbol_decl (decl->v_arguments);
173 param_list = chainon (param_list, parm_decl);
176 /* Now add on formal function parameters. */
177 size_t n_parameters = decl->parameters ? decl->parameters->length : 0;
179 for (size_t i = 0; i < n_parameters; i++)
181 VarDeclaration *param = (*decl->parameters)[i];
182 tree parm_decl = get_symbol_decl (param);
184 /* Type `noreturn` is a terminator, as no other arguments can possibly
185 be evaluated after it. */
186 if (TREE_TYPE (parm_decl) == noreturn_type_node)
187 break;
189 /* Chain them in the correct order. */
190 param_list = chainon (param_list, parm_decl);
193 else
195 /* Build parameters from the function type. */
196 tree fntype = TREE_TYPE (fndecl);
198 for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
200 if (t == void_list_node)
201 break;
203 tree param = build_decl (DECL_SOURCE_LOCATION (fndecl),
204 PARM_DECL, NULL_TREE, TREE_VALUE (t));
205 DECL_ARG_TYPE (param) = TREE_TYPE (param);
206 DECL_ARTIFICIAL (param) = 1;
207 DECL_IGNORED_P (param) = 1;
208 DECL_CONTEXT (param) = fndecl;
209 param_list = chainon (param_list, param);
213 DECL_ARGUMENTS (fndecl) = param_list;
214 return param_list;
217 /* Implements the visitor interface to lower all Declaration AST classes
218 emitted from the D Front-end to GCC trees.
219 All visit methods accept one parameter D, which holds the frontend AST
220 of the declaration to compile. These also don't return any value, instead
221 generated code are appened to global_declarations or added to the
222 current_binding_level by d_pushdecl(). */
224 class DeclVisitor : public Visitor
226 using Visitor::visit;
228 /* If we're lowering the body of a version(unittest) condition. */
229 bool in_version_unittest_;
231 public:
232 DeclVisitor (void)
234 this->in_version_unittest_ = false;
237 /* Helper for generating code for the dsymbol AST class D.
238 Sets up the location of the symbol before lowering. */
240 void build_dsymbol (Dsymbol *d)
242 location_t saved_location = input_location;
243 input_location = make_location_t (d->loc);
244 d->accept (this);
245 input_location = saved_location;
248 /* This should be overridden by each declaration class. */
250 void visit (Dsymbol *) final override
254 /* Compile a D module, and all members of it. */
256 void visit (Module *d) final override
258 if (d->semanticRun >= PASS::obj)
259 return;
261 build_module_tree (d);
262 d->semanticRun = PASS::obj;
265 /* Write the imported symbol to debug. */
267 void visit (Import *d) final override
269 if (d->semanticRun >= PASS::obj)
270 return;
272 /* Implements import declarations by telling the debug back-end we are
273 importing the NAMESPACE_DECL of the module or IMPORTED_DECL of the
274 declaration into the current lexical scope CONTEXT. NAME is set if
275 this is a renamed import. */
276 if (d->isstatic)
277 return;
279 /* Get the context of this import, this should never be null. */
280 tree context = d_module_context ();
282 if (d->ident == NULL)
284 /* Importing declaration list. */
285 for (size_t i = 0; i < d->names.length; i++)
287 AliasDeclaration *aliasdecl = d->aliasdecls[i];
288 tree decl = build_import_decl (aliasdecl);
290 /* Skip over unhandled imports. */
291 if (decl == NULL_TREE)
292 continue;
294 Identifier *alias = d->aliases[i];
295 tree name = (alias != NULL)
296 ? get_identifier (alias->toChars ()) : NULL_TREE;
298 if (TREE_CODE (decl) != TREE_LIST)
299 debug_hooks->imported_module_or_decl (decl, name, context,
300 false, false);
301 else
303 /* Overload sets return a list of imported decls. */
304 for (; decl != NULL_TREE; decl = TREE_CHAIN (decl))
305 debug_hooks->imported_module_or_decl (TREE_VALUE (decl), name,
306 context, false, false);
310 else
312 /* Importing the entire module. */
313 tree decl = build_import_decl (d->mod);
315 tree name = (d->aliasId != NULL)
316 ? get_identifier (d->aliasId->toChars ()) : NULL_TREE;
318 debug_hooks->imported_module_or_decl (decl, name, context,
319 false, false);
322 d->semanticRun = PASS::obj;
325 /* Finish a top-level `asm` definition. */
327 void visit (CAsmDeclaration *d) final override
329 tree asm_str = build_expr (d->code);
330 symtab->finalize_toplevel_asm (asm_str);
333 /* Expand any local variables found in tuples. */
335 void visit (TupleDeclaration *d) final override
337 for (size_t i = 0; i < d->objects->length; i++)
339 RootObject *o = (*d->objects)[i];
340 if (o->dyncast () == DYNCAST_EXPRESSION)
342 VarExp *ve = ((Expression *) o)->isVarExp ();
343 if (ve)
344 this->build_dsymbol (ve->var);
349 /* Walk over all declarations in the attribute scope. */
351 void visit (AttribDeclaration *d) final override
353 Dsymbols *ds = d->include (NULL);
355 if (!ds)
356 return;
358 for (size_t i = 0; i < ds->length; i++)
359 this->build_dsymbol ((*ds)[i]);
362 /* Pragmas are a way to pass special information to the compiler and to add
363 vendor specific extensions to D. */
365 void visit (PragmaDeclaration *d) final override
367 if (d->ident == Identifier::idPool ("lib")
368 || d->ident == Identifier::idPool ("startaddress"))
370 if (!global.params.ignoreUnsupportedPragmas)
372 warning_at (make_location_t (d->loc), OPT_Wunknown_pragmas,
373 "pragma(%s) not implemented", d->ident->toChars ());
377 visit ((AttribDeclaration *) d);
380 /* Conditional compilation is the process of selecting which code to compile
381 and which code to not compile. Look for version conditions that may */
383 void visit (ConditionalDeclaration *d) final override
385 bool old_condition = this->in_version_unittest_;
387 if (global.params.useUnitTests)
389 VersionCondition *vc = d->condition->isVersionCondition ();
390 if (vc && vc->ident == Identifier::idPool ("unittest"))
391 this->in_version_unittest_ = true;
394 visit ((AttribDeclaration *) d);
396 this->in_version_unittest_ = old_condition;
399 /* Walk over all members in the namespace scope. */
401 void visit (Nspace *d) final override
403 if (dmd::isError (d) || !d->members)
404 return;
406 for (size_t i = 0; i < d->members->length; i++)
407 this->build_dsymbol ((*d->members)[i]);
410 /* Templates are D's approach to generic programming. They have no members
411 that can be emitted, however if the template is nested and used as a
412 voldemort type, then it's members must be compiled before the parent
413 function finishes. */
415 void visit (TemplateDeclaration *d) final override
417 /* Type cannot be directly named outside of the scope it's declared in, so
418 the only way it can be escaped is if the function has auto return. */
419 FuncDeclaration *fd = d_function_chain ? d_function_chain->function : NULL;
421 if (!fd || !fd->isAuto ())
422 return;
424 /* Check if the function returns an instantiated type that may contain
425 nested members. Only applies to classes or structs. */
426 Type *tb = fd->type->nextOf ()->baseElemOf ();
428 while (tb->ty == TY::Tarray || tb->ty == TY::Tpointer)
429 tb = tb->nextOf ()->baseElemOf ();
431 TemplateInstance *ti = NULL;
433 if (tb->ty == TY::Tstruct)
434 ti = tb->isTypeStruct ()->sym->isInstantiated ();
435 else if (tb->ty == TY::Tclass)
436 ti = tb->isTypeClass ()->sym->isInstantiated ();
438 /* Return type is instantiated from this template declaration, walk over
439 all members of the instance. */
440 if (ti && ti->tempdecl == d)
441 this->build_dsymbol (ti);
444 /* Walk over all members in the instantiated template. */
446 void visit (TemplateInstance *d) final override
448 if (dmd::isError (d)|| !d->members)
449 return;
451 if (!d->needsCodegen ())
452 return;
454 for (size_t i = 0; i < d->members->length; i++)
455 this->build_dsymbol ((*d->members)[i]);
458 /* Walk over all members in the mixin template scope. */
460 void visit (TemplateMixin *d) final override
462 if (dmd::isError (d)|| !d->members)
463 return;
465 for (size_t i = 0; i < d->members->length; i++)
466 this->build_dsymbol ((*d->members)[i]);
469 /* Write out compiler generated TypeInfo, initializer and functions for the
470 given struct declaration, walking over all static members. */
472 void visit (StructDeclaration *d) final override
474 if (d->semanticRun >= PASS::obj)
475 return;
477 if (d->type->ty == TY::Terror)
479 error_at (make_location_t (d->loc),
480 "had semantic errors when compiling");
481 return;
484 /* Don't emit any symbols from gcc.attributes module. */
485 if (gcc_attribute_p (d))
486 return;
488 /* Add this decl to the current binding level. */
489 tree ctype = build_ctype (d->type);
490 if (TYPE_NAME (ctype))
491 d_pushdecl (TYPE_NAME (ctype));
493 /* Anonymous structs/unions only exist as part of others,
494 do not output forward referenced structs. */
495 if (d->isAnonymous () || !d->members)
496 return;
498 /* Generate TypeInfo. */
499 if (have_typeinfo_p (Type::dtypeinfo))
500 create_typeinfo (d->type, NULL);
502 /* Generate static initializer. */
503 tree sinit = aggregate_initializer_decl (d);
504 DECL_INITIAL (sinit) = layout_struct_initializer (d);
505 d_finish_decl (sinit);
507 /* Put out the members. There might be static constructors in the members
508 list, and they cannot be put in separate object files. */
509 for (size_t i = 0; i < d->members->length; i++)
510 this->build_dsymbol ((*d->members)[i]);
512 /* Put out xopEquals, xopCmp and xopHash. */
513 if (d->xeq && d->xeq != d->xerreq)
514 this->build_dsymbol (d->xeq);
516 if (d->xcmp && d->xcmp != d->xerrcmp)
517 this->build_dsymbol (d->xcmp);
519 if (d->xhash)
520 this->build_dsymbol (d->xhash);
522 d->semanticRun = PASS::obj;
525 /* Finish semantic analysis of functions in vtbl for class CD. */
527 bool finish_vtable (ClassDeclaration *d)
529 bool has_errors = false;
531 /* Finish semantic analysis of functions in vtbl[]. */
532 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
534 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
536 if (!fd || (!fd->fbody && d->isAbstract ()))
537 continue;
539 /* Ensure function has a return value. */
540 if (!dmd::functionSemantic (fd))
541 has_errors = true;
543 /* No name hiding to check for. */
544 if (!d->isFuncHidden (fd) || fd->isFuture ())
545 continue;
547 /* The function fd is hidden from the view of the class.
548 If it overlaps with any function in the vtbl[], then
549 issue an error. */
550 for (size_t j = 1; j < d->vtbl.length; j++)
552 if (j == i)
553 continue;
555 FuncDeclaration *fd2 = d->vtbl[j]->isFuncDeclaration ();
556 if (!fd2->ident->equals (fd->ident))
557 continue;
559 /* The function is marked as @__future, a deprecation has
560 already been given by the frontend. */
561 if (fd2->isFuture ())
562 continue;
564 if (FuncDeclaration::leastAsSpecialized (fd, fd2, NULL)
565 == MATCH::nomatch
566 && FuncDeclaration::leastAsSpecialized (fd2, fd, NULL)
567 == MATCH::nomatch)
568 continue;
570 /* Hiding detected; same name, overlapping specializations. */
571 error_at (make_location_t (fd->loc), "use of %qs",
572 fd->toPrettyChars ());
573 inform (make_location_t (fd2->loc), "is hidden by %qs",
574 fd2->toPrettyChars ());
575 inform (make_location_t (d->loc),
576 "use %<alias %s = %s.%s;%> to introduce base class "
577 "overload set", fd->toChars (),
578 fd->parent->toChars (), fd->toChars ());
579 has_errors = true;
580 break;
584 return !has_errors;
587 /* Write out compiler generated TypeInfo, initializer and vtables for the
588 given class declaration, walking over all static members. */
590 void visit (ClassDeclaration *d) final override
592 if (d->semanticRun >= PASS::obj)
593 return;
595 if (d->type->ty == TY::Terror)
597 error_at (make_location_t (d->loc),
598 "had semantic errors when compiling");
599 return;
602 /* Add this decl to the current binding level. */
603 tree ctype = TREE_TYPE (build_ctype (d->type));
604 if (TYPE_NAME (ctype))
605 d_pushdecl (TYPE_NAME (ctype));
607 if (!d->members)
608 return;
610 /* Put out the members. */
611 for (size_t i = 0; i < d->members->length; i++)
612 this->build_dsymbol ((*d->members)[i]);
614 /* If something goes wrong during final semantic pass, don't bother with
615 the rest as we may have incomplete info. */
616 if (!this->finish_vtable (d))
617 return;
619 /* Generate C symbols. */
620 d->csym = get_classinfo_decl (d);
621 Dsymbol *vtblsym = d->vtblSymbol ();
622 vtblsym->csym = get_vtable_decl (d);
623 tree sinit = aggregate_initializer_decl (d);
625 /* Generate static initializer. */
626 DECL_INITIAL (sinit) = layout_class_initializer (d);
627 d_finish_decl (sinit);
629 /* Put out the TypeInfo. */
630 if (have_typeinfo_p (Type::dtypeinfo))
631 create_typeinfo (d->type, NULL);
633 DECL_INITIAL (d->csym) = layout_classinfo (d);
634 d_finish_decl (d->csym);
636 /* Put out the vtbl[]. */
637 vec <constructor_elt, va_gc> *elms = NULL;
639 /* First entry is ClassInfo reference. */
640 if (d->vtblOffset ())
641 CONSTRUCTOR_APPEND_ELT (elms, size_zero_node, build_address (d->csym));
643 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
645 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
647 if (fd && (fd->fbody || !d->isAbstract ()))
649 CONSTRUCTOR_APPEND_ELT (elms, size_int (i),
650 build_address (get_symbol_decl (fd)));
654 DECL_INITIAL (vtblsym->csym)
655 = build_constructor (TREE_TYPE (vtblsym->csym), elms);
656 d_finish_decl (vtblsym->csym);
658 d->semanticRun = PASS::obj;
661 /* Write out compiler generated TypeInfo and vtables for the given interface
662 declaration, walking over all static members. */
664 void visit (InterfaceDeclaration *d) final override
666 if (d->semanticRun >= PASS::obj)
667 return;
669 if (d->type->ty == TY::Terror)
671 error_at (make_location_t (d->loc),
672 "had semantic errors when compiling");
673 return;
676 /* Add this decl to the current binding level. */
677 tree ctype = TREE_TYPE (build_ctype (d->type));
678 if (TYPE_NAME (ctype))
679 d_pushdecl (TYPE_NAME (ctype));
681 if (!d->members)
682 return;
684 /* Put out the members. */
685 for (size_t i = 0; i < d->members->length; i++)
686 this->build_dsymbol ((*d->members)[i]);
688 /* Generate C symbols. */
689 d->csym = get_classinfo_decl (d);
691 /* Put out the TypeInfo. */
692 if (have_typeinfo_p (Type::dtypeinfo))
694 create_typeinfo (d->type, NULL);
695 this->build_dsymbol (d->type->vtinfo);
698 DECL_INITIAL (d->csym) = layout_classinfo (d);
699 d_finish_decl (d->csym);
701 d->semanticRun = PASS::obj;
704 /* Write out compiler generated TypeInfo and initializer for the given
705 enum declaration. */
707 void visit (EnumDeclaration *d) final override
709 if (d->semanticRun >= PASS::obj)
710 return;
712 if (d->errors || d->type->ty == TY::Terror)
714 error_at (make_location_t (d->loc),
715 "had semantic errors when compiling");
716 return;
719 /* Add this decl to the current binding level. */
720 tree ctype = build_ctype (d->type);
721 if (TREE_CODE (ctype) == ENUMERAL_TYPE && TYPE_NAME (ctype))
722 d_pushdecl (TYPE_NAME (ctype));
724 if (d->isAnonymous ())
725 return;
727 /* Generate TypeInfo. */
728 if (have_typeinfo_p (Type::dtypeinfo))
729 create_typeinfo (d->type, NULL);
731 TypeEnum *tc = d->type->isTypeEnum ();
732 if (tc->sym->members && !d->type->isZeroInit ())
734 /* Generate static initializer. */
735 d->sinit = enum_initializer_decl (d);
736 DECL_INITIAL (d->sinit) = build_expr (tc->sym->defaultval, true);
737 d_finish_decl (d->sinit);
740 d->semanticRun = PASS::obj;
743 /* Finish up a variable declaration and push it into the current scope.
744 This can either be a static, local or manifest constant. */
746 void visit (VarDeclaration *d) final override
748 if (d->semanticRun >= PASS::obj)
749 return;
751 if (d->type->ty == TY::Terror)
753 error_at (make_location_t (d->loc),
754 "had semantic errors when compiling");
755 return;
758 /* Variables of type `noreturn` are just placeholders, and evaluate to
759 `assert(0)` if ever read. */
760 if (d->type->isTypeNoreturn ())
762 if (!d->isDataseg () && !d->isMember ()
763 && d->_init && !d->_init->isVoidInitializer ())
765 /* Evaluate RHS for side effects first. */
766 Expression *ie = dmd::initializerToExpression (d->_init);
767 add_stmt (build_expr (ie));
769 Expression *e = d->type->defaultInitLiteral (d->loc);
770 add_stmt (build_expr (e));
773 return;
776 if (d->aliasTuple)
778 this->build_dsymbol (d->toAlias ());
779 return;
782 if (!d->canTakeAddressOf ())
784 /* Do not store variables we cannot take the address of,
785 but keep the values for purposes of debugging. */
786 if (d->type->isscalar () && !dmd::hasPointers (d->type))
788 tree decl = get_symbol_decl (d);
789 d_pushdecl (decl);
790 rest_of_decl_compilation (decl, 1, 0);
793 else if (d->isDataseg ())
795 tree decl = get_symbol_decl (d);
797 /* Only need to build the VAR_DECL for extern declarations. */
798 if (d->storage_class & STCextern)
799 return;
801 /* Duplicated VarDeclarations map to the same symbol. Check if this
802 is the one declaration which will be emitted. */
803 tree ident = DECL_ASSEMBLER_NAME (decl);
804 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
805 return;
807 /* How big a symbol can be should depend on back-end. */
808 tree size = build_integer_cst (d->type->size (d->loc),
809 build_ctype (Type::tsize_t));
810 if (!valid_constant_size_p (size))
812 error_at (make_location_t (d->loc), "size is too large");
813 return;
816 if (d->_init)
818 /* Use the explicit initializer, this includes `void`. */
819 if (!d->_init->isVoidInitializer ())
821 Expression *e =
822 dmd::initializerToExpression (d->_init, d->type);
823 DECL_INITIAL (decl) = build_expr (e, true);
826 else if (!d->type->isZeroInit ())
828 /* Use default initializer for the type. */
829 if (TypeStruct *ts = d->type->isTypeStruct ())
830 DECL_INITIAL (decl) = layout_struct_initializer (ts->sym);
831 else
833 Expression *e = d->type->defaultInitLiteral (d->loc);
834 DECL_INITIAL (decl) = build_expr (e, true);
838 /* Frontend should have already caught this. */
839 gcc_assert (!integer_zerop (size)
840 || d->type->toBasetype ()->isTypeSArray ());
842 d_finish_decl (decl);
844 /* Maybe record the var against the current module. */
845 register_module_decl (d);
847 else if (!d->isDataseg () && !d->isMember ())
849 /* This is needed for VarDeclarations in mixins that are to be local
850 variables of a function. Otherwise, it would be enough to make
851 a check for isVarDeclaration() in DeclarationExp codegen. */
852 declare_local_var (d);
854 if (d->_init && !d->_init->isVoidInitializer ())
856 tree decl = get_symbol_decl (d);
858 ExpInitializer *vinit = d->_init->isExpInitializer ();
859 Expression *ie = dmd::initializerToExpression (vinit);
860 tree exp = build_expr (ie);
862 /* Maybe put variable on list of things needing destruction. */
863 if (d->needsScopeDtor ())
865 /* Rewrite: `decl = exp' => TARGET_EXPR(decl, exp, dtor). */
866 vec_safe_push (d_function_chain->vars_in_scope, decl);
868 /* Force a TARGET_EXPR to add the corresponding cleanup. */
869 if (TREE_CODE (exp) != TARGET_EXPR)
871 if (VOID_TYPE_P (TREE_TYPE (exp)))
872 exp = compound_expr (exp, decl);
874 exp = force_target_expr (exp);
877 TARGET_EXPR_CLEANUP (exp)
878 = compound_expr (TARGET_EXPR_CLEANUP (exp),
879 build_expr (d->edtor));
881 /* The decl is really an alias for the TARGET_EXPR slot. */
882 SET_DECL_VALUE_EXPR (decl, TARGET_EXPR_SLOT (exp));
883 DECL_HAS_VALUE_EXPR_P (decl) = 1;
884 /* This tells the gimplifier not to emit a clobber for the decl
885 as its lifetime ends when the slot gets cleaned up. */
886 TREE_ADDRESSABLE (decl) = 0;
889 add_stmt (exp);
893 d->semanticRun = PASS::obj;
896 /* Generate and compile a static TypeInfo declaration, but only if it is
897 needed in the current compilation. */
899 void visit (TypeInfoDeclaration *d) final override
901 if (d->semanticRun >= PASS::obj)
902 return;
904 if (speculative_type_p (d->tinfo))
905 return;
907 tree t = get_typeinfo_decl (d);
908 DECL_INITIAL (t) = layout_typeinfo (d);
909 d_finish_decl (t);
910 d->semanticRun = PASS::obj;
913 /* Finish up a function declaration and compile it all the way
914 down to assembler language output. */
916 void visit (FuncDeclaration *d) final override
918 /* Already generated the function. */
919 if (d->semanticRun >= PASS::obj)
920 return;
922 /* Don't emit any symbols from gcc.attributes module. */
923 if (gcc_attribute_p (d))
924 return;
926 /* Front-end decided this function doesn't require code generation. */
927 if (d->skipCodegen ())
928 return;
930 /* Not emitting unittest functions. */
931 if (!global.params.useUnitTests && d->isUnitTestDeclaration ())
932 return;
934 /* Check if any errors occurred when running semantic. */
935 if (TypeFunction *tf = d->type->isTypeFunction ())
937 if (tf->next == NULL || tf->next->ty == TY::Terror)
938 return;
941 if (d->hasSemantic3Errors ())
942 return;
944 if (d->isNested ())
946 FuncDeclaration *fdp = d;
947 while (fdp && fdp->isNested ())
949 fdp = fdp->toParent2 ()->isFuncDeclaration ();
951 if (fdp == NULL)
952 break;
954 /* Parent failed to compile, but errors were gagged. */
955 if (fdp->hasSemantic3Errors ())
956 return;
960 /* Ensure all semantic passes have run. */
961 if (d->semanticRun < PASS::semantic3)
963 gcc_assert (!doing_semantic_analysis_p);
965 doing_semantic_analysis_p = true;
966 dmd::functionSemantic3 (d);
967 Module::runDeferredSemantic3 ();
968 doing_semantic_analysis_p = false;
971 if (global.errors)
972 return;
974 /* Start generating code for this function. */
975 gcc_assert (d->semanticRun == PASS::semantic3done);
976 d->semanticRun = PASS::obj;
978 /* Duplicated FuncDeclarations map to the same symbol. Check if this
979 is the one declaration which will be emitted. */
980 tree fndecl = get_symbol_decl (d);
981 tree ident = DECL_ASSEMBLER_NAME (fndecl);
982 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
983 return;
985 if (!d->fbody)
987 rest_of_decl_compilation (fndecl, 1, 0);
988 return;
991 if (global.params.v.verbose)
992 message ("function %s", d->toPrettyChars ());
994 tree old_context = start_function (d);
995 tree param_list = get_fndecl_arguments (d);
997 DECL_IN_UNITTEST_CONDITION_P (fndecl) = this->in_version_unittest_;
998 rest_of_decl_compilation (fndecl, 1, 0);
1000 /* If this is a member function that nested (possibly indirectly) in another
1001 function, construct an expession for this member function's static chain
1002 by going through parent link of nested classes. */
1003 if (d->vthis)
1004 d_function_chain->static_chain = get_symbol_decl (d->vthis);
1006 if (d->isThis ())
1008 AggregateDeclaration *ad = d->isThis ();
1009 tree this_tree = get_symbol_decl (d->vthis);
1011 while (ad->isNested ())
1013 Dsymbol *pd = ad->toParent2 ();
1014 tree vthis_field = get_symbol_decl (ad->vthis);
1015 this_tree = component_ref (build_deref (this_tree), vthis_field);
1017 ad = pd->isAggregateDeclaration ();
1018 if (ad == NULL)
1020 d_function_chain->static_chain = this_tree;
1021 break;
1026 /* Named return value optimisation support for D.
1027 Implemented by overriding all the RETURN_EXPRs and replacing all
1028 occurrences of VAR with the RESULT_DECL for the function.
1029 This is only worth doing for functions that can return in memory. */
1030 tree resdecl = DECL_RESULT (fndecl);
1032 if (TREE_ADDRESSABLE (TREE_TYPE (resdecl))
1033 || aggregate_value_p (TREE_TYPE (resdecl), fndecl))
1035 /* Return non-trivial structs by invisible reference. */
1036 if (TREE_ADDRESSABLE (TREE_TYPE (resdecl)))
1038 TREE_TYPE (resdecl) = build_reference_type (TREE_TYPE (resdecl));
1039 DECL_BY_REFERENCE (resdecl) = 1;
1040 TREE_ADDRESSABLE (resdecl) = 0;
1041 relayout_decl (resdecl);
1042 d->shidden = build_deref (resdecl);
1044 else
1045 d->shidden = resdecl;
1047 if (d->isNRVO () && d->nrvo_var)
1049 tree var = get_symbol_decl (d->nrvo_var);
1051 /* Copy name from VAR to RESULT. */
1052 DECL_NAME (resdecl) = DECL_NAME (var);
1053 /* Don't forget that we take its address. */
1054 TREE_ADDRESSABLE (var) = 1;
1056 SET_DECL_VALUE_EXPR (var, resdecl);
1057 DECL_HAS_VALUE_EXPR_P (var) = 1;
1058 SET_DECL_LANG_NRVO (var, d->shidden);
1062 /* May change cfun->static_chain. */
1063 build_closure (d);
1065 /* Replace generic pointer with back-end closure type
1066 (this wins for gdb). */
1067 if (d->vthis && d->vthis->type == Type::tvoidptr)
1069 tree frame_type = FRAMEINFO_TYPE (get_frameinfo (d));
1070 gcc_assert (frame_type != NULL_TREE);
1071 tree parm_decl = get_symbol_decl (d->vthis);
1072 TREE_TYPE (parm_decl) = build_pointer_type (frame_type);
1075 if (d->vresult)
1076 declare_local_var (d->vresult);
1078 if (d->v_argptr)
1079 push_stmt_list ();
1081 build_function_body (d);
1083 /* Initialize the _argptr variable. */
1084 if (d->v_argptr)
1086 tree body = pop_stmt_list ();
1087 tree var = get_decl_tree (d->v_argptr);
1088 var = build_address (var);
1090 tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
1091 2, var, tree_last (param_list));
1092 declare_local_var (d->v_argptr);
1093 add_stmt (init);
1095 tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
1096 1, var);
1097 add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
1100 finish_function (old_context);
1102 /* Maybe record the function against the current module. */
1103 register_module_decl (d);
1107 /* Main entry point for the DeclVisitor interface to send
1108 the Declaration AST class D to GCC back-end. */
1110 void
1111 build_decl_tree (Dsymbol *d)
1113 location_t saved_location = input_location;
1115 /* Set input location, empty DECL_SOURCE_FILE can crash debug generator. */
1116 if (d->loc.filename ())
1117 input_location = make_location_t (d->loc);
1118 else
1119 input_location = make_location_t (Loc ("<no_file>", 1, 0));
1121 DeclVisitor v = DeclVisitor ();
1122 v.build_dsymbol (d);
1124 input_location = saved_location;
1127 /* Returns true if function FD always needs to be implicitly defined, such as
1128 it was declared `pragma(inline)'. */
1130 static bool
1131 function_needs_inline_definition_p (FuncDeclaration *fd)
1133 /* Function has already been defined. */
1134 if (!DECL_EXTERNAL (fd->csym))
1135 return false;
1137 /* No function body available for inlining. */
1138 if (!fd->fbody)
1139 return false;
1141 /* These functions are tied to the module they are defined in. */
1142 if (fd->isFuncLiteralDeclaration ()
1143 || fd->isUnitTestDeclaration ()
1144 || fd->isFuncAliasDeclaration ()
1145 || fd->isInvariantDeclaration ())
1146 return false;
1148 /* Check whether function will be regularly defined later in the current
1149 translation unit. */
1150 Module *md = fd->getModule ();
1151 if (md && md->isRoot ())
1152 return false;
1154 /* Non-inlineable functions are always external. */
1155 if (DECL_UNINLINABLE (fd->csym))
1156 return false;
1158 /* Ignore functions that aren't decorated with `pragma(inline)'. */
1159 if (!DECL_DECLARED_INLINE_P (fd->csym))
1160 return false;
1162 /* Weak functions cannot be inlined. */
1163 if (lookup_attribute ("weak", DECL_ATTRIBUTES (fd->csym)))
1164 return false;
1166 /* Naked functions cannot be inlined. */
1167 if (lookup_attribute ("naked", DECL_ATTRIBUTES (fd->csym)))
1168 return false;
1170 return true;
1173 /* If the variable or function declaration in DECL needs to be defined, add it
1174 to the list of deferred declarations to build later. */
1176 static tree
1177 maybe_build_decl_tree (Declaration *decl)
1179 gcc_assert (decl->csym != NULL_TREE);
1181 /* Still running semantic analysis on declaration, or it has already had its
1182 code generated. */
1183 if (doing_semantic_analysis_p || decl->semanticRun >= PASS::obj)
1184 return decl->csym;
1186 if (error_operand_p (decl->csym))
1187 return decl->csym;
1189 if (FuncDeclaration *fd = decl->isFuncDeclaration ())
1191 /* Externally defined inline functions need to be emitted. */
1192 if (function_needs_inline_definition_p (fd))
1194 DECL_EXTERNAL (fd->csym) = 0;
1195 d_defer_declaration (fd);
1199 return decl->csym;
1202 /* Return the decl for the symbol, create it if it doesn't already exist. */
1204 tree
1205 get_symbol_decl (Declaration *decl)
1207 if (decl->csym)
1208 return maybe_build_decl_tree (decl);
1210 /* Deal with placeholder symbols immediately:
1211 SymbolDeclaration is used as a shell around an initializer symbol. */
1212 SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1213 if (sd)
1215 decl->csym = aggregate_initializer_decl (sd->dsym);
1216 return decl->csym;
1219 /* Global static TypeInfo declaration. */
1220 if (decl->isTypeInfoDeclaration ())
1221 return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1223 /* FuncAliasDeclaration is used to import functions from another scope. */
1224 FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1225 if (fad)
1227 decl->csym = get_symbol_decl (fad->funcalias);
1228 return decl->csym;
1231 /* It is possible for a field declaration symbol to be requested
1232 before the parent type has been built. */
1233 if (decl->isField ())
1235 AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1236 gcc_assert (ad != NULL);
1238 /* Finishing off the type should create the associated FIELD_DECL. */
1239 build_ctype (ad->type);
1240 gcc_assert (decl->csym != NULL);
1242 return decl->csym;
1245 if (VarDeclaration *vd = decl->isVarDeclaration ())
1247 /* CONST_DECL was initially intended for enumerals and may be used for
1248 scalars in general, but not for aggregates. Here a non-constant
1249 value is generated anyway so as its value can be used. */
1250 if (!vd->canTakeAddressOf () && !vd->type->isscalar ())
1252 gcc_assert (vd->_init && !vd->_init->isVoidInitializer ());
1253 Expression *ie = dmd::initializerToExpression (vd->_init);
1254 decl->csym = build_expr (ie, false);
1255 return decl->csym;
1259 /* Build the tree for the symbol. */
1260 FuncDeclaration *fd = decl->isFuncDeclaration ();
1261 if (fd)
1263 /* Run full semantic on functions we need to know about. */
1264 if (!dmd::functionSemantic (fd))
1266 decl->csym = error_mark_node;
1267 return decl->csym;
1270 decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1271 get_identifier (decl->ident->toChars ()),
1272 NULL_TREE);
1274 /* Set function type afterwards as there could be self references. */
1275 TREE_TYPE (decl->csym) = build_ctype (fd->type);
1277 /* Set DECL_INITIAL now if the function has a definition. */
1278 if (fd->fbody)
1279 DECL_INITIAL (decl->csym) = error_mark_node;
1280 else
1281 DECL_EXTERNAL (decl->csym) = 1;
1283 else
1285 /* Build the variable declaration. */
1286 VarDeclaration *vd = decl->isVarDeclaration ();
1287 gcc_assert (vd != NULL);
1289 tree_code code = vd->isParameter () ? PARM_DECL
1290 : !vd->canTakeAddressOf () ? CONST_DECL
1291 : VAR_DECL;
1292 decl->csym = build_decl (make_location_t (decl->loc), code,
1293 get_identifier (decl->ident->toChars ()),
1294 declaration_type (vd));
1296 /* If any alignment was set on the declaration. */
1297 if (!vd->alignment.isDefault ())
1299 SET_DECL_ALIGN (decl->csym, vd->alignment.get () * BITS_PER_UNIT);
1300 DECL_USER_ALIGN (decl->csym) = 1;
1303 if (vd->storage_class & STCextern)
1304 DECL_EXTERNAL (decl->csym) = 1;
1306 if (!vd->canTakeAddressOf ())
1308 /* Cannot make an expression out of a void initializer. */
1309 gcc_assert (vd->_init && !vd->_init->isVoidInitializer ());
1310 /* Non-scalar manifest constants have already been dealt with. */
1311 gcc_assert (vd->type->isscalar ());
1313 Expression *ie = dmd::initializerToExpression (vd->_init);
1314 DECL_INITIAL (decl->csym) = build_expr (ie, true);
1317 /* [type-qualifiers/const-and-immutable]
1319 `immutable` applies to data that cannot change. Immutable data values,
1320 once constructed, remain the same for the duration of the program's
1321 execution. */
1322 if (vd->isImmutable () && !vd->setInCtorOnly ())
1323 TREE_READONLY (decl->csym) = 1;
1325 /* `const` applies to data that cannot be changed by the const reference
1326 to that data. It may, however, be changed by another reference to that
1327 same data. */
1328 if (vd->isConst () && !vd->isDataseg ())
1329 TREE_READONLY (decl->csym) = 1;
1332 /* Set the declaration mangled identifier if static. */
1333 if (decl->isCodeseg () || decl->isDataseg ())
1335 tree mangled_name;
1337 if (decl->mangleOverride.length)
1339 mangled_name =
1340 get_identifier_with_length (decl->mangleOverride.ptr,
1341 decl->mangleOverride.length);
1343 else
1344 mangled_name = get_identifier (d_mangle_decl (decl));
1346 mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1347 mangled_name);
1348 /* The frontend doesn't handle duplicate definitions of unused symbols
1349 with the same mangle. So a check is done here instead. */
1350 if (IDENTIFIER_DSYMBOL (mangled_name))
1352 Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1353 tree olddecl = decl->csym;
1354 decl->csym = get_symbol_decl (other);
1356 /* Update the symbol location to the current definition. */
1357 if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1358 DECL_SOURCE_LOCATION (decl->csym) = DECL_SOURCE_LOCATION (olddecl);
1360 /* The current declaration is a prototype or marked extern, merge
1361 applied user attributes and return. */
1362 if (DECL_EXTERNAL (olddecl) && !DECL_INITIAL (olddecl))
1364 apply_user_attributes (decl, decl->csym);
1365 return decl->csym;
1367 /* The previous declaration is a prototype or marked extern, set the
1368 current declaration as the main reference of the symbol. */
1369 else if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1371 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1372 DECL_EXTERNAL (decl->csym) = 0;
1374 /* Non-extern, non-templated decls shouldn't be defined twice. */
1375 else if (!decl->isInstantiated ())
1376 ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1378 else
1380 IDENTIFIER_PRETTY_NAME (mangled_name)
1381 = get_identifier (decl->toPrettyChars (true));
1382 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1384 SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1388 DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1389 DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1391 if (TREE_CODE (decl->csym) == PARM_DECL)
1393 /* Pass non-trivial structs by invisible reference. */
1394 if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1396 tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1397 argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1398 gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1399 TREE_TYPE (decl->csym) = argtype;
1400 DECL_BY_REFERENCE (decl->csym) = 1;
1401 TREE_ADDRESSABLE (decl->csym) = 0;
1402 relayout_decl (decl->csym);
1403 decl->storage_class |= STCref;
1406 DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1407 gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1409 else if (TREE_CODE (decl->csym) == CONST_DECL)
1411 /* Manifest constants have no address in memory. */
1412 TREE_CONSTANT (decl->csym) = 1;
1413 TREE_READONLY (decl->csym) = 1;
1415 else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1417 /* Dual-context functions require the code generation to build an array
1418 for the context pointer of the function, making the delicate task of
1419 tracking which context to follow when encountering a non-local symbol,
1420 and so are a not planned to be supported. */
1421 if (fd->needThis () && !fd->isMember2 ())
1423 fatal_error (make_location_t (fd->loc),
1424 "function requires a dual-context, which is not yet "
1425 "supported by GDC");
1428 /* The real function type may differ from its declaration. */
1429 tree fntype = TREE_TYPE (decl->csym);
1430 tree newfntype = NULL_TREE;
1432 if (fd->isNested ())
1434 /* Add an extra argument for the frame/closure pointer, this is also
1435 required to be compatible with D delegates. */
1436 newfntype = build_vthis_function (void_type_node, fntype);
1438 else if (fd->isThis ())
1440 /* Add an extra argument for the `this' parameter. The handle type is
1441 used even if there is no debug info. It is needed to make sure
1442 virtual member functions are not called statically. */
1443 AggregateDeclaration *ad = fd->isMember2 ();
1444 tree handle = build_ctype (ad->handleType ());
1446 /* If handle is a pointer type, get record type. */
1447 if (!ad->isStructDeclaration ())
1448 handle = TREE_TYPE (handle);
1450 newfntype = build_vthis_function (handle, fntype);
1452 /* Set the vindex on virtual functions. */
1453 if (fd->isVirtual () && fd->vtblIndex != -1)
1455 DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1456 DECL_VIRTUAL_P (decl->csym) = 1;
1459 /* Align method to the minimum boundary for target. */
1460 SET_DECL_ALIGN (decl->csym, MINIMUM_METHOD_BOUNDARY);
1462 else if (fd->isMain () || fd->isCMain ())
1464 /* The main function is named `D main' to distinguish from C main. */
1465 if (fd->isMain ())
1466 DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1468 /* `void main' is implicitly converted to returning an int. */
1469 newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1472 if (newfntype != NULL_TREE)
1474 /* Copy the old attributes from the original type. */
1475 TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1476 TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1477 TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1478 TREE_TYPE (decl->csym) = newfntype;
1479 d_keep (newfntype);
1482 /* Miscellaneous function flags. */
1484 /* In [pragma/inline], functions decorated with `pragma(inline)' affects
1485 whether they are inlined or not. */
1486 if (fd->inlining == PINLINE::always)
1487 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1488 else if (fd->inlining == PINLINE::never)
1489 DECL_UNINLINABLE (decl->csym) = 1;
1491 /* In [pragma/crtctor], Annotates a function so it is run after the C
1492 runtime library is initialized and before the D runtime library is
1493 initialized. */
1494 if (fd->isCrtCtor ())
1496 DECL_STATIC_CONSTRUCTOR (decl->csym) = 1;
1497 decl_init_priority_insert (decl->csym, DEFAULT_INIT_PRIORITY);
1499 else if (fd->isCrtDtor ())
1501 DECL_STATIC_DESTRUCTOR (decl->csym) = 1;
1502 decl_fini_priority_insert (decl->csym, DEFAULT_INIT_PRIORITY);
1505 /* Function was declared `naked'. */
1506 if (fd->isNaked ())
1508 insert_decl_attribute (decl->csym, "naked");
1509 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1512 /* In [expression/function_literals], function literals (aka lambdas)
1513 enable embedding anonymous functions and anonymous delegates directly
1514 into expressions. They are defined in each referencing module. */
1515 if (fd->isFuncLiteralDeclaration ())
1516 DECL_SET_LAMBDA_FUNCTION (decl->csym, true);
1518 /* Mark compiler generated functions as artificial. */
1519 if (fd->isGenerated ())
1520 DECL_ARTIFICIAL (decl->csym) = 1;
1522 /* Ensure and require contracts are lexically nested in the function they
1523 part of, but are always publicly callable. */
1524 if (fd->ident == Identifier::idPool ("ensure")
1525 || fd->ident == Identifier::idPool ("require"))
1526 TREE_PUBLIC (decl->csym) = 1;
1528 if (decl->storage_class & STCfinal)
1529 DECL_FINAL_P (decl->csym) = 1;
1531 /* Function is of type `noreturn' or `typeof(*null)'. */
1532 if (fd->type->nextOf ()->isTypeNoreturn ())
1533 TREE_THIS_VOLATILE (decl->csym) = 1;
1535 /* Check whether this function is expanded by the frontend. */
1536 DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1537 maybe_set_intrinsic (fd);
1539 /* For nested functions in particular, unnest fndecl in the cgraph, as
1540 all static chain passing is handled by the front-end. Do this even
1541 if we are not emitting the body. */
1542 struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1543 if (nested_function_origin (node))
1544 unnest_function (node);
1547 /* Mark compiler generated temporaries as artificial. */
1548 if (decl->storage_class & STCtemp)
1549 DECL_ARTIFICIAL (decl->csym) = 1;
1551 /* Propagate shared on the decl. */
1552 if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1553 TREE_ADDRESSABLE (decl->csym) = 1;
1555 /* Symbol was marked volatile. */
1556 if (decl->storage_class & STCvolatile)
1557 TREE_THIS_VOLATILE (decl->csym) = 1;
1559 /* Symbol was marked register. */
1560 if (decl->storage_class & STCregister)
1561 DECL_REGISTER (decl->csym) = 1;
1563 /* Symbol was declared with deprecated attribute. */
1564 if (decl->storage_class & STCdeprecated)
1565 TREE_DEPRECATED (decl->csym) = 1;
1567 if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1569 /* Set TREE_PUBLIC by default, but allow private template to override. */
1570 if (!fd || !fd->isNested ())
1571 TREE_PUBLIC (decl->csym) = 1;
1573 TREE_STATIC (decl->csym) = 1;
1574 /* The decl has not been defined -- yet. */
1575 DECL_EXTERNAL (decl->csym) = 1;
1577 /* Visibility attributes are used by the debugger. */
1578 set_visibility_for_decl (decl->csym, decl);
1580 DECL_INSTANTIATED (decl->csym) = (decl->isInstantiated () != NULL);
1581 set_linkage_for_decl (decl->csym);
1584 /* Symbol is going in thread local storage. */
1585 if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1587 if (global.params.v.tls)
1588 message (decl->loc, "`%s` is thread local", decl->toChars ());
1590 set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1593 /* Apply any user attributes that may affect semantic meaning. */
1594 apply_user_attributes (decl, decl->csym);
1596 /* Handle any conflicts between D language attributes and compiler-recognized
1597 * user attributes. */
1598 if (VAR_P (decl->csym) && DECL_HARD_REGISTER (decl->csym))
1600 if (decl->storage_class & STCextern)
1601 error_at (make_location_t (decl->loc), "explicit register variable "
1602 "%qs declared %<extern%>", decl->toChars ());
1603 else if (decl->isThreadlocal ())
1604 error_at (make_location_t (decl->loc), "explicit register variable "
1605 "%qs declared thread local", decl->toChars ());
1608 /* %% Probably should be a little more intelligent about setting this. */
1609 TREE_USED (decl->csym) = 1;
1610 d_keep (decl->csym);
1612 return maybe_build_decl_tree (decl);
1615 /* Returns a declaration for a VAR_DECL. Used to create compiler-generated
1616 global variables. */
1618 tree
1619 declare_extern_var (tree ident, tree type)
1621 /* If the VAR_DECL has already been declared, return it. */
1622 if (IDENTIFIER_DECL_TREE (ident))
1623 return IDENTIFIER_DECL_TREE (ident);
1625 tree name = IDENTIFIER_PRETTY_NAME (ident)
1626 ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1627 tree decl = build_decl (input_location, VAR_DECL, name, type);
1629 IDENTIFIER_DECL_TREE (ident) = decl;
1630 d_keep (decl);
1632 SET_DECL_ASSEMBLER_NAME (decl, ident);
1633 DECL_ARTIFICIAL (decl) = 1;
1634 TREE_STATIC (decl) = 1;
1635 TREE_PUBLIC (decl) = 1;
1637 /* The decl has not been defined -- yet. */
1638 DECL_EXTERNAL (decl) = 1;
1640 set_linkage_for_decl (decl);
1642 return decl;
1645 /* Add local variable VAR into the current function body. */
1647 void
1648 declare_local_var (VarDeclaration *var)
1650 gcc_assert (!var->isDataseg () && !var->isMember ());
1651 gcc_assert (current_function_decl != NULL_TREE);
1653 FuncDeclaration *fd = cfun->language->function;
1654 tree decl = get_symbol_decl (var);
1656 gcc_assert (!TREE_STATIC (decl));
1657 d_pushdecl (decl);
1658 DECL_CONTEXT (decl) = current_function_decl;
1660 /* Compiler generated symbols. */
1661 if (var == fd->vresult || var == fd->v_argptr)
1662 DECL_ARTIFICIAL (decl) = 1;
1664 if (DECL_LANG_FRAME_FIELD (decl))
1666 /* Fixes debugging local variables. */
1667 SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1668 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1672 /* Return an unnamed local temporary of type TYPE. */
1674 tree
1675 build_local_temp (tree type)
1677 tree decl = create_tmp_var_raw (type);
1678 d_pushdecl (decl);
1680 return decl;
1683 /* Return the correct decl to be used for DECL. For VAR_DECLs, this could
1684 instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1685 value. For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1686 For all other kinds of decls, this just returns the result of
1687 get_symbol_decl(). */
1689 tree
1690 get_decl_tree (Declaration *decl)
1692 tree t = get_symbol_decl (decl);
1693 FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1694 VarDeclaration *vd = decl->isVarDeclaration ();
1696 /* If cfun is NULL, then this is a global static. */
1697 if (vd == NULL || fd == NULL)
1698 return t;
1700 /* Get the closure holding the var decl. */
1701 if (DECL_LANG_FRAME_FIELD (t))
1703 FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1704 tree frame_ref = get_framedecl (fd, parent);
1706 tree field = component_ref (build_deref (frame_ref),
1707 DECL_LANG_FRAME_FIELD (t));
1708 /* Frame field can also be a reference to the DECL_RESULT of a function.
1709 Dereference it to get the value. */
1710 if (DECL_LANG_NRVO (t))
1711 field = build_deref (field);
1713 return field;
1716 /* Get the named return value. */
1717 if (DECL_LANG_NRVO (t))
1718 return DECL_LANG_NRVO (t);
1720 /* Get the non-local `this' value by going through parent link
1721 of nested classes, this routine pretty much undoes what
1722 getRightThis in the frontend removes from codegen. */
1723 if (vd->parent != fd && vd->isThisDeclaration ())
1725 /* Find the first parent that is a member function. */
1726 while (!fd->isMember2 ())
1728 gcc_assert (fd->vthis);
1729 fd = fd->toParent2 ()->isFuncDeclaration ();
1730 gcc_assert (fd != NULL);
1733 AggregateDeclaration *ad = fd->isThis ();
1734 gcc_assert (ad != NULL);
1736 /* The parent function is for the same `this' declaration we are
1737 building a chain to. Non-local declaration is inaccessible. */
1738 if (fd->vthis == vd)
1739 return error_no_frame_access (fd);
1741 t = get_decl_tree (fd->vthis);
1742 Dsymbol *outer = fd;
1744 while (outer != vd->parent)
1746 gcc_assert (ad != NULL);
1747 outer = ad->toParent2 ();
1749 /* Get the this->this parent link. */
1750 tree vfield = get_symbol_decl (ad->vthis);
1751 t = component_ref (build_deref (t), vfield);
1753 ad = outer->isAggregateDeclaration ();
1754 if (ad != NULL)
1755 continue;
1757 fd = outer->isFuncDeclaration ();
1758 while (fd != NULL)
1760 /* If outer function creates a closure, then the `this'
1761 value would be the closure pointer, and the real
1762 `this' the first field of that closure. */
1763 tree ff = get_frameinfo (fd);
1764 if (FRAMEINFO_CREATES_FRAME (ff))
1766 t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1767 t = indirect_ref (build_ctype (fd->vthis->type), t);
1770 if (fd == vd->parent)
1771 break;
1773 /* Continue looking for the right `this'. */
1774 outer = outer->toParent2 ();
1775 fd = outer->isFuncDeclaration ();
1778 ad = outer->isAggregateDeclaration ();
1781 return t;
1784 /* Auto variable that the back end will handle for us. */
1785 return t;
1788 /* Finish up a variable declaration and compile it all the way to
1789 the assembler language output. */
1791 void
1792 d_finish_decl (tree decl)
1794 gcc_assert (!error_operand_p (decl));
1796 /* We are sending this symbol to object file, can't be extern. */
1797 TREE_STATIC (decl) = 1;
1798 DECL_EXTERNAL (decl) = 0;
1800 /* Update the TLS model as the linkage has been modified. */
1801 if (DECL_THREAD_LOCAL_P (decl))
1802 set_decl_tls_model (decl, decl_default_tls_model (decl));
1804 relayout_decl (decl);
1806 if (flag_checking && DECL_INITIAL (decl))
1808 /* Initializer must never be bigger than symbol size. */
1809 HOST_WIDE_INT tsize = int_size_in_bytes (TREE_TYPE (decl));
1810 HOST_WIDE_INT dtsize =
1811 int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1813 if (tsize < dtsize)
1815 tree name = DECL_ASSEMBLER_NAME (decl);
1817 internal_error ("mismatch between declaration %qE size (%wd) and "
1818 "its initializer size (%wd)",
1819 IDENTIFIER_PRETTY_NAME (name)
1820 ? IDENTIFIER_PRETTY_NAME (name) : name,
1821 tsize, dtsize);
1825 /* Without weak symbols, symbol should be put in .common, but that can't
1826 be done if there is a nonzero initializer. */
1827 if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1828 && initializer_zerop (DECL_INITIAL (decl)))
1829 DECL_INITIAL (decl) = error_mark_node;
1831 /* Add this decl to the current binding level. */
1832 d_pushdecl (decl);
1834 rest_of_decl_compilation (decl, 1, 0);
1837 /* Thunk code is based on g++. */
1839 static int thunk_labelno;
1841 /* Create a static alias to function. */
1843 static tree
1844 make_alias_for_thunk (tree function)
1846 tree alias;
1847 char buf[256];
1849 /* Thunks may reference extern functions which cannot be aliased. */
1850 if (DECL_EXTERNAL (function))
1851 return function;
1853 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1854 thunk_labelno++;
1856 alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1857 get_identifier (buf), TREE_TYPE (function));
1858 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1859 lang_hooks.dup_lang_specific_decl (alias);
1860 DECL_CONTEXT (alias) = NULL_TREE;
1861 TREE_READONLY (alias) = TREE_READONLY (function);
1862 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1863 TREE_PUBLIC (alias) = 0;
1865 DECL_EXTERNAL (alias) = 0;
1866 DECL_ARTIFICIAL (alias) = 1;
1868 DECL_DECLARED_INLINE_P (alias) = 0;
1869 DECL_INITIAL (alias) = error_mark_node;
1870 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1872 TREE_ADDRESSABLE (alias) = 1;
1873 TREE_USED (alias) = 1;
1874 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1876 if (!flag_syntax_only)
1878 cgraph_node *aliasn;
1879 aliasn = cgraph_node::create_same_body_alias (alias, function);
1880 gcc_assert (aliasn != NULL);
1882 return alias;
1885 /* Emit the definition of a D vtable thunk. */
1887 static void
1888 finish_thunk (tree thunk, tree function)
1890 /* Setup how D thunks are outputted. */
1891 int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1892 bool this_adjusting = true;
1893 tree alias;
1895 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1896 alias = make_alias_for_thunk (function);
1897 else
1898 alias = function;
1900 TREE_ADDRESSABLE (function) = 1;
1901 TREE_USED (function) = 1;
1902 DECL_EXTERNAL (thunk) = 0;
1904 if (flag_syntax_only)
1906 TREE_ASM_WRITTEN (thunk) = 1;
1907 return;
1910 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1911 && targetm_common.have_named_sections)
1913 tree fn = function;
1914 symtab_node *symbol = symtab_node::get (function);
1916 if (symbol != NULL && symbol->alias)
1918 if (symbol->analyzed)
1919 fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1920 else
1921 fn = symtab_node::get (function)->alias_target;
1923 resolve_unique_section (fn, 0, flag_function_sections);
1925 if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1927 resolve_unique_section (thunk, 0, flag_function_sections);
1929 /* Output the thunk into the same section as function. */
1930 set_decl_section_name (thunk, fn);
1931 symtab_node::get (thunk)->implicit_section
1932 = symtab_node::get (fn)->implicit_section;
1936 /* Set up cloned argument trees for the thunk. */
1937 tree t = NULL_TREE;
1938 for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1940 tree x = copy_node (a);
1941 DECL_CHAIN (x) = t;
1942 DECL_CONTEXT (x) = thunk;
1943 SET_DECL_RTL (x, NULL);
1944 DECL_HAS_VALUE_EXPR_P (x) = 0;
1945 TREE_ADDRESSABLE (x) = 0;
1946 t = x;
1948 DECL_ARGUMENTS (thunk) = nreverse (t);
1949 TREE_ASM_WRITTEN (thunk) = 1;
1951 cgraph_node *funcn, *thunk_node;
1953 funcn = cgraph_node::get_create (function);
1954 gcc_assert (funcn);
1955 thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1956 fixed_offset, 0, 0, 0, alias);
1958 if (DECL_ONE_ONLY (function))
1959 thunk_node->add_to_same_comdat_group (funcn);
1962 /* Return a thunk to DECL. Thunks adjust the incoming `this' pointer by OFFSET.
1963 Adjustor thunks are created and pointers to them stored in the method entries
1964 in the vtable in order to set the this pointer to the start of the object
1965 instance corresponding to the implementing method. */
1967 tree
1968 make_thunk (FuncDeclaration *decl, int offset)
1970 tree function = get_symbol_decl (decl);
1972 if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1974 /* Build parameters for functions that are not being compiled,
1975 so that they can be correctly cloned in finish_thunk. */
1976 tree function = get_symbol_decl (decl);
1977 DECL_ARGUMENTS (function) = get_fndecl_arguments (decl);
1979 /* Also build the result decl, which is needed when force creating
1980 the thunk in gimple inside cgraph_node::expand_thunk. */
1981 DECL_RESULT (function) = get_fndecl_result (decl);
1984 /* Don't build the thunk if the compilation step failed. */
1985 if (global.errors)
1986 return error_mark_node;
1988 /* See if we already have the thunk in question. */
1989 for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1991 if (THUNK_LANG_OFFSET (t) == offset)
1992 return t;
1995 tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1996 FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1997 DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1998 lang_hooks.dup_lang_specific_decl (thunk);
1999 THUNK_LANG_OFFSET (thunk) = offset;
2001 TREE_READONLY (thunk) = TREE_READONLY (function);
2002 TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
2003 TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
2005 DECL_CONTEXT (thunk) = d_decl_context (decl);
2007 /* Thunks inherit the public access of the function they are targeting. */
2008 TREE_PUBLIC (thunk) = TREE_PUBLIC (function);
2009 /* The thunk has not been defined -- yet. */
2010 DECL_EXTERNAL (thunk) = 1;
2012 /* Thunks are always addressable. */
2013 TREE_ADDRESSABLE (thunk) = 1;
2014 TREE_USED (thunk) = 1;
2015 DECL_ARTIFICIAL (thunk) = 1;
2016 DECL_DECLARED_INLINE_P (thunk) = 0;
2018 if (TREE_PUBLIC (thunk))
2020 DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
2021 DECL_COMDAT (thunk) = DECL_COMDAT (function);
2022 DECL_WEAK (thunk) = DECL_WEAK (function);
2025 /* When the thunk is for an extern C++ function, let C++ do the thunk
2026 generation and just reference the symbol as extern, instead of
2027 forcing a D local thunk to be emitted. */
2028 const char *ident;
2030 if (decl->resolvedLinkage () == LINK::cpp)
2031 ident = target.cpp.thunkMangle (decl, offset);
2032 else
2034 tree target_name = DECL_ASSEMBLER_NAME (function);
2035 unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
2036 ident = XNEWVEC (const char, identlen);
2038 snprintf (CONST_CAST (char *, ident), identlen,
2039 "_DTi%u%s", offset, IDENTIFIER_POINTER (target_name));
2042 DECL_NAME (thunk) = get_identifier (ident);
2043 SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
2045 d_keep (thunk);
2047 if (decl->resolvedLinkage () != LINK::cpp)
2048 free (CONST_CAST (char *, ident));
2050 /* Thunks are connected to the definitions of the functions, so thunks are
2051 not produced for external functions. */
2052 if (!DECL_EXTERNAL (function))
2053 finish_thunk (thunk, function);
2055 /* Add it to the list of thunks associated with the function. */
2056 DECL_LANG_THUNKS (thunk) = NULL_TREE;
2057 DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
2058 DECL_LANG_THUNKS (function) = thunk;
2060 return thunk;
2063 /* Create the FUNCTION_DECL for a function definition.
2064 This function creates a binding context for the function body
2065 as well as setting up the FUNCTION_DECL in current_function_decl.
2066 Returns the previous function context if it was already set. */
2068 tree
2069 start_function (FuncDeclaration *fd)
2071 tree fndecl = get_symbol_decl (fd);
2073 /* Function has been defined. Whether we intend to send it to object file, or
2074 discard it has already been determined by set_linkage_for_decl. */
2075 DECL_EXTERNAL (fndecl) = 0;
2076 DECL_INITIAL (fndecl) = error_mark_node;
2078 /* Add this decl to the current binding level. */
2079 d_pushdecl (fndecl);
2081 /* Save the current function context. */
2082 tree old_context = current_function_decl;
2084 if (old_context)
2085 push_function_context ();
2087 /* Let GCC know the current scope is this function. */
2088 current_function_decl = fndecl;
2090 /* Build the result decl before calling allocate_struct_function. */
2091 DECL_RESULT (fndecl) = get_fndecl_result (fd);
2093 /* Initialize the RTL code for the function. */
2094 allocate_struct_function (fndecl, false);
2096 /* Store the end of the function. */
2097 if (fd->endloc.filename ())
2098 cfun->function_end_locus = make_location_t (fd->endloc);
2099 else
2100 cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
2102 cfun->language = ggc_cleared_alloc <language_function> ();
2103 cfun->language->function = fd;
2105 /* Default chain value is `null' unless parent found. */
2106 cfun->language->static_chain = null_pointer_node;
2108 /* Find module for this function. */
2109 for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
2111 cfun->language->module = p->isModule ();
2112 if (cfun->language->module)
2113 break;
2115 gcc_assert (cfun->language->module != NULL);
2117 /* Begin the statement tree for this function. */
2118 push_stmt_list ();
2119 push_binding_level (level_function);
2121 return old_context;
2124 /* Finish up a function declaration and compile that function all
2125 the way to assembler language output. The free the storage for
2126 the function definition. Restores the previous function context. */
2128 void
2129 finish_function (tree old_context)
2131 tree fndecl = current_function_decl;
2133 /* Tie off the statement tree for this function. */
2134 tree block = pop_binding_level ();
2135 tree body = pop_stmt_list ();
2136 tree bind = build3 (BIND_EXPR, void_type_node,
2137 BLOCK_VARS (block), body, block);
2139 gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
2141 /* Back-end expects a statement list to come from somewhere, however
2142 pop_stmt_list returns expressions when there is a single statement.
2143 So here we create a statement list unconditionally. */
2144 if (TREE_CODE (body) != STATEMENT_LIST)
2146 tree stmtlist = alloc_stmt_list ();
2147 append_to_statement_list_force (body, &stmtlist);
2148 BIND_EXPR_BODY (bind) = stmtlist;
2150 else if (!STATEMENT_LIST_HEAD (body))
2152 /* For empty functions add a void return. */
2153 append_to_statement_list_force (return_expr (NULL_TREE), &body);
2156 DECL_SAVED_TREE (fndecl) = bind;
2158 /* Finish any forward referenced thunks for the function. */
2159 for (tree t = DECL_LANG_THUNKS (fndecl); t; t = DECL_CHAIN (t))
2160 finish_thunk (t, fndecl);
2162 if (!errorcount && !global.errors)
2164 /* Dump the D-specific tree IR. */
2165 dump_function (TDI_original, fndecl);
2167 cgraph_node::finalize_function (fndecl, true);
2170 /* We're leaving the context of this function, so free it. */
2171 ggc_free (cfun->language);
2172 cfun->language = NULL;
2173 set_cfun (NULL);
2175 if (old_context)
2176 pop_function_context ();
2178 current_function_decl = old_context;
2181 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
2182 must be emitted in this, output module. */
2184 static void
2185 d_mark_needed (tree decl)
2187 TREE_USED (decl) = 1;
2189 if (TREE_CODE (decl) == FUNCTION_DECL)
2191 struct cgraph_node *node = cgraph_node::get_create (decl);
2192 node->forced_by_abi = true;
2194 else if (VAR_P (decl))
2196 struct varpool_node *node = varpool_node::get_create (decl);
2197 node->forced_by_abi = true;
2201 /* Get the VAR_DECL of the vtable symbol for DECL. If this does not yet exist,
2202 create it. The vtable is accessible via ClassInfo, but since it is needed
2203 frequently (like for rtti comparisons), make it directly accessible. */
2205 tree
2206 get_vtable_decl (ClassDeclaration *decl)
2208 if (decl->vtblsym && decl->vtblsym->csym)
2209 return decl->vtblsym->csym;
2211 tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
2212 /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
2213 will have a different type. However the back-end seems to accept this. */
2214 tree type = build_ctype (dmd::sarrayOf (Type::tvoidptr, decl->vtbl.length));
2216 Dsymbol *vtblsym = decl->vtblSymbol ();
2217 vtblsym->csym = declare_extern_var (ident, type);
2218 DECL_LANG_SPECIFIC (vtblsym->csym) = build_lang_decl (NULL);
2220 /* Class is a reference, want the record type. */
2221 DECL_CONTEXT (vtblsym->csym) = TREE_TYPE (build_ctype (decl->type));
2222 TREE_READONLY (vtblsym->csym) = 1;
2223 DECL_VIRTUAL_P (vtblsym->csym) = 1;
2225 SET_DECL_ALIGN (vtblsym->csym, TARGET_VTABLE_ENTRY_ALIGN);
2226 DECL_USER_ALIGN (vtblsym->csym) = true;
2228 return vtblsym->csym;
2231 /* Helper function of build_class_instance. Find the field inside aggregate
2232 TYPE identified by IDENT at field OFFSET. */
2234 static tree
2235 find_aggregate_field (tree type, tree ident, tree offset)
2237 tree fields = TYPE_FIELDS (type);
2239 for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2241 if (DECL_NAME (field) == NULL_TREE
2242 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2243 && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2245 /* Search nesting anonymous structs and unions. */
2246 tree vfield = find_aggregate_field (TREE_TYPE (field),
2247 ident, offset);
2248 if (vfield != NULL_TREE)
2249 return vfield;
2251 else if (DECL_NAME (field) == ident
2252 && (offset == NULL_TREE
2253 || DECL_FIELD_OFFSET (field) == offset))
2255 /* Found matching field at offset. */
2256 return field;
2260 return NULL_TREE;
2263 /* Helper function of build_new_class_expr. Return a constructor that matches
2264 the layout of the class expression EXP. */
2266 static tree
2267 build_class_instance (ClassReferenceExp *exp)
2269 ClassDeclaration *cd = exp->originalClass ();
2270 tree type = TREE_TYPE (build_ctype (exp->value->stype));
2271 vec <constructor_elt, va_gc> *ve = NULL;
2273 /* The set base vtable field. */
2274 tree vptr = build_address (get_vtable_decl (cd));
2275 CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2277 /* Go through the inheritance graph from top to bottom. This will add all
2278 values to the constructor out of order, however build_struct_literal
2279 will re-order all values before returning the finished literal. */
2280 for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2282 /* Anonymous vtable interface fields are laid out before the fields of
2283 each class. The interface offset is used to determine where to put
2284 the classinfo offset reference. */
2285 for (size_t i = 0; i < bcd->vtblInterfaces->length; i++)
2287 BaseClass *bc = (*bcd->vtblInterfaces)[i];
2289 for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2291 gcc_assert (cd2 != NULL);
2293 unsigned csymoffset = base_vtable_offset (cd2, bc);
2294 /* If the base class vtable was found. */
2295 if (csymoffset != ~0u)
2297 tree csym = build_address (get_classinfo_decl (cd2));
2298 csym = build_offset (csym, size_int (csymoffset));
2300 tree field = find_aggregate_field (type, NULL_TREE,
2301 size_int (bc->offset));
2302 gcc_assert (field != NULL_TREE);
2304 CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2305 break;
2310 /* Generate initial values of all fields owned by current class.
2311 Use both the name and offset to find the right field. */
2312 for (size_t i = 0; i < bcd->fields.length; i++)
2314 VarDeclaration *vfield = bcd->fields[i];
2315 int index = exp->findFieldIndexByName (vfield);
2316 gcc_assert (index != -1);
2318 Expression *value = (*exp->value->elements)[index];
2319 if (!value)
2320 continue;
2322 /* Use find_aggregate_field to get the overridden field decl,
2323 instead of the field associated with the base class. */
2324 tree field = get_symbol_decl (bcd->fields[i]);
2325 field = find_aggregate_field (type, DECL_NAME (field),
2326 DECL_FIELD_OFFSET (field));
2327 gcc_assert (field != NULL_TREE);
2329 CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2333 return build_struct_literal (type, ve);
2336 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2337 If this does not yet exist, create it. This is used to support initializing
2338 a static variable that is of a class type using values known during CTFE.
2339 In user code, it is analogous to the following code snippet.
2341 enum E = new C(1, 2, 3);
2343 That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2344 implementation detail. The initialization of these symbols could be done at
2345 run-time using during as part of the module initialization or shared static
2346 constructors phase of run-time start-up - whichever comes after `gc_init()'.
2347 And infact that would be the better thing to do here eventually. */
2349 tree
2350 build_new_class_expr (ClassReferenceExp *expr)
2352 if (expr->value->sym)
2353 return expr->value->sym;
2355 /* Build the reference symbol. */
2356 tree type = build_ctype (expr->value->stype);
2357 expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2359 DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2360 d_pushdecl (expr->value->sym);
2361 rest_of_decl_compilation (expr->value->sym, 1, 0);
2363 return expr->value->sym;
2366 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2367 If this does not yet exist, create it. The static initializer data is
2368 accessible via TypeInfo, and is also used in `new class' and default
2369 initializing struct literals. */
2371 tree
2372 aggregate_initializer_decl (AggregateDeclaration *decl)
2374 if (decl->sinit)
2375 return (tree) decl->sinit;
2377 /* Class is a reference, want the record type. */
2378 tree type = build_ctype (decl->type);
2379 StructDeclaration *sd = decl->isStructDeclaration ();
2380 if (!sd)
2381 type = TREE_TYPE (type);
2383 tree ident = mangle_internal_decl (decl, "__init", "Z");
2385 tree sinit = declare_extern_var (ident, type);
2386 DECL_LANG_SPECIFIC (sinit) = build_lang_decl (NULL);
2388 DECL_CONTEXT (sinit) = type;
2389 TREE_READONLY (sinit) = 1;
2391 /* Honor struct alignment set by user. */
2392 if (sd && !sd->alignment.isDefault ())
2394 SET_DECL_ALIGN (sinit, sd->alignment.get () * BITS_PER_UNIT);
2395 DECL_USER_ALIGN (sinit) = true;
2398 decl->sinit = sinit;
2399 return sinit;
2402 /* Generate the data for the static initializer. */
2404 tree
2405 layout_class_initializer (ClassDeclaration *cd)
2407 NewExp *ne = NewExp::create (cd->loc, NULL, cd->type, NULL);
2408 ne->type = cd->type;
2410 Expression *e = dmd::ctfeInterpret (ne);
2411 gcc_assert (e->op == EXP::classReference);
2413 return build_class_instance (e->isClassReferenceExp ());
2416 tree
2417 layout_struct_initializer (StructDeclaration *sd)
2419 StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2421 if (!sd->fill (sd->loc, *sle->elements, true))
2422 gcc_unreachable ();
2424 sle->type = sd->type;
2425 return build_expr (sle, true);
2428 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2429 If this does not yet exist, create it. The static initializer data is
2430 accessible via TypeInfo_Enum, but the field member type is a byte[] that
2431 requires a pointer to a symbol reference. */
2433 tree
2434 enum_initializer_decl (EnumDeclaration *decl)
2436 if (decl->sinit)
2437 return decl->sinit;
2439 gcc_assert (decl->ident);
2441 tree type = build_ctype (decl->type);
2442 tree ident = mangle_internal_decl (decl, "__init", "Z");
2444 decl->sinit = declare_extern_var (ident, type);
2445 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2447 DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2448 TREE_READONLY (decl->sinit) = 1;
2450 return decl->sinit;
2453 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2454 and optionally prefixing the name with PREFIX. */
2456 tree
2457 build_artificial_decl (tree type, tree init, const char *prefix)
2459 tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2460 const char *name = prefix ? prefix : "___s";
2461 char *label;
2463 ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2464 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2465 DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2467 TREE_PUBLIC (decl) = 0;
2468 TREE_STATIC (decl) = 1;
2469 TREE_USED (decl) = 1;
2470 DECL_IGNORED_P (decl) = 1;
2471 DECL_ARTIFICIAL (decl) = 1;
2473 /* Perhaps at some point the initializer constant should be hashed
2474 to remove duplicates. */
2475 DECL_INITIAL (decl) = init;
2477 return decl;
2480 /* Build TYPE_DECL for the declaration DSYM. */
2482 void
2483 build_type_decl (tree type, Dsymbol *dsym)
2485 if (TYPE_STUB_DECL (type))
2486 return;
2488 /* If a templated type, use the template instance name, as that includes all
2489 template parameters. */
2490 const char *name = dsym->parent->isTemplateInstance ()
2491 ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2493 tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2494 get_identifier (name), type);
2495 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (d_mangle_decl (dsym)));
2496 TREE_PUBLIC (decl) = 1;
2497 DECL_CONTEXT (decl) = d_decl_context (dsym);
2499 TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2500 TYPE_NAME (type) = decl;
2502 /* Not sure if there is a need for separate TYPE_DECLs in
2503 TYPE_NAME and TYPE_STUB_DECL. */
2504 if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2506 DECL_ARTIFICIAL (decl) = 1;
2507 TYPE_STUB_DECL (type) = decl;
2509 else if (type != TYPE_MAIN_VARIANT (type))
2510 DECL_ORIGINAL_TYPE (decl) = TYPE_MAIN_VARIANT (type);
2513 /* Create a declaration for field NAME of a given TYPE, setting the flags
2514 for whether the field is ARTIFICIAL and/or IGNORED. */
2516 tree
2517 create_field_decl (tree type, const char *name, int artificial, int ignored)
2519 tree decl = build_decl (input_location, FIELD_DECL,
2520 name ? get_identifier (name) : NULL_TREE, type);
2521 DECL_ARTIFICIAL (decl) = artificial;
2522 DECL_IGNORED_P (decl) = ignored;
2524 return decl;
2527 /* Return the COMDAT group into which DECL should be placed. */
2529 static tree
2530 d_comdat_group (tree decl)
2532 /* If already part of a comdat group, use that. */
2533 if (DECL_COMDAT_GROUP (decl))
2534 return DECL_COMDAT_GROUP (decl);
2536 return DECL_ASSEMBLER_NAME (decl);
2539 /* Set DECL up to have the closest approximation of "initialized common"
2540 linkage available. */
2542 static void
2543 d_comdat_linkage (tree decl)
2545 /* COMDAT definitions have to be public. */
2546 gcc_assert (TREE_PUBLIC (decl));
2548 if (supports_one_only ())
2549 make_decl_one_only (decl, d_comdat_group (decl));
2550 else if ((TREE_CODE (decl) == FUNCTION_DECL && DECL_INSTANTIATED (decl))
2551 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2552 /* We can just emit function and compiler-generated variables statically;
2553 having multiple copies is (for the most part) only a waste of space. */
2554 TREE_PUBLIC (decl) = 0;
2555 else if (DECL_INITIAL (decl) == NULL_TREE
2556 || DECL_INITIAL (decl) == error_mark_node)
2557 /* Fallback, cannot have multiple copies. */
2558 DECL_COMMON (decl) = 1;
2560 if (TREE_PUBLIC (decl) && DECL_INSTANTIATED (decl))
2561 DECL_COMDAT (decl) = 1;
2564 /* Set DECL up to have the closest approximation of "weak" linkage. */
2566 static void
2567 d_weak_linkage (tree decl)
2569 /* Weak definitions have to be public. */
2570 gcc_assert (TREE_PUBLIC (decl));
2572 /* Allow comdat linkage to be forced with the flag `-fno-weak-templates'. */
2573 if (!flag_weak_templates || !TARGET_SUPPORTS_WEAK)
2574 return d_comdat_linkage (decl);
2576 declare_weak (decl);
2579 /* DECL is a FUNCTION_DECL or a VAR_DECL with static storage. Set flags to
2580 reflect the linkage that DECL will receive in the object file. */
2582 void
2583 set_linkage_for_decl (tree decl)
2585 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl) && TREE_STATIC (decl));
2587 /* Non-public decls keep their internal linkage. */
2588 if (!TREE_PUBLIC (decl))
2589 return;
2591 /* Function literals and functions declared as `pragma(inline, true)' can
2592 appear in multiple translation units. */
2593 if (TREE_CODE (decl) == FUNCTION_DECL
2594 && (DECL_DECLARED_INLINE_P (decl) || DECL_LAMBDA_FUNCTION_P (decl)))
2595 return d_comdat_linkage (decl);
2597 /* Don't need to give private or protected symbols a special linkage. */
2598 if ((TREE_PRIVATE (decl) || TREE_PROTECTED (decl))
2599 && !DECL_INSTANTIATED (decl))
2600 return;
2602 /* If all instantiations must go in COMDAT, give them that linkage.
2603 This also applies to other extern declarations, so that it is possible
2604 for them to override template declarations. */
2605 if (targetdm.d_templates_always_comdat)
2607 /* Make sure that instantiations are not removed. */
2608 if (flag_weak_templates && DECL_INSTANTIATED (decl))
2609 d_mark_needed (decl);
2611 return d_comdat_linkage (decl);
2614 /* Instantiated variables and functions need to be overridable by any other
2615 symbol with the same name, so give them weak linkage. */
2616 if (DECL_INSTANTIATED (decl))
2617 return d_weak_linkage (decl);
2619 /* Compiler generated public symbols can appear in multiple contexts. */
2620 if (DECL_ARTIFICIAL (decl))
2621 return d_weak_linkage (decl);
2624 /* NODE is a FUNCTION_DECL, VAR_DECL or RECORD_TYPE for the declaration SYM.
2625 Set flags to reflect visibility that NODE will get in the object file. */
2627 void
2628 set_visibility_for_decl (tree node, Dsymbol *sym)
2630 Visibility visibility = sym->visible ();
2631 if (visibility.kind == Visibility::private_)
2632 TREE_PRIVATE (node) = 1;
2633 else if (visibility.kind == Visibility::protected_)
2634 TREE_PROTECTED (node) = 1;
2636 /* If the declaration was declared `export', append either the dllimport
2637 or dllexport attribute. */
2638 if (TARGET_DLLIMPORT_DECL_ATTRIBUTES)
2640 const char *attrname = NULL;
2642 /* Have to test for import first. */
2643 if (sym->isImportedSymbol ())
2644 attrname = "dllimport";
2645 else if (sym->isExport ())
2646 attrname = "dllexport";
2648 if (attrname != NULL)
2650 if (DECL_P (node))
2651 insert_decl_attribute (node, attrname);
2652 else if (TYPE_P (node))
2653 insert_type_attribute (node, attrname);