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