]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/d/decl.cc
d: Use new isXxxxExp helpers where possible
[thirdparty/gcc.git] / gcc / d / decl.cc
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2 Copyright (C) 2006-2020 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
17
18 #include "config.h"
19 #include "system.h"
20 #include "coretypes.h"
21
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"
39
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
57 #include "d-tree.h"
58
59
60 /* Return identifier for the external mangled name of DECL. */
61
62 const char *
63 d_mangle_decl (Dsymbol *decl)
64 {
65 if (decl->isFuncDeclaration ())
66 return mangleExact ((FuncDeclaration *)decl);
67 else
68 {
69 OutBuffer buf;
70 mangleToBuffer (decl, &buf);
71 return buf.extractChars ();
72 }
73 }
74
75 /* Generate a mangled identifier using NAME and SUFFIX, prefixed by the
76 assembler name for DECL. */
77
78 tree
79 mangle_internal_decl (Dsymbol *decl, const char *name, const char *suffix)
80 {
81 const char *prefix = d_mangle_decl (decl);
82 unsigned namelen = strlen (name);
83 unsigned buflen = (2 + strlen (prefix) + namelen + strlen (suffix)) * 2;
84 char *buf = (char *) alloca (buflen);
85
86 snprintf (buf, buflen, "_D%s%u%s%s", prefix, namelen, name, suffix);
87 tree ident = get_identifier (buf);
88
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);
93
94 return ident;
95 }
96
97 /* Returns true if DECL is from the gcc.attribute module. */
98
99 static bool
100 gcc_attribute_p (Dsymbol *decl)
101 {
102 ModuleDeclaration *md = decl->getModule ()->md;
103
104 if (md && md->packages && md->packages->length == 1)
105 {
106 if (!strcmp ((*md->packages)[0]->toChars (), "gcc")
107 && !strcmp (md->id->toChars (), "attribute"))
108 return true;
109 }
110
111 return false;
112 }
113
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(). */
120
121 class DeclVisitor : public Visitor
122 {
123 using Visitor::visit;
124
125 /* If we're lowering the body of a version(unittest) condition. */
126 bool in_version_unittest_;
127
128 public:
129 DeclVisitor (void)
130 {
131 this->in_version_unittest_ = false;
132 }
133
134 /* Helper for generating code for the dsymbol AST class D.
135 Sets up the location of the symbol before lowering. */
136
137 void build_dsymbol (Dsymbol *d)
138 {
139 location_t saved_location = input_location;
140 input_location = make_location_t (d->loc);
141 d->accept (this);
142 input_location = saved_location;
143 }
144
145 /* This should be overridden by each declaration class. */
146
147 void visit (Dsymbol *)
148 {
149 }
150
151 /* Compile a D module, and all members of it. */
152
153 void visit (Module *d)
154 {
155 if (d->semanticRun >= PASSobj)
156 return;
157
158 build_module_tree (d);
159 d->semanticRun = PASSobj;
160 }
161
162 /* Write the imported symbol to debug. */
163
164 void visit (Import *d)
165 {
166 if (d->semanticRun >= PASSobj)
167 return;
168
169 /* Implements import declarations by telling the debug back-end we are
170 importing the NAMESPACE_DECL of the module or IMPORTED_DECL of the
171 declaration into the current lexical scope CONTEXT. NAME is set if
172 this is a renamed import. */
173 if (d->isstatic)
174 return;
175
176 /* Get the context of this import, this should never be null. */
177 tree context = d_module_context ();
178
179 if (d->ident == NULL)
180 {
181 /* Importing declaration list. */
182 for (size_t i = 0; i < d->names.length; i++)
183 {
184 AliasDeclaration *aliasdecl = d->aliasdecls[i];
185 tree decl = build_import_decl (aliasdecl);
186
187 /* Skip over unhandled imports. */
188 if (decl == NULL_TREE)
189 continue;
190
191 Identifier *alias = d->aliases[i];
192 tree name = (alias != NULL)
193 ? get_identifier (alias->toChars ()) : NULL_TREE;
194
195 debug_hooks->imported_module_or_decl (decl, name, context,
196 false, false);
197 }
198 }
199 else
200 {
201 /* Importing the entire module. */
202 tree decl = build_import_decl (d->mod);
203
204 tree name = (d->aliasId != NULL)
205 ? get_identifier (d->aliasId->toChars ()) : NULL_TREE;
206
207 debug_hooks->imported_module_or_decl (decl, name, context,
208 false, false);
209 }
210
211 d->semanticRun = PASSobj;
212 }
213
214 /* Expand any local variables found in tuples. */
215
216 void visit (TupleDeclaration *d)
217 {
218 for (size_t i = 0; i < d->objects->length; i++)
219 {
220 RootObject *o = (*d->objects)[i];
221 if (o->dyncast () == DYNCAST_EXPRESSION)
222 {
223 DsymbolExp *de = ((Expression *) o)->isDsymbolExp ();
224 if (de != NULL && de->s->isDeclaration ())
225 this->build_dsymbol (de->s);
226 }
227 }
228 }
229
230 /* Walk over all declarations in the attribute scope. */
231
232 void visit (AttribDeclaration *d)
233 {
234 Dsymbols *ds = d->include (NULL);
235
236 if (!ds)
237 return;
238
239 for (size_t i = 0; i < ds->length; i++)
240 this->build_dsymbol ((*ds)[i]);
241 }
242
243 /* Pragmas are a way to pass special information to the compiler and to add
244 vendor specific extensions to D. We don't do anything here, yet. */
245
246 void visit (PragmaDeclaration *d)
247 {
248 if (!global.params.ignoreUnsupportedPragmas)
249 {
250 if (d->ident == Identifier::idPool ("lib")
251 || d->ident == Identifier::idPool ("startaddress"))
252 {
253 warning_at (make_location_t (d->loc), OPT_Wunknown_pragmas,
254 "pragma(%s) not implemented", d->ident->toChars ());
255 }
256 }
257
258 visit ((AttribDeclaration *) d);
259 }
260
261 /* Conditional compilation is the process of selecting which code to compile
262 and which code to not compile. Look for version conditions that may */
263
264 void visit (ConditionalDeclaration *d)
265 {
266 bool old_condition = this->in_version_unittest_;
267
268 if (global.params.useUnitTests)
269 {
270 VersionCondition *vc = d->condition->isVersionCondition ();
271 if (vc && vc->ident == Identifier::idPool ("unittest"))
272 this->in_version_unittest_ = true;
273 }
274
275 visit ((AttribDeclaration *) d);
276
277 this->in_version_unittest_ = old_condition;
278 }
279
280 /* Walk over all members in the namespace scope. */
281
282 void visit (Nspace *d)
283 {
284 if (isError (d) || !d->members)
285 return;
286
287 for (size_t i = 0; i < d->members->length; i++)
288 this->build_dsymbol ((*d->members)[i]);
289 }
290
291 /* Templates are D's approach to generic programming. They have no members
292 that can be emitted, however if the template is nested and used as a
293 voldemort type, then it's members must be compiled before the parent
294 function finishes. */
295
296 void visit (TemplateDeclaration *d)
297 {
298 /* Type cannot be directly named outside of the scope it's declared in, so
299 the only way it can be escaped is if the function has auto return. */
300 FuncDeclaration *fd = d_function_chain ? d_function_chain->function : NULL;
301
302 if (!fd || !fd->isAuto ())
303 return;
304
305 /* Check if the function returns an instantiated type that may contain
306 nested members. Only applies to classes or structs. */
307 Type *tb = fd->type->nextOf ()->baseElemOf ();
308
309 while (tb->ty == Tarray || tb->ty == Tpointer)
310 tb = tb->nextOf ()->baseElemOf ();
311
312 TemplateInstance *ti = NULL;
313
314 if (tb->ty == Tstruct)
315 ti = tb->isTypeStruct ()->sym->isInstantiated ();
316 else if (tb->ty == Tclass)
317 ti = tb->isTypeClass ()->sym->isInstantiated ();
318
319 /* Return type is instantiated from this template declaration, walk over
320 all members of the instance. */
321 if (ti && ti->tempdecl == d)
322 this->build_dsymbol (ti);
323 }
324
325 /* Walk over all members in the instantiated template. */
326
327 void visit (TemplateInstance *d)
328 {
329 if (isError (d)|| !d->members)
330 return;
331
332 if (!d->needsCodegen ())
333 return;
334
335 for (size_t i = 0; i < d->members->length; i++)
336 this->build_dsymbol ((*d->members)[i]);
337 }
338
339 /* Walk over all members in the mixin template scope. */
340
341 void visit (TemplateMixin *d)
342 {
343 if (isError (d)|| !d->members)
344 return;
345
346 for (size_t i = 0; i < d->members->length; i++)
347 this->build_dsymbol ((*d->members)[i]);
348 }
349
350 /* Write out compiler generated TypeInfo, initializer and functions for the
351 given struct declaration, walking over all static members. */
352
353 void visit (StructDeclaration *d)
354 {
355 if (d->semanticRun >= PASSobj)
356 return;
357
358 if (d->type->ty == Terror)
359 {
360 error_at (make_location_t (d->loc),
361 "had semantic errors when compiling");
362 return;
363 }
364
365 /* Add this decl to the current binding level. */
366 tree ctype = build_ctype (d->type);
367 if (TYPE_NAME (ctype))
368 d_pushdecl (TYPE_NAME (ctype));
369
370 /* Anonymous structs/unions only exist as part of others,
371 do not output forward referenced structs. */
372 if (d->isAnonymous () || !d->members)
373 return;
374
375 /* Don't emit any symbols from gcc.attribute module. */
376 if (gcc_attribute_p (d))
377 return;
378
379 /* Generate TypeInfo. */
380 if (have_typeinfo_p (Type::dtypeinfo))
381 create_typeinfo (d->type, NULL);
382
383 /* Generate static initializer. */
384 d->sinit = aggregate_initializer_decl (d);
385 DECL_INITIAL (d->sinit) = layout_struct_initializer (d);
386
387 if (d->isInstantiated ())
388 d_linkonce_linkage (d->sinit);
389
390 d_finish_decl (d->sinit);
391
392 /* Put out the members. There might be static constructors in the members
393 list, and they cannot be put in separate object files. */
394 for (size_t i = 0; i < d->members->length; i++)
395 this->build_dsymbol ((*d->members)[i]);
396
397 /* Put out xopEquals, xopCmp and xopHash. */
398 if (d->xeq && d->xeq != d->xerreq)
399 this->build_dsymbol (d->xeq);
400
401 if (d->xcmp && d->xcmp != d->xerrcmp)
402 this->build_dsymbol (d->xcmp);
403
404 if (d->xhash)
405 this->build_dsymbol (d->xhash);
406
407 d->semanticRun = PASSobj;
408 }
409
410 /* Finish semantic analysis of functions in vtbl for class CD. */
411
412 bool finish_vtable (ClassDeclaration *d)
413 {
414 bool has_errors = false;
415
416 /* Finish semantic analysis of functions in vtbl[]. */
417 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
418 {
419 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
420
421 if (!fd || (!fd->fbody && d->isAbstract ()))
422 continue;
423
424 /* Ensure function has a return value. */
425 if (!fd->functionSemantic ())
426 has_errors = true;
427
428 /* No name hiding to check for. */
429 if (!d->isFuncHidden (fd) || fd->isFuture ())
430 continue;
431
432 /* The function fd is hidden from the view of the class.
433 If it overlaps with any function in the vtbl[], then
434 issue an error. */
435 for (size_t j = 1; j < d->vtbl.length; j++)
436 {
437 if (j == i)
438 continue;
439
440 FuncDeclaration *fd2 = d->vtbl[j]->isFuncDeclaration ();
441 if (!fd2->ident->equals (fd->ident))
442 continue;
443
444 /* The function is marked as @__future, a deprecation has
445 already been given by the frontend. */
446 if (fd2->isFuture ())
447 continue;
448
449 if (fd->leastAsSpecialized (fd2) || fd2->leastAsSpecialized (fd))
450 {
451 error_at (make_location_t (fd->loc), "use of %qs",
452 fd->toPrettyChars ());
453 inform (make_location_t (fd2->loc), "is hidden by %qs",
454 fd2->toPrettyChars ());
455 inform (make_location_t (d->loc),
456 "use %<alias %s = %s.%s;%> to introduce base class "
457 "overload set", fd->toChars (),
458 fd->parent->toChars (), fd->toChars ());
459 has_errors = true;
460 break;
461 }
462 }
463 }
464
465 return !has_errors;
466 }
467
468 /* Write out compiler generated TypeInfo, initializer and vtables for the
469 given class declaration, walking over all static members. */
470
471 void visit (ClassDeclaration *d)
472 {
473 if (d->semanticRun >= PASSobj)
474 return;
475
476 if (d->type->ty == Terror)
477 {
478 error_at (make_location_t (d->loc),
479 "had semantic errors when compiling");
480 return;
481 }
482
483 if (!d->members)
484 return;
485
486 /* Put out the members. */
487 for (size_t i = 0; i < d->members->length; i++)
488 this->build_dsymbol ((*d->members)[i]);
489
490 /* If something goes wrong during final semantic pass, don't bother with
491 the rest as we may have incomplete info. */
492 if (!this->finish_vtable (d))
493 return;
494
495 /* Generate C symbols. */
496 d->csym = get_classinfo_decl (d);
497 d->vtblsym = get_vtable_decl (d);
498 d->sinit = aggregate_initializer_decl (d);
499
500 /* Generate static initializer. */
501 DECL_INITIAL (d->sinit) = layout_class_initializer (d);
502 d_linkonce_linkage (d->sinit);
503 d_finish_decl (d->sinit);
504
505 /* Put out the TypeInfo. */
506 if (have_typeinfo_p (Type::dtypeinfo))
507 create_typeinfo (d->type, NULL);
508
509 DECL_INITIAL (d->csym) = layout_classinfo (d);
510 d_linkonce_linkage (d->csym);
511 d_finish_decl (d->csym);
512
513 /* Put out the vtbl[]. */
514 vec<constructor_elt, va_gc> *elms = NULL;
515
516 /* First entry is ClassInfo reference. */
517 if (d->vtblOffset ())
518 CONSTRUCTOR_APPEND_ELT (elms, size_zero_node, build_address (d->csym));
519
520 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
521 {
522 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
523
524 if (fd && (fd->fbody || !d->isAbstract()))
525 {
526 CONSTRUCTOR_APPEND_ELT (elms, size_int (i),
527 build_address (get_symbol_decl (fd)));
528 }
529 }
530
531 DECL_INITIAL (d->vtblsym)
532 = build_constructor (TREE_TYPE (d->vtblsym), elms);
533 d_comdat_linkage (d->vtblsym);
534 d_finish_decl (d->vtblsym);
535
536 /* Add this decl to the current binding level. */
537 tree ctype = TREE_TYPE (build_ctype (d->type));
538 if (TYPE_NAME (ctype))
539 d_pushdecl (TYPE_NAME (ctype));
540
541 d->semanticRun = PASSobj;
542 }
543
544 /* Write out compiler generated TypeInfo and vtables for the given interface
545 declaration, walking over all static members. */
546
547 void visit (InterfaceDeclaration *d)
548 {
549 if (d->semanticRun >= PASSobj)
550 return;
551
552 if (d->type->ty == Terror)
553 {
554 error_at (make_location_t (d->loc),
555 "had semantic errors when compiling");
556 return;
557 }
558
559 if (!d->members)
560 return;
561
562 /* Put out the members. */
563 for (size_t i = 0; i < d->members->length; i++)
564 this->build_dsymbol ((*d->members)[i]);
565
566 /* Generate C symbols. */
567 d->csym = get_classinfo_decl (d);
568
569 /* Put out the TypeInfo. */
570 if (have_typeinfo_p (Type::dtypeinfo))
571 {
572 create_typeinfo (d->type, NULL);
573 this->build_dsymbol (d->type->vtinfo);
574 }
575
576 DECL_INITIAL (d->csym) = layout_classinfo (d);
577 d_linkonce_linkage (d->csym);
578 d_finish_decl (d->csym);
579
580 /* Add this decl to the current binding level. */
581 tree ctype = TREE_TYPE (build_ctype (d->type));
582 if (TYPE_NAME (ctype))
583 d_pushdecl (TYPE_NAME (ctype));
584
585 d->semanticRun = PASSobj;
586 }
587
588 /* Write out compiler generated TypeInfo and initializer for the given
589 enum declaration. */
590
591 void visit (EnumDeclaration *d)
592 {
593 if (d->semanticRun >= PASSobj)
594 return;
595
596 if (d->errors || d->type->ty == Terror)
597 {
598 error_at (make_location_t (d->loc),
599 "had semantic errors when compiling");
600 return;
601 }
602
603 if (d->isAnonymous ())
604 return;
605
606 /* Generate TypeInfo. */
607 if (have_typeinfo_p (Type::dtypeinfo))
608 create_typeinfo (d->type, NULL);
609
610 TypeEnum *tc = d->type->isTypeEnum ();
611 if (tc->sym->members && !d->type->isZeroInit ())
612 {
613 /* Generate static initializer. */
614 d->sinit = enum_initializer_decl (d);
615 DECL_INITIAL (d->sinit) = build_expr (tc->sym->defaultval, true);
616
617 if (d->isInstantiated ())
618 d_linkonce_linkage (d->sinit);
619
620 d_finish_decl (d->sinit);
621
622 /* Add this decl to the current binding level. */
623 tree ctype = build_ctype (d->type);
624 if (TREE_CODE (ctype) == ENUMERAL_TYPE && TYPE_NAME (ctype))
625 d_pushdecl (TYPE_NAME (ctype));
626 }
627
628 d->semanticRun = PASSobj;
629 }
630
631 /* Finish up a variable declaration and push it into the current scope.
632 This can either be a static, local or manifest constant. */
633
634 void visit (VarDeclaration *d)
635 {
636 if (d->semanticRun >= PASSobj)
637 return;
638
639 if (d->type->ty == Terror)
640 {
641 error_at (make_location_t (d->loc),
642 "had semantic errors when compiling");
643 return;
644 }
645
646 if (d->aliassym)
647 {
648 this->build_dsymbol (d->toAlias ());
649 return;
650 }
651
652 /* Do not store variables we cannot take the address of,
653 but keep the values for purposes of debugging. */
654 if (!d->canTakeAddressOf ())
655 {
656 /* Don't know if there is a good way to handle instantiations. */
657 if (d->isInstantiated ())
658 return;
659
660 /* Cannot make an expression out of a void initializer. */
661 if (!d->_init || d->_init->isVoidInitializer ())
662 return;
663
664 tree decl = get_symbol_decl (d);
665 Expression *ie = initializerToExpression (d->_init);
666
667 /* CONST_DECL was initially intended for enumerals and may be used for
668 scalars in general, but not for aggregates. Here a non-constant
669 value is generated anyway so as the CONST_DECL only serves as a
670 placeholder for the value, however the DECL itself should never be
671 referenced in any generated code, or passed to the back-end. */
672 if (!d->type->isscalar ())
673 DECL_INITIAL (decl) = build_expr (ie, false);
674 else
675 {
676 DECL_INITIAL (decl) = build_expr (ie, true);
677 d_pushdecl (decl);
678 rest_of_decl_compilation (decl, 1, 0);
679 }
680 }
681 else if (d->isDataseg () && !(d->storage_class & STCextern))
682 {
683 tree decl = get_symbol_decl (d);
684
685 /* Duplicated VarDeclarations map to the same symbol. Check if this
686 is the one declaration which will be emitted. */
687 tree ident = DECL_ASSEMBLER_NAME (decl);
688 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
689 return;
690
691 /* How big a symbol can be should depend on back-end. */
692 tree size = build_integer_cst (d->type->size (d->loc),
693 build_ctype (Type::tsize_t));
694 if (!valid_constant_size_p (size))
695 {
696 error_at (make_location_t (d->loc), "size is too large");
697 return;
698 }
699
700 if (d->_init && !d->_init->isVoidInitializer ())
701 {
702 Expression *e = initializerToExpression (d->_init, d->type);
703 DECL_INITIAL (decl) = build_expr (e, true);
704 }
705 else
706 {
707 if (TypeStruct *ts = d->type->isTypeStruct ())
708 DECL_INITIAL (decl) = layout_struct_initializer (ts->sym);
709 else
710 {
711 Expression *e = d->type->defaultInitLiteral (d->loc);
712 DECL_INITIAL (decl) = build_expr (e, true);
713 }
714 }
715
716 /* Frontend should have already caught this. */
717 gcc_assert (!integer_zerop (size)
718 || d->type->toBasetype ()->ty == Tsarray);
719
720 d_finish_decl (decl);
721
722 /* Maybe record the var against the current module. */
723 register_module_decl (d);
724 }
725 else if (!d->isDataseg () && !d->isMember ())
726 {
727 /* This is needed for VarDeclarations in mixins that are to be local
728 variables of a function. Otherwise, it would be enough to make
729 a check for isVarDeclaration() in DeclarationExp codegen. */
730 declare_local_var (d);
731
732 if (d->_init)
733 {
734 tree decl = get_symbol_decl (d);
735
736 if (!d->_init->isVoidInitializer ())
737 {
738 ExpInitializer *vinit = d->_init->isExpInitializer ();
739 Expression *ie = initializerToExpression (vinit);
740 tree exp = build_expr (ie);
741
742 /* Maybe put variable on list of things needing destruction. */
743 if (d->needsScopeDtor ())
744 {
745 vec_safe_push (d_function_chain->vars_in_scope, decl);
746 /* Force a TARGET_EXPR to add the corresponding cleanup. */
747 exp = force_target_expr (compound_expr (exp, decl));
748 TARGET_EXPR_CLEANUP (exp) = build_expr (d->edtor);
749 }
750
751 add_stmt (exp);
752 }
753 else if (d->size (d->loc) != 0)
754 {
755 /* Zero-length arrays do not have an initializer. */
756 warning (OPT_Wuninitialized, "uninitialized variable '%s'",
757 d->ident ? d->ident->toChars () : "(no name)");
758 }
759 }
760 }
761
762 d->semanticRun = PASSobj;
763 }
764
765 /* Generate and compile a static TypeInfo declaration, but only if it is
766 needed in the current compilation. */
767
768 void visit (TypeInfoDeclaration *d)
769 {
770 if (d->semanticRun >= PASSobj)
771 return;
772
773 if (speculative_type_p (d->tinfo))
774 return;
775
776 tree t = get_typeinfo_decl (d);
777 DECL_INITIAL (t) = layout_typeinfo (d);
778 d_finish_decl (t);
779 d->semanticRun = PASSobj;
780 }
781
782 /* Finish up a function declaration and compile it all the way
783 down to assembler language output. */
784
785 void visit (FuncDeclaration *d)
786 {
787 /* Already generated the function. */
788 if (d->semanticRun >= PASSobj)
789 return;
790
791 /* Don't emit any symbols from gcc.attribute module. */
792 if (gcc_attribute_p (d))
793 return;
794
795 /* Not emitting unittest functions. */
796 if (!global.params.useUnitTests && d->isUnitTestDeclaration ())
797 return;
798
799 /* Check if any errors occurred when running semantic. */
800 if (TypeFunction *tf = d->type->isTypeFunction ())
801 {
802 if (tf->next == NULL || tf->next->ty == Terror)
803 return;
804 }
805
806 if (d->semantic3Errors)
807 return;
808
809 if (d->isNested ())
810 {
811 FuncDeclaration *fdp = d;
812 while (fdp && fdp->isNested ())
813 {
814 fdp = fdp->toParent2 ()->isFuncDeclaration ();
815
816 if (fdp == NULL)
817 break;
818
819 /* Parent failed to compile, but errors were gagged. */
820 if (fdp->semantic3Errors)
821 return;
822 }
823 }
824
825 /* Ensure all semantic passes have run. */
826 if (d->semanticRun < PASSsemantic3)
827 {
828 d->functionSemantic3 ();
829 Module::runDeferredSemantic3 ();
830 }
831
832 if (global.errors)
833 return;
834
835 /* Duplicated FuncDeclarations map to the same symbol. Check if this
836 is the one declaration which will be emitted. */
837 tree fndecl = get_symbol_decl (d);
838 tree ident = DECL_ASSEMBLER_NAME (fndecl);
839 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
840 return;
841
842 if (!d->fbody)
843 {
844 rest_of_decl_compilation (fndecl, 1, 0);
845 return;
846 }
847
848 if (global.params.verbose)
849 message ("function %s", d->toPrettyChars ());
850
851 /* Start generating code for this function. */
852 gcc_assert (d->semanticRun == PASSsemantic3done);
853 d->semanticRun = PASSobj;
854
855 tree old_context = start_function (d);
856
857 tree parm_decl = NULL_TREE;
858 tree param_list = NULL_TREE;
859
860 /* Special arguments... */
861
862 /* 'this' parameter:
863 For nested functions, D still generates a vthis, but it
864 should not be referenced in any expression. */
865 if (d->vthis)
866 {
867 parm_decl = get_symbol_decl (d->vthis);
868 DECL_ARTIFICIAL (parm_decl) = 1;
869 TREE_READONLY (parm_decl) = 1;
870
871 if (d->vthis->type == Type::tvoidptr)
872 {
873 /* Replace generic pointer with back-end closure type
874 (this wins for gdb). */
875 tree frame_type = FRAMEINFO_TYPE (get_frameinfo (d));
876 gcc_assert (frame_type != NULL_TREE);
877 TREE_TYPE (parm_decl) = build_pointer_type (frame_type);
878 }
879
880 param_list = chainon (param_list, parm_decl);
881 d_function_chain->static_chain = parm_decl;
882 }
883
884 /* _arguments parameter. */
885 if (d->v_arguments)
886 {
887 parm_decl = get_symbol_decl (d->v_arguments);
888 param_list = chainon (param_list, parm_decl);
889 }
890
891 /* formal function parameters. */
892 size_t n_parameters = d->parameters ? d->parameters->length : 0;
893
894 for (size_t i = 0; i < n_parameters; i++)
895 {
896 VarDeclaration *param = (*d->parameters)[i];
897 parm_decl = get_symbol_decl (param);
898 /* Chain them in the correct order. */
899 param_list = chainon (param_list, parm_decl);
900 }
901
902 DECL_ARGUMENTS (fndecl) = param_list;
903 DECL_IN_UNITTEST_CONDITION_P (fndecl) = this->in_version_unittest_;
904 rest_of_decl_compilation (fndecl, 1, 0);
905
906 /* If this is a member function that nested (possibly indirectly) in another
907 function, construct an expession for this member function's static chain
908 by going through parent link of nested classes. */
909 if (d->isThis ())
910 {
911 AggregateDeclaration *ad = d->isThis ();
912 tree this_tree = get_symbol_decl (d->vthis);
913
914 while (ad->isNested ())
915 {
916 Dsymbol *pd = ad->toParent2 ();
917 tree vthis_field = get_symbol_decl (ad->vthis);
918 this_tree = component_ref (build_deref (this_tree), vthis_field);
919
920 ad = pd->isAggregateDeclaration ();
921 if (ad == NULL)
922 {
923 cfun->language->static_chain = this_tree;
924 break;
925 }
926 }
927 }
928
929 /* May change cfun->static_chain. */
930 build_closure (d);
931
932 if (d->vresult)
933 declare_local_var (d->vresult);
934
935 if (d->v_argptr)
936 push_stmt_list ();
937
938 /* Named return value optimisation support for D.
939 Implemented by overriding all the RETURN_EXPRs and replacing all
940 occurrences of VAR with the RESULT_DECL for the function.
941 This is only worth doing for functions that can return in memory. */
942 if (d->nrvo_can)
943 {
944 tree restype = TREE_TYPE (DECL_RESULT (fndecl));
945
946 if (!AGGREGATE_TYPE_P (restype))
947 d->nrvo_can = 0;
948 else
949 d->nrvo_can = aggregate_value_p (restype, fndecl);
950 }
951
952 if (d->nrvo_can)
953 {
954 tree resdecl = DECL_RESULT (fndecl);
955
956 TREE_TYPE (resdecl)
957 = build_reference_type (TREE_TYPE (resdecl));
958 DECL_BY_REFERENCE (resdecl) = 1;
959 TREE_ADDRESSABLE (resdecl) = 0;
960 relayout_decl (resdecl);
961
962 if (d->nrvo_var)
963 {
964 tree var = get_symbol_decl (d->nrvo_var);
965
966 /* Copy name from VAR to RESULT. */
967 DECL_NAME (resdecl) = DECL_NAME (var);
968 /* Don't forget that we take its address. */
969 TREE_ADDRESSABLE (var) = 1;
970 resdecl = build_deref (resdecl);
971
972 SET_DECL_VALUE_EXPR (var, resdecl);
973 DECL_HAS_VALUE_EXPR_P (var) = 1;
974 SET_DECL_LANG_NRVO (var, resdecl);
975 }
976 }
977
978 build_function_body (d);
979
980 /* Initialize the _argptr variable. */
981 if (d->v_argptr)
982 {
983 tree body = pop_stmt_list ();
984 tree var = get_decl_tree (d->v_argptr);
985 var = build_address (var);
986
987 tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
988 2, var, parm_decl);
989 declare_local_var (d->v_argptr);
990 add_stmt (init);
991
992 tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
993 1, var);
994 add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
995 }
996
997 finish_function (old_context);
998
999 /* Maybe record the function against the current module. */
1000 register_module_decl (d);
1001 }
1002 };
1003
1004 /* Main entry point for the DeclVisitor interface to send
1005 the Declaration AST class D to GCC back-end. */
1006
1007 void
1008 build_decl_tree (Dsymbol *d)
1009 {
1010 location_t saved_location = input_location;
1011
1012 /* Set input location, empty DECL_SOURCE_FILE can crash debug generator. */
1013 if (d->loc.filename)
1014 input_location = make_location_t (d->loc);
1015 else
1016 input_location = make_location_t (Loc ("<no_file>", 1, 0));
1017
1018 DeclVisitor v = DeclVisitor ();
1019 v.build_dsymbol (d);
1020
1021 input_location = saved_location;
1022 }
1023
1024 /* Return the decl for the symbol, create it if it doesn't already exist. */
1025
1026 tree
1027 get_symbol_decl (Declaration *decl)
1028 {
1029 if (decl->csym)
1030 return decl->csym;
1031
1032 /* Deal with placeholder symbols immediately:
1033 SymbolDeclaration is used as a shell around an initializer symbol. */
1034 SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1035 if (sd)
1036 {
1037 decl->csym = aggregate_initializer_decl (sd->dsym);
1038 return decl->csym;
1039 }
1040
1041 /* Global static TypeInfo declaration. */
1042 if (decl->isTypeInfoDeclaration ())
1043 return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1044
1045 /* FuncAliasDeclaration is used to import functions from another scope. */
1046 FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1047 if (fad)
1048 {
1049 decl->csym = get_symbol_decl (fad->funcalias);
1050 return decl->csym;
1051 }
1052
1053 /* It is possible for a field declaration symbol to be requested
1054 before the parent type has been built. */
1055 if (decl->isField ())
1056 {
1057 AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1058 gcc_assert (ad != NULL);
1059
1060 /* Finishing off the type should create the associated FIELD_DECL. */
1061 build_ctype (ad->type);
1062 gcc_assert (decl->csym != NULL);
1063
1064 return decl->csym;
1065 }
1066
1067 /* Build the tree for the symbol. */
1068 FuncDeclaration *fd = decl->isFuncDeclaration ();
1069 if (fd)
1070 {
1071 /* Run full semantic on functions we need to know about. */
1072 if (!fd->functionSemantic ())
1073 {
1074 decl->csym = error_mark_node;
1075 return decl->csym;
1076 }
1077
1078 decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1079 get_identifier (decl->ident->toChars ()),
1080 NULL_TREE);
1081
1082 /* Set function type afterwards as there could be self references. */
1083 TREE_TYPE (decl->csym) = build_ctype (fd->type);
1084
1085 /* Set DECL_INITIAL now if the function has a definition. */
1086 if (fd->fbody)
1087 DECL_INITIAL (decl->csym) = error_mark_node;
1088 else
1089 DECL_EXTERNAL (decl->csym) = 1;
1090 }
1091 else
1092 {
1093 /* Build the variable declaration. */
1094 VarDeclaration *vd = decl->isVarDeclaration ();
1095 gcc_assert (vd != NULL);
1096
1097 tree_code code = vd->isParameter () ? PARM_DECL
1098 : !vd->canTakeAddressOf () ? CONST_DECL
1099 : VAR_DECL;
1100 decl->csym = build_decl (make_location_t (decl->loc), code,
1101 get_identifier (decl->ident->toChars ()),
1102 declaration_type (vd));
1103
1104 /* If any alignment was set on the declaration. */
1105 if (vd->alignment != STRUCTALIGN_DEFAULT)
1106 {
1107 SET_DECL_ALIGN (decl->csym, vd->alignment * BITS_PER_UNIT);
1108 DECL_USER_ALIGN (decl->csym) = 1;
1109 }
1110
1111 if (vd->storage_class & STCextern)
1112 DECL_EXTERNAL (decl->csym) = 1;
1113 }
1114
1115 /* Set the declaration mangled identifier if static. */
1116 if (decl->isCodeseg () || decl->isDataseg ())
1117 {
1118 tree mangled_name;
1119
1120 if (decl->mangleOverride.length)
1121 {
1122 mangled_name =
1123 get_identifier_with_length (decl->mangleOverride.ptr,
1124 decl->mangleOverride.length);
1125 }
1126 else
1127 mangled_name = get_identifier (d_mangle_decl (decl));
1128
1129 mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1130 mangled_name);
1131 /* The frontend doesn't handle duplicate definitions of unused symbols
1132 with the same mangle. So a check is done here instead. */
1133 if (IDENTIFIER_DSYMBOL (mangled_name))
1134 {
1135 Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1136 tree olddecl = decl->csym;
1137 decl->csym = get_symbol_decl (other);
1138
1139 /* The current declaration is a prototype or marked extern, merge
1140 applied user attributes and return. */
1141 if (DECL_EXTERNAL (olddecl) && !DECL_INITIAL (olddecl))
1142 {
1143 apply_user_attributes (decl, decl->csym);
1144 return decl->csym;
1145 }
1146 /* The previous declaration is a prototype or marked extern, set the
1147 current declaration as the main reference of the symbol. */
1148 else if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1149 {
1150 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1151 DECL_EXTERNAL (decl->csym) = 0;
1152 }
1153 /* Non-extern, non-templated decls shouldn't be defined twice. */
1154 else if (!decl->isInstantiated ())
1155 ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1156 }
1157 else
1158 {
1159 IDENTIFIER_PRETTY_NAME (mangled_name)
1160 = get_identifier (decl->toPrettyChars (true));
1161 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1162
1163 SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1164 }
1165 }
1166
1167 DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1168 DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1169
1170 if (TREE_CODE (decl->csym) == PARM_DECL)
1171 {
1172 /* Pass non-trivial structs by invisible reference. */
1173 if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1174 {
1175 tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1176 argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1177 gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1178 TREE_TYPE (decl->csym) = argtype;
1179 DECL_BY_REFERENCE (decl->csym) = 1;
1180 TREE_ADDRESSABLE (decl->csym) = 0;
1181 relayout_decl (decl->csym);
1182 decl->storage_class |= STCref;
1183 }
1184
1185 DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1186 gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1187 }
1188 else if (TREE_CODE (decl->csym) == CONST_DECL)
1189 {
1190 /* Manifest constants have no address in memory. */
1191 TREE_CONSTANT (decl->csym) = 1;
1192 TREE_READONLY (decl->csym) = 1;
1193 }
1194 else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1195 {
1196 /* The real function type may differ from its declaration. */
1197 tree fntype = TREE_TYPE (decl->csym);
1198 tree newfntype = NULL_TREE;
1199
1200 if (fd->isNested ())
1201 {
1202 /* Add an extra argument for the frame/closure pointer, this is also
1203 required to be compatible with D delegates. */
1204 newfntype = build_vthis_function (void_type_node, fntype);
1205 }
1206 else if (fd->isThis ())
1207 {
1208 /* Add an extra argument for the 'this' parameter. The handle type is
1209 used even if there is no debug info. It is needed to make sure
1210 virtual member functions are not called statically. */
1211 AggregateDeclaration *ad = fd->isMember2 ();
1212 tree handle = build_ctype (ad->handleType ());
1213
1214 /* If handle is a pointer type, get record type. */
1215 if (!ad->isStructDeclaration ())
1216 handle = TREE_TYPE (handle);
1217
1218 newfntype = build_vthis_function (handle, fntype);
1219
1220 /* Set the vindex on virtual functions. */
1221 if (fd->isVirtual () && fd->vtblIndex != -1)
1222 {
1223 DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1224 DECL_VIRTUAL_P (decl->csym) = 1;
1225 }
1226 }
1227 else if (fd->isMain () || fd->isCMain ())
1228 {
1229 /* The main function is named 'D main' to distinguish from C main. */
1230 if (fd->isMain ())
1231 DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1232
1233 /* 'void main' is implicitly converted to returning an int. */
1234 newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1235 }
1236
1237 if (newfntype != NULL_TREE)
1238 {
1239 /* Copy the old attributes from the original type. */
1240 TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1241 TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1242 TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1243 TREE_TYPE (decl->csym) = newfntype;
1244 d_keep (newfntype);
1245 }
1246
1247 /* Miscellaneous function flags. */
1248 if (fd->isMember2 () || fd->isFuncLiteralDeclaration ())
1249 {
1250 /* See grokmethod in cp/decl.c. Maybe we shouldn't be setting inline
1251 flags without reason or proper handling. */
1252 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1253 DECL_NO_INLINE_WARNING_P (decl->csym) = 1;
1254 }
1255
1256 /* In [pragma/inline], functions decorated with 'pragma(inline)' affects
1257 whether they are inlined or not. */
1258 if (fd->inlining == PINLINEalways)
1259 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1260 else if (fd->inlining == PINLINEnever)
1261 DECL_UNINLINABLE (decl->csym) = 1;
1262
1263 /* Function was declared 'naked'. */
1264 if (fd->naked)
1265 {
1266 insert_decl_attribute (decl->csym, "naked");
1267 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1268 }
1269
1270 /* Vector array operations are always compiler generated. */
1271 if (fd->isArrayOp)
1272 {
1273 TREE_PUBLIC (decl->csym) = 1;
1274 DECL_ARTIFICIAL (decl->csym) = 1;
1275 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1276 d_comdat_linkage (decl->csym);
1277 }
1278
1279 /* And so are ensure and require contracts. */
1280 if (fd->ident == Identifier::idPool ("ensure")
1281 || fd->ident == Identifier::idPool ("require"))
1282 {
1283 DECL_ARTIFICIAL (decl->csym) = 1;
1284 TREE_PUBLIC (decl->csym) = 1;
1285 }
1286
1287 if (decl->storage_class & STCfinal)
1288 DECL_FINAL_P (decl->csym) = 1;
1289
1290 /* Check whether this function is expanded by the frontend. */
1291 DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1292 maybe_set_intrinsic (fd);
1293
1294 /* For nested functions in particular, unnest fndecl in the cgraph, as
1295 all static chain passing is handled by the front-end. Do this even
1296 if we are not emitting the body. */
1297 struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1298 if (node->origin)
1299 node->unnest ();
1300 }
1301
1302 /* Mark compiler generated temporaries as artificial. */
1303 if (decl->storage_class & STCtemp)
1304 DECL_ARTIFICIAL (decl->csym) = 1;
1305
1306 /* Propagate shared on the decl. */
1307 if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1308 TREE_ADDRESSABLE (decl->csym) = 1;
1309
1310 /* Symbol was marked volatile. */
1311 if (decl->storage_class & STCvolatile)
1312 TREE_THIS_VOLATILE (decl->csym) = 1;
1313
1314 /* Protection attributes are used by the debugger. */
1315 if (decl->protection.kind == Prot::private_)
1316 TREE_PRIVATE (decl->csym) = 1;
1317 else if (decl->protection.kind == Prot::protected_)
1318 TREE_PROTECTED (decl->csym) = 1;
1319
1320 /* Likewise, so could the deprecated attribute. */
1321 if (decl->storage_class & STCdeprecated)
1322 TREE_DEPRECATED (decl->csym) = 1;
1323
1324 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1325 /* Have to test for import first. */
1326 if (decl->isImportedSymbol ())
1327 {
1328 insert_decl_attribute (decl->csym, "dllimport");
1329 DECL_DLLIMPORT_P (decl->csym) = 1;
1330 }
1331 else if (decl->isExport ())
1332 insert_decl_attribute (decl->csym, "dllexport");
1333 #endif
1334
1335 if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1336 {
1337 /* Set TREE_PUBLIC by default, but allow private template to override. */
1338 if (!fd || !fd->isNested ())
1339 TREE_PUBLIC (decl->csym) = 1;
1340
1341 TREE_STATIC (decl->csym) = 1;
1342 /* The decl has not been defined -- yet. */
1343 DECL_EXTERNAL (decl->csym) = 1;
1344
1345 if (decl->isInstantiated ())
1346 d_linkonce_linkage (decl->csym);
1347 }
1348
1349 /* Symbol is going in thread local storage. */
1350 if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1351 {
1352 if (global.params.vtls)
1353 message (decl->loc, "`%s` is thread local", decl->toChars ());
1354
1355 set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1356 }
1357
1358 /* Apply any user attributes that may affect semantic meaning. */
1359 apply_user_attributes (decl, decl->csym);
1360
1361 /* %% Probably should be a little more intelligent about setting this. */
1362 TREE_USED (decl->csym) = 1;
1363 d_keep (decl->csym);
1364
1365 return decl->csym;
1366 }
1367
1368 /* Returns a declaration for a VAR_DECL. Used to create compiler-generated
1369 global variables. */
1370
1371 tree
1372 declare_extern_var (tree ident, tree type)
1373 {
1374 /* If the VAR_DECL has already been declared, return it. */
1375 if (IDENTIFIER_DECL_TREE (ident))
1376 return IDENTIFIER_DECL_TREE (ident);
1377
1378 tree name = IDENTIFIER_PRETTY_NAME (ident)
1379 ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1380 tree decl = build_decl (input_location, VAR_DECL, name, type);
1381
1382 IDENTIFIER_DECL_TREE (ident) = decl;
1383 d_keep (decl);
1384
1385 SET_DECL_ASSEMBLER_NAME (decl, ident);
1386 DECL_ARTIFICIAL (decl) = 1;
1387 TREE_STATIC (decl) = 1;
1388 TREE_PUBLIC (decl) = 1;
1389
1390 /* The decl has not been defined -- yet. */
1391 DECL_EXTERNAL (decl) = 1;
1392
1393 return decl;
1394 }
1395
1396 /* Add local variable VAR into the current function body. */
1397
1398 void
1399 declare_local_var (VarDeclaration *var)
1400 {
1401 gcc_assert (!var->isDataseg () && !var->isMember ());
1402 gcc_assert (current_function_decl != NULL_TREE);
1403
1404 FuncDeclaration *fd = cfun->language->function;
1405 tree decl = get_symbol_decl (var);
1406
1407 gcc_assert (!TREE_STATIC (decl));
1408 d_pushdecl (decl);
1409 DECL_CONTEXT (decl) = current_function_decl;
1410
1411 /* Compiler generated symbols. */
1412 if (var == fd->vresult || var == fd->v_argptr)
1413 DECL_ARTIFICIAL (decl) = 1;
1414
1415 if (DECL_LANG_FRAME_FIELD (decl))
1416 {
1417 /* Fixes debugging local variables. */
1418 SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1419 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1420 }
1421 }
1422
1423 /* Return an unnamed local temporary of type TYPE. */
1424
1425 tree
1426 build_local_temp (tree type)
1427 {
1428 tree decl = build_decl (input_location, VAR_DECL, NULL_TREE, type);
1429
1430 DECL_CONTEXT (decl) = current_function_decl;
1431 DECL_ARTIFICIAL (decl) = 1;
1432 DECL_IGNORED_P (decl) = 1;
1433 d_pushdecl (decl);
1434
1435 return decl;
1436 }
1437
1438 /* Return the correct decl to be used for DECL. For VAR_DECLs, this could
1439 instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1440 value. For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1441 For all other kinds of decls, this just returns the result of
1442 get_symbol_decl(). */
1443
1444 tree
1445 get_decl_tree (Declaration *decl)
1446 {
1447 tree t = get_symbol_decl (decl);
1448 FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1449 VarDeclaration *vd = decl->isVarDeclaration ();
1450
1451 /* If cfun is NULL, then this is a global static. */
1452 if (vd == NULL || fd == NULL)
1453 return t;
1454
1455 /* Get the named return value. */
1456 if (DECL_LANG_NRVO (t))
1457 return DECL_LANG_NRVO (t);
1458
1459 /* Get the closure holding the var decl. */
1460 if (DECL_LANG_FRAME_FIELD (t))
1461 {
1462 FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1463 tree frame_ref = get_framedecl (fd, parent);
1464
1465 return component_ref (build_deref (frame_ref),
1466 DECL_LANG_FRAME_FIELD (t));
1467 }
1468
1469 /* Get the non-local 'this' value by going through parent link
1470 of nested classes, this routine pretty much undoes what
1471 getRightThis in the frontend removes from codegen. */
1472 if (vd->parent != fd && vd->isThisDeclaration ())
1473 {
1474 /* Find the first parent that is a member function. */
1475 while (!fd->isMember2 ())
1476 {
1477 gcc_assert (fd->vthis);
1478 fd = fd->toParent2 ()->isFuncDeclaration ();
1479 gcc_assert (fd != NULL);
1480 }
1481
1482 AggregateDeclaration *ad = fd->isThis ();
1483 gcc_assert (ad != NULL);
1484
1485 t = get_decl_tree (fd->vthis);
1486 Dsymbol *outer = fd;
1487
1488 while (outer != vd->parent)
1489 {
1490 gcc_assert (ad != NULL);
1491 outer = ad->toParent2 ();
1492
1493 /* Get the this->this parent link. */
1494 tree vfield = get_symbol_decl (ad->vthis);
1495 t = component_ref (build_deref (t), vfield);
1496
1497 ad = outer->isAggregateDeclaration ();
1498 if (ad != NULL)
1499 continue;
1500
1501 fd = outer->isFuncDeclaration ();
1502 while (fd != NULL)
1503 {
1504 /* If outer function creates a closure, then the 'this'
1505 value would be the closure pointer, and the real
1506 'this' the first field of that closure. */
1507 tree ff = get_frameinfo (fd);
1508 if (FRAMEINFO_CREATES_FRAME (ff))
1509 {
1510 t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1511 t = indirect_ref (build_ctype (fd->vthis->type), t);
1512 }
1513
1514 if (fd == vd->parent)
1515 break;
1516
1517 /* Continue looking for the right `this'. */
1518 outer = outer->toParent2 ();
1519 fd = outer->isFuncDeclaration ();
1520 }
1521
1522 ad = outer->isAggregateDeclaration ();
1523 }
1524
1525 return t;
1526 }
1527
1528 /* Auto variable that the back end will handle for us. */
1529 return t;
1530 }
1531
1532 /* Finish up a variable declaration and compile it all the way to
1533 the assembler language output. */
1534
1535 void
1536 d_finish_decl (tree decl)
1537 {
1538 gcc_assert (!error_operand_p (decl));
1539
1540 /* We are sending this symbol to object file, can't be extern. */
1541 TREE_STATIC (decl) = 1;
1542 DECL_EXTERNAL (decl) = 0;
1543
1544 /* Update the TLS model as the linkage has been modified. */
1545 if (DECL_THREAD_LOCAL_P (decl))
1546 set_decl_tls_model (decl, decl_default_tls_model (decl));
1547
1548 relayout_decl (decl);
1549
1550 if (flag_checking && DECL_INITIAL (decl))
1551 {
1552 /* Initializer must never be bigger than symbol size. */
1553 dinteger_t tsize = int_size_in_bytes (TREE_TYPE (decl));
1554 dinteger_t dtsize = int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1555
1556 if (tsize < dtsize)
1557 {
1558 tree name = DECL_ASSEMBLER_NAME (decl);
1559
1560 internal_error ("Mismatch between declaration %qE size (%wd) and "
1561 "its initializer size (%wd).",
1562 IDENTIFIER_PRETTY_NAME (name)
1563 ? IDENTIFIER_PRETTY_NAME (name) : name,
1564 tsize, dtsize);
1565 }
1566 }
1567
1568 /* Without weak symbols, symbol should be put in .common, but that can't
1569 be done if there is a nonzero initializer. */
1570 if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1571 && initializer_zerop (DECL_INITIAL (decl)))
1572 DECL_INITIAL (decl) = error_mark_node;
1573
1574 /* Add this decl to the current binding level. */
1575 d_pushdecl (decl);
1576
1577 rest_of_decl_compilation (decl, 1, 0);
1578 }
1579
1580 /* Thunk code is based on g++. */
1581
1582 static int thunk_labelno;
1583
1584 /* Create a static alias to function. */
1585
1586 static tree
1587 make_alias_for_thunk (tree function)
1588 {
1589 tree alias;
1590 char buf[256];
1591
1592 /* Thunks may reference extern functions which cannot be aliased. */
1593 if (DECL_EXTERNAL (function))
1594 return function;
1595
1596 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1597 thunk_labelno++;
1598
1599 alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1600 get_identifier (buf), TREE_TYPE (function));
1601 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1602 lang_hooks.dup_lang_specific_decl (alias);
1603 DECL_CONTEXT (alias) = NULL_TREE;
1604 TREE_READONLY (alias) = TREE_READONLY (function);
1605 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1606 TREE_PUBLIC (alias) = 0;
1607
1608 DECL_EXTERNAL (alias) = 0;
1609 DECL_ARTIFICIAL (alias) = 1;
1610
1611 DECL_DECLARED_INLINE_P (alias) = 0;
1612 DECL_INITIAL (alias) = error_mark_node;
1613 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1614
1615 TREE_ADDRESSABLE (alias) = 1;
1616 TREE_USED (alias) = 1;
1617 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1618
1619 if (!flag_syntax_only)
1620 {
1621 cgraph_node *aliasn;
1622 aliasn = cgraph_node::create_same_body_alias (alias, function);
1623 gcc_assert (aliasn != NULL);
1624 }
1625 return alias;
1626 }
1627
1628 /* Emit the definition of a D vtable thunk. */
1629
1630 static void
1631 finish_thunk (tree thunk, tree function)
1632 {
1633 /* Setup how D thunks are outputted. */
1634 int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1635 bool this_adjusting = true;
1636 tree alias;
1637
1638 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1639 alias = make_alias_for_thunk (function);
1640 else
1641 alias = function;
1642
1643 TREE_ADDRESSABLE (function) = 1;
1644 TREE_USED (function) = 1;
1645
1646 if (flag_syntax_only)
1647 {
1648 TREE_ASM_WRITTEN (thunk) = 1;
1649 return;
1650 }
1651
1652 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1653 && targetm_common.have_named_sections)
1654 {
1655 tree fn = function;
1656 symtab_node *symbol = symtab_node::get (function);
1657
1658 if (symbol != NULL && symbol->alias)
1659 {
1660 if (symbol->analyzed)
1661 fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1662 else
1663 fn = symtab_node::get (function)->alias_target;
1664 }
1665 resolve_unique_section (fn, 0, flag_function_sections);
1666
1667 if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1668 {
1669 resolve_unique_section (thunk, 0, flag_function_sections);
1670
1671 /* Output the thunk into the same section as function. */
1672 set_decl_section_name (thunk, DECL_SECTION_NAME (fn));
1673 symtab_node::get (thunk)->implicit_section
1674 = symtab_node::get (fn)->implicit_section;
1675 }
1676 }
1677
1678 /* Set up cloned argument trees for the thunk. */
1679 tree t = NULL_TREE;
1680 for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1681 {
1682 tree x = copy_node (a);
1683 DECL_CHAIN (x) = t;
1684 DECL_CONTEXT (x) = thunk;
1685 SET_DECL_RTL (x, NULL);
1686 DECL_HAS_VALUE_EXPR_P (x) = 0;
1687 TREE_ADDRESSABLE (x) = 0;
1688 t = x;
1689 }
1690 DECL_ARGUMENTS (thunk) = nreverse (t);
1691 TREE_ASM_WRITTEN (thunk) = 1;
1692
1693 cgraph_node *funcn, *thunk_node;
1694
1695 funcn = cgraph_node::get_create (function);
1696 gcc_assert (funcn);
1697 thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1698 fixed_offset, 0, 0, 0, alias);
1699
1700 if (DECL_ONE_ONLY (function))
1701 thunk_node->add_to_same_comdat_group (funcn);
1702
1703 /* Target assemble_mi_thunk doesn't work across section boundaries
1704 on many targets, instead force thunk to be expanded in gimple. */
1705 if (DECL_EXTERNAL (function))
1706 {
1707 /* cgraph::expand_thunk writes over current_function_decl, so if this
1708 could ever be in use by the codegen pass, we want to know about it. */
1709 gcc_assert (current_function_decl == NULL_TREE);
1710
1711 if (!stdarg_p (TREE_TYPE (thunk)))
1712 {
1713 thunk_node->create_edge (funcn, NULL, thunk_node->count);
1714 thunk_node->expand_thunk (false, true);
1715 }
1716
1717 /* Tell the back-end to not bother inlining the function, this is
1718 assumed not to work as it could be referencing symbols outside
1719 of the current compilation unit. */
1720 DECL_UNINLINABLE (function) = 1;
1721 }
1722 }
1723
1724 /* Return a thunk to DECL. Thunks adjust the incoming `this' pointer by OFFSET.
1725 Adjustor thunks are created and pointers to them stored in the method entries
1726 in the vtable in order to set the this pointer to the start of the object
1727 instance corresponding to the implementing method. */
1728
1729 tree
1730 make_thunk (FuncDeclaration *decl, int offset)
1731 {
1732 tree function = get_symbol_decl (decl);
1733
1734 if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1735 {
1736 /* Compile the function body before generating the thunk, this is done
1737 even if the decl is external to the current module. */
1738 if (decl->fbody)
1739 build_decl_tree (decl);
1740 else
1741 {
1742 /* Build parameters for functions that are not being compiled,
1743 so that they can be correctly cloned in finish_thunk. */
1744 tree fntype = TREE_TYPE (function);
1745 tree params = NULL_TREE;
1746
1747 for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
1748 {
1749 if (t == void_list_node)
1750 break;
1751
1752 tree param = build_decl (DECL_SOURCE_LOCATION (function),
1753 PARM_DECL, NULL_TREE, TREE_VALUE (t));
1754 DECL_ARG_TYPE (param) = TREE_TYPE (param);
1755 DECL_ARTIFICIAL (param) = 1;
1756 DECL_IGNORED_P (param) = 1;
1757 DECL_CONTEXT (param) = function;
1758 params = chainon (params, param);
1759 }
1760
1761 DECL_ARGUMENTS (function) = params;
1762
1763 /* Also build the result decl, which is needed when force creating
1764 the thunk in gimple inside cgraph_node::expand_thunk. */
1765 tree resdecl = build_decl (DECL_SOURCE_LOCATION (function),
1766 RESULT_DECL, NULL_TREE,
1767 TREE_TYPE (fntype));
1768 DECL_ARTIFICIAL (resdecl) = 1;
1769 DECL_IGNORED_P (resdecl) = 1;
1770 DECL_CONTEXT (resdecl) = function;
1771 DECL_RESULT (function) = resdecl;
1772 }
1773 }
1774
1775 /* Don't build the thunk if the compilation step failed. */
1776 if (global.errors)
1777 return error_mark_node;
1778
1779 /* See if we already have the thunk in question. */
1780 for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1781 {
1782 if (THUNK_LANG_OFFSET (t) == offset)
1783 return t;
1784 }
1785
1786 tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1787 FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1788 DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1789 lang_hooks.dup_lang_specific_decl (thunk);
1790 THUNK_LANG_OFFSET (thunk) = offset;
1791
1792 TREE_READONLY (thunk) = TREE_READONLY (function);
1793 TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
1794 TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
1795
1796 DECL_CONTEXT (thunk) = d_decl_context (decl);
1797
1798 /* Thunks inherit the public access of the function they are targetting.
1799 When the function is outside the current compilation unit however, then the
1800 thunk must be kept private to not conflict. */
1801 TREE_PUBLIC (thunk) = TREE_PUBLIC (function) && !DECL_EXTERNAL (function);
1802
1803 DECL_EXTERNAL (thunk) = 0;
1804
1805 /* Thunks are always addressable. */
1806 TREE_ADDRESSABLE (thunk) = 1;
1807 TREE_USED (thunk) = 1;
1808 DECL_ARTIFICIAL (thunk) = 1;
1809 DECL_DECLARED_INLINE_P (thunk) = 0;
1810
1811 DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
1812 DECL_COMDAT (thunk) = DECL_COMDAT (function);
1813 DECL_WEAK (thunk) = DECL_WEAK (function);
1814
1815 tree target_name = DECL_ASSEMBLER_NAME (function);
1816 unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
1817 const char *ident = XNEWVEC (const char, identlen);
1818 snprintf (CONST_CAST (char *, ident), identlen,
1819 "_DT%u%s", offset, IDENTIFIER_POINTER (target_name));
1820
1821 DECL_NAME (thunk) = get_identifier (ident);
1822 SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
1823
1824 d_keep (thunk);
1825
1826 finish_thunk (thunk, function);
1827
1828 /* Add it to the list of thunks associated with the function. */
1829 DECL_LANG_THUNKS (thunk) = NULL_TREE;
1830 DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
1831 DECL_LANG_THUNKS (function) = thunk;
1832
1833 return thunk;
1834 }
1835
1836 /* Create the FUNCTION_DECL for a function definition.
1837 This function creates a binding context for the function body
1838 as well as setting up the FUNCTION_DECL in current_function_decl.
1839 Returns the previous function context if it was already set. */
1840
1841 tree
1842 start_function (FuncDeclaration *fd)
1843 {
1844 tree fndecl = get_symbol_decl (fd);
1845
1846 /* Function has been defined, check now whether we intend to send it to
1847 object file, or it really is extern. Such as inlinable functions from
1848 modules not in this compilation, or thunk aliases. */
1849 TemplateInstance *ti = fd->isInstantiated ();
1850 if (ti && ti->needsCodegen ())
1851 {
1852 /* Warn about templates instantiated in this compilation. */
1853 if (ti == fd->parent)
1854 {
1855 warning (OPT_Wtemplates, "%s %qs instantiated",
1856 ti->kind (), ti->toPrettyChars (false));
1857 }
1858
1859 DECL_EXTERNAL (fndecl) = 0;
1860 }
1861 else
1862 {
1863 Module *md = fd->getModule ();
1864 if (md && md->isRoot ())
1865 DECL_EXTERNAL (fndecl) = 0;
1866 }
1867
1868 DECL_INITIAL (fndecl) = error_mark_node;
1869
1870 /* Add this decl to the current binding level. */
1871 d_pushdecl (fndecl);
1872
1873 /* Save the current function context. */
1874 tree old_context = current_function_decl;
1875
1876 if (old_context)
1877 push_function_context ();
1878
1879 /* Let GCC know the current scope is this function. */
1880 current_function_decl = fndecl;
1881
1882 tree restype = TREE_TYPE (TREE_TYPE (fndecl));
1883 tree resdecl = build_decl (make_location_t (fd->loc), RESULT_DECL,
1884 NULL_TREE, restype);
1885
1886 DECL_RESULT (fndecl) = resdecl;
1887 DECL_CONTEXT (resdecl) = fndecl;
1888 DECL_ARTIFICIAL (resdecl) = 1;
1889 DECL_IGNORED_P (resdecl) = 1;
1890
1891 /* Initialize the RTL code for the function. */
1892 allocate_struct_function (fndecl, false);
1893
1894 /* Store the end of the function. */
1895 if (fd->endloc.filename)
1896 cfun->function_end_locus = make_location_t (fd->endloc);
1897 else
1898 cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
1899
1900 cfun->language = ggc_cleared_alloc<language_function> ();
1901 cfun->language->function = fd;
1902
1903 /* Default chain value is 'null' unless parent found. */
1904 cfun->language->static_chain = null_pointer_node;
1905
1906 /* Find module for this function. */
1907 for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
1908 {
1909 cfun->language->module = p->isModule ();
1910 if (cfun->language->module)
1911 break;
1912 }
1913 gcc_assert (cfun->language->module != NULL);
1914
1915 /* Begin the statement tree for this function. */
1916 push_stmt_list ();
1917 push_binding_level (level_function);
1918
1919 return old_context;
1920 }
1921
1922 /* Finish up a function declaration and compile that function all
1923 the way to assembler language output. The free the storage for
1924 the function definition. Restores the previous function context. */
1925
1926 void
1927 finish_function (tree old_context)
1928 {
1929 tree fndecl = current_function_decl;
1930
1931 /* Tie off the statement tree for this function. */
1932 tree block = pop_binding_level ();
1933 tree body = pop_stmt_list ();
1934 tree bind = build3 (BIND_EXPR, void_type_node,
1935 BLOCK_VARS (block), body, block);
1936
1937 gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
1938
1939 /* Back-end expects a statement list to come from somewhere, however
1940 pop_stmt_list returns expressions when there is a single statement.
1941 So here we create a statement list unconditionally. */
1942 if (TREE_CODE (body) != STATEMENT_LIST)
1943 {
1944 tree stmtlist = alloc_stmt_list ();
1945 append_to_statement_list_force (body, &stmtlist);
1946 BIND_EXPR_BODY (bind) = stmtlist;
1947 }
1948 else if (!STATEMENT_LIST_HEAD (body))
1949 {
1950 /* For empty functions add a void return. */
1951 append_to_statement_list_force (return_expr (NULL_TREE), &body);
1952 }
1953
1954 DECL_SAVED_TREE (fndecl) = bind;
1955
1956 if (!errorcount && !global.errors)
1957 {
1958 /* Dump the D-specific tree IR. */
1959 dump_function (TDI_original, fndecl);
1960
1961 cgraph_node::finalize_function (fndecl, true);
1962 }
1963
1964 /* We're leaving the context of this function, so free it. */
1965 ggc_free (cfun->language);
1966 cfun->language = NULL;
1967 set_cfun (NULL);
1968
1969 if (old_context)
1970 pop_function_context ();
1971
1972 current_function_decl = old_context;
1973 }
1974
1975 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
1976 must be emitted in this, output module. */
1977
1978 void
1979 mark_needed (tree decl)
1980 {
1981 TREE_USED (decl) = 1;
1982
1983 if (TREE_CODE (decl) == FUNCTION_DECL)
1984 {
1985 struct cgraph_node *node = cgraph_node::get_create (decl);
1986 node->forced_by_abi = true;
1987 }
1988 else if (VAR_P (decl))
1989 {
1990 struct varpool_node *node = varpool_node::get_create (decl);
1991 node->forced_by_abi = true;
1992 }
1993 }
1994
1995 /* Get the offset to the BC's vtbl[] initializer from the start of CD.
1996 Returns "~0u" if the base class is not found in any vtable interfaces. */
1997
1998 unsigned
1999 base_vtable_offset (ClassDeclaration *cd, BaseClass *bc)
2000 {
2001 unsigned csymoffset = target.classinfosize;
2002 unsigned interfacesize = int_size_in_bytes (vtbl_interface_type_node);
2003 csymoffset += cd->vtblInterfaces->length * interfacesize;
2004
2005 for (size_t i = 0; i < cd->vtblInterfaces->length; i++)
2006 {
2007 BaseClass *b = (*cd->vtblInterfaces)[i];
2008 if (b == bc)
2009 return csymoffset;
2010 csymoffset += b->sym->vtbl.length * target.ptrsize;
2011 }
2012
2013 /* Check all overriding interface vtbl[]s. */
2014 for (ClassDeclaration *cd2 = cd->baseClass; cd2; cd2 = cd2->baseClass)
2015 {
2016 for (size_t k = 0; k < cd2->vtblInterfaces->length; k++)
2017 {
2018 BaseClass *bs = (*cd2->vtblInterfaces)[k];
2019 if (bs->fillVtbl (cd, NULL, 0))
2020 {
2021 if (bc == bs)
2022 return csymoffset;
2023 csymoffset += bs->sym->vtbl.length * target.ptrsize;
2024 }
2025 }
2026 }
2027
2028 return ~0u;
2029 }
2030
2031 /* Get the VAR_DECL of the vtable symbol for DECL. If this does not yet exist,
2032 create it. The vtable is accessible via ClassInfo, but since it is needed
2033 frequently (like for rtti comparisons), make it directly accessible. */
2034
2035 tree
2036 get_vtable_decl (ClassDeclaration *decl)
2037 {
2038 if (decl->vtblsym)
2039 return decl->vtblsym;
2040
2041 tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
2042 /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
2043 will have a different type. However the back-end seems to accept this. */
2044 tree type = build_ctype (Type::tvoidptr->sarrayOf (decl->vtbl.length));
2045
2046 decl->vtblsym = declare_extern_var (ident, type);
2047 DECL_LANG_SPECIFIC (decl->vtblsym) = build_lang_decl (NULL);
2048
2049 /* Class is a reference, want the record type. */
2050 DECL_CONTEXT (decl->vtblsym) = TREE_TYPE (build_ctype (decl->type));
2051 TREE_READONLY (decl->vtblsym) = 1;
2052 DECL_VIRTUAL_P (decl->vtblsym) = 1;
2053
2054 SET_DECL_ALIGN (decl->vtblsym, TARGET_VTABLE_ENTRY_ALIGN);
2055 DECL_USER_ALIGN (decl->vtblsym) = true;
2056
2057 return decl->vtblsym;
2058 }
2059
2060 /* Helper function of build_class_instance. Find the field inside aggregate
2061 TYPE identified by IDENT at field OFFSET. */
2062
2063 static tree
2064 find_aggregate_field (tree type, tree ident, tree offset)
2065 {
2066 tree fields = TYPE_FIELDS (type);
2067
2068 for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2069 {
2070 if (DECL_NAME (field) == NULL_TREE
2071 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2072 && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2073 {
2074 /* Search nesting anonymous structs and unions. */
2075 tree vfield = find_aggregate_field (TREE_TYPE (field),
2076 ident, offset);
2077 if (vfield != NULL_TREE)
2078 return vfield;
2079 }
2080 else if (DECL_NAME (field) == ident
2081 && (offset == NULL_TREE
2082 || DECL_FIELD_OFFSET (field) == offset))
2083 {
2084 /* Found matching field at offset. */
2085 return field;
2086 }
2087 }
2088
2089 return NULL_TREE;
2090 }
2091
2092 /* Helper function of build_new_class_expr. Return a constructor that matches
2093 the layout of the class expression EXP. */
2094
2095 static tree
2096 build_class_instance (ClassReferenceExp *exp)
2097 {
2098 ClassDeclaration *cd = exp->originalClass ();
2099 tree type = TREE_TYPE (build_ctype (exp->value->stype));
2100 vec<constructor_elt, va_gc> *ve = NULL;
2101
2102 /* The set base vtable field. */
2103 tree vptr = build_address (get_vtable_decl (cd));
2104 CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2105
2106 /* Go through the inheritance graph from top to bottom. This will add all
2107 values to the constructor out of order, however build_struct_literal
2108 will re-order all values before returning the finished literal. */
2109 for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2110 {
2111 /* Anonymous vtable interface fields are laid out before the fields of
2112 each class. The interface offset is used to determine where to put
2113 the classinfo offset reference. */
2114 for (size_t i = 0; i < bcd->vtblInterfaces->length; i++)
2115 {
2116 BaseClass *bc = (*bcd->vtblInterfaces)[i];
2117
2118 for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2119 {
2120 gcc_assert (cd2 != NULL);
2121
2122 unsigned csymoffset = base_vtable_offset (cd2, bc);
2123 /* If the base class vtable was found. */
2124 if (csymoffset != ~0u)
2125 {
2126 tree csym = build_address (get_classinfo_decl (cd2));
2127 csym = build_offset (csym, size_int (csymoffset));
2128
2129 tree field = find_aggregate_field (type, NULL_TREE,
2130 size_int (bc->offset));
2131 gcc_assert (field != NULL_TREE);
2132
2133 CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2134 break;
2135 }
2136 }
2137 }
2138
2139 /* Generate initial values of all fields owned by current class.
2140 Use both the name and offset to find the right field. */
2141 for (size_t i = 0; i < bcd->fields.length; i++)
2142 {
2143 VarDeclaration *vfield = bcd->fields[i];
2144 int index = exp->findFieldIndexByName (vfield);
2145 gcc_assert (index != -1);
2146
2147 Expression *value = (*exp->value->elements)[index];
2148 if (!value)
2149 continue;
2150
2151 /* Use find_aggregate_field to get the overridden field decl,
2152 instead of the field associated with the base class. */
2153 tree field = get_symbol_decl (bcd->fields[i]);
2154 field = find_aggregate_field (type, DECL_NAME (field),
2155 DECL_FIELD_OFFSET (field));
2156 gcc_assert (field != NULL_TREE);
2157
2158 CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2159 }
2160 }
2161
2162 return build_struct_literal (type, ve);
2163 }
2164
2165 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2166 If this does not yet exist, create it. This is used to support initializing
2167 a static variable that is of a class type using values known during CTFE.
2168 In user code, it is analogous to the following code snippet.
2169
2170 enum E = new C(1, 2, 3);
2171
2172 That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2173 implementation detail. The initialization of these symbols could be done at
2174 run-time using during as part of the module initialization or shared static
2175 constructors phase of run-time start-up - whichever comes after `gc_init()'.
2176 And infact that would be the better thing to do here eventually. */
2177
2178 tree
2179 build_new_class_expr (ClassReferenceExp *expr)
2180 {
2181 if (expr->value->sym)
2182 return expr->value->sym;
2183
2184 /* Build the reference symbol. */
2185 tree type = build_ctype (expr->value->stype);
2186 expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2187
2188 DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2189 d_pushdecl (expr->value->sym);
2190 rest_of_decl_compilation (expr->value->sym, 1, 0);
2191
2192 return expr->value->sym;
2193 }
2194
2195 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2196 If this does not yet exist, create it. The static initializer data is
2197 accessible via TypeInfo, and is also used in 'new class' and default
2198 initializing struct literals. */
2199
2200 tree
2201 aggregate_initializer_decl (AggregateDeclaration *decl)
2202 {
2203 if (decl->sinit)
2204 return decl->sinit;
2205
2206 /* Class is a reference, want the record type. */
2207 tree type = build_ctype (decl->type);
2208 StructDeclaration *sd = decl->isStructDeclaration ();
2209 if (!sd)
2210 type = TREE_TYPE (type);
2211
2212 tree ident = mangle_internal_decl (decl, "__init", "Z");
2213
2214 decl->sinit = declare_extern_var (ident, type);
2215 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2216
2217 DECL_CONTEXT (decl->sinit) = type;
2218 TREE_READONLY (decl->sinit) = 1;
2219
2220 /* Honor struct alignment set by user. */
2221 if (sd && sd->alignment != STRUCTALIGN_DEFAULT)
2222 {
2223 SET_DECL_ALIGN (decl->sinit, sd->alignment * BITS_PER_UNIT);
2224 DECL_USER_ALIGN (decl->sinit) = true;
2225 }
2226
2227 return decl->sinit;
2228 }
2229
2230 /* Generate the data for the static initializer. */
2231
2232 tree
2233 layout_class_initializer (ClassDeclaration *cd)
2234 {
2235 NewExp *ne = NewExp::create (cd->loc, NULL, NULL, cd->type, NULL);
2236 ne->type = cd->type;
2237
2238 Expression *e = ne->ctfeInterpret ();
2239 gcc_assert (e->op == TOKclassreference);
2240
2241 return build_class_instance (e->isClassReferenceExp ());
2242 }
2243
2244 tree
2245 layout_struct_initializer (StructDeclaration *sd)
2246 {
2247 StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2248
2249 if (!sd->fill (sd->loc, sle->elements, true))
2250 gcc_unreachable ();
2251
2252 sle->type = sd->type;
2253 return build_expr (sle, true);
2254 }
2255
2256 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2257 If this does not yet exist, create it. The static initializer data is
2258 accessible via TypeInfo_Enum, but the field member type is a byte[] that
2259 requires a pointer to a symbol reference. */
2260
2261 tree
2262 enum_initializer_decl (EnumDeclaration *decl)
2263 {
2264 if (decl->sinit)
2265 return decl->sinit;
2266
2267 tree type = build_ctype (decl->type);
2268
2269 Identifier *ident_save = decl->ident;
2270 if (!decl->ident)
2271 decl->ident = Identifier::generateId ("__enum");
2272 tree ident = mangle_internal_decl (decl, "__init", "Z");
2273 decl->ident = ident_save;
2274
2275 decl->sinit = declare_extern_var (ident, type);
2276 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2277
2278 DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2279 TREE_READONLY (decl->sinit) = 1;
2280
2281 return decl->sinit;
2282 }
2283
2284 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2285 and optionally prefixing the name with PREFIX. */
2286
2287 tree
2288 build_artificial_decl (tree type, tree init, const char *prefix)
2289 {
2290 tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2291 const char *name = prefix ? prefix : "___s";
2292 char *label;
2293
2294 ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2295 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2296 DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2297
2298 TREE_PUBLIC (decl) = 0;
2299 TREE_STATIC (decl) = 1;
2300 TREE_USED (decl) = 1;
2301 DECL_IGNORED_P (decl) = 1;
2302 DECL_ARTIFICIAL (decl) = 1;
2303
2304 /* Perhaps at some point the initializer constant should be hashed
2305 to remove duplicates. */
2306 DECL_INITIAL (decl) = init;
2307
2308 return decl;
2309 }
2310
2311 /* Build TYPE_DECL for the declaration DSYM. */
2312
2313 void
2314 build_type_decl (tree type, Dsymbol *dsym)
2315 {
2316 if (TYPE_STUB_DECL (type))
2317 return;
2318
2319 gcc_assert (!POINTER_TYPE_P (type));
2320
2321 /* If a templated type, use the template instance name, as that includes all
2322 template parameters. */
2323 const char *name = dsym->parent->isTemplateInstance ()
2324 ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2325
2326 tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2327 get_identifier (name), type);
2328 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (d_mangle_decl (dsym)));
2329 TREE_PUBLIC (decl) = 1;
2330 DECL_ARTIFICIAL (decl) = 1;
2331 DECL_CONTEXT (decl) = d_decl_context (dsym);
2332
2333 TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2334 TYPE_NAME (type) = decl;
2335
2336 /* Not sure if there is a need for separate TYPE_DECLs in
2337 TYPE_NAME and TYPE_STUB_DECL. */
2338 if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2339 TYPE_STUB_DECL (type) = decl;
2340
2341 rest_of_decl_compilation (decl, SCOPE_FILE_SCOPE_P (decl), 0);
2342 }
2343
2344 /* Create a declaration for field NAME of a given TYPE, setting the flags
2345 for whether the field is ARTIFICIAL and/or IGNORED. */
2346
2347 tree
2348 create_field_decl (tree type, const char *name, int artificial, int ignored)
2349 {
2350 tree decl = build_decl (input_location, FIELD_DECL,
2351 name ? get_identifier (name) : NULL_TREE, type);
2352 DECL_ARTIFICIAL (decl) = artificial;
2353 DECL_IGNORED_P (decl) = ignored;
2354
2355 return decl;
2356 }
2357
2358 /* Return the COMDAT group into which DECL should be placed. */
2359
2360 static tree
2361 d_comdat_group (tree decl)
2362 {
2363 /* If already part of a comdat group, use that. */
2364 if (DECL_COMDAT_GROUP (decl))
2365 return DECL_COMDAT_GROUP (decl);
2366
2367 return DECL_ASSEMBLER_NAME (decl);
2368 }
2369
2370 /* Set DECL up to have the closest approximation of "initialized common"
2371 linkage available. */
2372
2373 void
2374 d_comdat_linkage (tree decl)
2375 {
2376 if (flag_weak)
2377 make_decl_one_only (decl, d_comdat_group (decl));
2378 else if (TREE_CODE (decl) == FUNCTION_DECL
2379 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2380 /* We can just emit function and compiler-generated variables statically;
2381 having multiple copies is (for the most part) only a waste of space. */
2382 TREE_PUBLIC (decl) = 0;
2383 else if (DECL_INITIAL (decl) == NULL_TREE
2384 || DECL_INITIAL (decl) == error_mark_node)
2385 /* Fallback, cannot have multiple copies. */
2386 DECL_COMMON (decl) = 1;
2387
2388 if (TREE_PUBLIC (decl))
2389 DECL_COMDAT (decl) = 1;
2390 }
2391
2392 /* Set DECL up to have the closest approximation of "linkonce" linkage. */
2393
2394 void
2395 d_linkonce_linkage (tree decl)
2396 {
2397 /* Weak definitions have to be public. */
2398 if (!TREE_PUBLIC (decl))
2399 return;
2400
2401 /* Necessary to allow DECL_ONE_ONLY or DECL_WEAK functions to be inlined. */
2402 if (TREE_CODE (decl) == FUNCTION_DECL)
2403 DECL_DECLARED_INLINE_P (decl) = 1;
2404
2405 /* No weak support, fallback to COMDAT linkage. */
2406 if (!flag_weak)
2407 return d_comdat_linkage (decl);
2408
2409 make_decl_one_only (decl, d_comdat_group (decl));
2410 }