1 /* types.cc -- Lower D frontend types to GCC trees.
2    Copyright (C) 2006-2019 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/attrib.h"
23 #include "dmd/aggregate.h"
24 #include "dmd/enum.h"
25 #include "dmd/expression.h"
26 #include "dmd/identifier.h"
27 #include "dmd/mtype.h"
28 #include "dmd/target.h"
29 
30 #include "tree.h"
31 #include "fold-const.h"
32 #include "diagnostic.h"
33 #include "langhooks.h"
34 #include "tm.h"
35 #include "function.h"
36 #include "toplev.h"
37 #include "target.h"
38 #include "stringpool.h"
39 #include "stor-layout.h"
40 #include "attribs.h"
41 
42 #include "d-tree.h"
43 
44 
45 /* Return TRUE if TYPE is a static array va_list.  This is for compatibility
46    with the C ABI, where va_list static arrays are passed by reference.
47    However for every other case in D, static arrays are passed by value.  */
48 
49 bool
valist_array_p(Type * type)50 valist_array_p (Type *type)
51 {
52   if (Type::tvalist->ty == Tsarray)
53     {
54       Type *tb = type->toBasetype ();
55       if (same_type_p (tb, Type::tvalist))
56 	return true;
57     }
58 
59   return false;
60 }
61 
62 /* Returns true if TYPE contains no actual data, just various
63    possible combinations of empty aggregates.  */
64 
65 bool
empty_aggregate_p(tree type)66 empty_aggregate_p (tree type)
67 {
68   if (!AGGREGATE_TYPE_P (type))
69     return false;
70 
71   /* Want the element type for arrays.  */
72   if (TREE_CODE (type) == ARRAY_TYPE)
73     return empty_aggregate_p (TREE_TYPE (type));
74 
75   /* Recursively check all fields.  */
76   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
77     {
78       if (TREE_CODE (field) == FIELD_DECL
79 	  && !empty_aggregate_p (TREE_TYPE (field)))
80 	return false;
81     }
82 
83   return true;
84 }
85 
86 /* Returns true if T1 and T2 are related to each other.  */
87 
88 bool
same_type_p(Type * t1,Type * t2)89 same_type_p (Type *t1, Type *t2)
90 {
91   /* Types are equal.  */
92   if (t1 == t2)
93     return true;
94 
95   /* Types derive from the same base.  */
96   Type *tb1 = t1->toBasetype ();
97   Type *tb2 = t2->toBasetype ();
98   if (tb1 == tb2)
99     return true;
100 
101   /* Types are mutably the same type.  */
102   if (tb1->ty == tb2->ty && tb1->equivalent (tb2))
103     return true;
104 
105   return false;
106 }
107 
108 /* Returns 'Object' type which all D classes are derived from.  */
109 
110 Type *
get_object_type(void)111 get_object_type (void)
112 {
113   if (ClassDeclaration::object)
114     return ClassDeclaration::object->type;
115 
116   error ("missing or corrupt object.d");
117   return Type::terror;
118 }
119 
120 
121 /* Returns a static array of TYPE which has SIZE number of elements.  */
122 
123 tree
make_array_type(Type * type,unsigned HOST_WIDE_INT size)124 make_array_type (Type *type, unsigned HOST_WIDE_INT size)
125 {
126   /* In [arrays/void-arrays], void arrays can also be static, the length is
127      specified in bytes.  */
128   if (type->toBasetype ()->ty == Tvoid)
129     type = Type::tuns8;
130 
131   /* In [arrays/static-arrays], a static array with a dimension of 0 is allowed,
132      but no space is allocated for it.  */
133   if (size == 0)
134     {
135       tree range = lang_hooks.types.type_for_size (TYPE_PRECISION (sizetype),
136 						   TYPE_UNSIGNED (sizetype));
137       tree index = build_range_type (range, size_zero_node, NULL_TREE);
138 
139       tree t = build_array_type (build_ctype (type), index);
140       TYPE_SIZE (t) = bitsize_zero_node;
141       TYPE_SIZE_UNIT (t) = size_zero_node;
142       return t;
143     }
144 
145   return build_array_type (build_ctype (type),
146 			   build_index_type (size_int (size - 1)));
147 }
148 
149 /* Builds a record type whose name is NAME.  NFIELDS is the number of fields,
150    provided as field ident/type pairs.  */
151 
152 tree
make_struct_type(const char * name,int nfields,...)153 make_struct_type (const char *name, int nfields, ...)
154 {
155   tree fields = NULL_TREE;
156   va_list ap;
157 
158   va_start (ap, nfields);
159 
160   for (int i = 0; i < nfields; i++)
161     {
162       tree ident = va_arg (ap, tree);
163       tree type = va_arg (ap, tree);
164       tree field = build_decl (BUILTINS_LOCATION, FIELD_DECL, ident, type);
165       DECL_CHAIN (field) = fields;
166       fields = field;
167     }
168 
169   va_end (ap);
170 
171   tree type = make_node (RECORD_TYPE);
172   finish_builtin_struct (type, name, fields, NULL_TREE);
173 
174   return type;
175 }
176 
177 /* Return qualified type variant of TYPE determined by modifier value MOD.  */
178 
179 tree
insert_type_modifiers(tree type,unsigned mod)180 insert_type_modifiers (tree type, unsigned mod)
181 {
182   int quals = 0;
183 
184   switch (mod)
185     {
186     case MODconst:
187     case MODwild:
188     case MODwildconst:
189     case MODimmutable:
190     case MODshared | MODconst:
191     case MODshared | MODwild:
192     case MODshared | MODwildconst:
193       quals |= TYPE_QUAL_CONST;
194       break;
195 
196     case 0:
197     case MODshared:
198       break;
199 
200     default:
201       gcc_unreachable ();
202     }
203 
204   tree qualtype = build_qualified_type (type, quals);
205 
206   /* Mark whether the type is qualified 'shared'.  */
207   if (mod & MODshared)
208     TYPE_SHARED (qualtype) = 1;
209 
210   return qualtype;
211 }
212 
213 /* Adds FIELD into the aggregate TYPE at OFFSET.  */
214 
215 void
insert_aggregate_field(tree type,tree field,size_t offset)216 insert_aggregate_field (tree type, tree field, size_t offset)
217 {
218   DECL_FIELD_CONTEXT (field) = type;
219   SET_DECL_OFFSET_ALIGN (field, TYPE_ALIGN (TREE_TYPE (field)));
220   DECL_FIELD_OFFSET (field) = size_int (offset);
221   DECL_FIELD_BIT_OFFSET (field) = bitsize_zero_node;
222 
223   TREE_ADDRESSABLE (field) = TYPE_SHARED (TREE_TYPE (field));
224 
225   layout_decl (field, 0);
226   TYPE_FIELDS (type) = chainon (TYPE_FIELDS (type), field);
227 }
228 
229 /* For all decls in the FIELDS chain, adjust their field offset by OFFSET.
230    This is done as the frontend puts fields into the outer struct, and so
231    their offset is from the beginning of the aggregate.
232    We want the offset to be from the beginning of the anonymous aggregate.  */
233 
234 static void
fixup_anonymous_offset(tree fields,tree offset)235 fixup_anonymous_offset (tree fields, tree offset)
236 {
237   while (fields != NULL_TREE)
238     {
239       /* Traverse all nested anonymous aggregates to update their offset.
240 	 Set the anonymous decl offset to its first member.  */
241       tree ftype = TREE_TYPE (fields);
242       if (TYPE_NAME (ftype) && anon_aggrname_p (TYPE_IDENTIFIER (ftype)))
243 	{
244 	  tree vfields = TYPE_FIELDS (ftype);
245 	  fixup_anonymous_offset (vfields, offset);
246 	  DECL_FIELD_OFFSET (fields) = DECL_FIELD_OFFSET (vfields);
247 	}
248       else
249 	{
250 	  tree voffset = DECL_FIELD_OFFSET (fields);
251 	  DECL_FIELD_OFFSET (fields) = size_binop (MINUS_EXPR, voffset, offset);
252 	}
253 
254       fields = DECL_CHAIN (fields);
255     }
256 }
257 
258 /* Iterate over all MEMBERS of an aggregate, and add them as fields to CONTEXT.
259    If INHERITED_P is true, then the members derive from a base class.
260    Returns the number of fields found.  */
261 
262 static size_t
layout_aggregate_members(Dsymbols * members,tree context,bool inherited_p)263 layout_aggregate_members (Dsymbols *members, tree context, bool inherited_p)
264 {
265   size_t fields = 0;
266 
267   for (size_t i = 0; i < members->dim; i++)
268     {
269       Dsymbol *sym = (*members)[i];
270       VarDeclaration *var = sym->isVarDeclaration ();
271       if (var != NULL)
272 	{
273 	  /* Skip fields that have already been added.  */
274 	  if (!inherited_p && var->csym != NULL)
275 	    continue;
276 
277 	  /* If this variable was really a tuple, add all tuple fields.  */
278 	  if (var->aliassym)
279 	    {
280 	      TupleDeclaration *td = var->aliassym->isTupleDeclaration ();
281 	      Dsymbols tmembers;
282 	      /* No other way to coerce the underlying type out of the tuple.
283 		 Frontend should have already validated this.  */
284 	      for (size_t j = 0; j < td->objects->dim; j++)
285 		{
286 		  RootObject *ro = (*td->objects)[j];
287 		  gcc_assert (ro->dyncast () == DYNCAST_EXPRESSION);
288 		  Expression *e = (Expression *) ro;
289 		  gcc_assert (e->op == TOKdsymbol);
290 		  DsymbolExp *se = (DsymbolExp *) e;
291 
292 		  tmembers.push (se->s);
293 		}
294 
295 	      fields += layout_aggregate_members (&tmembers, context,
296 						  inherited_p);
297 	      continue;
298 	    }
299 
300 	  /* Insert the field declaration at its given offset.  */
301 	  if (var->isField ())
302 	    {
303 	      const char *ident = var->ident ? var->ident->toChars () : NULL;
304 	      tree field = create_field_decl (declaration_type (var), ident,
305 					      inherited_p, inherited_p);
306 	      insert_aggregate_field (context, field, var->offset);
307 
308 	      /* Because the front-end shares field decls across classes, don't
309 		 create the corresponding back-end symbol unless we are adding
310 		 it to the aggregate it is defined in.  */
311 	      if (!inherited_p)
312 		{
313 		  DECL_LANG_SPECIFIC (field) = build_lang_decl (var);
314 		  var->csym = field;
315 		}
316 
317 	      fields += 1;
318 	      continue;
319 	    }
320 	}
321 
322       /* Anonymous struct/union are flattened by the frontend.  However, we
323 	 want to keep the record layout in-tact when building the type.  */
324       AnonDeclaration *ad = sym->isAnonDeclaration ();
325       if (ad != NULL)
326 	{
327 	  /* Use a counter to create anonymous type names.  */
328 	  static int anon_cnt = 0;
329 	  char buf[32];
330 	  sprintf (buf, anon_aggrname_format (), anon_cnt++);
331 
332 	  tree ident = get_identifier (buf);
333 	  tree type = make_node (ad->isunion ? UNION_TYPE : RECORD_TYPE);
334 	  ANON_AGGR_TYPE_P (type) = 1;
335 	  d_keep (type);
336 
337 	  /* Build the type declaration.  */
338 	  tree decl = build_decl (make_location_t (ad->loc),
339 				  TYPE_DECL, ident, type);
340 	  DECL_CONTEXT (decl) = context;
341 	  DECL_ARTIFICIAL (decl) = 1;
342 
343 	  TYPE_CONTEXT (type) = context;
344 	  TYPE_NAME (type) = decl;
345 	  TYPE_STUB_DECL (type) = decl;
346 
347 	  /* Recursively iterator over the anonymous members.  */
348 	  fields += layout_aggregate_members (ad->decl, type, inherited_p);
349 
350 	  /* Remove from the anon fields the base offset of this anonymous
351 	     aggregate.  Undoes what is set-up in setFieldOffset, but doesn't
352 	     affect field accesses.  */
353 	  tree offset = size_int (ad->anonoffset);
354 	  fixup_anonymous_offset (TYPE_FIELDS (type), offset);
355 
356 	  finish_aggregate_type (ad->anonstructsize, ad->anonalignsize,
357 				 type, NULL);
358 
359 	  /* And make the corresponding data member.  */
360 	  tree field = create_field_decl (type, NULL, 0, 0);
361 	  insert_aggregate_field (context, field, ad->anonoffset);
362 	  continue;
363 	}
364 
365       /* Other kinds of attributes don't create a scope.  */
366       AttribDeclaration *attrib = sym->isAttribDeclaration ();
367       if (attrib != NULL)
368 	{
369 	  Dsymbols *decls = attrib->include (NULL, NULL);
370 	  if (decls != NULL)
371 	    {
372 	      fields += layout_aggregate_members (decls, context, inherited_p);
373 	      continue;
374 	    }
375 	}
376 
377       /* Same with template mixins and namespaces.  */
378       if (sym->isTemplateMixin () || sym->isNspace ())
379 	{
380 	  ScopeDsymbol *scopesym = sym->isScopeDsymbol ();
381 	  if (scopesym->members)
382 	    {
383 	      fields += layout_aggregate_members (scopesym->members, context,
384 						  inherited_p);
385 	      continue;
386 	    }
387 	}
388     }
389 
390   return fields;
391 }
392 
393 /* Write out all fields for aggregate BASE.  For classes, write out all
394    interfaces first, then the base class fields.  */
395 
396 static void
layout_aggregate_type(AggregateDeclaration * decl,tree type,AggregateDeclaration * base)397 layout_aggregate_type (AggregateDeclaration *decl, tree type,
398 		       AggregateDeclaration *base)
399 {
400   ClassDeclaration *cd = base->isClassDeclaration ();
401   bool inherited_p = (decl != base);
402 
403   if (cd != NULL)
404     {
405       if (cd->baseClass)
406 	layout_aggregate_type (decl, type, cd->baseClass);
407       else
408 	{
409 	  /* This is the base class (Object) or interface.  */
410 	  tree objtype = TREE_TYPE (build_ctype (cd->type));
411 
412 	  /* Add the vtable pointer, and optionally the monitor fields.  */
413 	  InterfaceDeclaration *id = cd->isInterfaceDeclaration ();
414 	  if (!id || id->vtblInterfaces->dim == 0)
415 	    {
416 	      tree field = create_field_decl (vtbl_ptr_type_node, "__vptr", 1,
417 					      inherited_p);
418 	      DECL_VIRTUAL_P (field) = 1;
419 	      TYPE_VFIELD (type) = field;
420 	      DECL_FCONTEXT (field) = objtype;
421 	      insert_aggregate_field (type, field, 0);
422 	    }
423 
424 	  if (!id && !cd->isCPPclass ())
425 	    {
426 	      tree field = create_field_decl (ptr_type_node, "__monitor", 1,
427 					      inherited_p);
428 	      insert_aggregate_field (type, field, Target::ptrsize);
429 	    }
430 	}
431 
432       if (cd->vtblInterfaces)
433 	{
434 	  for (size_t i = 0; i < cd->vtblInterfaces->dim; i++)
435 	    {
436 	      BaseClass *bc = (*cd->vtblInterfaces)[i];
437 	      tree field = create_field_decl (vtbl_ptr_type_node, NULL, 1, 1);
438 	      insert_aggregate_field (type, field, bc->offset);
439 	    }
440 	}
441     }
442 
443   if (base->members)
444     {
445       size_t fields = layout_aggregate_members (base->members, type,
446 						inherited_p);
447       gcc_assert (fields == base->fields.dim);
448 
449       /* Make sure that all fields have been created.  */
450       if (!inherited_p)
451 	{
452 	  for (size_t i = 0; i < base->fields.dim; i++)
453 	    {
454 	      VarDeclaration *var = base->fields[i];
455 	      gcc_assert (var->csym != NULL);
456 	    }
457 	}
458     }
459 }
460 
461 /* Given a record type TYPE, whose size and alignment are determined by
462    STRUCTSIZE and ALIGNSIZE.  Apply any type attributes ATTRS and compute
463    the finalized record mode.  */
464 
465 void
finish_aggregate_type(unsigned structsize,unsigned alignsize,tree type,UserAttributeDeclaration * attrs)466 finish_aggregate_type (unsigned structsize, unsigned alignsize,
467 		       tree type, UserAttributeDeclaration *attrs)
468 {
469   TYPE_SIZE (type) = NULL_TREE;
470 
471   /* Write out any GCC attributes that were applied to the type declaration.  */
472   if (attrs)
473     {
474       Expressions *eattrs = attrs->getAttributes ();
475       decl_attributes (&type, build_attributes (eattrs),
476 		       ATTR_FLAG_TYPE_IN_PLACE);
477     }
478 
479   /* Set size and alignment as requested by frontend.  */
480   TYPE_SIZE (type) = bitsize_int (structsize * BITS_PER_UNIT);
481   TYPE_SIZE_UNIT (type) = size_int (structsize);
482   SET_TYPE_ALIGN (type, alignsize * BITS_PER_UNIT);
483   TYPE_PACKED (type) = (alignsize == 1);
484 
485   /* Set the back-end type mode.  */
486   compute_record_mode (type);
487 
488   /* Fix up all variants of this aggregate type.  */
489   for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
490     {
491       if (t == type)
492 	continue;
493 
494       TYPE_FIELDS (t) = TYPE_FIELDS (type);
495       TYPE_LANG_SPECIFIC (t) = TYPE_LANG_SPECIFIC (type);
496       SET_TYPE_ALIGN (t, TYPE_ALIGN (type));
497       TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (type);
498       gcc_assert (TYPE_MODE (t) == TYPE_MODE (type));
499     }
500 }
501 
502 
503 /* Implements the visitor interface to build the GCC trees of all
504    Type AST classes emitted from the D Front-end, where CTYPE holds
505    the cached back-end representation to be returned.  */
506 
507 class TypeVisitor : public Visitor
508 {
509   using Visitor::visit;
510 
511 public:
TypeVisitor(void)512   TypeVisitor (void)
513   {
514   }
515 
516   /* This should be overridden by each type class.  */
517 
visit(Type *)518   void visit (Type *)
519   {
520     gcc_unreachable ();
521   }
522 
523   /* Type assigned to erroneous expressions or constructs that
524      failed during the semantic stage.  */
525 
visit(TypeError * t)526   void visit (TypeError *t)
527   {
528     t->ctype = error_mark_node;
529   }
530 
531   /* Type assigned to generic nullable types.  */
532 
visit(TypeNull * t)533   void visit (TypeNull *t)
534   {
535     t->ctype = ptr_type_node;
536   }
537 
538 
539   /* Basic Data Types.  */
540 
visit(TypeBasic * t)541   void visit (TypeBasic *t)
542   {
543     /* [type/basic-data-types]
544 
545        void	no type.
546        bool	8-bit boolean value.
547        byte	8-bit signed value.
548        ubyte	8-bit unsigned value.
549        short	16-bit signed value.
550        ushort	16-bit unsigned value.
551        int	32-bit signed value.
552        uint	32-bit unsigned value.
553        long	64-bit signed value.
554        ulong	64-bit unsigned value.
555        cent	128-bit signed value.
556        ucent	128-bit unsigned value.
557        float	32-bit IEEE 754 floating-point value.
558        double	64-bit IEEE 754 floating-point value.
559        real	largest FP size implemented in hardware.
560        ifloat	imaginary float.
561        idouble	imaginary double.
562        ireal	imaginary real.
563        cfloat	complex float.
564        cdouble	complex double.
565        creal	complex real.
566        char	UTF-8 code unit.
567        wchar	UTF-16 code unit.
568        dchar	UTF-32 code unit.  */
569 
570     switch (t->ty)
571       {
572       case Tvoid:	  t->ctype = void_type_node; break;
573       case Tbool:	  t->ctype = d_bool_type; break;
574       case Tint8:	  t->ctype = d_byte_type; break;
575       case Tuns8:	  t->ctype = d_ubyte_type; break;
576       case Tint16:	  t->ctype = d_short_type; break;
577       case Tuns16:	  t->ctype = d_ushort_type; break;
578       case Tint32:	  t->ctype = d_int_type; break;
579       case Tuns32:	  t->ctype = d_uint_type; break;
580       case Tint64:	  t->ctype = d_long_type; break;
581       case Tuns64:	  t->ctype = d_ulong_type; break;
582       case Tint128:	  t->ctype = d_cent_type; break;
583       case Tuns128:	  t->ctype = d_ucent_type; break;
584       case Tfloat32:	  t->ctype = float_type_node; break;
585       case Tfloat64:	  t->ctype = double_type_node; break;
586       case Tfloat80:	  t->ctype = long_double_type_node; break;
587       case Timaginary32:  t->ctype = ifloat_type_node; break;
588       case Timaginary64:  t->ctype = idouble_type_node; break;
589       case Timaginary80:  t->ctype = ireal_type_node; break;
590       case Tcomplex32:	  t->ctype = complex_float_type_node; break;
591       case Tcomplex64:	  t->ctype = complex_double_type_node; break;
592       case Tcomplex80:	  t->ctype = complex_long_double_type_node; break;
593       case Tchar:	  t->ctype = char8_type_node; break;
594       case Twchar:	  t->ctype = char16_type_node; break;
595       case Tdchar:	  t->ctype = char32_type_node; break;
596       default:		  gcc_unreachable ();
597       }
598 
599     TYPE_NAME (t->ctype) = get_identifier (t->toChars ());
600   }
601 
602 
603   /* Derived Data Types.  */
604 
605   /* Build a simple pointer to data type, analogous to C pointers.  */
606 
visit(TypePointer * t)607   void visit (TypePointer *t)
608   {
609     t->ctype = build_pointer_type (build_ctype (t->next));
610   }
611 
612   /* Build a dynamic array type, consisting of a length and a pointer
613      to the array data.  */
614 
visit(TypeDArray * t)615   void visit (TypeDArray *t)
616   {
617     /* In [abi/arrays], dynamic array layout is:
618 	.length	array dimension.
619 	.ptr	pointer to array data.  */
620     t->ctype = make_struct_type (t->toChars (), 2,
621 				 get_identifier ("length"),
622 				 build_ctype (Type::tsize_t),
623 				 get_identifier ("ptr"),
624 				 build_pointer_type (build_ctype (t->next)));
625     TYPE_DYNAMIC_ARRAY (t->ctype) = 1;
626     TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
627     d_keep (t->ctype);
628   }
629 
630   /* Build a static array type, distinguished from dynamic arrays by
631      having a length fixed at compile-time, analogous to C arrays.  */
632 
visit(TypeSArray * t)633   void visit (TypeSArray *t)
634   {
635     if (t->dim->isConst () && t->dim->type->isintegral ())
636       {
637 	uinteger_t size = t->dim->toUInteger ();
638 	t->ctype = make_array_type (t->next, size);
639       }
640     else
641       {
642 	error ("invalid expression for static array dimension: %s",
643 	       t->dim->toChars ());
644 	gcc_unreachable ();
645       }
646   }
647 
648   /* Build a vector type, a fixed array of floating or integer types.  */
649 
visit(TypeVector * t)650   void visit (TypeVector *t)
651   {
652     int nunits = ((TypeSArray *) t->basetype)->dim->toUInteger ();
653     tree inner = build_ctype (t->elementType ());
654 
655     /* Same rationale as void static arrays.  */
656     if (inner == void_type_node)
657       inner = build_ctype (Type::tuns8);
658 
659     t->ctype = build_vector_type (inner, nunits);
660     TYPE_NAME (t->ctype) = get_identifier (t->toChars ());
661     layout_type (t->ctype);
662   }
663 
664   /* Build an associative array type, distinguished from arrays by having an
665      index that's not necessarily an integer, and can be sparsely populated.  */
666 
visit(TypeAArray * t)667   void visit (TypeAArray *t)
668   {
669     /* In [abi/associative-arrays], associative arrays are a struct that only
670        consist of a pointer to an opaque, implementation defined type.  */
671     t->ctype = make_struct_type (t->toChars (), 1,
672 				 get_identifier ("ptr"), ptr_type_node);
673     TYPE_ASSOCIATIVE_ARRAY (t->ctype) = 1;
674     TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
675     d_keep (t->ctype);
676   }
677 
678   /* Build type for a function declaration, which consists of a return type,
679      and a list of parameter types, and a linkage attribute.  */
680 
visit(TypeFunction * t)681   void visit (TypeFunction *t)
682   {
683     tree fnparams = NULL_TREE;
684     tree fntype;
685 
686     /* [function/variadic]
687 
688        Variadic functions with D linkage have an additional hidden argument
689        with the name _arguments passed to the function.  */
690     if (t->varargs == 1 && t->linkage == LINKd)
691       {
692 	tree type = build_ctype (Type::typeinfotypelist->type);
693 	fnparams = chainon (fnparams, build_tree_list (0, type));
694       }
695 
696     if (t->parameters)
697       {
698 	size_t n_args = Parameter::dim (t->parameters);
699 
700 	for (size_t i = 0; i < n_args; i++)
701 	  {
702 	    tree type = type_passed_as (Parameter::getNth (t->parameters, i));
703 	    fnparams = chainon (fnparams, build_tree_list (0, type));
704 	  }
705       }
706 
707     /* When the last parameter is void_list_node, that indicates a fixed length
708        parameter list, otherwise function is treated as variadic.  */
709     if (t->varargs != 1)
710       fnparams = chainon (fnparams, void_list_node);
711 
712     if (t->next != NULL)
713       {
714 	fntype = build_ctype (t->next);
715 	if (t->isref)
716 	  fntype = build_reference_type (fntype);
717       }
718     else
719       fntype = void_type_node;
720 
721     /* Could the function type be self referenced by parameters?  */
722     t->ctype = build_function_type (fntype, fnparams);
723     TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
724     d_keep (t->ctype);
725 
726     /* Handle any special support for calling conventions.  */
727     switch (t->linkage)
728       {
729       case LINKpascal:
730       case LINKwindows:
731 	/* [attribute/linkage]
732 
733 	   The Windows convention is distinct from the C convention only
734 	   on Win32, where it is equivalent to the stdcall convention.  */
735 	if (!global.params.is64bit)
736 	  t->ctype = insert_type_attribute (t->ctype, "stdcall");
737 	break;
738 
739       case LINKc:
740       case LINKcpp:
741       case LINKd:
742       case LINKobjc:
743 	/* [abi/function-calling-conventions]
744 
745 	  The extern (C) and extern (D) calling convention matches
746 	  the C calling convention used by the supported C compiler
747 	  on the host system.  */
748 	break;
749 
750       default:
751 	gcc_unreachable ();
752       }
753   }
754 
755   /* Build a delegate type, an aggregate of two pieces of data, an object
756      reference and a pointer to a non-static member function, or a pointer
757      to a closure and a pointer to a nested function.  */
758 
visit(TypeDelegate * t)759   void visit (TypeDelegate *t)
760   {
761     /* In [abi/delegates], delegate layout is:
762 	.ptr	    context pointer.
763 	.funcptr    pointer to function.  */
764     tree fntype = build_ctype (t->next);
765     tree dgtype = build_vthis_function (void_type_node, fntype);
766 
767     TYPE_ATTRIBUTES (dgtype) = TYPE_ATTRIBUTES (fntype);
768     TYPE_LANG_SPECIFIC (dgtype) = TYPE_LANG_SPECIFIC (fntype);
769 
770     t->ctype = make_struct_type (t->toChars (), 2,
771 				 get_identifier ("ptr"),
772 				 build_ctype (Type::tvoidptr),
773 				 get_identifier ("funcptr"),
774 				 build_pointer_type (dgtype));
775     TYPE_DELEGATE (t->ctype) = 1;
776     TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
777     d_keep (t->ctype);
778   }
779 
780 
781   /* User Defined Types.  */
782 
783   /* Build a named enum type, a distinct value whose values are restrict to
784      a group of constants of the same underlying base type.  */
785 
visit(TypeEnum * t)786   void visit (TypeEnum *t)
787   {
788     tree basetype = (t->sym->memtype)
789       ? build_ctype (t->sym->memtype) : void_type_node;
790 
791     if (!INTEGRAL_TYPE_P (basetype) || TREE_CODE (basetype) == BOOLEAN_TYPE)
792       {
793 	/* Enums in D2 can have a base type that is not necessarily integral.
794 	   For these, we simplify this a little by using the base type directly
795 	   instead of building an ENUMERAL_TYPE.  */
796 	t->ctype = build_variant_type_copy (basetype);
797       }
798     else
799       {
800 	t->ctype = make_node (ENUMERAL_TYPE);
801 	ENUM_IS_SCOPED (t->ctype) = 1;
802 	TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
803 	d_keep (t->ctype);
804 
805 	if (flag_short_enums)
806 	  TYPE_PACKED (t->ctype) = 1;
807 
808 	TYPE_PRECISION (t->ctype) = t->size (t->sym->loc) * 8;
809 	TYPE_SIZE (t->ctype) = 0;
810 
811 	TYPE_MIN_VALUE (t->ctype) = TYPE_MIN_VALUE (basetype);
812 	TYPE_MAX_VALUE (t->ctype) = TYPE_MAX_VALUE (basetype);
813 	layout_type (t->ctype);
814 
815 	tree values = NULL_TREE;
816 	if (t->sym->members)
817 	  {
818 	    for (size_t i = 0; i < t->sym->members->dim; i++)
819 	      {
820 		EnumMember *member = (*t->sym->members)[i]->isEnumMember ();
821 		/* Templated functions can seep through to the back-end
822 		   just ignore for now.  */
823 		if (member == NULL)
824 		  continue;
825 
826 		tree ident = get_identifier (member->ident->toChars ());
827 		tree value = build_integer_cst (member->value ()->toInteger (),
828 						basetype);
829 
830 		/* Build an identifier for the enumeration constant.  */
831 		tree decl = build_decl (make_location_t (member->loc),
832 					CONST_DECL, ident, basetype);
833 		DECL_CONTEXT (decl) = t->ctype;
834 		TREE_CONSTANT (decl) = 1;
835 		TREE_READONLY (decl) = 1;
836 		DECL_INITIAL (decl) = value;
837 
838 		/* Add this enumeration constant to the list for this type.  */
839 		values = chainon (values, build_tree_list (ident, decl));
840 	      }
841 	  }
842 
843 	TYPE_VALUES (t->ctype) = values;
844 	TYPE_UNSIGNED (t->ctype) = TYPE_UNSIGNED (basetype);
845 	build_type_decl (t->ctype, t->sym);
846       }
847 
848     if (t->sym->userAttribDecl)
849       {
850 	Expressions *eattrs = t->sym->userAttribDecl->getAttributes ();
851 	decl_attributes (&t->ctype, build_attributes (eattrs),
852 			 ATTR_FLAG_TYPE_IN_PLACE);
853       }
854   }
855 
856   /* Build a struct or union type.  Layout should be exactly represented
857      as an equivalent C struct, except for non-POD or nested structs.  */
858 
visit(TypeStruct * t)859   void visit (TypeStruct *t)
860   {
861     /* Need to set this right away in case of self-references.  */
862     t->ctype = make_node (t->sym->isUnionDeclaration ()
863 			  ? UNION_TYPE : RECORD_TYPE);
864     d_keep (t->ctype);
865 
866     TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
867 
868     if (t->sym->members)
869       {
870 	/* Must set up the overall size and alignment before determining
871 	   the context or laying out fields as those types may make
872 	   recursive references to this type.  */
873 	unsigned structsize = t->sym->structsize;
874 	unsigned alignsize = (t->sym->alignment != STRUCTALIGN_DEFAULT)
875 	  ? t->sym->alignment : t->sym->alignsize;
876 
877 	TYPE_SIZE (t->ctype) = bitsize_int (structsize * BITS_PER_UNIT);
878 	TYPE_SIZE_UNIT (t->ctype) = size_int (structsize);
879 	SET_TYPE_ALIGN (t->ctype, alignsize * BITS_PER_UNIT);
880 	TYPE_PACKED (t->ctype) = (alignsize == 1);
881 	compute_record_mode (t->ctype);
882 
883 	/* Put out all fields.  */
884 	layout_aggregate_type (t->sym, t->ctype, t->sym);
885 	finish_aggregate_type (structsize, alignsize, t->ctype,
886 			       t->sym->userAttribDecl);
887       }
888 
889     TYPE_CONTEXT (t->ctype) = d_decl_context (t->sym);
890     build_type_decl (t->ctype, t->sym);
891 
892     /* For structs with a user defined postblit or a destructor,
893        also set TREE_ADDRESSABLE on the type and all variants.
894        This will make the struct be passed around by reference.  */
895     if (t->sym->postblit || t->sym->dtor)
896       {
897 	for (tree tv = t->ctype; tv != NULL_TREE; tv = TYPE_NEXT_VARIANT (tv))
898 	  TREE_ADDRESSABLE (tv) = 1;
899       }
900   }
901 
902   /* Build a class type.  Whereas structs are value types, classes are
903      reference types, with all the object-orientated features.  */
904 
visit(TypeClass * t)905   void visit (TypeClass *t)
906   {
907     /* Need to set ctype right away in case of self-references to
908        the type during this call.  */
909     tree basetype = make_node (RECORD_TYPE);
910     t->ctype = build_pointer_type (basetype);
911     d_keep (t->ctype);
912 
913     /* Note that lang_specific data is assigned to both the reference
914        and the underlying record type.  */
915     TYPE_LANG_SPECIFIC (t->ctype) = build_lang_type (t);
916     TYPE_LANG_SPECIFIC (basetype) = TYPE_LANG_SPECIFIC (t->ctype);
917     CLASS_TYPE_P (basetype) = 1;
918 
919     /* Put out all fields, including from each base class.  */
920     layout_aggregate_type (t->sym, basetype, t->sym);
921     finish_aggregate_type (t->sym->structsize, t->sym->alignsize,
922 			   basetype, t->sym->userAttribDecl);
923 
924     /* Classes only live in memory, so always set the TREE_ADDRESSABLE bit.  */
925     for (tree tv = basetype; tv != NULL_TREE; tv = TYPE_NEXT_VARIANT (tv))
926       TREE_ADDRESSABLE (tv) = 1;
927 
928     /* Type is final, there are no derivations.  */
929     if (t->sym->storage_class & STCfinal)
930       TYPE_FINAL_P (basetype) = 1;
931 
932     /* Create BINFO even if debugging is off.  This is needed to keep
933        references to inherited types.  */
934     if (!t->sym->isInterfaceDeclaration ())
935       TYPE_BINFO (basetype) = build_class_binfo (NULL_TREE, t->sym);
936     else
937       {
938 	unsigned offset = 0;
939 
940 	TYPE_BINFO (basetype) = build_interface_binfo (NULL_TREE, t->sym,
941 						       offset);
942       }
943 
944     /* Associate all virtual methods with the class too.  */
945     for (size_t i = 0; i < t->sym->vtbl.dim; i++)
946       {
947 	FuncDeclaration *fd = t->sym->vtbl[i]->isFuncDeclaration ();
948 	tree method = fd ? get_symbol_decl (fd) : error_mark_node;
949 
950 	if (!error_operand_p (method)
951 	    && DECL_CONTEXT (method) == basetype
952 	    && !chain_member (method, TYPE_FIELDS (basetype)))
953 	  TYPE_FIELDS (basetype) = chainon (TYPE_FIELDS (basetype), method);
954       }
955 
956     TYPE_CONTEXT (basetype) = d_decl_context (t->sym);
957     build_type_decl (basetype, t->sym);
958   }
959 };
960 
961 
962 /* Build a tree from a frontend Type.  */
963 
964 tree
build_ctype(Type * t)965 build_ctype (Type *t)
966 {
967   if (!t->ctype)
968     {
969       TypeVisitor v;
970 
971       /* Strip const modifiers from type before building.  This is done
972 	 to ensure that back-end treats e.g: const (T) as a variant of T,
973 	 and not as two distinct types.  */
974       if (t->isNaked ())
975 	t->accept (&v);
976       else
977 	{
978 	  Type *tb = t->castMod (0);
979 	  if (!tb->ctype)
980 	    tb->accept (&v);
981 	  t->ctype = insert_type_modifiers (tb->ctype, t->mod);
982 	}
983     }
984 
985   return t->ctype;
986 }
987