1 // types.cc -- Go frontend types.
2 
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6 
7 #include "go-system.h"
8 
9 #include <ostream>
10 
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "operator.h"
16 #include "expressions.h"
17 #include "statements.h"
18 #include "export.h"
19 #include "import.h"
20 #include "backend.h"
21 #include "types.h"
22 
23 // Forward declarations so that we don't have to make types.h #include
24 // backend.h.
25 
26 static void
27 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
28 			  bool use_placeholder,
29 			  std::vector<Backend::Btyped_identifier>* bfields);
30 
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 			 std::vector<Backend::Btyped_identifier>* bfields);
34 
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 			     bool use_placeholder,
38 			     std::vector<Backend::Btyped_identifier>* bfields);
39 
40 // Class Type.
41 
Type(Type_classification classification)42 Type::Type(Type_classification classification)
43   : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44     gc_symbol_var_(NULL)
45 {
46 }
47 
~Type()48 Type::~Type()
49 {
50 }
51 
52 // Get the base type for a type--skip names and forward declarations.
53 
54 Type*
base()55 Type::base()
56 {
57   switch (this->classification_)
58     {
59     case TYPE_NAMED:
60       return this->named_type()->named_base();
61     case TYPE_FORWARD:
62       return this->forward_declaration_type()->real_type()->base();
63     default:
64       return this;
65     }
66 }
67 
68 const Type*
base() const69 Type::base() const
70 {
71   switch (this->classification_)
72     {
73     case TYPE_NAMED:
74       return this->named_type()->named_base();
75     case TYPE_FORWARD:
76       return this->forward_declaration_type()->real_type()->base();
77     default:
78       return this;
79     }
80 }
81 
82 // Skip defined forward declarations.
83 
84 Type*
forwarded()85 Type::forwarded()
86 {
87   Type* t = this;
88   Forward_declaration_type* ftype = t->forward_declaration_type();
89   while (ftype != NULL && ftype->is_defined())
90     {
91       t = ftype->real_type();
92       ftype = t->forward_declaration_type();
93     }
94   return t;
95 }
96 
97 const Type*
forwarded() const98 Type::forwarded() const
99 {
100   const Type* t = this;
101   const Forward_declaration_type* ftype = t->forward_declaration_type();
102   while (ftype != NULL && ftype->is_defined())
103     {
104       t = ftype->real_type();
105       ftype = t->forward_declaration_type();
106     }
107   return t;
108 }
109 
110 // Skip alias definitions.
111 
112 Type*
unalias()113 Type::unalias()
114 {
115   Type* t = this->forwarded();
116   Named_type* nt = t->named_type();
117   while (nt != NULL && nt->is_alias())
118     {
119       t = nt->real_type()->forwarded();
120       nt = t->named_type();
121     }
122   return t;
123 }
124 
125 const Type*
unalias() const126 Type::unalias() const
127 {
128   const Type* t = this->forwarded();
129   const Named_type* nt = t->named_type();
130   while (nt != NULL && nt->is_alias())
131     {
132       t = nt->real_type()->forwarded();
133       nt = t->named_type();
134     }
135   return t;
136 }
137 
138 // If this is a named type, return it.  Otherwise, return NULL.
139 
140 Named_type*
named_type()141 Type::named_type()
142 {
143   return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
144 }
145 
146 const Named_type*
named_type() const147 Type::named_type() const
148 {
149   return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
150 }
151 
152 // Return true if this type is not defined.
153 
154 bool
is_undefined() const155 Type::is_undefined() const
156 {
157   return this->forwarded()->forward_declaration_type() != NULL;
158 }
159 
160 // Return true if this is a basic type: a type which is not composed
161 // of other types, and is not void.
162 
163 bool
is_basic_type() const164 Type::is_basic_type() const
165 {
166   switch (this->classification_)
167     {
168     case TYPE_INTEGER:
169     case TYPE_FLOAT:
170     case TYPE_COMPLEX:
171     case TYPE_BOOLEAN:
172     case TYPE_STRING:
173     case TYPE_NIL:
174       return true;
175 
176     case TYPE_ERROR:
177     case TYPE_VOID:
178     case TYPE_FUNCTION:
179     case TYPE_POINTER:
180     case TYPE_STRUCT:
181     case TYPE_ARRAY:
182     case TYPE_MAP:
183     case TYPE_CHANNEL:
184     case TYPE_INTERFACE:
185       return false;
186 
187     case TYPE_NAMED:
188     case TYPE_FORWARD:
189       return this->base()->is_basic_type();
190 
191     default:
192       go_unreachable();
193     }
194 }
195 
196 // Return true if this is an abstract type.
197 
198 bool
is_abstract() const199 Type::is_abstract() const
200 {
201   switch (this->classification())
202     {
203     case TYPE_INTEGER:
204       return this->integer_type()->is_abstract();
205     case TYPE_FLOAT:
206       return this->float_type()->is_abstract();
207     case TYPE_COMPLEX:
208       return this->complex_type()->is_abstract();
209     case TYPE_STRING:
210       return this->is_abstract_string_type();
211     case TYPE_BOOLEAN:
212       return this->is_abstract_boolean_type();
213     default:
214       return false;
215     }
216 }
217 
218 // Return a non-abstract version of an abstract type.
219 
220 Type*
make_non_abstract_type()221 Type::make_non_abstract_type()
222 {
223   go_assert(this->is_abstract());
224   switch (this->classification())
225     {
226     case TYPE_INTEGER:
227       if (this->integer_type()->is_rune())
228 	return Type::lookup_integer_type("int32");
229       else
230 	return Type::lookup_integer_type("int");
231     case TYPE_FLOAT:
232       return Type::lookup_float_type("float64");
233     case TYPE_COMPLEX:
234       return Type::lookup_complex_type("complex128");
235     case TYPE_STRING:
236       return Type::lookup_string_type();
237     case TYPE_BOOLEAN:
238       return Type::lookup_bool_type();
239     default:
240       go_unreachable();
241     }
242 }
243 
244 // Return true if this is an error type.  Don't give an error if we
245 // try to dereference an undefined forwarding type, as this is called
246 // in the parser when the type may legitimately be undefined.
247 
248 bool
is_error_type() const249 Type::is_error_type() const
250 {
251   const Type* t = this->forwarded();
252   // Note that we return false for an undefined forward type.
253   switch (t->classification_)
254     {
255     case TYPE_ERROR:
256       return true;
257     case TYPE_NAMED:
258       return t->named_type()->is_named_error_type();
259     default:
260       return false;
261     }
262 }
263 
264 // If this is a pointer type, return the type to which it points.
265 // Otherwise, return NULL.
266 
267 Type*
points_to() const268 Type::points_to() const
269 {
270   const Pointer_type* ptype = this->convert<const Pointer_type,
271 					    TYPE_POINTER>();
272   return ptype == NULL ? NULL : ptype->points_to();
273 }
274 
275 // Return whether this is a slice type.
276 
277 bool
is_slice_type() const278 Type::is_slice_type() const
279 {
280   return this->array_type() != NULL && this->array_type()->length() == NULL;
281 }
282 
283 // Return whether this is the predeclared constant nil being used as a
284 // type.
285 
286 bool
is_nil_constant_as_type() const287 Type::is_nil_constant_as_type() const
288 {
289   const Type* t = this->forwarded();
290   if (t->forward_declaration_type() != NULL)
291     {
292       const Named_object* no = t->forward_declaration_type()->named_object();
293       if (no->is_unknown())
294 	no = no->unknown_value()->real_named_object();
295       if (no != NULL
296 	  && no->is_const()
297 	  && no->const_value()->expr()->is_nil_expression())
298 	return true;
299     }
300   return false;
301 }
302 
303 // Traverse a type.
304 
305 int
traverse(Type * type,Traverse * traverse)306 Type::traverse(Type* type, Traverse* traverse)
307 {
308   go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
309 	     || (traverse->traverse_mask()
310 		 & Traverse::traverse_expressions) != 0);
311   if (traverse->remember_type(type))
312     {
313       // We have already traversed this type.
314       return TRAVERSE_CONTINUE;
315     }
316   if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
317     {
318       int t = traverse->type(type);
319       if (t == TRAVERSE_EXIT)
320 	return TRAVERSE_EXIT;
321       else if (t == TRAVERSE_SKIP_COMPONENTS)
322 	return TRAVERSE_CONTINUE;
323     }
324   // An array type has an expression which we need to traverse if
325   // traverse_expressions is set.
326   if (type->do_traverse(traverse) == TRAVERSE_EXIT)
327     return TRAVERSE_EXIT;
328   return TRAVERSE_CONTINUE;
329 }
330 
331 // Default implementation for do_traverse for child class.
332 
333 int
do_traverse(Traverse *)334 Type::do_traverse(Traverse*)
335 {
336   return TRAVERSE_CONTINUE;
337 }
338 
339 // Return whether two types are identical.  If ERRORS_ARE_IDENTICAL,
340 // then return true for all erroneous types; this is used to avoid
341 // cascading errors.  If REASON is not NULL, optionally set *REASON to
342 // the reason the types are not identical.
343 
344 bool
are_identical(const Type * t1,const Type * t2,bool errors_are_identical,std::string * reason)345 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
346 		    std::string* reason)
347 {
348   return Type::are_identical_cmp_tags(t1, t2, COMPARE_TAGS,
349 				      errors_are_identical, reason);
350 }
351 
352 // Like are_identical, but with a CMP_TAGS parameter.
353 
354 bool
are_identical_cmp_tags(const Type * t1,const Type * t2,Cmp_tags cmp_tags,bool errors_are_identical,std::string * reason)355 Type::are_identical_cmp_tags(const Type* t1, const Type* t2, Cmp_tags cmp_tags,
356 			     bool errors_are_identical, std::string* reason)
357 {
358   if (t1 == NULL || t2 == NULL)
359     {
360       // Something is wrong.
361       return errors_are_identical ? true : t1 == t2;
362     }
363 
364   // Skip defined forward declarations.  Ignore aliases.
365   t1 = t1->unalias();
366   t2 = t2->unalias();
367 
368   if (t1 == t2)
369     return true;
370 
371   // An undefined forward declaration is an error.
372   if (t1->forward_declaration_type() != NULL
373       || t2->forward_declaration_type() != NULL)
374     return errors_are_identical;
375 
376   // Avoid cascading errors with error types.
377   if (t1->is_error_type() || t2->is_error_type())
378     {
379       if (errors_are_identical)
380 	return true;
381       return t1->is_error_type() && t2->is_error_type();
382     }
383 
384   // Get a good reason for the sink type.  Note that the sink type on
385   // the left hand side of an assignment is handled in are_assignable.
386   if (t1->is_sink_type() || t2->is_sink_type())
387     {
388       if (reason != NULL)
389 	*reason = "invalid use of _";
390       return false;
391     }
392 
393   // A named type is only identical to itself.
394   if (t1->named_type() != NULL || t2->named_type() != NULL)
395     return false;
396 
397   // Check type shapes.
398   if (t1->classification() != t2->classification())
399     return false;
400 
401   switch (t1->classification())
402     {
403     case TYPE_VOID:
404     case TYPE_BOOLEAN:
405     case TYPE_STRING:
406     case TYPE_NIL:
407       // These types are always identical.
408       return true;
409 
410     case TYPE_INTEGER:
411       return t1->integer_type()->is_identical(t2->integer_type());
412 
413     case TYPE_FLOAT:
414       return t1->float_type()->is_identical(t2->float_type());
415 
416     case TYPE_COMPLEX:
417       return t1->complex_type()->is_identical(t2->complex_type());
418 
419     case TYPE_FUNCTION:
420       return t1->function_type()->is_identical(t2->function_type(),
421 					       false,
422 					       cmp_tags,
423 					       errors_are_identical,
424 					       reason);
425 
426     case TYPE_POINTER:
427       return Type::are_identical_cmp_tags(t1->points_to(), t2->points_to(),
428 					  cmp_tags, errors_are_identical,
429 					  reason);
430 
431     case TYPE_STRUCT:
432       return t1->struct_type()->is_identical(t2->struct_type(), cmp_tags,
433 					     errors_are_identical);
434 
435     case TYPE_ARRAY:
436       return t1->array_type()->is_identical(t2->array_type(), cmp_tags,
437 					    errors_are_identical);
438 
439     case TYPE_MAP:
440       return t1->map_type()->is_identical(t2->map_type(), cmp_tags,
441 					  errors_are_identical);
442 
443     case TYPE_CHANNEL:
444       return t1->channel_type()->is_identical(t2->channel_type(), cmp_tags,
445 					      errors_are_identical);
446 
447     case TYPE_INTERFACE:
448       return t1->interface_type()->is_identical(t2->interface_type(), cmp_tags,
449 						errors_are_identical);
450 
451     case TYPE_CALL_MULTIPLE_RESULT:
452       if (reason != NULL)
453 	*reason = "invalid use of multiple-value function call";
454       return false;
455 
456     default:
457       go_unreachable();
458     }
459 }
460 
461 // Return true if it's OK to have a binary operation with types LHS
462 // and RHS.  This is not used for shifts or comparisons.
463 
464 bool
are_compatible_for_binop(const Type * lhs,const Type * rhs)465 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
466 {
467   if (Type::are_identical(lhs, rhs, true, NULL))
468     return true;
469 
470   // A constant of abstract bool type may be mixed with any bool type.
471   if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
472       || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
473     return true;
474 
475   // A constant of abstract string type may be mixed with any string
476   // type.
477   if ((rhs->is_abstract_string_type() && lhs->is_string_type())
478       || (lhs->is_abstract_string_type() && rhs->is_string_type()))
479     return true;
480 
481   lhs = lhs->base();
482   rhs = rhs->base();
483 
484   // A constant of abstract integer, float, or complex type may be
485   // mixed with an integer, float, or complex type.
486   if ((rhs->is_abstract()
487        && (rhs->integer_type() != NULL
488 	   || rhs->float_type() != NULL
489 	   || rhs->complex_type() != NULL)
490        && (lhs->integer_type() != NULL
491 	   || lhs->float_type() != NULL
492 	   || lhs->complex_type() != NULL))
493       || (lhs->is_abstract()
494 	  && (lhs->integer_type() != NULL
495 	      || lhs->float_type() != NULL
496 	      || lhs->complex_type() != NULL)
497 	  && (rhs->integer_type() != NULL
498 	      || rhs->float_type() != NULL
499 	      || rhs->complex_type() != NULL)))
500     return true;
501 
502   // The nil type may be compared to a pointer, an interface type, a
503   // slice type, a channel type, a map type, or a function type.
504   if (lhs->is_nil_type()
505       && (rhs->points_to() != NULL
506 	  || rhs->interface_type() != NULL
507 	  || rhs->is_slice_type()
508 	  || rhs->map_type() != NULL
509 	  || rhs->channel_type() != NULL
510 	  || rhs->function_type() != NULL))
511     return true;
512   if (rhs->is_nil_type()
513       && (lhs->points_to() != NULL
514 	  || lhs->interface_type() != NULL
515 	  || lhs->is_slice_type()
516 	  || lhs->map_type() != NULL
517 	  || lhs->channel_type() != NULL
518 	  || lhs->function_type() != NULL))
519     return true;
520 
521   return false;
522 }
523 
524 // Return true if a value with type T1 may be compared with a value of
525 // type T2.  IS_EQUALITY_OP is true for == or !=, false for <, etc.
526 
527 bool
are_compatible_for_comparison(bool is_equality_op,const Type * t1,const Type * t2,std::string * reason)528 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
529 				    const Type *t2, std::string *reason)
530 {
531   if (t1 != t2
532       && !Type::are_assignable(t1, t2, NULL)
533       && !Type::are_assignable(t2, t1, NULL))
534     {
535       if (reason != NULL)
536 	*reason = "incompatible types in binary expression";
537       return false;
538     }
539 
540   if (!is_equality_op)
541     {
542       if (t1->integer_type() == NULL
543 	  && t1->float_type() == NULL
544 	  && !t1->is_string_type())
545 	{
546 	  if (reason != NULL)
547 	    *reason = _("invalid comparison of non-ordered type");
548 	  return false;
549 	}
550     }
551   else if (t1->is_slice_type()
552 	   || t1->map_type() != NULL
553 	   || t1->function_type() != NULL
554 	   || t2->is_slice_type()
555 	   || t2->map_type() != NULL
556 	   || t2->function_type() != NULL)
557     {
558       if (!t1->is_nil_type() && !t2->is_nil_type())
559 	{
560 	  if (reason != NULL)
561 	    {
562 	      if (t1->is_slice_type() || t2->is_slice_type())
563 		*reason = _("slice can only be compared to nil");
564 	      else if (t1->map_type() != NULL || t2->map_type() != NULL)
565 		*reason = _("map can only be compared to nil");
566 	      else
567 		*reason = _("func can only be compared to nil");
568 
569 	      // Match 6g error messages.
570 	      if (t1->interface_type() != NULL || t2->interface_type() != NULL)
571 		{
572 		  char buf[200];
573 		  snprintf(buf, sizeof buf, _("invalid operation (%s)"),
574 			   reason->c_str());
575 		  *reason = buf;
576 		}
577 	    }
578 	  return false;
579 	}
580     }
581   else
582     {
583       if (!t1->is_boolean_type()
584 	  && t1->integer_type() == NULL
585 	  && t1->float_type() == NULL
586 	  && t1->complex_type() == NULL
587 	  && !t1->is_string_type()
588 	  && t1->points_to() == NULL
589 	  && t1->channel_type() == NULL
590 	  && t1->interface_type() == NULL
591 	  && t1->struct_type() == NULL
592 	  && t1->array_type() == NULL
593 	  && !t1->is_nil_type())
594 	{
595 	  if (reason != NULL)
596 	    *reason = _("invalid comparison of non-comparable type");
597 	  return false;
598 	}
599 
600       if (t1->unalias()->named_type() != NULL)
601 	return t1->unalias()->named_type()->named_type_is_comparable(reason);
602       else if (t2->unalias()->named_type() != NULL)
603 	return t2->unalias()->named_type()->named_type_is_comparable(reason);
604       else if (t1->struct_type() != NULL)
605 	{
606 	  if (t1->struct_type()->is_struct_incomparable())
607 	    {
608 	      if (reason != NULL)
609 		*reason = _("invalid comparison of generated struct");
610 	      return false;
611 	    }
612 	  const Struct_field_list* fields = t1->struct_type()->fields();
613 	  for (Struct_field_list::const_iterator p = fields->begin();
614 	       p != fields->end();
615 	       ++p)
616 	    {
617 	      if (!p->type()->is_comparable())
618 		{
619 		  if (reason != NULL)
620 		    *reason = _("invalid comparison of non-comparable struct");
621 		  return false;
622 		}
623 	    }
624 	}
625       else if (t1->array_type() != NULL)
626 	{
627 	  if (t1->array_type()->is_array_incomparable())
628 	    {
629 	      if (reason != NULL)
630 		*reason = _("invalid comparison of generated array");
631 	      return false;
632 	    }
633 	  if (t1->array_type()->length()->is_nil_expression()
634 	      || !t1->array_type()->element_type()->is_comparable())
635 	    {
636 	      if (reason != NULL)
637 		*reason = _("invalid comparison of non-comparable array");
638 	      return false;
639 	    }
640 	}
641     }
642 
643   return true;
644 }
645 
646 // Return true if a value with type RHS may be assigned to a variable
647 // with type LHS.  If REASON is not NULL, set *REASON to the reason
648 // the types are not assignable.
649 
650 bool
are_assignable(const Type * lhs,const Type * rhs,std::string * reason)651 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
652 {
653   // Do some checks first.  Make sure the types are defined.
654   if (rhs != NULL && !rhs->is_undefined())
655     {
656       if (rhs->is_void_type())
657 	{
658 	  if (reason != NULL)
659 	    *reason = "non-value used as value";
660 	  return false;
661 	}
662       if (rhs->is_call_multiple_result_type())
663 	{
664 	  if (reason != NULL)
665 	    reason->assign(_("multiple-value function call in "
666 			     "single-value context"));
667 	  return false;
668 	}
669     }
670 
671   // Any value may be assigned to the blank identifier.
672   if (lhs != NULL
673       && !lhs->is_undefined()
674       && lhs->is_sink_type())
675     return true;
676 
677   // Identical types are assignable.
678   if (Type::are_identical(lhs, rhs, true, reason))
679     return true;
680 
681   // Ignore aliases, except for error messages.
682   const Type* lhs_orig = lhs;
683   const Type* rhs_orig = rhs;
684   lhs = lhs->unalias();
685   rhs = rhs->unalias();
686 
687   // The types are assignable if they have identical underlying types
688   // and either LHS or RHS is not a named type.
689   if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
690        || (rhs->named_type() != NULL && lhs->named_type() == NULL))
691       && Type::are_identical(lhs->base(), rhs->base(), true, reason))
692     return true;
693 
694   // The types are assignable if LHS is an interface type and RHS
695   // implements the required methods.
696   const Interface_type* lhs_interface_type = lhs->interface_type();
697   if (lhs_interface_type != NULL)
698     {
699       if (lhs_interface_type->implements_interface(rhs, reason))
700 	return true;
701       const Interface_type* rhs_interface_type = rhs->interface_type();
702       if (rhs_interface_type != NULL
703 	  && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
704 							  reason))
705 	return true;
706     }
707 
708   // The type are assignable if RHS is a bidirectional channel type,
709   // LHS is a channel type, they have identical element types, and
710   // either LHS or RHS is not a named type.
711   if (lhs->channel_type() != NULL
712       && rhs->channel_type() != NULL
713       && rhs->channel_type()->may_send()
714       && rhs->channel_type()->may_receive()
715       && (lhs->named_type() == NULL || rhs->named_type() == NULL)
716       && Type::are_identical(lhs->channel_type()->element_type(),
717 			     rhs->channel_type()->element_type(),
718 			     true,
719 			     reason))
720     return true;
721 
722   // The nil type may be assigned to a pointer, function, slice, map,
723   // channel, or interface type.
724   if (rhs->is_nil_type()
725       && (lhs->points_to() != NULL
726 	  || lhs->function_type() != NULL
727 	  || lhs->is_slice_type()
728 	  || lhs->map_type() != NULL
729 	  || lhs->channel_type() != NULL
730 	  || lhs->interface_type() != NULL))
731     return true;
732 
733   // An untyped numeric constant may be assigned to a numeric type if
734   // it is representable in that type.
735   if ((rhs->is_abstract()
736        && (rhs->integer_type() != NULL
737 	   || rhs->float_type() != NULL
738 	   || rhs->complex_type() != NULL))
739       && (lhs->integer_type() != NULL
740 	  || lhs->float_type() != NULL
741 	  || lhs->complex_type() != NULL))
742     return true;
743 
744   // Give some better error messages.
745   if (reason != NULL && reason->empty())
746     {
747       if (rhs->interface_type() != NULL)
748 	reason->assign(_("need explicit conversion"));
749       else if (lhs_orig->named_type() != NULL
750 	       && rhs_orig->named_type() != NULL)
751 	{
752 	  size_t len = (lhs_orig->named_type()->name().length()
753 			+ rhs_orig->named_type()->name().length()
754 			+ 100);
755 	  char* buf = new char[len];
756 	  snprintf(buf, len, _("cannot use type %s as type %s"),
757 		   rhs_orig->named_type()->message_name().c_str(),
758 		   lhs_orig->named_type()->message_name().c_str());
759 	  reason->assign(buf);
760 	  delete[] buf;
761 	}
762     }
763 
764   return false;
765 }
766 
767 // Return true if a value with type RHS may be converted to type LHS.
768 // If REASON is not NULL, set *REASON to the reason the types are not
769 // convertible.
770 
771 bool
are_convertible(const Type * lhs,const Type * rhs,std::string * reason)772 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
773 {
774   // The types are convertible if they are assignable.
775   if (Type::are_assignable(lhs, rhs, reason))
776     return true;
777 
778   // Ignore aliases.
779   lhs = lhs->unalias();
780   rhs = rhs->unalias();
781 
782   // A pointer to a regular type may not be converted to a pointer to
783   // a type that may not live in the heap, except when converting from
784   // unsafe.Pointer.
785   if (lhs->points_to() != NULL
786       && rhs->points_to() != NULL
787       && !lhs->points_to()->in_heap()
788       && rhs->points_to()->in_heap()
789       && !rhs->is_unsafe_pointer_type())
790     {
791       if (reason != NULL)
792 	reason->assign(_("conversion from normal type to notinheap type"));
793       return false;
794     }
795 
796   // The types are convertible if they have identical underlying
797   // types, ignoring struct field tags.
798   if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
799       && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
800 				      true, reason))
801     return true;
802 
803   // The types are convertible if they are both unnamed pointer types
804   // and their pointer base types have identical underlying types,
805   // ignoring struct field tags.
806   if (lhs->named_type() == NULL
807       && rhs->named_type() == NULL
808       && lhs->points_to() != NULL
809       && rhs->points_to() != NULL
810       && (lhs->points_to()->named_type() != NULL
811 	  || rhs->points_to()->named_type() != NULL)
812       && Type::are_identical_cmp_tags(lhs->points_to()->base(),
813 				      rhs->points_to()->base(),
814 				      IGNORE_TAGS,
815 				      true,
816 				      reason))
817     return true;
818 
819   // Integer and floating point types are convertible to each other.
820   if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
821       && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
822     return true;
823 
824   // Complex types are convertible to each other.
825   if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
826     return true;
827 
828   // An integer, or []byte, or []rune, may be converted to a string.
829   if (lhs->is_string_type())
830     {
831       if (rhs->integer_type() != NULL)
832 	return true;
833       if (rhs->is_slice_type())
834 	{
835 	  const Type* e = rhs->array_type()->element_type()->forwarded();
836 	  if (e->integer_type() != NULL
837 	      && (e->integer_type()->is_byte()
838 		  || e->integer_type()->is_rune()))
839 	    return true;
840 	}
841     }
842 
843   // A string may be converted to []byte or []rune.
844   if (rhs->is_string_type() && lhs->is_slice_type())
845     {
846       const Type* e = lhs->array_type()->element_type()->forwarded();
847       if (e->integer_type() != NULL
848 	  && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
849 	return true;
850     }
851 
852   // An unsafe.Pointer type may be converted to any pointer type or to
853   // a type whose underlying type is uintptr, and vice-versa.
854   if (lhs->is_unsafe_pointer_type()
855       && (rhs->points_to() != NULL
856 	  || (rhs->integer_type() != NULL
857 	      && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
858     return true;
859   if (rhs->is_unsafe_pointer_type()
860       && (lhs->points_to() != NULL
861 	  || (lhs->integer_type() != NULL
862 	      && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
863     return true;
864 
865   // Give a better error message.
866   if (reason != NULL)
867     {
868       if (reason->empty())
869 	*reason = "invalid type conversion";
870       else
871 	{
872 	  std::string s = "invalid type conversion (";
873 	  s += *reason;
874 	  s += ')';
875 	  *reason = s;
876 	}
877     }
878 
879   return false;
880 }
881 
882 // Copy expressions if it may change the size.
883 //
884 // The only type that has an expression is an array type.  The only
885 // types whose size can be changed by the size of an array type are an
886 // array type itself, or a struct type with an array field.
887 Type*
copy_expressions()888 Type::copy_expressions()
889 {
890   // This is run during parsing, so types may not be valid yet.
891   // We only have to worry about array type literals.
892   switch (this->classification_)
893     {
894     default:
895       return this;
896 
897     case TYPE_ARRAY:
898       {
899 	Array_type* at = this->array_type();
900 	if (at->length() == NULL)
901 	  return this;
902 	Expression* len = at->length()->copy();
903 	if (at->length() == len)
904 	  return this;
905 	return Type::make_array_type(at->element_type(), len);
906       }
907 
908     case TYPE_STRUCT:
909       {
910 	Struct_type* st = this->struct_type();
911 	const Struct_field_list* sfl = st->fields();
912 	if (sfl == NULL)
913 	  return this;
914 	bool changed = false;
915 	Struct_field_list *nsfl = new Struct_field_list();
916 	for (Struct_field_list::const_iterator pf = sfl->begin();
917 	     pf != sfl->end();
918 	     ++pf)
919 	  {
920 	    Type* ft = pf->type()->copy_expressions();
921 	    Struct_field nf(Typed_identifier((pf->is_anonymous()
922 					      ? ""
923 					      : pf->field_name()),
924 					     ft,
925 					     pf->location()));
926 	    if (pf->has_tag())
927 	      nf.set_tag(pf->tag());
928 	    nsfl->push_back(nf);
929 	    if (ft != pf->type())
930 	      changed = true;
931 	  }
932 	if (!changed)
933 	  {
934 	    delete(nsfl);
935 	    return this;
936 	  }
937 	return Type::make_struct_type(nsfl, st->location());
938       }
939     }
940 
941   go_unreachable();
942 }
943 
944 // Return a hash code for the type to be used for method lookup.
945 
946 unsigned int
hash_for_method(Gogo * gogo) const947 Type::hash_for_method(Gogo* gogo) const
948 {
949   if (this->named_type() != NULL && this->named_type()->is_alias())
950     return this->named_type()->real_type()->hash_for_method(gogo);
951   unsigned int ret = 0;
952   if (this->classification_ != TYPE_FORWARD)
953     ret += this->classification_;
954   return ret + this->do_hash_for_method(gogo);
955 }
956 
957 // Default implementation of do_hash_for_method.  This is appropriate
958 // for types with no subfields.
959 
960 unsigned int
do_hash_for_method(Gogo *) const961 Type::do_hash_for_method(Gogo*) const
962 {
963   return 0;
964 }
965 
966 // Return a hash code for a string, given a starting hash.
967 
968 unsigned int
hash_string(const std::string & s,unsigned int h)969 Type::hash_string(const std::string& s, unsigned int h)
970 {
971   const char* p = s.data();
972   size_t len = s.length();
973   for (; len > 0; --len)
974     {
975       h ^= *p++;
976       h*= 16777619;
977     }
978   return h;
979 }
980 
981 // A hash table mapping unnamed types to the backend representation of
982 // those types.
983 
984 Type::Type_btypes Type::type_btypes;
985 
986 // Return the backend representation for this type.
987 
988 Btype*
get_backend(Gogo * gogo)989 Type::get_backend(Gogo* gogo)
990 {
991   if (this->btype_ != NULL)
992     return this->btype_;
993 
994   if (this->forward_declaration_type() != NULL
995       || this->named_type() != NULL)
996     return this->get_btype_without_hash(gogo);
997 
998   if (this->is_error_type())
999     return gogo->backend()->error_type();
1000 
1001   // To avoid confusing the backend, translate all identical Go types
1002   // to the same backend representation.  We use a hash table to do
1003   // that.  There is no need to use the hash table for named types, as
1004   // named types are only identical to themselves.
1005 
1006   std::pair<Type*, Type_btype_entry> val;
1007   val.first = this;
1008   val.second.btype = NULL;
1009   val.second.is_placeholder = false;
1010   std::pair<Type_btypes::iterator, bool> ins =
1011     Type::type_btypes.insert(val);
1012   if (!ins.second && ins.first->second.btype != NULL)
1013     {
1014       // Note that GOGO can be NULL here, but only when the GCC
1015       // middle-end is asking for a frontend type.  That will only
1016       // happen for simple types, which should never require
1017       // placeholders.
1018       if (!ins.first->second.is_placeholder)
1019 	this->btype_ = ins.first->second.btype;
1020       else if (gogo->named_types_are_converted())
1021 	{
1022 	  this->finish_backend(gogo, ins.first->second.btype);
1023 	  ins.first->second.is_placeholder = false;
1024 	}
1025 
1026       return ins.first->second.btype;
1027     }
1028 
1029   Btype* bt = this->get_btype_without_hash(gogo);
1030 
1031   if (ins.first->second.btype == NULL)
1032     {
1033       ins.first->second.btype = bt;
1034       ins.first->second.is_placeholder = false;
1035     }
1036   else
1037     {
1038       // We have already created a backend representation for this
1039       // type.  This can happen when an unnamed type is defined using
1040       // a named type which in turns uses an identical unnamed type.
1041       // Use the representation we created earlier and ignore the one we just
1042       // built.
1043       if (this->btype_ == bt)
1044 	this->btype_ = ins.first->second.btype;
1045       bt = ins.first->second.btype;
1046     }
1047 
1048   return bt;
1049 }
1050 
1051 // Return the backend representation for a type without looking in the
1052 // hash table for identical types.  This is used for named types,
1053 // since a named type is never identical to any other type.
1054 
1055 Btype*
get_btype_without_hash(Gogo * gogo)1056 Type::get_btype_without_hash(Gogo* gogo)
1057 {
1058   if (this->btype_ == NULL)
1059     {
1060       Btype* bt = this->do_get_backend(gogo);
1061 
1062       // For a recursive function or pointer type, we will temporarily
1063       // return a circular pointer type during the recursion.  We
1064       // don't want to record that for a forwarding type, as it may
1065       // confuse us later.
1066       if (this->forward_declaration_type() != NULL
1067 	  && gogo->backend()->is_circular_pointer_type(bt))
1068 	return bt;
1069 
1070       if (gogo == NULL || !gogo->named_types_are_converted())
1071 	return bt;
1072 
1073       this->btype_ = bt;
1074     }
1075   return this->btype_;
1076 }
1077 
1078 // Get the backend representation of a type without forcing the
1079 // creation of the backend representation of all supporting types.
1080 // This will return a backend type that has the correct size but may
1081 // be incomplete.  E.g., a pointer will just be a placeholder pointer,
1082 // and will not contain the final representation of the type to which
1083 // it points.  This is used while converting all named types to the
1084 // backend representation, to avoid problems with indirect references
1085 // to types which are not yet complete.  When this is called, the
1086 // sizes of all direct references (e.g., a struct field) should be
1087 // known, but the sizes of indirect references (e.g., the type to
1088 // which a pointer points) may not.
1089 
1090 Btype*
get_backend_placeholder(Gogo * gogo)1091 Type::get_backend_placeholder(Gogo* gogo)
1092 {
1093   if (gogo->named_types_are_converted())
1094     return this->get_backend(gogo);
1095   if (this->btype_ != NULL)
1096     return this->btype_;
1097 
1098   Btype* bt;
1099   switch (this->classification_)
1100     {
1101     case TYPE_ERROR:
1102     case TYPE_VOID:
1103     case TYPE_BOOLEAN:
1104     case TYPE_INTEGER:
1105     case TYPE_FLOAT:
1106     case TYPE_COMPLEX:
1107     case TYPE_STRING:
1108     case TYPE_NIL:
1109       // These are simple types that can just be created directly.
1110       return this->get_backend(gogo);
1111 
1112     case TYPE_MAP:
1113     case TYPE_CHANNEL:
1114       // All maps and channels have the same backend representation.
1115       return this->get_backend(gogo);
1116 
1117     case TYPE_NAMED:
1118     case TYPE_FORWARD:
1119       // Named types keep track of their own dependencies and manage
1120       // their own placeholders.
1121       return this->get_backend(gogo);
1122 
1123     case TYPE_INTERFACE:
1124       if (this->interface_type()->is_empty())
1125 	return Interface_type::get_backend_empty_interface_type(gogo);
1126       break;
1127 
1128     default:
1129       break;
1130     }
1131 
1132   std::pair<Type*, Type_btype_entry> val;
1133   val.first = this;
1134   val.second.btype = NULL;
1135   val.second.is_placeholder = false;
1136   std::pair<Type_btypes::iterator, bool> ins =
1137     Type::type_btypes.insert(val);
1138   if (!ins.second && ins.first->second.btype != NULL)
1139     return ins.first->second.btype;
1140 
1141   switch (this->classification_)
1142     {
1143     case TYPE_FUNCTION:
1144       {
1145 	// A Go function type is a pointer to a struct type.
1146 	Location loc = this->function_type()->location();
1147 	bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1148       }
1149       break;
1150 
1151     case TYPE_POINTER:
1152       {
1153 	Location loc = Linemap::unknown_location();
1154 	bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1155 	Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1156 	Type::placeholder_pointers.push_back(pt);
1157       }
1158       break;
1159 
1160     case TYPE_STRUCT:
1161       // We don't have to make the struct itself be a placeholder.  We
1162       // are promised that we know the sizes of the struct fields.
1163       // But we may have to use a placeholder for any particular
1164       // struct field.
1165       {
1166 	std::vector<Backend::Btyped_identifier> bfields;
1167 	get_backend_struct_fields(gogo, this->struct_type()->fields(),
1168 				  true, &bfields);
1169 	bt = gogo->backend()->struct_type(bfields);
1170       }
1171       break;
1172 
1173     case TYPE_ARRAY:
1174       if (this->is_slice_type())
1175 	{
1176 	  std::vector<Backend::Btyped_identifier> bfields;
1177 	  get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1178 	  bt = gogo->backend()->struct_type(bfields);
1179 	}
1180       else
1181 	{
1182 	  Btype* element = this->array_type()->get_backend_element(gogo, true);
1183 	  Bexpression* len = this->array_type()->get_backend_length(gogo);
1184 	  bt = gogo->backend()->array_type(element, len);
1185 	}
1186       break;
1187 
1188     case TYPE_INTERFACE:
1189       {
1190 	go_assert(!this->interface_type()->is_empty());
1191 	std::vector<Backend::Btyped_identifier> bfields;
1192 	get_backend_interface_fields(gogo, this->interface_type(), true,
1193 				     &bfields);
1194 	bt = gogo->backend()->struct_type(bfields);
1195       }
1196       break;
1197 
1198     case TYPE_SINK:
1199     case TYPE_CALL_MULTIPLE_RESULT:
1200       /* Note that various classifications were handled in the earlier
1201 	 switch.  */
1202     default:
1203       go_unreachable();
1204     }
1205 
1206   if (ins.first->second.btype == NULL)
1207     {
1208       ins.first->second.btype = bt;
1209       ins.first->second.is_placeholder = true;
1210     }
1211   else
1212     {
1213       // A placeholder for this type got created along the way.  Use
1214       // that one and ignore the one we just built.
1215       bt = ins.first->second.btype;
1216     }
1217 
1218   return bt;
1219 }
1220 
1221 // Complete the backend representation.  This is called for a type
1222 // using a placeholder type.
1223 
1224 void
finish_backend(Gogo * gogo,Btype * placeholder)1225 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1226 {
1227   switch (this->classification_)
1228     {
1229     case TYPE_ERROR:
1230     case TYPE_VOID:
1231     case TYPE_BOOLEAN:
1232     case TYPE_INTEGER:
1233     case TYPE_FLOAT:
1234     case TYPE_COMPLEX:
1235     case TYPE_STRING:
1236     case TYPE_NIL:
1237       go_unreachable();
1238 
1239     case TYPE_FUNCTION:
1240       {
1241 	Btype* bt = this->do_get_backend(gogo);
1242 	if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1243 	  go_assert(saw_errors());
1244       }
1245       break;
1246 
1247     case TYPE_POINTER:
1248       {
1249 	Btype* bt = this->do_get_backend(gogo);
1250 	if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1251 	  go_assert(saw_errors());
1252       }
1253       break;
1254 
1255     case TYPE_STRUCT:
1256       // The struct type itself is done, but we have to make sure that
1257       // all the field types are converted.
1258       this->struct_type()->finish_backend_fields(gogo);
1259       break;
1260 
1261     case TYPE_ARRAY:
1262       // The array type itself is done, but make sure the element type
1263       // is converted.
1264       this->array_type()->finish_backend_element(gogo);
1265       break;
1266 
1267     case TYPE_MAP:
1268     case TYPE_CHANNEL:
1269       go_unreachable();
1270 
1271     case TYPE_INTERFACE:
1272       // The interface type itself is done, but make sure the method
1273       // types are converted.
1274       this->interface_type()->finish_backend_methods(gogo);
1275       break;
1276 
1277     case TYPE_NAMED:
1278     case TYPE_FORWARD:
1279       go_unreachable();
1280 
1281     case TYPE_SINK:
1282     case TYPE_CALL_MULTIPLE_RESULT:
1283     default:
1284       go_unreachable();
1285     }
1286 
1287   this->btype_ = placeholder;
1288 }
1289 
1290 // Return a pointer to the type descriptor for this type.
1291 
1292 Bexpression*
type_descriptor_pointer(Gogo * gogo,Location location)1293 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1294 {
1295   Type* t = this->unalias();
1296   if (t->type_descriptor_var_ == NULL)
1297     {
1298       t->make_type_descriptor_var(gogo);
1299       go_assert(t->type_descriptor_var_ != NULL);
1300     }
1301   Bexpression* var_expr =
1302       gogo->backend()->var_expression(t->type_descriptor_var_, location);
1303   Bexpression* var_addr =
1304       gogo->backend()->address_expression(var_expr, location);
1305   Type* td_type = Type::make_type_descriptor_type();
1306   Btype* td_btype = td_type->get_backend(gogo);
1307   Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1308   return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1309 }
1310 
1311 // A mapping from unnamed types to type descriptor variables.
1312 
1313 Type::Type_descriptor_vars Type::type_descriptor_vars;
1314 
1315 // Build the type descriptor for this type.
1316 
1317 void
make_type_descriptor_var(Gogo * gogo)1318 Type::make_type_descriptor_var(Gogo* gogo)
1319 {
1320   go_assert(this->type_descriptor_var_ == NULL);
1321 
1322   Named_type* nt = this->named_type();
1323 
1324   // We can have multiple instances of unnamed types, but we only want
1325   // to emit the type descriptor once.  We use a hash table.  This is
1326   // not necessary for named types, as they are unique, and we store
1327   // the type descriptor in the type itself.
1328   Bvariable** phash = NULL;
1329   if (nt == NULL)
1330     {
1331       Bvariable* bvnull = NULL;
1332       std::pair<Type_descriptor_vars::iterator, bool> ins =
1333 	Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1334       if (!ins.second)
1335 	{
1336 	  // We've already built a type descriptor for this type.
1337 	  this->type_descriptor_var_ = ins.first->second;
1338 	  return;
1339 	}
1340       phash = &ins.first->second;
1341     }
1342 
1343   // The type descriptor symbol for the unsafe.Pointer type is defined in
1344   // libgo/go-unsafe-pointer.c, so we just return a reference to that
1345   // symbol if necessary.
1346   if (this->is_unsafe_pointer_type())
1347     {
1348       Location bloc = Linemap::predeclared_location();
1349 
1350       Type* td_type = Type::make_type_descriptor_type();
1351       Btype* td_btype = td_type->get_backend(gogo);
1352       std::string name = gogo->type_descriptor_name(this, nt);
1353       std::string asm_name(go_selectively_encode_id(name));
1354       this->type_descriptor_var_ =
1355 	  gogo->backend()->immutable_struct_reference(name, asm_name,
1356 						      td_btype,
1357 						      bloc);
1358 
1359       if (phash != NULL)
1360 	*phash = this->type_descriptor_var_;
1361       return;
1362     }
1363 
1364   std::string var_name = gogo->type_descriptor_name(this, nt);
1365 
1366   // Build the contents of the type descriptor.
1367   Expression* initializer = this->do_type_descriptor(gogo, NULL);
1368 
1369   Btype* initializer_btype = initializer->type()->get_backend(gogo);
1370 
1371   Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1372 
1373   const Package* dummy;
1374   if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1375     {
1376       std::string asm_name(go_selectively_encode_id(var_name));
1377       this->type_descriptor_var_ =
1378 	  gogo->backend()->immutable_struct_reference(var_name, asm_name,
1379 						      initializer_btype,
1380 						      loc);
1381       if (phash != NULL)
1382 	*phash = this->type_descriptor_var_;
1383       return;
1384     }
1385 
1386   // See if this type descriptor can appear in multiple packages.
1387   bool is_common = false;
1388   if (nt != NULL)
1389     {
1390       // We create the descriptor for a builtin type whenever we need
1391       // it.
1392       is_common = nt->is_builtin();
1393     }
1394   else
1395     {
1396       // This is an unnamed type.  The descriptor could be defined in
1397       // any package where it is needed, and the linker will pick one
1398       // descriptor to keep.
1399       is_common = true;
1400     }
1401 
1402   // We are going to build the type descriptor in this package.  We
1403   // must create the variable before we convert the initializer to the
1404   // backend representation, because the initializer may refer to the
1405   // type descriptor of this type.  By setting type_descriptor_var_ we
1406   // ensure that type_descriptor_pointer will work if called while
1407   // converting INITIALIZER.
1408 
1409   std::string asm_name(go_selectively_encode_id(var_name));
1410   this->type_descriptor_var_ =
1411       gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1412 				      initializer_btype, loc);
1413   if (phash != NULL)
1414     *phash = this->type_descriptor_var_;
1415 
1416   Translate_context context(gogo, NULL, NULL, NULL);
1417   context.set_is_const();
1418   Bexpression* binitializer = initializer->get_backend(&context);
1419 
1420   gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1421 					     var_name, false, is_common,
1422 					     initializer_btype, loc,
1423 					     binitializer);
1424 }
1425 
1426 // Return true if this type descriptor is defined in a different
1427 // package.  If this returns true it sets *PACKAGE to the package.
1428 
1429 bool
type_descriptor_defined_elsewhere(Named_type * nt,const Package ** package)1430 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1431 					const Package** package)
1432 {
1433   if (nt != NULL)
1434     {
1435       if (nt->named_object()->package() != NULL)
1436 	{
1437 	  // This is a named type defined in a different package.  The
1438 	  // type descriptor should be defined in that package.
1439 	  *package = nt->named_object()->package();
1440 	  return true;
1441 	}
1442     }
1443   else
1444     {
1445       if (this->points_to() != NULL
1446 	  && this->points_to()->named_type() != NULL
1447 	  && this->points_to()->named_type()->named_object()->package() != NULL)
1448 	{
1449 	  // This is an unnamed pointer to a named type defined in a
1450 	  // different package.  The descriptor should be defined in
1451 	  // that package.
1452 	  *package = this->points_to()->named_type()->named_object()->package();
1453 	  return true;
1454 	}
1455     }
1456   return false;
1457 }
1458 
1459 // Return a composite literal for a type descriptor.
1460 
1461 Expression*
type_descriptor(Gogo * gogo,Type * type)1462 Type::type_descriptor(Gogo* gogo, Type* type)
1463 {
1464   return type->do_type_descriptor(gogo, NULL);
1465 }
1466 
1467 // Return a composite literal for a type descriptor with a name.
1468 
1469 Expression*
named_type_descriptor(Gogo * gogo,Type * type,Named_type * name)1470 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1471 {
1472   go_assert(name != NULL && type->named_type() != name);
1473   return type->do_type_descriptor(gogo, name);
1474 }
1475 
1476 // Make a builtin struct type from a list of fields.  The fields are
1477 // pairs of a name and a type.
1478 
1479 Struct_type*
make_builtin_struct_type(int nfields,...)1480 Type::make_builtin_struct_type(int nfields, ...)
1481 {
1482   va_list ap;
1483   va_start(ap, nfields);
1484 
1485   Location bloc = Linemap::predeclared_location();
1486   Struct_field_list* sfl = new Struct_field_list();
1487   for (int i = 0; i < nfields; i++)
1488     {
1489       const char* field_name = va_arg(ap, const char *);
1490       Type* type = va_arg(ap, Type*);
1491       sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1492     }
1493 
1494   va_end(ap);
1495 
1496   Struct_type* ret = Type::make_struct_type(sfl, bloc);
1497   ret->set_is_struct_incomparable();
1498   return ret;
1499 }
1500 
1501 // A list of builtin named types.
1502 
1503 std::vector<Named_type*> Type::named_builtin_types;
1504 
1505 // Make a builtin named type.
1506 
1507 Named_type*
make_builtin_named_type(const char * name,Type * type)1508 Type::make_builtin_named_type(const char* name, Type* type)
1509 {
1510   Location bloc = Linemap::predeclared_location();
1511   Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1512   Named_type* ret = no->type_value();
1513   Type::named_builtin_types.push_back(ret);
1514   return ret;
1515 }
1516 
1517 // Convert the named builtin types.
1518 
1519 void
convert_builtin_named_types(Gogo * gogo)1520 Type::convert_builtin_named_types(Gogo* gogo)
1521 {
1522   for (std::vector<Named_type*>::const_iterator p =
1523 	 Type::named_builtin_types.begin();
1524        p != Type::named_builtin_types.end();
1525        ++p)
1526     {
1527       bool r = (*p)->verify();
1528       go_assert(r);
1529       (*p)->convert(gogo);
1530     }
1531 }
1532 
1533 // Return the type of a type descriptor.  We should really tie this to
1534 // runtime.Type rather than copying it.  This must match the struct "_type"
1535 // declared in libgo/go/runtime/type.go.
1536 
1537 Type*
make_type_descriptor_type()1538 Type::make_type_descriptor_type()
1539 {
1540   static Type* ret;
1541   if (ret == NULL)
1542     {
1543       Location bloc = Linemap::predeclared_location();
1544 
1545       Type* uint8_type = Type::lookup_integer_type("uint8");
1546       Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1547       Type* uint32_type = Type::lookup_integer_type("uint32");
1548       Type* uintptr_type = Type::lookup_integer_type("uintptr");
1549       Type* string_type = Type::lookup_string_type();
1550       Type* pointer_string_type = Type::make_pointer_type(string_type);
1551 
1552       // This is an unnamed version of unsafe.Pointer.  Perhaps we
1553       // should use the named version instead, although that would
1554       // require us to create the unsafe package if it has not been
1555       // imported.  It probably doesn't matter.
1556       Type* void_type = Type::make_void_type();
1557       Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1558 
1559       Typed_identifier_list *params = new Typed_identifier_list();
1560       params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1561       params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1562 
1563       Typed_identifier_list* results = new Typed_identifier_list();
1564       results->push_back(Typed_identifier("", uintptr_type, bloc));
1565 
1566       Type* hash_fntype = Type::make_function_type(NULL, params, results,
1567 						   bloc);
1568 
1569       params = new Typed_identifier_list();
1570       params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1571       params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1572 
1573       results = new Typed_identifier_list();
1574       results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1575 
1576       Type* equal_fntype = Type::make_function_type(NULL, params, results,
1577 						    bloc);
1578 
1579       // Forward declaration for the type descriptor type.
1580       Named_object* named_type_descriptor_type =
1581 	Named_object::make_type_declaration("_type", NULL, bloc);
1582       Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1583       Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1584 
1585       // The type of a method on a concrete type.
1586       Struct_type* method_type =
1587 	Type::make_builtin_struct_type(5,
1588 				       "name", pointer_string_type,
1589 				       "pkgPath", pointer_string_type,
1590 				       "mtyp", pointer_type_descriptor_type,
1591 				       "typ", pointer_type_descriptor_type,
1592 				       "tfn", unsafe_pointer_type);
1593       Named_type* named_method_type =
1594 	Type::make_builtin_named_type("method", method_type);
1595 
1596       // Information for types with a name or methods.
1597       Type* slice_named_method_type =
1598 	Type::make_array_type(named_method_type, NULL);
1599       Struct_type* uncommon_type =
1600 	Type::make_builtin_struct_type(3,
1601 				       "name", pointer_string_type,
1602 				       "pkgPath", pointer_string_type,
1603 				       "methods", slice_named_method_type);
1604       Named_type* named_uncommon_type =
1605 	Type::make_builtin_named_type("uncommonType", uncommon_type);
1606 
1607       Type* pointer_uncommon_type =
1608 	Type::make_pointer_type(named_uncommon_type);
1609 
1610       // The type descriptor type.
1611 
1612       Struct_type* type_descriptor_type =
1613 	Type::make_builtin_struct_type(12,
1614 				       "size", uintptr_type,
1615 				       "ptrdata", uintptr_type,
1616 				       "hash", uint32_type,
1617 				       "kind", uint8_type,
1618 				       "align", uint8_type,
1619 				       "fieldAlign", uint8_type,
1620 				       "hashfn", hash_fntype,
1621 				       "equalfn", equal_fntype,
1622 				       "gcdata", pointer_uint8_type,
1623 				       "string", pointer_string_type,
1624 				       "", pointer_uncommon_type,
1625 				       "ptrToThis",
1626 				       pointer_type_descriptor_type);
1627 
1628       Named_type* named = Type::make_builtin_named_type("_type",
1629 							type_descriptor_type);
1630 
1631       named_type_descriptor_type->set_type_value(named);
1632 
1633       ret = named;
1634     }
1635 
1636   return ret;
1637 }
1638 
1639 // Make the type of a pointer to a type descriptor as represented in
1640 // Go.
1641 
1642 Type*
make_type_descriptor_ptr_type()1643 Type::make_type_descriptor_ptr_type()
1644 {
1645   static Type* ret;
1646   if (ret == NULL)
1647     ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1648   return ret;
1649 }
1650 
1651 // Return the alignment required by the memequalN function.  N is a
1652 // type size: 16, 32, 64, or 128.  The memequalN functions are defined
1653 // in libgo/go/runtime/alg.go.
1654 
1655 int64_t
memequal_align(Gogo * gogo,int size)1656 Type::memequal_align(Gogo* gogo, int size)
1657 {
1658   const char* tn;
1659   switch (size)
1660     {
1661     case 16:
1662       tn = "int16";
1663       break;
1664     case 32:
1665       tn = "int32";
1666       break;
1667     case 64:
1668       tn = "int64";
1669       break;
1670     case 128:
1671       // The code uses [2]int64, which must have the same alignment as
1672       // int64.
1673       tn = "int64";
1674       break;
1675     default:
1676       go_unreachable();
1677     }
1678 
1679   Type* t = Type::lookup_integer_type(tn);
1680 
1681   int64_t ret;
1682   if (!t->backend_type_align(gogo, &ret))
1683     go_unreachable();
1684   return ret;
1685 }
1686 
1687 // Return whether this type needs specially built type functions.
1688 // This returns true for types that are comparable and either can not
1689 // use an identity comparison, or are a non-standard size.
1690 
1691 bool
needs_specific_type_functions(Gogo * gogo)1692 Type::needs_specific_type_functions(Gogo* gogo)
1693 {
1694   Named_type* nt = this->named_type();
1695   if (nt != NULL && nt->is_alias())
1696     return false;
1697   if (!this->is_comparable())
1698     return false;
1699   if (!this->compare_is_identity(gogo))
1700     return true;
1701 
1702   // We create a few predeclared types for type descriptors; they are
1703   // really just for the backend and don't need hash or equality
1704   // functions.
1705   if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1706     return false;
1707 
1708   int64_t size, align;
1709   if (!this->backend_type_size(gogo, &size)
1710       || !this->backend_type_align(gogo, &align))
1711     {
1712       go_assert(saw_errors());
1713       return false;
1714     }
1715   // This switch matches the one in Type::type_functions.
1716   switch (size)
1717     {
1718     case 0:
1719     case 1:
1720     case 2:
1721       return align < Type::memequal_align(gogo, 16);
1722     case 4:
1723       return align < Type::memequal_align(gogo, 32);
1724     case 8:
1725       return align < Type::memequal_align(gogo, 64);
1726     case 16:
1727       return align < Type::memequal_align(gogo, 128);
1728     default:
1729       return true;
1730     }
1731 }
1732 
1733 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1734 // hash code for this type and which compare whether two values of
1735 // this type are equal.  If NAME is not NULL it is the name of this
1736 // type.  HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1737 // functions, for convenience; they may be NULL.
1738 
1739 void
type_functions(Gogo * gogo,Named_type * name,Function_type * hash_fntype,Function_type * equal_fntype,Named_object ** hash_fn,Named_object ** equal_fn)1740 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1741 		     Function_type* equal_fntype, Named_object** hash_fn,
1742 		     Named_object** equal_fn)
1743 {
1744   // If the unaliased type is not a named type, then the type does not
1745   // have a name after all.
1746   if (name != NULL)
1747     name = name->unalias()->named_type();
1748 
1749   if (!this->is_comparable())
1750     {
1751       *hash_fn = NULL;
1752       *equal_fn = NULL;
1753       return;
1754     }
1755 
1756   if (hash_fntype == NULL || equal_fntype == NULL)
1757     {
1758       Location bloc = Linemap::predeclared_location();
1759 
1760       Type* uintptr_type = Type::lookup_integer_type("uintptr");
1761       Type* void_type = Type::make_void_type();
1762       Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1763 
1764       if (hash_fntype == NULL)
1765 	{
1766 	  Typed_identifier_list* params = new Typed_identifier_list();
1767 	  params->push_back(Typed_identifier("key", unsafe_pointer_type,
1768 					     bloc));
1769 	  params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1770 
1771 	  Typed_identifier_list* results = new Typed_identifier_list();
1772 	  results->push_back(Typed_identifier("", uintptr_type, bloc));
1773 
1774 	  hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1775 	}
1776       if (equal_fntype == NULL)
1777 	{
1778 	  Typed_identifier_list* params = new Typed_identifier_list();
1779 	  params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1780 					     bloc));
1781 	  params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1782 					     bloc));
1783 
1784 	  Typed_identifier_list* results = new Typed_identifier_list();
1785 	  results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1786 					      bloc));
1787 
1788 	  equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1789 	}
1790     }
1791 
1792   const char* hash_fnname;
1793   const char* equal_fnname;
1794   if (this->compare_is_identity(gogo))
1795     {
1796       int64_t size, align;
1797       if (!this->backend_type_size(gogo, &size)
1798 	  || !this->backend_type_align(gogo, &align))
1799 	{
1800 	  go_assert(saw_errors());
1801 	  return;
1802 	}
1803       bool build_functions = false;
1804       // This switch matches the one in Type::needs_specific_type_functions.
1805       // The alignment tests are because of the memequal functions,
1806       // which assume that the values are aligned as required for an
1807       // integer of that size.
1808       switch (size)
1809 	{
1810 	case 0:
1811 	  hash_fnname = "runtime.memhash0";
1812 	  equal_fnname = "runtime.memequal0";
1813 	  break;
1814 	case 1:
1815 	  hash_fnname = "runtime.memhash8";
1816 	  equal_fnname = "runtime.memequal8";
1817 	  break;
1818 	case 2:
1819 	  if (align < Type::memequal_align(gogo, 16))
1820 	    build_functions = true;
1821 	  else
1822 	    {
1823 	      hash_fnname = "runtime.memhash16";
1824 	      equal_fnname = "runtime.memequal16";
1825 	    }
1826 	  break;
1827 	case 4:
1828 	  if (align < Type::memequal_align(gogo, 32))
1829 	    build_functions = true;
1830 	  else
1831 	    {
1832 	      hash_fnname = "runtime.memhash32";
1833 	      equal_fnname = "runtime.memequal32";
1834 	    }
1835 	  break;
1836 	case 8:
1837 	  if (align < Type::memequal_align(gogo, 64))
1838 	    build_functions = true;
1839 	  else
1840 	    {
1841 	      hash_fnname = "runtime.memhash64";
1842 	      equal_fnname = "runtime.memequal64";
1843 	    }
1844 	  break;
1845 	case 16:
1846 	  if (align < Type::memequal_align(gogo, 128))
1847 	    build_functions = true;
1848 	  else
1849 	    {
1850 	      hash_fnname = "runtime.memhash128";
1851 	      equal_fnname = "runtime.memequal128";
1852 	    }
1853 	  break;
1854 	default:
1855 	  build_functions = true;
1856 	  break;
1857 	}
1858       if (build_functions)
1859 	{
1860 	  // We don't have a built-in function for a type of this size
1861 	  // and alignment.  Build a function to use that calls the
1862 	  // generic hash/equality functions for identity, passing the size.
1863 	  this->specific_type_functions(gogo, name, size, hash_fntype,
1864 					equal_fntype, hash_fn, equal_fn);
1865 	  return;
1866 	}
1867     }
1868   else
1869     {
1870       switch (this->base()->classification())
1871 	{
1872 	case Type::TYPE_ERROR:
1873 	case Type::TYPE_VOID:
1874 	case Type::TYPE_NIL:
1875 	case Type::TYPE_FUNCTION:
1876 	case Type::TYPE_MAP:
1877 	  // For these types is_comparable should have returned false.
1878 	  go_unreachable();
1879 
1880 	case Type::TYPE_BOOLEAN:
1881 	case Type::TYPE_INTEGER:
1882 	case Type::TYPE_POINTER:
1883 	case Type::TYPE_CHANNEL:
1884 	  // For these types compare_is_identity should have returned true.
1885 	  go_unreachable();
1886 
1887 	case Type::TYPE_FLOAT:
1888 	  switch (this->float_type()->bits())
1889 	    {
1890 	    case 32:
1891 	      hash_fnname = "runtime.f32hash";
1892 	      equal_fnname = "runtime.f32equal";
1893 	      break;
1894 	    case 64:
1895 	      hash_fnname = "runtime.f64hash";
1896 	      equal_fnname = "runtime.f64equal";
1897 	      break;
1898 	    default:
1899 	      go_unreachable();
1900 	    }
1901 	  break;
1902 
1903 	case Type::TYPE_COMPLEX:
1904 	  switch (this->complex_type()->bits())
1905 	    {
1906 	    case 64:
1907 	      hash_fnname = "runtime.c64hash";
1908 	      equal_fnname = "runtime.c64equal";
1909 	      break;
1910 	    case 128:
1911 	      hash_fnname = "runtime.c128hash";
1912 	      equal_fnname = "runtime.c128equal";
1913 	      break;
1914 	    default:
1915 	      go_unreachable();
1916 	    }
1917 	  break;
1918 
1919 	case Type::TYPE_STRING:
1920 	  hash_fnname = "runtime.strhash";
1921 	  equal_fnname = "runtime.strequal";
1922 	  break;
1923 
1924 	case Type::TYPE_STRUCT:
1925 	  {
1926 	    // This is a struct which can not be compared using a
1927 	    // simple identity function.  We need to build a function
1928 	    // for comparison.
1929 	    this->specific_type_functions(gogo, name, -1, hash_fntype,
1930 					  equal_fntype, hash_fn, equal_fn);
1931 	    return;
1932 	  }
1933 
1934 	case Type::TYPE_ARRAY:
1935 	  if (this->is_slice_type())
1936 	    {
1937 	      // Type::is_compatible_for_comparison should have
1938 	      // returned false.
1939 	      go_unreachable();
1940 	    }
1941 	  else
1942 	    {
1943 	      // This is an array which can not be compared using a
1944 	      // simple identity function.  We need to build a
1945 	      // function for comparison.
1946 	      this->specific_type_functions(gogo, name, -1, hash_fntype,
1947 					    equal_fntype, hash_fn, equal_fn);
1948 	      return;
1949 	    }
1950 	  break;
1951 
1952 	case Type::TYPE_INTERFACE:
1953 	  if (this->interface_type()->is_empty())
1954 	    {
1955 	      hash_fnname = "runtime.nilinterhash";
1956 	      equal_fnname = "runtime.nilinterequal";
1957 	    }
1958 	  else
1959 	    {
1960 	      hash_fnname = "runtime.interhash";
1961 	      equal_fnname = "runtime.interequal";
1962 	    }
1963 	  break;
1964 
1965 	case Type::TYPE_NAMED:
1966 	case Type::TYPE_FORWARD:
1967 	  go_unreachable();
1968 
1969 	default:
1970 	  go_unreachable();
1971 	}
1972     }
1973 
1974 
1975   Location bloc = Linemap::predeclared_location();
1976   *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1977 						     hash_fntype, bloc);
1978   (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1979   *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1980 						      equal_fntype, bloc);
1981   (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1982 }
1983 
1984 // A hash table mapping types to the specific hash functions.
1985 
1986 Type::Type_functions Type::type_functions_table;
1987 
1988 // Handle a type function which is specific to a type: if SIZE == -1,
1989 // this is a struct or array that can not use an identity comparison.
1990 // Otherwise, it is a type that uses an identity comparison but is not
1991 // one of the standard supported sizes.
1992 
1993 void
specific_type_functions(Gogo * gogo,Named_type * name,int64_t size,Function_type * hash_fntype,Function_type * equal_fntype,Named_object ** hash_fn,Named_object ** equal_fn)1994 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1995 			      Function_type* hash_fntype,
1996 			      Function_type* equal_fntype,
1997 			      Named_object** hash_fn,
1998 			      Named_object** equal_fn)
1999 {
2000   Hash_equal_fn fnull(NULL, NULL);
2001   std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
2002   std::pair<Type_functions::iterator, bool> ins =
2003     Type::type_functions_table.insert(val);
2004   if (!ins.second)
2005     {
2006       // We already have functions for this type
2007       *hash_fn = ins.first->second.first;
2008       *equal_fn = ins.first->second.second;
2009       return;
2010     }
2011 
2012   std::string hash_name;
2013   std::string equal_name;
2014   gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
2015 
2016   Location bloc = Linemap::predeclared_location();
2017 
2018   const Package* package = NULL;
2019   bool is_defined_elsewhere =
2020     this->type_descriptor_defined_elsewhere(name, &package);
2021   if (is_defined_elsewhere)
2022     {
2023       *hash_fn = Named_object::make_function_declaration(hash_name, package,
2024 							 hash_fntype, bloc);
2025       *equal_fn = Named_object::make_function_declaration(equal_name, package,
2026 							  equal_fntype, bloc);
2027     }
2028   else
2029     {
2030       *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2031       *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2032 						 bloc);
2033     }
2034 
2035   ins.first->second.first = *hash_fn;
2036   ins.first->second.second = *equal_fn;
2037 
2038   if (!is_defined_elsewhere)
2039     {
2040       if (gogo->in_global_scope())
2041 	this->write_specific_type_functions(gogo, name, size, hash_name,
2042 					    hash_fntype, equal_name,
2043 					    equal_fntype);
2044       else
2045 	gogo->queue_specific_type_function(this, name, size, hash_name,
2046 					   hash_fntype, equal_name,
2047 					   equal_fntype);
2048     }
2049 }
2050 
2051 // Write the hash and equality functions for a type which needs to be
2052 // written specially.
2053 
2054 void
write_specific_type_functions(Gogo * gogo,Named_type * name,int64_t size,const std::string & hash_name,Function_type * hash_fntype,const std::string & equal_name,Function_type * equal_fntype)2055 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2056 				    const std::string& hash_name,
2057 				    Function_type* hash_fntype,
2058 				    const std::string& equal_name,
2059 				    Function_type* equal_fntype)
2060 {
2061   Location bloc = Linemap::predeclared_location();
2062 
2063   if (gogo->specific_type_functions_are_written())
2064     {
2065       go_assert(saw_errors());
2066       return;
2067     }
2068 
2069   go_assert(this->is_comparable());
2070 
2071   Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2072 					       bloc);
2073   hash_fn->func_value()->set_is_type_specific_function();
2074   gogo->start_block(bloc);
2075 
2076   if (size != -1)
2077     this->write_identity_hash(gogo, size);
2078   else if (name != NULL && name->real_type()->named_type() != NULL)
2079     this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2080   else if (this->struct_type() != NULL)
2081     this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2082 					     equal_fntype);
2083   else if (this->array_type() != NULL)
2084     this->array_type()->write_hash_function(gogo, name, hash_fntype,
2085 					    equal_fntype);
2086   else
2087     go_unreachable();
2088 
2089   Block* b = gogo->finish_block(bloc);
2090   gogo->add_block(b, bloc);
2091   gogo->lower_block(hash_fn, b);
2092   gogo->finish_function(bloc);
2093 
2094   Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2095 						false, bloc);
2096   equal_fn->func_value()->set_is_type_specific_function();
2097   gogo->start_block(bloc);
2098 
2099   if (size != -1)
2100     this->write_identity_equal(gogo, size);
2101   else if (name != NULL && name->real_type()->named_type() != NULL)
2102     this->write_named_equal(gogo, name);
2103   else if (this->struct_type() != NULL)
2104     this->struct_type()->write_equal_function(gogo, name);
2105   else if (this->array_type() != NULL)
2106     this->array_type()->write_equal_function(gogo, name);
2107   else
2108     go_unreachable();
2109 
2110   b = gogo->finish_block(bloc);
2111   gogo->add_block(b, bloc);
2112   gogo->lower_block(equal_fn, b);
2113   gogo->finish_function(bloc);
2114 
2115   // Build the function descriptors for the type descriptor to refer to.
2116   hash_fn->func_value()->descriptor(gogo, hash_fn);
2117   equal_fn->func_value()->descriptor(gogo, equal_fn);
2118 }
2119 
2120 // Write a hash function for a type that can use an identity hash but
2121 // is not one of the standard supported sizes.  For example, this
2122 // would be used for the type [3]byte.  This builds a return statement
2123 // that returns a call to the memhash function, passing the key and
2124 // seed from the function arguments (already constructed before this
2125 // is called), and the constant size.
2126 
2127 void
write_identity_hash(Gogo * gogo,int64_t size)2128 Type::write_identity_hash(Gogo* gogo, int64_t size)
2129 {
2130   Location bloc = Linemap::predeclared_location();
2131 
2132   Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2133   Type* uintptr_type = Type::lookup_integer_type("uintptr");
2134 
2135   Typed_identifier_list* params = new Typed_identifier_list();
2136   params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2137   params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2138   params->push_back(Typed_identifier("size", uintptr_type, bloc));
2139 
2140   Typed_identifier_list* results = new Typed_identifier_list();
2141   results->push_back(Typed_identifier("", uintptr_type, bloc));
2142 
2143   Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2144 							   results, bloc);
2145 
2146   Named_object* memhash =
2147     Named_object::make_function_declaration("runtime.memhash", NULL,
2148 					    memhash_fntype, bloc);
2149   memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2150 
2151   Named_object* key_arg = gogo->lookup("key", NULL);
2152   go_assert(key_arg != NULL);
2153   Named_object* seed_arg = gogo->lookup("seed", NULL);
2154   go_assert(seed_arg != NULL);
2155 
2156   Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2157   Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2158   Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2159 							bloc);
2160   Expression_list* args = new Expression_list();
2161   args->push_back(key_ref);
2162   args->push_back(seed_ref);
2163   args->push_back(size_arg);
2164   Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2165   Expression* call = Expression::make_call(func, args, false, bloc);
2166 
2167   Expression_list* vals = new Expression_list();
2168   vals->push_back(call);
2169   Statement* s = Statement::make_return_statement(vals, bloc);
2170   gogo->add_statement(s);
2171 }
2172 
2173 // Write an equality function for a type that can use an identity
2174 // equality comparison but is not one of the standard supported sizes.
2175 // For example, this would be used for the type [3]byte.  This builds
2176 // a return statement that returns a call to the memequal function,
2177 // passing the two keys from the function arguments (already
2178 // constructed before this is called), and the constant size.
2179 
2180 void
write_identity_equal(Gogo * gogo,int64_t size)2181 Type::write_identity_equal(Gogo* gogo, int64_t size)
2182 {
2183   Location bloc = Linemap::predeclared_location();
2184 
2185   Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2186   Type* uintptr_type = Type::lookup_integer_type("uintptr");
2187 
2188   Typed_identifier_list* params = new Typed_identifier_list();
2189   params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2190   params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2191   params->push_back(Typed_identifier("size", uintptr_type, bloc));
2192 
2193   Typed_identifier_list* results = new Typed_identifier_list();
2194   results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2195 
2196   Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2197 							    results, bloc);
2198 
2199   Named_object* memequal =
2200     Named_object::make_function_declaration("runtime.memequal", NULL,
2201 					    memequal_fntype, bloc);
2202   memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2203 
2204   Named_object* key1_arg = gogo->lookup("key1", NULL);
2205   go_assert(key1_arg != NULL);
2206   Named_object* key2_arg = gogo->lookup("key2", NULL);
2207   go_assert(key2_arg != NULL);
2208 
2209   Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2210   Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2211   Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2212 							bloc);
2213   Expression_list* args = new Expression_list();
2214   args->push_back(key1_ref);
2215   args->push_back(key2_ref);
2216   args->push_back(size_arg);
2217   Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2218   Expression* call = Expression::make_call(func, args, false, bloc);
2219 
2220   Expression_list* vals = new Expression_list();
2221   vals->push_back(call);
2222   Statement* s = Statement::make_return_statement(vals, bloc);
2223   gogo->add_statement(s);
2224 }
2225 
2226 // Write a hash function that simply calls the hash function for a
2227 // named type.  This is used when one named type is defined as
2228 // another.  This ensures that this case works when the other named
2229 // type is defined in another package and relies on calling hash
2230 // functions defined only in that package.
2231 
2232 void
write_named_hash(Gogo * gogo,Named_type * name,Function_type * hash_fntype,Function_type * equal_fntype)2233 Type::write_named_hash(Gogo* gogo, Named_type* name,
2234 		       Function_type* hash_fntype, Function_type* equal_fntype)
2235 {
2236   Location bloc = Linemap::predeclared_location();
2237 
2238   Named_type* base_type = name->real_type()->named_type();
2239   while (base_type->is_alias())
2240     {
2241       base_type = base_type->real_type()->named_type();
2242       go_assert(base_type != NULL);
2243     }
2244   go_assert(base_type != NULL);
2245 
2246   // The pointer to the type we are going to hash.  This is an
2247   // unsafe.Pointer.
2248   Named_object* key_arg = gogo->lookup("key", NULL);
2249   go_assert(key_arg != NULL);
2250 
2251   // The seed argument to the hash function.
2252   Named_object* seed_arg = gogo->lookup("seed", NULL);
2253   go_assert(seed_arg != NULL);
2254 
2255   Named_object* hash_fn;
2256   Named_object* equal_fn;
2257   name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2258 				    &hash_fn, &equal_fn);
2259 
2260   // Call the hash function for the base type.
2261   Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2262   Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2263   Expression_list* args = new Expression_list();
2264   args->push_back(key_ref);
2265   args->push_back(seed_ref);
2266   Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2267   Expression* call = Expression::make_call(func, args, false, bloc);
2268 
2269   // Return the hash of the base type.
2270   Expression_list* vals = new Expression_list();
2271   vals->push_back(call);
2272   Statement* s = Statement::make_return_statement(vals, bloc);
2273   gogo->add_statement(s);
2274 }
2275 
2276 // Write an equality function that simply calls the equality function
2277 // for a named type.  This is used when one named type is defined as
2278 // another.  This ensures that this case works when the other named
2279 // type is defined in another package and relies on calling equality
2280 // functions defined only in that package.
2281 
2282 void
write_named_equal(Gogo * gogo,Named_type * name)2283 Type::write_named_equal(Gogo* gogo, Named_type* name)
2284 {
2285   Location bloc = Linemap::predeclared_location();
2286 
2287   // The pointers to the types we are going to compare.  These have
2288   // type unsafe.Pointer.
2289   Named_object* key1_arg = gogo->lookup("key1", NULL);
2290   Named_object* key2_arg = gogo->lookup("key2", NULL);
2291   go_assert(key1_arg != NULL && key2_arg != NULL);
2292 
2293   Named_type* base_type = name->real_type()->named_type();
2294   go_assert(base_type != NULL);
2295 
2296   // Build temporaries with the base type.
2297   Type* pt = Type::make_pointer_type(base_type);
2298 
2299   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2300   ref = Expression::make_cast(pt, ref, bloc);
2301   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2302   gogo->add_statement(p1);
2303 
2304   ref = Expression::make_var_reference(key2_arg, bloc);
2305   ref = Expression::make_cast(pt, ref, bloc);
2306   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2307   gogo->add_statement(p2);
2308 
2309   // Compare the values for equality.
2310   Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2311   t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2312 
2313   Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2314   t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2315 
2316   Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2317 
2318   // Return the equality comparison.
2319   Expression_list* vals = new Expression_list();
2320   vals->push_back(cond);
2321   Statement* s = Statement::make_return_statement(vals, bloc);
2322   gogo->add_statement(s);
2323 }
2324 
2325 // Return a composite literal for the type descriptor for a plain type
2326 // of kind RUNTIME_TYPE_KIND named NAME.
2327 
2328 Expression*
type_descriptor_constructor(Gogo * gogo,int runtime_type_kind,Named_type * name,const Methods * methods,bool only_value_methods)2329 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2330 				  Named_type* name, const Methods* methods,
2331 				  bool only_value_methods)
2332 {
2333   Location bloc = Linemap::predeclared_location();
2334 
2335   Type* td_type = Type::make_type_descriptor_type();
2336   const Struct_field_list* fields = td_type->struct_type()->fields();
2337 
2338   Expression_list* vals = new Expression_list();
2339   vals->reserve(12);
2340 
2341   if (!this->has_pointer())
2342     runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2343   if (this->points_to() != NULL)
2344     runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2345   int64_t ptrsize;
2346   int64_t ptrdata;
2347   if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2348     runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2349 
2350   Struct_field_list::const_iterator p = fields->begin();
2351   go_assert(p->is_field_name("size"));
2352   Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2353   vals->push_back(Expression::make_type_info(this, type_info));
2354 
2355   ++p;
2356   go_assert(p->is_field_name("ptrdata"));
2357   type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2358   vals->push_back(Expression::make_type_info(this, type_info));
2359 
2360   ++p;
2361   go_assert(p->is_field_name("hash"));
2362   unsigned int h;
2363   if (name != NULL)
2364     h = name->hash_for_method(gogo);
2365   else
2366     h = this->hash_for_method(gogo);
2367   vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2368 
2369   ++p;
2370   go_assert(p->is_field_name("kind"));
2371   vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2372 					      bloc));
2373 
2374   ++p;
2375   go_assert(p->is_field_name("align"));
2376   type_info = Expression::TYPE_INFO_ALIGNMENT;
2377   vals->push_back(Expression::make_type_info(this, type_info));
2378 
2379   ++p;
2380   go_assert(p->is_field_name("fieldAlign"));
2381   type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2382   vals->push_back(Expression::make_type_info(this, type_info));
2383 
2384   ++p;
2385   go_assert(p->is_field_name("hashfn"));
2386   Function_type* hash_fntype = p->type()->function_type();
2387 
2388   ++p;
2389   go_assert(p->is_field_name("equalfn"));
2390   Function_type* equal_fntype = p->type()->function_type();
2391 
2392   Named_object* hash_fn;
2393   Named_object* equal_fn;
2394   this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2395 		       &equal_fn);
2396   if (hash_fn == NULL)
2397     vals->push_back(Expression::make_cast(hash_fntype,
2398 					  Expression::make_nil(bloc),
2399 					  bloc));
2400   else
2401     vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2402   if (equal_fn == NULL)
2403     vals->push_back(Expression::make_cast(equal_fntype,
2404 					  Expression::make_nil(bloc),
2405 					  bloc));
2406   else
2407     vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2408 
2409   ++p;
2410   go_assert(p->is_field_name("gcdata"));
2411   vals->push_back(Expression::make_gc_symbol(this));
2412 
2413   ++p;
2414   go_assert(p->is_field_name("string"));
2415   Expression* s = Expression::make_string((name != NULL
2416 					   ? name->reflection(gogo)
2417 					   : this->reflection(gogo)),
2418 					  bloc);
2419   vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2420 
2421   ++p;
2422   go_assert(p->is_field_name("uncommonType"));
2423   if (name == NULL && methods == NULL)
2424     vals->push_back(Expression::make_nil(bloc));
2425   else
2426     {
2427       if (methods == NULL)
2428 	methods = name->methods();
2429       vals->push_back(this->uncommon_type_constructor(gogo,
2430 						      p->type()->deref(),
2431 						      name, methods,
2432 						      only_value_methods));
2433     }
2434 
2435   ++p;
2436   go_assert(p->is_field_name("ptrToThis"));
2437   if (name == NULL && methods == NULL)
2438     vals->push_back(Expression::make_nil(bloc));
2439   else
2440     {
2441       Type* pt;
2442       if (name != NULL)
2443 	pt = Type::make_pointer_type(name);
2444       else
2445 	pt = Type::make_pointer_type(this);
2446       vals->push_back(Expression::make_type_descriptor(pt, bloc));
2447     }
2448 
2449   ++p;
2450   go_assert(p == fields->end());
2451 
2452   return Expression::make_struct_composite_literal(td_type, vals, bloc);
2453 }
2454 
2455 // The maximum length of a GC ptrmask bitmap.  This corresponds to the
2456 // length used by the gc toolchain, and also appears in
2457 // libgo/go/reflect/type.go.
2458 
2459 static const int64_t max_ptrmask_bytes = 2048;
2460 
2461 // Return a pointer to the Garbage Collection information for this type.
2462 
2463 Bexpression*
gc_symbol_pointer(Gogo * gogo)2464 Type::gc_symbol_pointer(Gogo* gogo)
2465 {
2466   Type* t = this->unalias();
2467 
2468   if (!t->has_pointer())
2469     return gogo->backend()->nil_pointer_expression();
2470 
2471   if (t->gc_symbol_var_ == NULL)
2472     {
2473       t->make_gc_symbol_var(gogo);
2474       go_assert(t->gc_symbol_var_ != NULL);
2475     }
2476   Location bloc = Linemap::predeclared_location();
2477   Bexpression* var_expr =
2478       gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2479   Bexpression* addr_expr =
2480       gogo->backend()->address_expression(var_expr, bloc);
2481 
2482   Type* uint8_type = Type::lookup_integer_type("uint8");
2483   Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2484   Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2485   return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2486 }
2487 
2488 // A mapping from unnamed types to GC symbol variables.
2489 
2490 Type::GC_symbol_vars Type::gc_symbol_vars;
2491 
2492 // Build the GC symbol for this type.
2493 
2494 void
make_gc_symbol_var(Gogo * gogo)2495 Type::make_gc_symbol_var(Gogo* gogo)
2496 {
2497   go_assert(this->gc_symbol_var_ == NULL);
2498 
2499   Named_type* nt = this->named_type();
2500 
2501   // We can have multiple instances of unnamed types and similar to type
2502   // descriptors, we only want to the emit the GC data once, so we use a
2503   // hash table.
2504   Bvariable** phash = NULL;
2505   if (nt == NULL)
2506     {
2507       Bvariable* bvnull = NULL;
2508       std::pair<GC_symbol_vars::iterator, bool> ins =
2509 	Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2510       if (!ins.second)
2511 	{
2512 	  // We've already built a gc symbol for this type.
2513 	  this->gc_symbol_var_ = ins.first->second;
2514 	  return;
2515 	}
2516       phash = &ins.first->second;
2517     }
2518 
2519   int64_t ptrsize;
2520   int64_t ptrdata;
2521   if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2522     {
2523       this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2524       if (phash != NULL)
2525 	*phash = this->gc_symbol_var_;
2526       return;
2527     }
2528 
2529   std::string sym_name = gogo->gc_symbol_name(this);
2530 
2531   // Build the contents of the gc symbol.
2532   Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2533   Btype* sym_btype = sym_init->type()->get_backend(gogo);
2534 
2535   // If the type descriptor for this type is defined somewhere else, so is the
2536   // GC symbol.
2537   const Package* dummy;
2538   if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2539     {
2540       std::string asm_name(go_selectively_encode_id(sym_name));
2541       this->gc_symbol_var_ =
2542           gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2543                                                        sym_btype);
2544       if (phash != NULL)
2545 	*phash = this->gc_symbol_var_;
2546       return;
2547     }
2548 
2549   // See if this gc symbol can appear in multiple packages.
2550   bool is_common = false;
2551   if (nt != NULL)
2552     {
2553       // We create the symbol for a builtin type whenever we need
2554       // it.
2555       is_common = nt->is_builtin();
2556     }
2557   else
2558     {
2559       // This is an unnamed type.  The descriptor could be defined in
2560       // any package where it is needed, and the linker will pick one
2561       // descriptor to keep.
2562       is_common = true;
2563     }
2564 
2565   // Since we are building the GC symbol in this package, we must create the
2566   // variable before converting the initializer to its backend representation
2567   // because the initializer may refer to the GC symbol for this type.
2568   std::string asm_name(go_selectively_encode_id(sym_name));
2569   this->gc_symbol_var_ =
2570       gogo->backend()->implicit_variable(sym_name, asm_name,
2571 					 sym_btype, false, true, is_common, 0);
2572   if (phash != NULL)
2573     *phash = this->gc_symbol_var_;
2574 
2575   Translate_context context(gogo, NULL, NULL, NULL);
2576   context.set_is_const();
2577   Bexpression* sym_binit = sym_init->get_backend(&context);
2578   gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2579 					      sym_btype, false, true, is_common,
2580 					      sym_binit);
2581 }
2582 
2583 // Return whether this type needs a GC program, and set *PTRDATA to
2584 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2585 // pointer.
2586 
2587 bool
needs_gcprog(Gogo * gogo,int64_t * ptrsize,int64_t * ptrdata)2588 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2589 {
2590   Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2591   if (!voidptr->backend_type_size(gogo, ptrsize))
2592     go_unreachable();
2593 
2594   if (!this->backend_type_ptrdata(gogo, ptrdata))
2595     {
2596       go_assert(saw_errors());
2597       return false;
2598     }
2599 
2600   return *ptrdata / *ptrsize > max_ptrmask_bytes;
2601 }
2602 
2603 // A simple class used to build a GC ptrmask for a type.
2604 
2605 class Ptrmask
2606 {
2607  public:
Ptrmask(size_t count)2608   Ptrmask(size_t count)
2609     : bits_((count + 7) / 8, 0)
2610   {}
2611 
2612   void
2613   set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2614 
2615   std::string
2616   symname() const;
2617 
2618   Expression*
2619   constructor(Gogo* gogo) const;
2620 
2621  private:
2622   void
set(size_t index)2623   set(size_t index)
2624   { this->bits_.at(index / 8) |= 1 << (index % 8); }
2625 
2626   // The actual bits.
2627   std::vector<unsigned char> bits_;
2628 };
2629 
2630 // Set bits in ptrmask starting from OFFSET based on TYPE.  OFFSET
2631 // counts in bytes.  PTRSIZE is the size of a pointer on the target
2632 // system.
2633 
2634 void
set_from(Gogo * gogo,Type * type,int64_t ptrsize,int64_t offset)2635 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2636 {
2637   switch (type->base()->classification())
2638     {
2639     default:
2640     case Type::TYPE_NIL:
2641     case Type::TYPE_CALL_MULTIPLE_RESULT:
2642     case Type::TYPE_NAMED:
2643     case Type::TYPE_FORWARD:
2644       go_unreachable();
2645 
2646     case Type::TYPE_ERROR:
2647     case Type::TYPE_VOID:
2648     case Type::TYPE_BOOLEAN:
2649     case Type::TYPE_INTEGER:
2650     case Type::TYPE_FLOAT:
2651     case Type::TYPE_COMPLEX:
2652     case Type::TYPE_SINK:
2653       break;
2654 
2655     case Type::TYPE_FUNCTION:
2656     case Type::TYPE_POINTER:
2657     case Type::TYPE_MAP:
2658     case Type::TYPE_CHANNEL:
2659       // These types are all a single pointer.
2660       go_assert((offset % ptrsize) == 0);
2661       this->set(offset / ptrsize);
2662       break;
2663 
2664     case Type::TYPE_STRING:
2665       // A string starts with a single pointer.
2666       go_assert((offset % ptrsize) == 0);
2667       this->set(offset / ptrsize);
2668       break;
2669 
2670     case Type::TYPE_INTERFACE:
2671       // An interface is two pointers.
2672       go_assert((offset % ptrsize) == 0);
2673       this->set(offset / ptrsize);
2674       this->set((offset / ptrsize) + 1);
2675       break;
2676 
2677     case Type::TYPE_STRUCT:
2678       {
2679 	if (!type->has_pointer())
2680 	  return;
2681 
2682 	const Struct_field_list* fields = type->struct_type()->fields();
2683 	int64_t soffset = 0;
2684 	for (Struct_field_list::const_iterator pf = fields->begin();
2685 	     pf != fields->end();
2686 	     ++pf)
2687 	  {
2688 	    int64_t field_align;
2689 	    if (!pf->type()->backend_type_field_align(gogo, &field_align))
2690 	      {
2691 		go_assert(saw_errors());
2692 		return;
2693 	      }
2694 	    soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2695 
2696 	    this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2697 
2698 	    int64_t field_size;
2699 	    if (!pf->type()->backend_type_size(gogo, &field_size))
2700 	      {
2701 		go_assert(saw_errors());
2702 		return;
2703 	      }
2704 	    soffset += field_size;
2705 	  }
2706       }
2707       break;
2708 
2709     case Type::TYPE_ARRAY:
2710       if (type->is_slice_type())
2711 	{
2712 	  // A slice starts with a single pointer.
2713 	  go_assert((offset % ptrsize) == 0);
2714 	  this->set(offset / ptrsize);
2715 	  break;
2716 	}
2717       else
2718 	{
2719 	  if (!type->has_pointer())
2720 	    return;
2721 
2722 	  int64_t len;
2723 	  if (!type->array_type()->int_length(&len))
2724 	    {
2725 	      go_assert(saw_errors());
2726 	      return;
2727 	    }
2728 
2729 	  Type* element_type = type->array_type()->element_type();
2730 	  int64_t ele_size;
2731 	  if (!element_type->backend_type_size(gogo, &ele_size))
2732 	    {
2733 	      go_assert(saw_errors());
2734 	      return;
2735 	    }
2736 
2737 	  int64_t eoffset = 0;
2738 	  for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2739 	    this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2740 	  break;
2741 	}
2742     }
2743 }
2744 
2745 // Return a symbol name for this ptrmask.  This is used to coalesce
2746 // identical ptrmasks, which are common.  The symbol name must use
2747 // only characters that are valid in symbols.  It's nice if it's
2748 // short.  We convert it to a string that uses only 32 characters,
2749 // avoiding digits and u and U.
2750 
2751 std::string
symname() const2752 Ptrmask::symname() const
2753 {
2754   const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2755   go_assert(chars[32] == '\0');
2756   std::string ret;
2757   unsigned int b = 0;
2758   int remaining = 0;
2759   for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2760        p != this->bits_.end();
2761        ++p)
2762     {
2763       b |= *p << remaining;
2764       remaining += 8;
2765       while (remaining >= 5)
2766 	{
2767 	  ret += chars[b & 0x1f];
2768 	  b >>= 5;
2769 	  remaining -= 5;
2770 	}
2771     }
2772   while (remaining > 0)
2773     {
2774       ret += chars[b & 0x1f];
2775       b >>= 5;
2776       remaining -= 5;
2777     }
2778   return ret;
2779 }
2780 
2781 // Return a constructor for this ptrmask.  This will be used to
2782 // initialize the runtime ptrmask value.
2783 
2784 Expression*
constructor(Gogo * gogo) const2785 Ptrmask::constructor(Gogo* gogo) const
2786 {
2787   Location bloc = Linemap::predeclared_location();
2788   Type* byte_type = gogo->lookup_global("byte")->type_value();
2789   Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2790 						bloc);
2791   Array_type* at = Type::make_array_type(byte_type, len);
2792   Expression_list* vals = new Expression_list();
2793   vals->reserve(this->bits_.size());
2794   for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2795        p != this->bits_.end();
2796        ++p)
2797     vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2798   return Expression::make_array_composite_literal(at, vals, bloc);
2799 }
2800 
2801 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2802 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2803 
2804 // Return a ptrmask variable for a type.  For a type descriptor this
2805 // is only used for variables that are small enough to not need a
2806 // gcprog, but for a global variable this is used for a variable of
2807 // any size.  PTRDATA is the number of bytes of the type that contain
2808 // pointer data.  PTRSIZE is the size of a pointer on the target
2809 // system.
2810 
2811 Bvariable*
gc_ptrmask_var(Gogo * gogo,int64_t ptrsize,int64_t ptrdata)2812 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2813 {
2814   Ptrmask ptrmask(ptrdata / ptrsize);
2815   if (ptrdata >= ptrsize)
2816     ptrmask.set_from(gogo, this, ptrsize, 0);
2817   else
2818     {
2819       // This can happen in error cases.  Just build an empty gcbits.
2820       go_assert(saw_errors());
2821     }
2822 
2823   std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2824   Bvariable* bvnull = NULL;
2825   std::pair<GC_gcbits_vars::iterator, bool> ins =
2826     Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2827   if (!ins.second)
2828     {
2829       // We've already built a GC symbol for this set of gcbits.
2830       return ins.first->second;
2831     }
2832 
2833   Expression* val = ptrmask.constructor(gogo);
2834   Translate_context context(gogo, NULL, NULL, NULL);
2835   context.set_is_const();
2836   Bexpression* bval = val->get_backend(&context);
2837 
2838   std::string asm_name(go_selectively_encode_id(sym_name));
2839   Btype *btype = val->type()->get_backend(gogo);
2840   Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2841 						      btype, false, true,
2842 						      true, 0);
2843   gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2844 					      true, true, bval);
2845   ins.first->second = ret;
2846   return ret;
2847 }
2848 
2849 // A GCProg is used to build a program for the garbage collector.
2850 // This is used for types with a lot of pointer data, to reduce the
2851 // size of the data in the compiled program.  The program is expanded
2852 // at runtime.  For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2853 
2854 class GCProg
2855 {
2856  public:
GCProg()2857   GCProg()
2858     : bytes_(), index_(0), nb_(0)
2859   {}
2860 
2861   // The number of bits described so far.
2862   int64_t
bit_index() const2863   bit_index() const
2864   { return this->index_; }
2865 
2866   void
2867   set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2868 
2869   void
2870   end();
2871 
2872   Expression*
2873   constructor(Gogo* gogo) const;
2874 
2875  private:
2876   void
2877   ptr(int64_t);
2878 
2879   bool
2880   should_repeat(int64_t, int64_t);
2881 
2882   void
2883   repeat(int64_t, int64_t);
2884 
2885   void
2886   zero_until(int64_t);
2887 
2888   void
2889   lit(unsigned char);
2890 
2891   void
2892   varint(int64_t);
2893 
2894   void
2895   flushlit();
2896 
2897   // Add a byte to the program.
2898   void
byte(unsigned char x)2899   byte(unsigned char x)
2900   { this->bytes_.push_back(x); }
2901 
2902   // The maximum number of bytes of literal bits.
2903   static const int max_literal = 127;
2904 
2905   // The program.
2906   std::vector<unsigned char> bytes_;
2907   // The index of the last bit described.
2908   int64_t index_;
2909   // The current set of literal bits.
2910   unsigned char b_[max_literal];
2911   // The current number of literal bits.
2912   int nb_;
2913 };
2914 
2915 // Set data in gcprog starting from OFFSET based on TYPE.  OFFSET
2916 // counts in bytes.  PTRSIZE is the size of a pointer on the target
2917 // system.
2918 
2919 void
set_from(Gogo * gogo,Type * type,int64_t ptrsize,int64_t offset)2920 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2921 {
2922   switch (type->base()->classification())
2923     {
2924     default:
2925     case Type::TYPE_NIL:
2926     case Type::TYPE_CALL_MULTIPLE_RESULT:
2927     case Type::TYPE_NAMED:
2928     case Type::TYPE_FORWARD:
2929       go_unreachable();
2930 
2931     case Type::TYPE_ERROR:
2932     case Type::TYPE_VOID:
2933     case Type::TYPE_BOOLEAN:
2934     case Type::TYPE_INTEGER:
2935     case Type::TYPE_FLOAT:
2936     case Type::TYPE_COMPLEX:
2937     case Type::TYPE_SINK:
2938       break;
2939 
2940     case Type::TYPE_FUNCTION:
2941     case Type::TYPE_POINTER:
2942     case Type::TYPE_MAP:
2943     case Type::TYPE_CHANNEL:
2944       // These types are all a single pointer.
2945       go_assert((offset % ptrsize) == 0);
2946       this->ptr(offset / ptrsize);
2947       break;
2948 
2949     case Type::TYPE_STRING:
2950       // A string starts with a single pointer.
2951       go_assert((offset % ptrsize) == 0);
2952       this->ptr(offset / ptrsize);
2953       break;
2954 
2955     case Type::TYPE_INTERFACE:
2956       // An interface is two pointers.
2957       go_assert((offset % ptrsize) == 0);
2958       this->ptr(offset / ptrsize);
2959       this->ptr((offset / ptrsize) + 1);
2960       break;
2961 
2962     case Type::TYPE_STRUCT:
2963       {
2964 	if (!type->has_pointer())
2965 	  return;
2966 
2967 	const Struct_field_list* fields = type->struct_type()->fields();
2968 	int64_t soffset = 0;
2969 	for (Struct_field_list::const_iterator pf = fields->begin();
2970 	     pf != fields->end();
2971 	     ++pf)
2972 	  {
2973 	    int64_t field_align;
2974 	    if (!pf->type()->backend_type_field_align(gogo, &field_align))
2975 	      {
2976 		go_assert(saw_errors());
2977 		return;
2978 	      }
2979 	    soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2980 
2981 	    this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2982 
2983 	    int64_t field_size;
2984 	    if (!pf->type()->backend_type_size(gogo, &field_size))
2985 	      {
2986 		go_assert(saw_errors());
2987 		return;
2988 	      }
2989 	    soffset += field_size;
2990 	  }
2991       }
2992       break;
2993 
2994     case Type::TYPE_ARRAY:
2995       if (type->is_slice_type())
2996 	{
2997 	  // A slice starts with a single pointer.
2998 	  go_assert((offset % ptrsize) == 0);
2999 	  this->ptr(offset / ptrsize);
3000 	  break;
3001 	}
3002       else
3003 	{
3004 	  if (!type->has_pointer())
3005 	    return;
3006 
3007 	  int64_t len;
3008 	  if (!type->array_type()->int_length(&len))
3009 	    {
3010 	      go_assert(saw_errors());
3011 	      return;
3012 	    }
3013 
3014 	  Type* element_type = type->array_type()->element_type();
3015 
3016 	  // Flatten array of array to a big array by multiplying counts.
3017 	  while (element_type->array_type() != NULL
3018 		 && !element_type->is_slice_type())
3019 	    {
3020 	      int64_t ele_len;
3021 	      if (!element_type->array_type()->int_length(&ele_len))
3022 		{
3023 		  go_assert(saw_errors());
3024 		  return;
3025 		}
3026 
3027 	      len *= ele_len;
3028 	      element_type = element_type->array_type()->element_type();
3029 	    }
3030 
3031 	  int64_t ele_size;
3032 	  if (!element_type->backend_type_size(gogo, &ele_size))
3033 	    {
3034 	      go_assert(saw_errors());
3035 	      return;
3036 	    }
3037 
3038 	  go_assert(len > 0 && ele_size > 0);
3039 
3040 	  if (!this->should_repeat(ele_size / ptrsize, len))
3041 	    {
3042 	      // Cheaper to just emit the bits.
3043 	      int64_t eoffset = 0;
3044 	      for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3045 		this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3046 	    }
3047 	  else
3048 	    {
3049 	      go_assert((offset % ptrsize) == 0);
3050 	      go_assert((ele_size % ptrsize) == 0);
3051 	      this->set_from(gogo, element_type, ptrsize, offset);
3052 	      this->zero_until((offset + ele_size) / ptrsize);
3053 	      this->repeat(ele_size / ptrsize, len - 1);
3054 	    }
3055 
3056 	  break;
3057 	}
3058     }
3059 }
3060 
3061 // Emit a 1 into the bit stream of a GC program at the given bit index.
3062 
3063 void
ptr(int64_t index)3064 GCProg::ptr(int64_t index)
3065 {
3066   go_assert(index >= this->index_);
3067   this->zero_until(index);
3068   this->lit(1);
3069 }
3070 
3071 // Return whether it is worthwhile to use a repeat to describe c
3072 // elements of n bits each, compared to just emitting c copies of the
3073 // n-bit description.
3074 
3075 bool
should_repeat(int64_t n,int64_t c)3076 GCProg::should_repeat(int64_t n, int64_t c)
3077 {
3078   // Repeat if there is more than 1 item and if the total data doesn't
3079   // fit into four bytes.
3080   return c > 1 && c * n > 4 * 8;
3081 }
3082 
3083 // Emit an instruction to repeat the description of the last n words c
3084 // times (including the initial description, so c + 1 times in total).
3085 
3086 void
repeat(int64_t n,int64_t c)3087 GCProg::repeat(int64_t n, int64_t c)
3088 {
3089   if (n == 0 || c == 0)
3090     return;
3091   this->flushlit();
3092   if (n < 128)
3093     this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3094   else
3095     {
3096       this->byte(0x80);
3097       this->varint(n);
3098     }
3099   this->varint(c);
3100   this->index_ += n * c;
3101 }
3102 
3103 // Add zeros to the bit stream up to the given index.
3104 
3105 void
zero_until(int64_t index)3106 GCProg::zero_until(int64_t index)
3107 {
3108   go_assert(index >= this->index_);
3109   int64_t skip = index - this->index_;
3110   if (skip == 0)
3111     return;
3112   if (skip < 4 * 8)
3113     {
3114       for (int64_t i = 0; i < skip; ++i)
3115 	this->lit(0);
3116       return;
3117     }
3118   this->lit(0);
3119   this->flushlit();
3120   this->repeat(1, skip - 1);
3121 }
3122 
3123 // Add a single literal bit to the program.
3124 
3125 void
lit(unsigned char x)3126 GCProg::lit(unsigned char x)
3127 {
3128   if (this->nb_ == GCProg::max_literal)
3129     this->flushlit();
3130   this->b_[this->nb_] = x;
3131   ++this->nb_;
3132   ++this->index_;
3133 }
3134 
3135 // Emit the varint encoding of x.
3136 
3137 void
varint(int64_t x)3138 GCProg::varint(int64_t x)
3139 {
3140   go_assert(x >= 0);
3141   while (x >= 0x80)
3142     {
3143       this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3144       x >>= 7;
3145     }
3146   this->byte(static_cast<unsigned char>(x & 0x7f));
3147 }
3148 
3149 // Flush any pending literal bits.
3150 
3151 void
flushlit()3152 GCProg::flushlit()
3153 {
3154   if (this->nb_ == 0)
3155     return;
3156   this->byte(static_cast<unsigned char>(this->nb_));
3157   unsigned char bits = 0;
3158   for (int i = 0; i < this->nb_; ++i)
3159     {
3160       bits |= this->b_[i] << (i % 8);
3161       if ((i + 1) % 8 == 0)
3162 	{
3163 	  this->byte(bits);
3164 	  bits = 0;
3165 	}
3166     }
3167   if (this->nb_ % 8 != 0)
3168     this->byte(bits);
3169   this->nb_ = 0;
3170 }
3171 
3172 // Mark the end of a GC program.
3173 
3174 void
end()3175 GCProg::end()
3176 {
3177   this->flushlit();
3178   this->byte(0);
3179 }
3180 
3181 // Return an Expression for the bytes in a GC program.
3182 
3183 Expression*
constructor(Gogo * gogo) const3184 GCProg::constructor(Gogo* gogo) const
3185 {
3186   Location bloc = Linemap::predeclared_location();
3187 
3188   // The first four bytes are the length of the program in target byte
3189   // order.  Build a struct whose first type is uint32 to make this
3190   // work.
3191 
3192   Type* uint32_type = Type::lookup_integer_type("uint32");
3193 
3194   Type* byte_type = gogo->lookup_global("byte")->type_value();
3195   Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3196 						bloc);
3197   Array_type* at = Type::make_array_type(byte_type, len);
3198 
3199   Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3200 						   "bytes", at);
3201 
3202   Expression_list* vals = new Expression_list();
3203   vals->reserve(this->bytes_.size());
3204   for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3205        p != this->bytes_.end();
3206        ++p)
3207     vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3208   Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3209 
3210   vals = new Expression_list();
3211   vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3212 					      bloc));
3213   vals->push_back(bytes);
3214 
3215   return Expression::make_struct_composite_literal(st, vals, bloc);
3216 }
3217 
3218 // Return a composite literal for the garbage collection program for
3219 // this type.  This is only used for types that are too large to use a
3220 // ptrmask.
3221 
3222 Expression*
gcprog_constructor(Gogo * gogo,int64_t ptrsize,int64_t ptrdata)3223 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3224 {
3225   Location bloc = Linemap::predeclared_location();
3226 
3227   GCProg prog;
3228   prog.set_from(gogo, this, ptrsize, 0);
3229   int64_t offset = prog.bit_index() * ptrsize;
3230   prog.end();
3231 
3232   int64_t type_size;
3233   if (!this->backend_type_size(gogo, &type_size))
3234     {
3235       go_assert(saw_errors());
3236       return Expression::make_error(bloc);
3237     }
3238 
3239   go_assert(offset >= ptrdata && offset <= type_size);
3240 
3241   return prog.constructor(gogo);
3242 }
3243 
3244 // Return a composite literal for the uncommon type information for
3245 // this type.  UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3246 // struct.  If name is not NULL, it is the name of the type.  If
3247 // METHODS is not NULL, it is the list of methods.  ONLY_VALUE_METHODS
3248 // is true if only value methods should be included.  At least one of
3249 // NAME and METHODS must not be NULL.
3250 
3251 Expression*
uncommon_type_constructor(Gogo * gogo,Type * uncommon_type,Named_type * name,const Methods * methods,bool only_value_methods) const3252 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3253 				Named_type* name, const Methods* methods,
3254 				bool only_value_methods) const
3255 {
3256   Location bloc = Linemap::predeclared_location();
3257 
3258   const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3259 
3260   Expression_list* vals = new Expression_list();
3261   vals->reserve(3);
3262 
3263   Struct_field_list::const_iterator p = fields->begin();
3264   go_assert(p->is_field_name("name"));
3265 
3266   ++p;
3267   go_assert(p->is_field_name("pkgPath"));
3268 
3269   if (name == NULL)
3270     {
3271       vals->push_back(Expression::make_nil(bloc));
3272       vals->push_back(Expression::make_nil(bloc));
3273     }
3274   else
3275     {
3276       Named_object* no = name->named_object();
3277       std::string n = Gogo::unpack_hidden_name(no->name());
3278       Expression* s = Expression::make_string(n, bloc);
3279       vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3280 
3281       if (name->is_builtin())
3282 	vals->push_back(Expression::make_nil(bloc));
3283       else
3284 	{
3285 	  const Package* package = no->package();
3286 	  const std::string& pkgpath(package == NULL
3287 				     ? gogo->pkgpath()
3288 				     : package->pkgpath());
3289 	  s = Expression::make_string(pkgpath, bloc);
3290 	  vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3291 	}
3292     }
3293 
3294   ++p;
3295   go_assert(p->is_field_name("methods"));
3296   vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3297 					    only_value_methods));
3298 
3299   ++p;
3300   go_assert(p == fields->end());
3301 
3302   Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3303 							    vals, bloc);
3304   return Expression::make_unary(OPERATOR_AND, r, bloc);
3305 }
3306 
3307 // Sort methods by name.
3308 
3309 class Sort_methods
3310 {
3311  public:
3312   bool
operator ()(const std::pair<std::string,const Method * > & m1,const std::pair<std::string,const Method * > & m2) const3313   operator()(const std::pair<std::string, const Method*>& m1,
3314 	     const std::pair<std::string, const Method*>& m2) const
3315   {
3316     return (Gogo::unpack_hidden_name(m1.first)
3317 	    < Gogo::unpack_hidden_name(m2.first));
3318   }
3319 };
3320 
3321 // Return a composite literal for the type method table for this type.
3322 // METHODS_TYPE is the type of the table, and is a slice type.
3323 // METHODS is the list of methods.  If ONLY_VALUE_METHODS is true,
3324 // then only value methods are used.
3325 
3326 Expression*
methods_constructor(Gogo * gogo,Type * methods_type,const Methods * methods,bool only_value_methods) const3327 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3328 			  const Methods* methods,
3329 			  bool only_value_methods) const
3330 {
3331   Location bloc = Linemap::predeclared_location();
3332 
3333   std::vector<std::pair<std::string, const Method*> > smethods;
3334   if (methods != NULL)
3335     {
3336       smethods.reserve(methods->count());
3337       for (Methods::const_iterator p = methods->begin();
3338 	   p != methods->end();
3339 	   ++p)
3340 	{
3341 	  if (p->second->is_ambiguous())
3342 	    continue;
3343 	  if (only_value_methods && !p->second->is_value_method())
3344 	    continue;
3345 
3346 	  // This is where we implement the magic //go:nointerface
3347 	  // comment.  If we saw that comment, we don't add this
3348 	  // method to the type descriptor.
3349 	  if (p->second->nointerface())
3350 	    continue;
3351 
3352 	  smethods.push_back(std::make_pair(p->first, p->second));
3353 	}
3354     }
3355 
3356   if (smethods.empty())
3357     return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3358 
3359   std::sort(smethods.begin(), smethods.end(), Sort_methods());
3360 
3361   Type* method_type = methods_type->array_type()->element_type();
3362 
3363   Expression_list* vals = new Expression_list();
3364   vals->reserve(smethods.size());
3365   for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3366 	 = smethods.begin();
3367        p != smethods.end();
3368        ++p)
3369     vals->push_back(this->method_constructor(gogo, method_type, p->first,
3370 					     p->second, only_value_methods));
3371 
3372   return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3373 }
3374 
3375 // Return a composite literal for a single method.  METHOD_TYPE is the
3376 // type of the entry.  METHOD_NAME is the name of the method and M is
3377 // the method information.
3378 
3379 Expression*
method_constructor(Gogo *,Type * method_type,const std::string & method_name,const Method * m,bool only_value_methods) const3380 Type::method_constructor(Gogo*, Type* method_type,
3381 			 const std::string& method_name,
3382 			 const Method* m,
3383 			 bool only_value_methods) const
3384 {
3385   Location bloc = Linemap::predeclared_location();
3386 
3387   const Struct_field_list* fields = method_type->struct_type()->fields();
3388 
3389   Expression_list* vals = new Expression_list();
3390   vals->reserve(5);
3391 
3392   Struct_field_list::const_iterator p = fields->begin();
3393   go_assert(p->is_field_name("name"));
3394   const std::string n = Gogo::unpack_hidden_name(method_name);
3395   Expression* s = Expression::make_string(n, bloc);
3396   vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3397 
3398   ++p;
3399   go_assert(p->is_field_name("pkgPath"));
3400   if (!Gogo::is_hidden_name(method_name))
3401     vals->push_back(Expression::make_nil(bloc));
3402   else
3403     {
3404       s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3405 				  bloc);
3406       vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3407     }
3408 
3409   Named_object* no = (m->needs_stub_method()
3410 		      ? m->stub_object()
3411 		      : m->named_object());
3412 
3413   Function_type* mtype;
3414   if (no->is_function())
3415     mtype = no->func_value()->type();
3416   else
3417     mtype = no->func_declaration_value()->type();
3418   go_assert(mtype->is_method());
3419   Type* nonmethod_type = mtype->copy_without_receiver();
3420 
3421   ++p;
3422   go_assert(p->is_field_name("mtyp"));
3423   vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3424 
3425   ++p;
3426   go_assert(p->is_field_name("typ"));
3427   bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3428   nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3429   vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3430 
3431   ++p;
3432   go_assert(p->is_field_name("tfn"));
3433   vals->push_back(Expression::make_func_code_reference(no, bloc));
3434 
3435   ++p;
3436   go_assert(p == fields->end());
3437 
3438   return Expression::make_struct_composite_literal(method_type, vals, bloc);
3439 }
3440 
3441 // Return a composite literal for the type descriptor of a plain type.
3442 // RUNTIME_TYPE_KIND is the value of the kind field.  If NAME is not
3443 // NULL, it is the name to use as well as the list of methods.
3444 
3445 Expression*
plain_type_descriptor(Gogo * gogo,int runtime_type_kind,Named_type * name)3446 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3447 			    Named_type* name)
3448 {
3449   return this->type_descriptor_constructor(gogo, runtime_type_kind,
3450 					   name, NULL, true);
3451 }
3452 
3453 // Return the type reflection string for this type.
3454 
3455 std::string
reflection(Gogo * gogo) const3456 Type::reflection(Gogo* gogo) const
3457 {
3458   std::string ret;
3459 
3460   // The do_reflection virtual function should set RET to the
3461   // reflection string.
3462   this->do_reflection(gogo, &ret);
3463 
3464   return ret;
3465 }
3466 
3467 // Return whether the backend size of the type is known.
3468 
3469 bool
is_backend_type_size_known(Gogo * gogo)3470 Type::is_backend_type_size_known(Gogo* gogo)
3471 {
3472   switch (this->classification_)
3473     {
3474     case TYPE_ERROR:
3475     case TYPE_VOID:
3476     case TYPE_BOOLEAN:
3477     case TYPE_INTEGER:
3478     case TYPE_FLOAT:
3479     case TYPE_COMPLEX:
3480     case TYPE_STRING:
3481     case TYPE_FUNCTION:
3482     case TYPE_POINTER:
3483     case TYPE_NIL:
3484     case TYPE_MAP:
3485     case TYPE_CHANNEL:
3486     case TYPE_INTERFACE:
3487       return true;
3488 
3489     case TYPE_STRUCT:
3490       {
3491 	const Struct_field_list* fields = this->struct_type()->fields();
3492 	for (Struct_field_list::const_iterator pf = fields->begin();
3493 	     pf != fields->end();
3494 	     ++pf)
3495 	  if (!pf->type()->is_backend_type_size_known(gogo))
3496 	    return false;
3497 	return true;
3498       }
3499 
3500     case TYPE_ARRAY:
3501       {
3502 	const Array_type* at = this->array_type();
3503 	if (at->length() == NULL)
3504 	  return true;
3505 	else
3506 	  {
3507 	    Numeric_constant nc;
3508 	    if (!at->length()->numeric_constant_value(&nc))
3509 	      return false;
3510 	    mpz_t ival;
3511 	    if (!nc.to_int(&ival))
3512 	      return false;
3513 	    mpz_clear(ival);
3514 	    return at->element_type()->is_backend_type_size_known(gogo);
3515 	  }
3516       }
3517 
3518     case TYPE_NAMED:
3519       this->named_type()->convert(gogo);
3520       return this->named_type()->is_named_backend_type_size_known();
3521 
3522     case TYPE_FORWARD:
3523       {
3524 	Forward_declaration_type* fdt = this->forward_declaration_type();
3525 	return fdt->real_type()->is_backend_type_size_known(gogo);
3526       }
3527 
3528     case TYPE_SINK:
3529     case TYPE_CALL_MULTIPLE_RESULT:
3530       go_unreachable();
3531 
3532     default:
3533       go_unreachable();
3534     }
3535 }
3536 
3537 // If the size of the type can be determined, set *PSIZE to the size
3538 // in bytes and return true.  Otherwise, return false.  This queries
3539 // the backend.
3540 
3541 bool
backend_type_size(Gogo * gogo,int64_t * psize)3542 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3543 {
3544   if (!this->is_backend_type_size_known(gogo))
3545     return false;
3546   if (this->is_error_type())
3547     return false;
3548   Btype* bt = this->get_backend_placeholder(gogo);
3549   *psize = gogo->backend()->type_size(bt);
3550   if (*psize == -1)
3551     {
3552       if (this->named_type() != NULL)
3553 	go_error_at(this->named_type()->location(),
3554 		 "type %s larger than address space",
3555 		 Gogo::message_name(this->named_type()->name()).c_str());
3556       else
3557 	go_error_at(Linemap::unknown_location(),
3558 		    "type %s larger than address space",
3559 		    this->reflection(gogo).c_str());
3560 
3561       // Make this an error type to avoid knock-on errors.
3562       this->classification_ = TYPE_ERROR;
3563       return false;
3564     }
3565   return true;
3566 }
3567 
3568 // If the alignment of the type can be determined, set *PALIGN to
3569 // the alignment in bytes and return true.  Otherwise, return false.
3570 
3571 bool
backend_type_align(Gogo * gogo,int64_t * palign)3572 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3573 {
3574   if (!this->is_backend_type_size_known(gogo))
3575     return false;
3576   Btype* bt = this->get_backend_placeholder(gogo);
3577   *palign = gogo->backend()->type_alignment(bt);
3578   return true;
3579 }
3580 
3581 // Like backend_type_align, but return the alignment when used as a
3582 // field.
3583 
3584 bool
backend_type_field_align(Gogo * gogo,int64_t * palign)3585 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3586 {
3587   if (!this->is_backend_type_size_known(gogo))
3588     return false;
3589   Btype* bt = this->get_backend_placeholder(gogo);
3590   *palign = gogo->backend()->type_field_alignment(bt);
3591   return true;
3592 }
3593 
3594 // Get the ptrdata value for a type.  This is the size of the prefix
3595 // of the type that contains all pointers.  Store the ptrdata in
3596 // *PPTRDATA and return whether we found it.
3597 
3598 bool
backend_type_ptrdata(Gogo * gogo,int64_t * pptrdata)3599 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3600 {
3601   *pptrdata = 0;
3602 
3603   if (!this->has_pointer())
3604     return true;
3605 
3606   if (!this->is_backend_type_size_known(gogo))
3607     return false;
3608 
3609   switch (this->classification_)
3610     {
3611     case TYPE_ERROR:
3612       return true;
3613 
3614     case TYPE_FUNCTION:
3615     case TYPE_POINTER:
3616     case TYPE_MAP:
3617     case TYPE_CHANNEL:
3618       // These types are nothing but a pointer.
3619       return this->backend_type_size(gogo, pptrdata);
3620 
3621     case TYPE_INTERFACE:
3622       // An interface is a struct of two pointers.
3623       return this->backend_type_size(gogo, pptrdata);
3624 
3625     case TYPE_STRING:
3626       {
3627 	// A string is a struct whose first field is a pointer, and
3628 	// whose second field is not.
3629 	Type* uint8_type = Type::lookup_integer_type("uint8");
3630 	Type* ptr = Type::make_pointer_type(uint8_type);
3631 	return ptr->backend_type_size(gogo, pptrdata);
3632       }
3633 
3634     case TYPE_NAMED:
3635     case TYPE_FORWARD:
3636       return this->base()->backend_type_ptrdata(gogo, pptrdata);
3637 
3638     case TYPE_STRUCT:
3639       {
3640 	const Struct_field_list* fields = this->struct_type()->fields();
3641 	int64_t offset = 0;
3642 	const Struct_field *ptr = NULL;
3643 	int64_t ptr_offset = 0;
3644 	for (Struct_field_list::const_iterator pf = fields->begin();
3645 	     pf != fields->end();
3646 	     ++pf)
3647 	  {
3648 	    int64_t field_align;
3649 	    if (!pf->type()->backend_type_field_align(gogo, &field_align))
3650 	      return false;
3651 	    offset = (offset + (field_align - 1)) &~ (field_align - 1);
3652 
3653 	    if (pf->type()->has_pointer())
3654 	      {
3655 		ptr = &*pf;
3656 		ptr_offset = offset;
3657 	      }
3658 
3659 	    int64_t field_size;
3660 	    if (!pf->type()->backend_type_size(gogo, &field_size))
3661 	      return false;
3662 	    offset += field_size;
3663 	  }
3664 
3665 	if (ptr != NULL)
3666 	  {
3667 	    int64_t ptr_ptrdata;
3668 	    if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3669 	      return false;
3670 	    *pptrdata = ptr_offset + ptr_ptrdata;
3671 	  }
3672 	return true;
3673       }
3674 
3675     case TYPE_ARRAY:
3676       if (this->is_slice_type())
3677 	{
3678 	  // A slice is a struct whose first field is a pointer, and
3679 	  // whose remaining fields are not.
3680 	  Type* element_type = this->array_type()->element_type();
3681 	  Type* ptr = Type::make_pointer_type(element_type);
3682 	  return ptr->backend_type_size(gogo, pptrdata);
3683 	}
3684       else
3685 	{
3686 	  Numeric_constant nc;
3687 	  if (!this->array_type()->length()->numeric_constant_value(&nc))
3688 	    return false;
3689 	  int64_t len;
3690 	  if (!nc.to_memory_size(&len))
3691 	    return false;
3692 
3693 	  Type* element_type = this->array_type()->element_type();
3694 	  int64_t ele_size;
3695 	  int64_t ele_ptrdata;
3696 	  if (!element_type->backend_type_size(gogo, &ele_size)
3697 	      || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3698 	    return false;
3699 	  go_assert(ele_size > 0 && ele_ptrdata > 0);
3700 
3701 	  *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3702 	  return true;
3703 	}
3704 
3705     default:
3706     case TYPE_VOID:
3707     case TYPE_BOOLEAN:
3708     case TYPE_INTEGER:
3709     case TYPE_FLOAT:
3710     case TYPE_COMPLEX:
3711     case TYPE_SINK:
3712     case TYPE_NIL:
3713     case TYPE_CALL_MULTIPLE_RESULT:
3714       go_unreachable();
3715     }
3716 }
3717 
3718 // Get the ptrdata value to store in a type descriptor.  This is
3719 // normally the same as backend_type_ptrdata, but for a type that is
3720 // large enough to use a gcprog we may need to store a different value
3721 // if it ends with an array.  If the gcprog uses a repeat descriptor
3722 // for the array, and if the array element ends with non-pointer data,
3723 // then the gcprog will produce a value that describes the complete
3724 // array where the backend ptrdata will omit the non-pointer elements
3725 // of the final array element.  This is a subtle difference but the
3726 // run time code checks it to verify that it has expanded a gcprog as
3727 // expected.
3728 
3729 bool
descriptor_ptrdata(Gogo * gogo,int64_t * pptrdata)3730 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3731 {
3732   int64_t backend_ptrdata;
3733   if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3734     return false;
3735 
3736   int64_t ptrsize;
3737   if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3738     {
3739       *pptrdata = backend_ptrdata;
3740       return true;
3741     }
3742 
3743   GCProg prog;
3744   prog.set_from(gogo, this, ptrsize, 0);
3745   int64_t offset = prog.bit_index() * ptrsize;
3746 
3747   go_assert(offset >= backend_ptrdata);
3748   *pptrdata = offset;
3749   return true;
3750 }
3751 
3752 // Default function to export a type.
3753 
3754 void
do_export(Export *) const3755 Type::do_export(Export*) const
3756 {
3757   go_unreachable();
3758 }
3759 
3760 // Import a type.
3761 
3762 Type*
import_type(Import * imp)3763 Type::import_type(Import* imp)
3764 {
3765   if (imp->match_c_string("("))
3766     return Function_type::do_import(imp);
3767   else if (imp->match_c_string("*"))
3768     return Pointer_type::do_import(imp);
3769   else if (imp->match_c_string("struct "))
3770     return Struct_type::do_import(imp);
3771   else if (imp->match_c_string("["))
3772     return Array_type::do_import(imp);
3773   else if (imp->match_c_string("map "))
3774     return Map_type::do_import(imp);
3775   else if (imp->match_c_string("chan "))
3776     return Channel_type::do_import(imp);
3777   else if (imp->match_c_string("interface"))
3778     return Interface_type::do_import(imp);
3779   else
3780     {
3781       go_error_at(imp->location(), "import error: expected type");
3782       return Type::make_error_type();
3783     }
3784 }
3785 
3786 // Class Error_type.
3787 
3788 // Return the backend representation of an Error type.
3789 
3790 Btype*
do_get_backend(Gogo * gogo)3791 Error_type::do_get_backend(Gogo* gogo)
3792 {
3793   return gogo->backend()->error_type();
3794 }
3795 
3796 // Return an expression for the type descriptor for an error type.
3797 
3798 
3799 Expression*
do_type_descriptor(Gogo *,Named_type *)3800 Error_type::do_type_descriptor(Gogo*, Named_type*)
3801 {
3802   return Expression::make_error(Linemap::predeclared_location());
3803 }
3804 
3805 // We should not be asked for the reflection string for an error type.
3806 
3807 void
do_reflection(Gogo *,std::string *) const3808 Error_type::do_reflection(Gogo*, std::string*) const
3809 {
3810   go_assert(saw_errors());
3811 }
3812 
3813 Type*
make_error_type()3814 Type::make_error_type()
3815 {
3816   static Error_type singleton_error_type;
3817   return &singleton_error_type;
3818 }
3819 
3820 // Class Void_type.
3821 
3822 // Get the backend representation of a void type.
3823 
3824 Btype*
do_get_backend(Gogo * gogo)3825 Void_type::do_get_backend(Gogo* gogo)
3826 {
3827   return gogo->backend()->void_type();
3828 }
3829 
3830 Type*
make_void_type()3831 Type::make_void_type()
3832 {
3833   static Void_type singleton_void_type;
3834   return &singleton_void_type;
3835 }
3836 
3837 // Class Boolean_type.
3838 
3839 // Return the backend representation of the boolean type.
3840 
3841 Btype*
do_get_backend(Gogo * gogo)3842 Boolean_type::do_get_backend(Gogo* gogo)
3843 {
3844   return gogo->backend()->bool_type();
3845 }
3846 
3847 // Make the type descriptor.
3848 
3849 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)3850 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3851 {
3852   if (name != NULL)
3853     return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3854   else
3855     {
3856       Named_object* no = gogo->lookup_global("bool");
3857       go_assert(no != NULL);
3858       return Type::type_descriptor(gogo, no->type_value());
3859     }
3860 }
3861 
3862 Type*
make_boolean_type()3863 Type::make_boolean_type()
3864 {
3865   static Boolean_type boolean_type;
3866   return &boolean_type;
3867 }
3868 
3869 // The named type "bool".
3870 
3871 static Named_type* named_bool_type;
3872 
3873 // Get the named type "bool".
3874 
3875 Named_type*
lookup_bool_type()3876 Type::lookup_bool_type()
3877 {
3878   return named_bool_type;
3879 }
3880 
3881 // Make the named type "bool".
3882 
3883 Named_type*
make_named_bool_type()3884 Type::make_named_bool_type()
3885 {
3886   Type* bool_type = Type::make_boolean_type();
3887   Named_object* named_object =
3888     Named_object::make_type("bool", NULL, bool_type,
3889                             Linemap::predeclared_location());
3890   Named_type* named_type = named_object->type_value();
3891   named_bool_type = named_type;
3892   return named_type;
3893 }
3894 
3895 // Class Integer_type.
3896 
3897 Integer_type::Named_integer_types Integer_type::named_integer_types;
3898 
3899 // Create a new integer type.  Non-abstract integer types always have
3900 // names.
3901 
3902 Named_type*
create_integer_type(const char * name,bool is_unsigned,int bits,int runtime_type_kind)3903 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3904 				  int bits, int runtime_type_kind)
3905 {
3906   Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3907 						runtime_type_kind);
3908   std::string sname(name);
3909   Named_object* named_object =
3910     Named_object::make_type(sname, NULL, integer_type,
3911                             Linemap::predeclared_location());
3912   Named_type* named_type = named_object->type_value();
3913   std::pair<Named_integer_types::iterator, bool> ins =
3914     Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3915   go_assert(ins.second);
3916   return named_type;
3917 }
3918 
3919 // Look up an existing integer type.
3920 
3921 Named_type*
lookup_integer_type(const char * name)3922 Integer_type::lookup_integer_type(const char* name)
3923 {
3924   Named_integer_types::const_iterator p =
3925     Integer_type::named_integer_types.find(name);
3926   go_assert(p != Integer_type::named_integer_types.end());
3927   return p->second;
3928 }
3929 
3930 // Create a new abstract integer type.
3931 
3932 Integer_type*
create_abstract_integer_type()3933 Integer_type::create_abstract_integer_type()
3934 {
3935   static Integer_type* abstract_type;
3936   if (abstract_type == NULL)
3937     {
3938       Type* int_type = Type::lookup_integer_type("int");
3939       abstract_type = new Integer_type(true, false,
3940 				       int_type->integer_type()->bits(),
3941 				       RUNTIME_TYPE_KIND_INT);
3942     }
3943   return abstract_type;
3944 }
3945 
3946 // Create a new abstract character type.
3947 
3948 Integer_type*
create_abstract_character_type()3949 Integer_type::create_abstract_character_type()
3950 {
3951   static Integer_type* abstract_type;
3952   if (abstract_type == NULL)
3953     {
3954       abstract_type = new Integer_type(true, false, 32,
3955 				       RUNTIME_TYPE_KIND_INT32);
3956       abstract_type->set_is_rune();
3957     }
3958   return abstract_type;
3959 }
3960 
3961 // Integer type compatibility.
3962 
3963 bool
is_identical(const Integer_type * t) const3964 Integer_type::is_identical(const Integer_type* t) const
3965 {
3966   if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3967     return false;
3968   return this->is_abstract_ == t->is_abstract_;
3969 }
3970 
3971 // Hash code.
3972 
3973 unsigned int
do_hash_for_method(Gogo *) const3974 Integer_type::do_hash_for_method(Gogo*) const
3975 {
3976   return ((this->bits_ << 4)
3977 	  + ((this->is_unsigned_ ? 1 : 0) << 8)
3978 	  + ((this->is_abstract_ ? 1 : 0) << 9));
3979 }
3980 
3981 // Convert an Integer_type to the backend representation.
3982 
3983 Btype*
do_get_backend(Gogo * gogo)3984 Integer_type::do_get_backend(Gogo* gogo)
3985 {
3986   if (this->is_abstract_)
3987     {
3988       go_assert(saw_errors());
3989       return gogo->backend()->error_type();
3990     }
3991   return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
3992 }
3993 
3994 // The type descriptor for an integer type.  Integer types are always
3995 // named.
3996 
3997 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)3998 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3999 {
4000   go_assert(name != NULL || saw_errors());
4001   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4002 }
4003 
4004 // We should not be asked for the reflection string of a basic type.
4005 
4006 void
do_reflection(Gogo *,std::string *) const4007 Integer_type::do_reflection(Gogo*, std::string*) const
4008 {
4009   go_assert(saw_errors());
4010 }
4011 
4012 // Make an integer type.
4013 
4014 Named_type*
make_integer_type(const char * name,bool is_unsigned,int bits,int runtime_type_kind)4015 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4016 			int runtime_type_kind)
4017 {
4018   return Integer_type::create_integer_type(name, is_unsigned, bits,
4019 					   runtime_type_kind);
4020 }
4021 
4022 // Make an abstract integer type.
4023 
4024 Integer_type*
make_abstract_integer_type()4025 Type::make_abstract_integer_type()
4026 {
4027   return Integer_type::create_abstract_integer_type();
4028 }
4029 
4030 // Make an abstract character type.
4031 
4032 Integer_type*
make_abstract_character_type()4033 Type::make_abstract_character_type()
4034 {
4035   return Integer_type::create_abstract_character_type();
4036 }
4037 
4038 // Look up an integer type.
4039 
4040 Named_type*
lookup_integer_type(const char * name)4041 Type::lookup_integer_type(const char* name)
4042 {
4043   return Integer_type::lookup_integer_type(name);
4044 }
4045 
4046 // Class Float_type.
4047 
4048 Float_type::Named_float_types Float_type::named_float_types;
4049 
4050 // Create a new float type.  Non-abstract float types always have
4051 // names.
4052 
4053 Named_type*
create_float_type(const char * name,int bits,int runtime_type_kind)4054 Float_type::create_float_type(const char* name, int bits,
4055 			      int runtime_type_kind)
4056 {
4057   Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4058   std::string sname(name);
4059   Named_object* named_object =
4060     Named_object::make_type(sname, NULL, float_type,
4061                             Linemap::predeclared_location());
4062   Named_type* named_type = named_object->type_value();
4063   std::pair<Named_float_types::iterator, bool> ins =
4064     Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4065   go_assert(ins.second);
4066   return named_type;
4067 }
4068 
4069 // Look up an existing float type.
4070 
4071 Named_type*
lookup_float_type(const char * name)4072 Float_type::lookup_float_type(const char* name)
4073 {
4074   Named_float_types::const_iterator p =
4075     Float_type::named_float_types.find(name);
4076   go_assert(p != Float_type::named_float_types.end());
4077   return p->second;
4078 }
4079 
4080 // Create a new abstract float type.
4081 
4082 Float_type*
create_abstract_float_type()4083 Float_type::create_abstract_float_type()
4084 {
4085   static Float_type* abstract_type;
4086   if (abstract_type == NULL)
4087     abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4088   return abstract_type;
4089 }
4090 
4091 // Whether this type is identical with T.
4092 
4093 bool
is_identical(const Float_type * t) const4094 Float_type::is_identical(const Float_type* t) const
4095 {
4096   if (this->bits_ != t->bits_)
4097     return false;
4098   return this->is_abstract_ == t->is_abstract_;
4099 }
4100 
4101 // Hash code.
4102 
4103 unsigned int
do_hash_for_method(Gogo *) const4104 Float_type::do_hash_for_method(Gogo*) const
4105 {
4106   return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4107 }
4108 
4109 // Convert to the backend representation.
4110 
4111 Btype*
do_get_backend(Gogo * gogo)4112 Float_type::do_get_backend(Gogo* gogo)
4113 {
4114   return gogo->backend()->float_type(this->bits_);
4115 }
4116 
4117 // The type descriptor for a float type.  Float types are always named.
4118 
4119 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)4120 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4121 {
4122   go_assert(name != NULL || saw_errors());
4123   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4124 }
4125 
4126 // We should not be asked for the reflection string of a basic type.
4127 
4128 void
do_reflection(Gogo *,std::string *) const4129 Float_type::do_reflection(Gogo*, std::string*) const
4130 {
4131   go_assert(saw_errors());
4132 }
4133 
4134 // Make a floating point type.
4135 
4136 Named_type*
make_float_type(const char * name,int bits,int runtime_type_kind)4137 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4138 {
4139   return Float_type::create_float_type(name, bits, runtime_type_kind);
4140 }
4141 
4142 // Make an abstract float type.
4143 
4144 Float_type*
make_abstract_float_type()4145 Type::make_abstract_float_type()
4146 {
4147   return Float_type::create_abstract_float_type();
4148 }
4149 
4150 // Look up a float type.
4151 
4152 Named_type*
lookup_float_type(const char * name)4153 Type::lookup_float_type(const char* name)
4154 {
4155   return Float_type::lookup_float_type(name);
4156 }
4157 
4158 // Class Complex_type.
4159 
4160 Complex_type::Named_complex_types Complex_type::named_complex_types;
4161 
4162 // Create a new complex type.  Non-abstract complex types always have
4163 // names.
4164 
4165 Named_type*
create_complex_type(const char * name,int bits,int runtime_type_kind)4166 Complex_type::create_complex_type(const char* name, int bits,
4167 				  int runtime_type_kind)
4168 {
4169   Complex_type* complex_type = new Complex_type(false, bits,
4170 						runtime_type_kind);
4171   std::string sname(name);
4172   Named_object* named_object =
4173     Named_object::make_type(sname, NULL, complex_type,
4174                             Linemap::predeclared_location());
4175   Named_type* named_type = named_object->type_value();
4176   std::pair<Named_complex_types::iterator, bool> ins =
4177     Complex_type::named_complex_types.insert(std::make_pair(sname,
4178 							    named_type));
4179   go_assert(ins.second);
4180   return named_type;
4181 }
4182 
4183 // Look up an existing complex type.
4184 
4185 Named_type*
lookup_complex_type(const char * name)4186 Complex_type::lookup_complex_type(const char* name)
4187 {
4188   Named_complex_types::const_iterator p =
4189     Complex_type::named_complex_types.find(name);
4190   go_assert(p != Complex_type::named_complex_types.end());
4191   return p->second;
4192 }
4193 
4194 // Create a new abstract complex type.
4195 
4196 Complex_type*
create_abstract_complex_type()4197 Complex_type::create_abstract_complex_type()
4198 {
4199   static Complex_type* abstract_type;
4200   if (abstract_type == NULL)
4201     abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4202   return abstract_type;
4203 }
4204 
4205 // Whether this type is identical with T.
4206 
4207 bool
is_identical(const Complex_type * t) const4208 Complex_type::is_identical(const Complex_type *t) const
4209 {
4210   if (this->bits_ != t->bits_)
4211     return false;
4212   return this->is_abstract_ == t->is_abstract_;
4213 }
4214 
4215 // Hash code.
4216 
4217 unsigned int
do_hash_for_method(Gogo *) const4218 Complex_type::do_hash_for_method(Gogo*) const
4219 {
4220   return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4221 }
4222 
4223 // Convert to the backend representation.
4224 
4225 Btype*
do_get_backend(Gogo * gogo)4226 Complex_type::do_get_backend(Gogo* gogo)
4227 {
4228   return gogo->backend()->complex_type(this->bits_);
4229 }
4230 
4231 // The type descriptor for a complex type.  Complex types are always
4232 // named.
4233 
4234 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)4235 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4236 {
4237   go_assert(name != NULL || saw_errors());
4238   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4239 }
4240 
4241 // We should not be asked for the reflection string of a basic type.
4242 
4243 void
do_reflection(Gogo *,std::string *) const4244 Complex_type::do_reflection(Gogo*, std::string*) const
4245 {
4246   go_assert(saw_errors());
4247 }
4248 
4249 // Make a complex type.
4250 
4251 Named_type*
make_complex_type(const char * name,int bits,int runtime_type_kind)4252 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4253 {
4254   return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4255 }
4256 
4257 // Make an abstract complex type.
4258 
4259 Complex_type*
make_abstract_complex_type()4260 Type::make_abstract_complex_type()
4261 {
4262   return Complex_type::create_abstract_complex_type();
4263 }
4264 
4265 // Look up a complex type.
4266 
4267 Named_type*
lookup_complex_type(const char * name)4268 Type::lookup_complex_type(const char* name)
4269 {
4270   return Complex_type::lookup_complex_type(name);
4271 }
4272 
4273 // Class String_type.
4274 
4275 // Convert String_type to the backend representation.  A string is a
4276 // struct with two fields: a pointer to the characters and a length.
4277 
4278 Btype*
do_get_backend(Gogo * gogo)4279 String_type::do_get_backend(Gogo* gogo)
4280 {
4281   static Btype* backend_string_type;
4282   if (backend_string_type == NULL)
4283     {
4284       std::vector<Backend::Btyped_identifier> fields(2);
4285 
4286       Type* b = gogo->lookup_global("byte")->type_value();
4287       Type* pb = Type::make_pointer_type(b);
4288 
4289       // We aren't going to get back to this field to finish the
4290       // backend representation, so force it to be finished now.
4291       if (!gogo->named_types_are_converted())
4292 	{
4293 	  Btype* bt = pb->get_backend_placeholder(gogo);
4294 	  pb->finish_backend(gogo, bt);
4295 	}
4296 
4297       fields[0].name = "__data";
4298       fields[0].btype = pb->get_backend(gogo);
4299       fields[0].location = Linemap::predeclared_location();
4300 
4301       Type* int_type = Type::lookup_integer_type("int");
4302       fields[1].name = "__length";
4303       fields[1].btype = int_type->get_backend(gogo);
4304       fields[1].location = fields[0].location;
4305 
4306       backend_string_type = gogo->backend()->struct_type(fields);
4307     }
4308   return backend_string_type;
4309 }
4310 
4311 // The type descriptor for the string type.
4312 
4313 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)4314 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4315 {
4316   if (name != NULL)
4317     return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4318   else
4319     {
4320       Named_object* no = gogo->lookup_global("string");
4321       go_assert(no != NULL);
4322       return Type::type_descriptor(gogo, no->type_value());
4323     }
4324 }
4325 
4326 // We should not be asked for the reflection string of a basic type.
4327 
4328 void
do_reflection(Gogo *,std::string * ret) const4329 String_type::do_reflection(Gogo*, std::string* ret) const
4330 {
4331   ret->append("string");
4332 }
4333 
4334 // Make a string type.
4335 
4336 Type*
make_string_type()4337 Type::make_string_type()
4338 {
4339   static String_type string_type;
4340   return &string_type;
4341 }
4342 
4343 // The named type "string".
4344 
4345 static Named_type* named_string_type;
4346 
4347 // Get the named type "string".
4348 
4349 Named_type*
lookup_string_type()4350 Type::lookup_string_type()
4351 {
4352   return named_string_type;
4353 }
4354 
4355 // Make the named type string.
4356 
4357 Named_type*
make_named_string_type()4358 Type::make_named_string_type()
4359 {
4360   Type* string_type = Type::make_string_type();
4361   Named_object* named_object =
4362     Named_object::make_type("string", NULL, string_type,
4363                             Linemap::predeclared_location());
4364   Named_type* named_type = named_object->type_value();
4365   named_string_type = named_type;
4366   return named_type;
4367 }
4368 
4369 // The sink type.  This is the type of the blank identifier _.  Any
4370 // type may be assigned to it.
4371 
4372 class Sink_type : public Type
4373 {
4374  public:
Sink_type()4375   Sink_type()
4376     : Type(TYPE_SINK)
4377   { }
4378 
4379  protected:
4380   bool
do_compare_is_identity(Gogo *)4381   do_compare_is_identity(Gogo*)
4382   { return false; }
4383 
4384   Btype*
do_get_backend(Gogo *)4385   do_get_backend(Gogo*)
4386   { go_unreachable(); }
4387 
4388   Expression*
do_type_descriptor(Gogo *,Named_type *)4389   do_type_descriptor(Gogo*, Named_type*)
4390   { go_unreachable(); }
4391 
4392   void
do_reflection(Gogo *,std::string *) const4393   do_reflection(Gogo*, std::string*) const
4394   { go_unreachable(); }
4395 
4396   void
do_mangled_name(Gogo *,std::string *) const4397   do_mangled_name(Gogo*, std::string*) const
4398   { go_unreachable(); }
4399 };
4400 
4401 // Make the sink type.
4402 
4403 Type*
make_sink_type()4404 Type::make_sink_type()
4405 {
4406   static Sink_type sink_type;
4407   return &sink_type;
4408 }
4409 
4410 // Class Function_type.
4411 
4412 // Traversal.
4413 
4414 int
do_traverse(Traverse * traverse)4415 Function_type::do_traverse(Traverse* traverse)
4416 {
4417   if (this->receiver_ != NULL
4418       && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4419     return TRAVERSE_EXIT;
4420   if (this->parameters_ != NULL
4421       && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4422     return TRAVERSE_EXIT;
4423   if (this->results_ != NULL
4424       && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4425     return TRAVERSE_EXIT;
4426   return TRAVERSE_CONTINUE;
4427 }
4428 
4429 // Returns whether T is a valid redeclaration of this type.  If this
4430 // returns false, and REASON is not NULL, *REASON may be set to a
4431 // brief explanation of why it returned false.
4432 
4433 bool
is_valid_redeclaration(const Function_type * t,std::string * reason) const4434 Function_type::is_valid_redeclaration(const Function_type* t,
4435 				      std::string* reason) const
4436 {
4437   if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4438     return false;
4439 
4440   // A redeclaration of a function is required to use the same names
4441   // for the receiver and parameters.
4442   if (this->receiver() != NULL
4443       && this->receiver()->name() != t->receiver()->name())
4444     {
4445       if (reason != NULL)
4446 	*reason = "receiver name changed";
4447       return false;
4448     }
4449 
4450   const Typed_identifier_list* parms1 = this->parameters();
4451   const Typed_identifier_list* parms2 = t->parameters();
4452   if (parms1 != NULL)
4453     {
4454       Typed_identifier_list::const_iterator p1 = parms1->begin();
4455       for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4456 	   p2 != parms2->end();
4457 	   ++p2, ++p1)
4458 	{
4459 	  if (p1->name() != p2->name())
4460 	    {
4461 	      if (reason != NULL)
4462 		*reason = "parameter name changed";
4463 	      return false;
4464 	    }
4465 
4466 	  // This is called at parse time, so we may have unknown
4467 	  // types.
4468 	  Type* t1 = p1->type()->forwarded();
4469 	  Type* t2 = p2->type()->forwarded();
4470 	  if (t1 != t2
4471 	      && t1->forward_declaration_type() != NULL
4472 	      && (t2->forward_declaration_type() == NULL
4473 		  || (t1->forward_declaration_type()->named_object()
4474 		      != t2->forward_declaration_type()->named_object())))
4475 	    return false;
4476 	}
4477     }
4478 
4479   const Typed_identifier_list* results1 = this->results();
4480   const Typed_identifier_list* results2 = t->results();
4481   if (results1 != NULL)
4482     {
4483       Typed_identifier_list::const_iterator res1 = results1->begin();
4484       for (Typed_identifier_list::const_iterator res2 = results2->begin();
4485 	   res2 != results2->end();
4486 	   ++res2, ++res1)
4487 	{
4488 	  if (res1->name() != res2->name())
4489 	    {
4490 	      if (reason != NULL)
4491 		*reason = "result name changed";
4492 	      return false;
4493 	    }
4494 
4495 	  // This is called at parse time, so we may have unknown
4496 	  // types.
4497 	  Type* t1 = res1->type()->forwarded();
4498 	  Type* t2 = res2->type()->forwarded();
4499 	  if (t1 != t2
4500 	      && t1->forward_declaration_type() != NULL
4501 	      && (t2->forward_declaration_type() == NULL
4502 		  || (t1->forward_declaration_type()->named_object()
4503 		      != t2->forward_declaration_type()->named_object())))
4504 	    return false;
4505 	}
4506     }
4507 
4508   return true;
4509 }
4510 
4511 // Check whether T is the same as this type.
4512 
4513 bool
is_identical(const Function_type * t,bool ignore_receiver,Cmp_tags cmp_tags,bool errors_are_identical,std::string * reason) const4514 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4515 			    Cmp_tags cmp_tags, bool errors_are_identical,
4516 			    std::string* reason) const
4517 {
4518   if (this->is_backend_function_type() != t->is_backend_function_type())
4519     return false;
4520 
4521   if (!ignore_receiver)
4522     {
4523       const Typed_identifier* r1 = this->receiver();
4524       const Typed_identifier* r2 = t->receiver();
4525       if ((r1 != NULL) != (r2 != NULL))
4526 	{
4527 	  if (reason != NULL)
4528 	    *reason = _("different receiver types");
4529 	  return false;
4530 	}
4531       if (r1 != NULL)
4532 	{
4533 	  if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4534 					    errors_are_identical, reason))
4535 	    {
4536 	      if (reason != NULL && !reason->empty())
4537 		*reason = "receiver: " + *reason;
4538 	      return false;
4539 	    }
4540 	}
4541     }
4542 
4543   const Typed_identifier_list* parms1 = this->parameters();
4544   if (parms1 != NULL && parms1->empty())
4545     parms1 = NULL;
4546   const Typed_identifier_list* parms2 = t->parameters();
4547   if (parms2 != NULL && parms2->empty())
4548     parms2 = NULL;
4549   if ((parms1 != NULL) != (parms2 != NULL))
4550     {
4551       if (reason != NULL)
4552 	*reason = _("different number of parameters");
4553       return false;
4554     }
4555   if (parms1 != NULL)
4556     {
4557       Typed_identifier_list::const_iterator p1 = parms1->begin();
4558       for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4559 	   p2 != parms2->end();
4560 	   ++p2, ++p1)
4561 	{
4562 	  if (p1 == parms1->end())
4563 	    {
4564 	      if (reason != NULL)
4565 		*reason = _("different number of parameters");
4566 	      return false;
4567 	    }
4568 
4569 	  if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4570 					    errors_are_identical, NULL))
4571 	    {
4572 	      if (reason != NULL)
4573 		*reason = _("different parameter types");
4574 	      return false;
4575 	    }
4576 	}
4577       if (p1 != parms1->end())
4578 	{
4579 	  if (reason != NULL)
4580 	    *reason = _("different number of parameters");
4581 	return false;
4582 	}
4583     }
4584 
4585   if (this->is_varargs() != t->is_varargs())
4586     {
4587       if (reason != NULL)
4588 	*reason = _("different varargs");
4589       return false;
4590     }
4591 
4592   const Typed_identifier_list* results1 = this->results();
4593   if (results1 != NULL && results1->empty())
4594     results1 = NULL;
4595   const Typed_identifier_list* results2 = t->results();
4596   if (results2 != NULL && results2->empty())
4597     results2 = NULL;
4598   if ((results1 != NULL) != (results2 != NULL))
4599     {
4600       if (reason != NULL)
4601 	*reason = _("different number of results");
4602       return false;
4603     }
4604   if (results1 != NULL)
4605     {
4606       Typed_identifier_list::const_iterator res1 = results1->begin();
4607       for (Typed_identifier_list::const_iterator res2 = results2->begin();
4608 	   res2 != results2->end();
4609 	   ++res2, ++res1)
4610 	{
4611 	  if (res1 == results1->end())
4612 	    {
4613 	      if (reason != NULL)
4614 		*reason = _("different number of results");
4615 	      return false;
4616 	    }
4617 
4618 	  if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4619 					    cmp_tags, errors_are_identical,
4620 					    NULL))
4621 	    {
4622 	      if (reason != NULL)
4623 		*reason = _("different result types");
4624 	      return false;
4625 	    }
4626 	}
4627       if (res1 != results1->end())
4628 	{
4629 	  if (reason != NULL)
4630 	    *reason = _("different number of results");
4631 	  return false;
4632 	}
4633     }
4634 
4635   return true;
4636 }
4637 
4638 // Hash code.
4639 
4640 unsigned int
do_hash_for_method(Gogo * gogo) const4641 Function_type::do_hash_for_method(Gogo* gogo) const
4642 {
4643   unsigned int ret = 0;
4644   // We ignore the receiver type for hash codes, because we need to
4645   // get the same hash code for a method in an interface and a method
4646   // declared for a type.  The former will not have a receiver.
4647   if (this->parameters_ != NULL)
4648     {
4649       int shift = 1;
4650       for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4651 	   p != this->parameters_->end();
4652 	   ++p, ++shift)
4653 	ret += p->type()->hash_for_method(gogo) << shift;
4654     }
4655   if (this->results_ != NULL)
4656     {
4657       int shift = 2;
4658       for (Typed_identifier_list::const_iterator p = this->results_->begin();
4659 	   p != this->results_->end();
4660 	   ++p, ++shift)
4661 	ret += p->type()->hash_for_method(gogo) << shift;
4662     }
4663   if (this->is_varargs_)
4664     ret += 1;
4665   ret <<= 4;
4666   return ret;
4667 }
4668 
4669 // Hash result parameters.
4670 
4671 unsigned int
operator ()(const Typed_identifier_list * t) const4672 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4673 {
4674   unsigned int hash = 0;
4675   for (Typed_identifier_list::const_iterator p = t->begin();
4676        p != t->end();
4677        ++p)
4678     {
4679       hash <<= 2;
4680       hash = Type::hash_string(p->name(), hash);
4681       hash += p->type()->hash_for_method(NULL);
4682     }
4683   return hash;
4684 }
4685 
4686 // Compare result parameters so that can map identical result
4687 // parameters to a single struct type.
4688 
4689 bool
operator ()(const Typed_identifier_list * a,const Typed_identifier_list * b) const4690 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4691 					 const Typed_identifier_list* b) const
4692 {
4693   if (a->size() != b->size())
4694     return false;
4695   Typed_identifier_list::const_iterator pa = a->begin();
4696   for (Typed_identifier_list::const_iterator pb = b->begin();
4697        pb != b->end();
4698        ++pa, ++pb)
4699     {
4700       if (pa->name() != pb->name()
4701 	  || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4702 	return false;
4703     }
4704   return true;
4705 }
4706 
4707 // Hash from results to a backend struct type.
4708 
4709 Function_type::Results_structs Function_type::results_structs;
4710 
4711 // Get the backend representation for a function type.
4712 
4713 Btype*
get_backend_fntype(Gogo * gogo)4714 Function_type::get_backend_fntype(Gogo* gogo)
4715 {
4716   if (this->fnbtype_ == NULL)
4717     {
4718       Backend::Btyped_identifier breceiver;
4719       if (this->receiver_ != NULL)
4720         {
4721           breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4722 
4723           // We always pass the address of the receiver parameter, in
4724           // order to make interface calls work with unknown types.
4725           Type* rtype = this->receiver_->type();
4726           if (rtype->points_to() == NULL)
4727             rtype = Type::make_pointer_type(rtype);
4728           breceiver.btype = rtype->get_backend(gogo);
4729           breceiver.location = this->receiver_->location();
4730         }
4731 
4732       std::vector<Backend::Btyped_identifier> bparameters;
4733       if (this->parameters_ != NULL)
4734         {
4735           bparameters.resize(this->parameters_->size());
4736           size_t i = 0;
4737           for (Typed_identifier_list::const_iterator p =
4738                    this->parameters_->begin(); p != this->parameters_->end();
4739                ++p, ++i)
4740 	    {
4741               bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4742               bparameters[i].btype = p->type()->get_backend(gogo);
4743               bparameters[i].location = p->location();
4744             }
4745           go_assert(i == bparameters.size());
4746         }
4747 
4748       std::vector<Backend::Btyped_identifier> bresults;
4749       Btype* bresult_struct = NULL;
4750       if (this->results_ != NULL)
4751         {
4752           bresults.resize(this->results_->size());
4753           size_t i = 0;
4754           for (Typed_identifier_list::const_iterator p =
4755                    this->results_->begin();
4756 	       p != this->results_->end();
4757                ++p, ++i)
4758 	    {
4759               bresults[i].name = Gogo::unpack_hidden_name(p->name());
4760               bresults[i].btype = p->type()->get_backend(gogo);
4761               bresults[i].location = p->location();
4762             }
4763           go_assert(i == bresults.size());
4764 
4765 	  if (this->results_->size() > 1)
4766 	    {
4767 	      // Use the same results struct for all functions that
4768 	      // return the same set of results.  This is useful to
4769 	      // unify calls to interface methods with other calls.
4770 	      std::pair<Typed_identifier_list*, Btype*> val;
4771 	      val.first = this->results_;
4772 	      val.second = NULL;
4773 	      std::pair<Results_structs::iterator, bool> ins =
4774 		Function_type::results_structs.insert(val);
4775 	      if (ins.second)
4776 		{
4777 		  // Build a new struct type.
4778 		  Struct_field_list* sfl = new Struct_field_list;
4779 		  for (Typed_identifier_list::const_iterator p =
4780 			 this->results_->begin();
4781 		       p != this->results_->end();
4782 		       ++p)
4783 		    {
4784 		      Typed_identifier tid = *p;
4785 		      if (tid.name().empty())
4786 			tid = Typed_identifier("UNNAMED", tid.type(),
4787 					       tid.location());
4788 		      sfl->push_back(Struct_field(tid));
4789 		    }
4790 		  Struct_type* st = Type::make_struct_type(sfl,
4791 							   this->location());
4792 		  st->set_is_struct_incomparable();
4793 		  ins.first->second = st->get_backend(gogo);
4794 		}
4795 	      bresult_struct = ins.first->second;
4796 	    }
4797         }
4798 
4799       this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4800                                                       bresults, bresult_struct,
4801                                                       this->location());
4802 
4803     }
4804 
4805   return this->fnbtype_;
4806 }
4807 
4808 // Get the backend representation for a Go function type.
4809 
4810 Btype*
do_get_backend(Gogo * gogo)4811 Function_type::do_get_backend(Gogo* gogo)
4812 {
4813   // When we do anything with a function value other than call it, it
4814   // is represented as a pointer to a struct whose first field is the
4815   // actual function.  So that is what we return as the type of a Go
4816   // function.
4817 
4818   Location loc = this->location();
4819   Btype* struct_type =
4820     gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4821   Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4822 
4823   std::vector<Backend::Btyped_identifier> fields(1);
4824   fields[0].name = "code";
4825   fields[0].btype = this->get_backend_fntype(gogo);
4826   fields[0].location = loc;
4827   if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4828     return gogo->backend()->error_type();
4829   return ptr_struct_type;
4830 }
4831 
4832 // The type of a function type descriptor.
4833 
4834 Type*
make_function_type_descriptor_type()4835 Function_type::make_function_type_descriptor_type()
4836 {
4837   static Type* ret;
4838   if (ret == NULL)
4839     {
4840       Type* tdt = Type::make_type_descriptor_type();
4841       Type* ptdt = Type::make_type_descriptor_ptr_type();
4842 
4843       Type* bool_type = Type::lookup_bool_type();
4844 
4845       Type* slice_type = Type::make_array_type(ptdt, NULL);
4846 
4847       Struct_type* s = Type::make_builtin_struct_type(4,
4848 						      "", tdt,
4849 						      "dotdotdot", bool_type,
4850 						      "in", slice_type,
4851 						      "out", slice_type);
4852 
4853       ret = Type::make_builtin_named_type("FuncType", s);
4854     }
4855 
4856   return ret;
4857 }
4858 
4859 // The type descriptor for a function type.
4860 
4861 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)4862 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4863 {
4864   Location bloc = Linemap::predeclared_location();
4865 
4866   Type* ftdt = Function_type::make_function_type_descriptor_type();
4867 
4868   const Struct_field_list* fields = ftdt->struct_type()->fields();
4869 
4870   Expression_list* vals = new Expression_list();
4871   vals->reserve(4);
4872 
4873   Struct_field_list::const_iterator p = fields->begin();
4874   go_assert(p->is_field_name("_type"));
4875   vals->push_back(this->type_descriptor_constructor(gogo,
4876 						    RUNTIME_TYPE_KIND_FUNC,
4877 						    name, NULL, true));
4878 
4879   ++p;
4880   go_assert(p->is_field_name("dotdotdot"));
4881   vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4882 
4883   ++p;
4884   go_assert(p->is_field_name("in"));
4885   vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4886 					       this->parameters()));
4887 
4888   ++p;
4889   go_assert(p->is_field_name("out"));
4890   vals->push_back(this->type_descriptor_params(p->type(), NULL,
4891 					       this->results()));
4892 
4893   ++p;
4894   go_assert(p == fields->end());
4895 
4896   return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4897 }
4898 
4899 // Return a composite literal for the parameters or results of a type
4900 // descriptor.
4901 
4902 Expression*
type_descriptor_params(Type * params_type,const Typed_identifier * receiver,const Typed_identifier_list * params)4903 Function_type::type_descriptor_params(Type* params_type,
4904 				      const Typed_identifier* receiver,
4905 				      const Typed_identifier_list* params)
4906 {
4907   Location bloc = Linemap::predeclared_location();
4908 
4909   if (receiver == NULL && params == NULL)
4910     return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4911 
4912   Expression_list* vals = new Expression_list();
4913   vals->reserve((params == NULL ? 0 : params->size())
4914 		+ (receiver != NULL ? 1 : 0));
4915 
4916   if (receiver != NULL)
4917     vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4918 
4919   if (params != NULL)
4920     {
4921       for (Typed_identifier_list::const_iterator p = params->begin();
4922 	   p != params->end();
4923 	   ++p)
4924 	vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4925     }
4926 
4927   return Expression::make_slice_composite_literal(params_type, vals, bloc);
4928 }
4929 
4930 // The reflection string.
4931 
4932 void
do_reflection(Gogo * gogo,std::string * ret) const4933 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4934 {
4935   // FIXME: Turn this off until we straighten out the type of the
4936   // struct field used in a go statement which calls a method.
4937   // go_assert(this->receiver_ == NULL);
4938 
4939   ret->append("func");
4940 
4941   if (this->receiver_ != NULL)
4942     {
4943       ret->push_back('(');
4944       this->append_reflection(this->receiver_->type(), gogo, ret);
4945       ret->push_back(')');
4946     }
4947 
4948   ret->push_back('(');
4949   const Typed_identifier_list* params = this->parameters();
4950   if (params != NULL)
4951     {
4952       bool is_varargs = this->is_varargs_;
4953       for (Typed_identifier_list::const_iterator p = params->begin();
4954 	   p != params->end();
4955 	   ++p)
4956 	{
4957 	  if (p != params->begin())
4958 	    ret->append(", ");
4959 	  if (!is_varargs || p + 1 != params->end())
4960 	    this->append_reflection(p->type(), gogo, ret);
4961 	  else
4962 	    {
4963 	      ret->append("...");
4964 	      this->append_reflection(p->type()->array_type()->element_type(),
4965 				      gogo, ret);
4966 	    }
4967 	}
4968     }
4969   ret->push_back(')');
4970 
4971   const Typed_identifier_list* results = this->results();
4972   if (results != NULL && !results->empty())
4973     {
4974       if (results->size() == 1)
4975 	ret->push_back(' ');
4976       else
4977 	ret->append(" (");
4978       for (Typed_identifier_list::const_iterator p = results->begin();
4979 	   p != results->end();
4980 	   ++p)
4981 	{
4982 	  if (p != results->begin())
4983 	    ret->append(", ");
4984 	  this->append_reflection(p->type(), gogo, ret);
4985 	}
4986       if (results->size() > 1)
4987 	ret->push_back(')');
4988     }
4989 }
4990 
4991 // Export a function type.
4992 
4993 void
do_export(Export * exp) const4994 Function_type::do_export(Export* exp) const
4995 {
4996   // We don't write out the receiver.  The only function types which
4997   // should have a receiver are the ones associated with explicitly
4998   // defined methods.  For those the receiver type is written out by
4999   // Function::export_func.
5000 
5001   exp->write_c_string("(");
5002   bool first = true;
5003   if (this->parameters_ != NULL)
5004     {
5005       bool is_varargs = this->is_varargs_;
5006       for (Typed_identifier_list::const_iterator p =
5007 	     this->parameters_->begin();
5008 	   p != this->parameters_->end();
5009 	   ++p)
5010 	{
5011 	  if (first)
5012 	    first = false;
5013 	  else
5014 	    exp->write_c_string(", ");
5015 	  exp->write_name(p->name());
5016 	  exp->write_c_string(" ");
5017 	  if (!is_varargs || p + 1 != this->parameters_->end())
5018 	    exp->write_type(p->type());
5019 	  else
5020 	    {
5021 	      exp->write_c_string("...");
5022 	      exp->write_type(p->type()->array_type()->element_type());
5023 	    }
5024 	}
5025     }
5026   exp->write_c_string(")");
5027 
5028   const Typed_identifier_list* results = this->results_;
5029   if (results != NULL)
5030     {
5031       exp->write_c_string(" ");
5032       if (results->size() == 1 && results->begin()->name().empty())
5033 	exp->write_type(results->begin()->type());
5034       else
5035 	{
5036 	  first = true;
5037 	  exp->write_c_string("(");
5038 	  for (Typed_identifier_list::const_iterator p = results->begin();
5039 	       p != results->end();
5040 	       ++p)
5041 	    {
5042 	      if (first)
5043 		first = false;
5044 	      else
5045 		exp->write_c_string(", ");
5046 	      exp->write_name(p->name());
5047 	      exp->write_c_string(" ");
5048 	      exp->write_type(p->type());
5049 	    }
5050 	  exp->write_c_string(")");
5051 	}
5052     }
5053 }
5054 
5055 // Import a function type.
5056 
5057 Function_type*
do_import(Import * imp)5058 Function_type::do_import(Import* imp)
5059 {
5060   imp->require_c_string("(");
5061   Typed_identifier_list* parameters;
5062   bool is_varargs = false;
5063   if (imp->peek_char() == ')')
5064     parameters = NULL;
5065   else
5066     {
5067       parameters = new Typed_identifier_list();
5068       while (true)
5069 	{
5070 	  std::string name = imp->read_name();
5071 	  imp->require_c_string(" ");
5072 
5073 	  if (imp->match_c_string("..."))
5074 	    {
5075 	      imp->advance(3);
5076 	      is_varargs = true;
5077 	    }
5078 
5079 	  Type* ptype = imp->read_type();
5080 	  if (is_varargs)
5081 	    ptype = Type::make_array_type(ptype, NULL);
5082 	  parameters->push_back(Typed_identifier(name, ptype,
5083 						 imp->location()));
5084 	  if (imp->peek_char() != ',')
5085 	    break;
5086 	  go_assert(!is_varargs);
5087 	  imp->require_c_string(", ");
5088 	}
5089     }
5090   imp->require_c_string(")");
5091 
5092   Typed_identifier_list* results;
5093   if (imp->peek_char() != ' ')
5094     results = NULL;
5095   else
5096     {
5097       imp->advance(1);
5098       results = new Typed_identifier_list;
5099       if (imp->peek_char() != '(')
5100 	{
5101 	  Type* rtype = imp->read_type();
5102 	  results->push_back(Typed_identifier("", rtype, imp->location()));
5103 	}
5104       else
5105 	{
5106 	  imp->advance(1);
5107 	  while (true)
5108 	    {
5109 	      std::string name = imp->read_name();
5110 	      imp->require_c_string(" ");
5111 	      Type* rtype = imp->read_type();
5112 	      results->push_back(Typed_identifier(name, rtype,
5113 						  imp->location()));
5114 	      if (imp->peek_char() != ',')
5115 		break;
5116 	      imp->require_c_string(", ");
5117 	    }
5118 	  imp->require_c_string(")");
5119 	}
5120     }
5121 
5122   Function_type* ret = Type::make_function_type(NULL, parameters, results,
5123 						imp->location());
5124   if (is_varargs)
5125     ret->set_is_varargs();
5126   return ret;
5127 }
5128 
5129 // Make a copy of a function type without a receiver.
5130 
5131 Function_type*
copy_without_receiver() const5132 Function_type::copy_without_receiver() const
5133 {
5134   go_assert(this->is_method());
5135   Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5136 						this->results_,
5137 						this->location_);
5138   if (this->is_varargs())
5139     ret->set_is_varargs();
5140   if (this->is_builtin())
5141     ret->set_is_builtin();
5142   return ret;
5143 }
5144 
5145 // Make a copy of a function type with a receiver.
5146 
5147 Function_type*
copy_with_receiver(Type * receiver_type) const5148 Function_type::copy_with_receiver(Type* receiver_type) const
5149 {
5150   go_assert(!this->is_method());
5151   Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5152 						    this->location_);
5153   Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5154 						this->results_,
5155 						this->location_);
5156   if (this->is_varargs_)
5157     ret->set_is_varargs();
5158   return ret;
5159 }
5160 
5161 // Make a copy of a function type with the receiver as the first
5162 // parameter.
5163 
5164 Function_type*
copy_with_receiver_as_param(bool want_pointer_receiver) const5165 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5166 {
5167   go_assert(this->is_method());
5168   Typed_identifier_list* new_params = new Typed_identifier_list();
5169   Type* rtype = this->receiver_->type();
5170   if (want_pointer_receiver)
5171     rtype = Type::make_pointer_type(rtype);
5172   Typed_identifier receiver(this->receiver_->name(), rtype,
5173 			    this->receiver_->location());
5174   new_params->push_back(receiver);
5175   const Typed_identifier_list* orig_params = this->parameters_;
5176   if (orig_params != NULL && !orig_params->empty())
5177     {
5178       for (Typed_identifier_list::const_iterator p = orig_params->begin();
5179 	   p != orig_params->end();
5180 	   ++p)
5181 	new_params->push_back(*p);
5182     }
5183   return Type::make_function_type(NULL, new_params, this->results_,
5184 				  this->location_);
5185 }
5186 
5187 // Make a copy of a function type ignoring any receiver and adding a
5188 // closure parameter.
5189 
5190 Function_type*
copy_with_names() const5191 Function_type::copy_with_names() const
5192 {
5193   Typed_identifier_list* new_params = new Typed_identifier_list();
5194   const Typed_identifier_list* orig_params = this->parameters_;
5195   if (orig_params != NULL && !orig_params->empty())
5196     {
5197       static int count;
5198       char buf[50];
5199       for (Typed_identifier_list::const_iterator p = orig_params->begin();
5200 	   p != orig_params->end();
5201 	   ++p)
5202 	{
5203 	  snprintf(buf, sizeof buf, "pt.%u", count);
5204 	  ++count;
5205 	  new_params->push_back(Typed_identifier(buf, p->type(),
5206 						 p->location()));
5207 	}
5208     }
5209 
5210   const Typed_identifier_list* orig_results = this->results_;
5211   Typed_identifier_list* new_results;
5212   if (orig_results == NULL || orig_results->empty())
5213     new_results = NULL;
5214   else
5215     {
5216       new_results = new Typed_identifier_list();
5217       for (Typed_identifier_list::const_iterator p = orig_results->begin();
5218 	   p != orig_results->end();
5219 	   ++p)
5220 	new_results->push_back(Typed_identifier("", p->type(),
5221 						p->location()));
5222     }
5223 
5224   return Type::make_function_type(NULL, new_params, new_results,
5225 				  this->location());
5226 }
5227 
5228 // Make a function type.
5229 
5230 Function_type*
make_function_type(Typed_identifier * receiver,Typed_identifier_list * parameters,Typed_identifier_list * results,Location location)5231 Type::make_function_type(Typed_identifier* receiver,
5232 			 Typed_identifier_list* parameters,
5233 			 Typed_identifier_list* results,
5234 			 Location location)
5235 {
5236   return new Function_type(receiver, parameters, results, location);
5237 }
5238 
5239 // Make a backend function type.
5240 
5241 Backend_function_type*
make_backend_function_type(Typed_identifier * receiver,Typed_identifier_list * parameters,Typed_identifier_list * results,Location location)5242 Type::make_backend_function_type(Typed_identifier* receiver,
5243                                  Typed_identifier_list* parameters,
5244                                  Typed_identifier_list* results,
5245                                  Location location)
5246 {
5247   return new Backend_function_type(receiver, parameters, results, location);
5248 }
5249 
5250 // Class Pointer_type.
5251 
5252 // Traversal.
5253 
5254 int
do_traverse(Traverse * traverse)5255 Pointer_type::do_traverse(Traverse* traverse)
5256 {
5257   return Type::traverse(this->to_type_, traverse);
5258 }
5259 
5260 // Hash code.
5261 
5262 unsigned int
do_hash_for_method(Gogo * gogo) const5263 Pointer_type::do_hash_for_method(Gogo* gogo) const
5264 {
5265   return this->to_type_->hash_for_method(gogo) << 4;
5266 }
5267 
5268 // Get the backend representation for a pointer type.
5269 
5270 Btype*
do_get_backend(Gogo * gogo)5271 Pointer_type::do_get_backend(Gogo* gogo)
5272 {
5273   Btype* to_btype = this->to_type_->get_backend(gogo);
5274   return gogo->backend()->pointer_type(to_btype);
5275 }
5276 
5277 // The type of a pointer type descriptor.
5278 
5279 Type*
make_pointer_type_descriptor_type()5280 Pointer_type::make_pointer_type_descriptor_type()
5281 {
5282   static Type* ret;
5283   if (ret == NULL)
5284     {
5285       Type* tdt = Type::make_type_descriptor_type();
5286       Type* ptdt = Type::make_type_descriptor_ptr_type();
5287 
5288       Struct_type* s = Type::make_builtin_struct_type(2,
5289 						      "", tdt,
5290 						      "elem", ptdt);
5291 
5292       ret = Type::make_builtin_named_type("PtrType", s);
5293     }
5294 
5295   return ret;
5296 }
5297 
5298 // The type descriptor for a pointer type.
5299 
5300 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)5301 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5302 {
5303   if (this->is_unsafe_pointer_type())
5304     {
5305       go_assert(name != NULL);
5306       return this->plain_type_descriptor(gogo,
5307 					 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5308 					 name);
5309     }
5310   else
5311     {
5312       Location bloc = Linemap::predeclared_location();
5313 
5314       const Methods* methods;
5315       Type* deref = this->points_to();
5316       if (deref->named_type() != NULL)
5317 	methods = deref->named_type()->methods();
5318       else if (deref->struct_type() != NULL)
5319 	methods = deref->struct_type()->methods();
5320       else
5321 	methods = NULL;
5322 
5323       Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5324 
5325       const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5326 
5327       Expression_list* vals = new Expression_list();
5328       vals->reserve(2);
5329 
5330       Struct_field_list::const_iterator p = fields->begin();
5331       go_assert(p->is_field_name("_type"));
5332       vals->push_back(this->type_descriptor_constructor(gogo,
5333 							RUNTIME_TYPE_KIND_PTR,
5334 							name, methods, false));
5335 
5336       ++p;
5337       go_assert(p->is_field_name("elem"));
5338       vals->push_back(Expression::make_type_descriptor(deref, bloc));
5339 
5340       return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5341     }
5342 }
5343 
5344 // Reflection string.
5345 
5346 void
do_reflection(Gogo * gogo,std::string * ret) const5347 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5348 {
5349   ret->push_back('*');
5350   this->append_reflection(this->to_type_, gogo, ret);
5351 }
5352 
5353 // Export.
5354 
5355 void
do_export(Export * exp) const5356 Pointer_type::do_export(Export* exp) const
5357 {
5358   exp->write_c_string("*");
5359   if (this->is_unsafe_pointer_type())
5360     exp->write_c_string("any");
5361   else
5362     exp->write_type(this->to_type_);
5363 }
5364 
5365 // Import.
5366 
5367 Pointer_type*
do_import(Import * imp)5368 Pointer_type::do_import(Import* imp)
5369 {
5370   imp->require_c_string("*");
5371   if (imp->match_c_string("any"))
5372     {
5373       imp->advance(3);
5374       return Type::make_pointer_type(Type::make_void_type());
5375     }
5376   Type* to = imp->read_type();
5377   return Type::make_pointer_type(to);
5378 }
5379 
5380 // Cache of pointer types. Key is "to" type, value is pointer type
5381 // that points to key.
5382 
5383 Type::Pointer_type_table Type::pointer_types;
5384 
5385 // A list of placeholder pointer types.  We keep this so we can ensure
5386 // they are finalized.
5387 
5388 std::vector<Pointer_type*> Type::placeholder_pointers;
5389 
5390 // Make a pointer type.
5391 
5392 Pointer_type*
make_pointer_type(Type * to_type)5393 Type::make_pointer_type(Type* to_type)
5394 {
5395   Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5396   if (p != pointer_types.end())
5397     return p->second;
5398   Pointer_type* ret = new Pointer_type(to_type);
5399   pointer_types[to_type] = ret;
5400   return ret;
5401 }
5402 
5403 // This helper is invoked immediately after named types have been
5404 // converted, to clean up any unresolved pointer types remaining in
5405 // the pointer type cache.
5406 //
5407 // The motivation for this routine: occasionally the compiler creates
5408 // some specific pointer type as part of a lowering operation (ex:
5409 // pointer-to-void), then Type::backend_type_size() is invoked on the
5410 // type (which creates a Btype placeholder for it), that placeholder
5411 // passed somewhere along the line to the back end, but since there is
5412 // no reference to the type in user code, there is never a call to
5413 // Type::finish_backend for the type (hence the Btype remains as an
5414 // unresolved placeholder).  Calling this routine will clean up such
5415 // instances.
5416 
5417 void
finish_pointer_types(Gogo * gogo)5418 Type::finish_pointer_types(Gogo* gogo)
5419 {
5420   // We don't use begin() and end() because it is possible to add new
5421   // placeholder pointer types as we finalized existing ones.
5422   for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5423     {
5424       Pointer_type* pt = Type::placeholder_pointers[i];
5425       Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5426       if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5427         {
5428           pt->finish_backend(gogo, tbti->second.btype);
5429           tbti->second.is_placeholder = false;
5430         }
5431     }
5432 }
5433 
5434 // Class Nil_type.
5435 
5436 // Get the backend representation of a nil type.  FIXME: Is this ever
5437 // actually called?
5438 
5439 Btype*
do_get_backend(Gogo * gogo)5440 Nil_type::do_get_backend(Gogo* gogo)
5441 {
5442   return gogo->backend()->pointer_type(gogo->backend()->void_type());
5443 }
5444 
5445 // Make the nil type.
5446 
5447 Type*
make_nil_type()5448 Type::make_nil_type()
5449 {
5450   static Nil_type singleton_nil_type;
5451   return &singleton_nil_type;
5452 }
5453 
5454 // The type of a function call which returns multiple values.  This is
5455 // really a struct, but we don't want to confuse a function call which
5456 // returns a struct with a function call which returns multiple
5457 // values.
5458 
5459 class Call_multiple_result_type : public Type
5460 {
5461  public:
Call_multiple_result_type(Call_expression * call)5462   Call_multiple_result_type(Call_expression* call)
5463     : Type(TYPE_CALL_MULTIPLE_RESULT),
5464       call_(call)
5465   { }
5466 
5467  protected:
5468   bool
do_has_pointer() const5469   do_has_pointer() const
5470   { return false; }
5471 
5472   bool
do_compare_is_identity(Gogo *)5473   do_compare_is_identity(Gogo*)
5474   { return false; }
5475 
5476   Btype*
do_get_backend(Gogo * gogo)5477   do_get_backend(Gogo* gogo)
5478   {
5479     go_assert(saw_errors());
5480     return gogo->backend()->error_type();
5481   }
5482 
5483   Expression*
do_type_descriptor(Gogo *,Named_type *)5484   do_type_descriptor(Gogo*, Named_type*)
5485   {
5486     go_assert(saw_errors());
5487     return Expression::make_error(Linemap::unknown_location());
5488   }
5489 
5490   void
do_reflection(Gogo *,std::string *) const5491   do_reflection(Gogo*, std::string*) const
5492   { go_assert(saw_errors()); }
5493 
5494   void
do_mangled_name(Gogo *,std::string *) const5495   do_mangled_name(Gogo*, std::string*) const
5496   { go_assert(saw_errors()); }
5497 
5498  private:
5499   // The expression being called.
5500   Call_expression* call_;
5501 };
5502 
5503 // Make a call result type.
5504 
5505 Type*
make_call_multiple_result_type(Call_expression * call)5506 Type::make_call_multiple_result_type(Call_expression* call)
5507 {
5508   return new Call_multiple_result_type(call);
5509 }
5510 
5511 // Class Struct_field.
5512 
5513 // Get the name of a field.
5514 
5515 const std::string&
field_name() const5516 Struct_field::field_name() const
5517 {
5518   const std::string& name(this->typed_identifier_.name());
5519   if (!name.empty())
5520     return name;
5521   else
5522     {
5523       // This is called during parsing, before anything is lowered, so
5524       // we have to be pretty careful to avoid dereferencing an
5525       // unknown type name.
5526       Type* t = this->typed_identifier_.type();
5527       Type* dt = t;
5528       if (t->classification() == Type::TYPE_POINTER)
5529 	{
5530 	  // Very ugly.
5531 	  Pointer_type* ptype = static_cast<Pointer_type*>(t);
5532 	  dt = ptype->points_to();
5533 	}
5534       if (dt->forward_declaration_type() != NULL)
5535 	return dt->forward_declaration_type()->name();
5536       else if (dt->named_type() != NULL)
5537 	{
5538 	  // Note that this can be an alias name.
5539 	  return dt->named_type()->name();
5540 	}
5541       else if (t->is_error_type() || dt->is_error_type())
5542 	{
5543 	  static const std::string error_string = "*error*";
5544 	  return error_string;
5545 	}
5546       else
5547 	{
5548 	  // Avoid crashing in the erroneous case where T is named but
5549 	  // DT is not.
5550 	  go_assert(t != dt);
5551 	  if (t->forward_declaration_type() != NULL)
5552 	    return t->forward_declaration_type()->name();
5553 	  else if (t->named_type() != NULL)
5554 	    return t->named_type()->name();
5555 	  else
5556 	    go_unreachable();
5557 	}
5558     }
5559 }
5560 
5561 // Return whether this field is named NAME.
5562 
5563 bool
is_field_name(const std::string & name) const5564 Struct_field::is_field_name(const std::string& name) const
5565 {
5566   const std::string& me(this->typed_identifier_.name());
5567   if (!me.empty())
5568     return me == name;
5569   else
5570     {
5571       Type* t = this->typed_identifier_.type();
5572       if (t->points_to() != NULL)
5573 	t = t->points_to();
5574       Named_type* nt = t->named_type();
5575       if (nt != NULL && nt->name() == name)
5576 	return true;
5577 
5578       // This is a horrible hack caused by the fact that we don't pack
5579       // the names of builtin types.  FIXME.
5580       if (!this->is_imported_
5581 	  && nt != NULL
5582 	  && nt->is_builtin()
5583 	  && nt->name() == Gogo::unpack_hidden_name(name))
5584 	return true;
5585 
5586       return false;
5587     }
5588 }
5589 
5590 // Return whether this field is an unexported field named NAME.
5591 
5592 bool
is_unexported_field_name(Gogo * gogo,const std::string & name) const5593 Struct_field::is_unexported_field_name(Gogo* gogo,
5594 				       const std::string& name) const
5595 {
5596   const std::string& field_name(this->field_name());
5597   if (Gogo::is_hidden_name(field_name)
5598       && name == Gogo::unpack_hidden_name(field_name)
5599       && gogo->pack_hidden_name(name, false) != field_name)
5600     return true;
5601 
5602   // Check for the name of a builtin type.  This is like the test in
5603   // is_field_name, only there we return false if this->is_imported_,
5604   // and here we return true.
5605   if (this->is_imported_ && this->is_anonymous())
5606     {
5607       Type* t = this->typed_identifier_.type();
5608       if (t->points_to() != NULL)
5609 	t = t->points_to();
5610       Named_type* nt = t->named_type();
5611       if (nt != NULL
5612 	  && nt->is_builtin()
5613 	  && nt->name() == Gogo::unpack_hidden_name(name))
5614 	return true;
5615     }
5616 
5617   return false;
5618 }
5619 
5620 // Return whether this field is an embedded built-in type.
5621 
5622 bool
is_embedded_builtin(Gogo * gogo) const5623 Struct_field::is_embedded_builtin(Gogo* gogo) const
5624 {
5625   const std::string& name(this->field_name());
5626   // We know that a field is an embedded type if it is anonymous.
5627   // We can decide if it is a built-in type by checking to see if it is
5628   // registered globally under the field's name.
5629   // This allows us to distinguish between embedded built-in types and
5630   // embedded types that are aliases to built-in types.
5631   return (this->is_anonymous()
5632           && !Gogo::is_hidden_name(name)
5633           && gogo->lookup_global(name.c_str()) != NULL);
5634 }
5635 
5636 // Class Struct_type.
5637 
5638 // A hash table used to find identical unnamed structs so that they
5639 // share method tables.
5640 
5641 Struct_type::Identical_structs Struct_type::identical_structs;
5642 
5643 // A hash table used to merge method sets for identical unnamed
5644 // structs.
5645 
5646 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5647 
5648 // Traversal.
5649 
5650 int
do_traverse(Traverse * traverse)5651 Struct_type::do_traverse(Traverse* traverse)
5652 {
5653   Struct_field_list* fields = this->fields_;
5654   if (fields != NULL)
5655     {
5656       for (Struct_field_list::iterator p = fields->begin();
5657 	   p != fields->end();
5658 	   ++p)
5659 	{
5660 	  if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5661 	    return TRAVERSE_EXIT;
5662 	}
5663     }
5664   return TRAVERSE_CONTINUE;
5665 }
5666 
5667 // Verify that the struct type is complete and valid.
5668 
5669 bool
do_verify()5670 Struct_type::do_verify()
5671 {
5672   Struct_field_list* fields = this->fields_;
5673   if (fields == NULL)
5674     return true;
5675   for (Struct_field_list::iterator p = fields->begin();
5676        p != fields->end();
5677        ++p)
5678     {
5679       Type* t = p->type();
5680       if (p->is_anonymous())
5681 	{
5682 	  if ((t->named_type() != NULL && t->points_to() != NULL)
5683               || (t->named_type() == NULL && t->points_to() != NULL
5684                   && t->points_to()->points_to() != NULL))
5685 	    {
5686 	      go_error_at(p->location(), "embedded type may not be a pointer");
5687 	      p->set_type(Type::make_error_type());
5688 	    }
5689 	  else if (t->points_to() != NULL
5690 		   && t->points_to()->interface_type() != NULL)
5691 	    {
5692 	      go_error_at(p->location(),
5693 		       "embedded type may not be pointer to interface");
5694 	      p->set_type(Type::make_error_type());
5695 	    }
5696 	}
5697     }
5698   return true;
5699 }
5700 
5701 // Whether this contains a pointer.
5702 
5703 bool
do_has_pointer() const5704 Struct_type::do_has_pointer() const
5705 {
5706   const Struct_field_list* fields = this->fields();
5707   if (fields == NULL)
5708     return false;
5709   for (Struct_field_list::const_iterator p = fields->begin();
5710        p != fields->end();
5711        ++p)
5712     {
5713       if (p->type()->has_pointer())
5714 	return true;
5715     }
5716   return false;
5717 }
5718 
5719 // Whether this type is identical to T.
5720 
5721 bool
is_identical(const Struct_type * t,Cmp_tags cmp_tags,bool errors_are_identical) const5722 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5723 			  bool errors_are_identical) const
5724 {
5725   if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5726     return false;
5727   const Struct_field_list* fields1 = this->fields();
5728   const Struct_field_list* fields2 = t->fields();
5729   if (fields1 == NULL || fields2 == NULL)
5730     return fields1 == fields2;
5731   Struct_field_list::const_iterator pf2 = fields2->begin();
5732   for (Struct_field_list::const_iterator pf1 = fields1->begin();
5733        pf1 != fields1->end();
5734        ++pf1, ++pf2)
5735     {
5736       if (pf2 == fields2->end())
5737 	return false;
5738       if (pf1->field_name() != pf2->field_name())
5739 	return false;
5740       if (pf1->is_anonymous() != pf2->is_anonymous()
5741 	  || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5742 					   errors_are_identical, NULL))
5743 	return false;
5744       if (cmp_tags == COMPARE_TAGS)
5745 	{
5746 	  if (!pf1->has_tag())
5747 	    {
5748 	      if (pf2->has_tag())
5749 		return false;
5750 	    }
5751 	  else
5752 	    {
5753 	      if (!pf2->has_tag())
5754 		return false;
5755 	      if (pf1->tag() != pf2->tag())
5756 		return false;
5757 	    }
5758 	}
5759     }
5760   if (pf2 != fields2->end())
5761     return false;
5762   return true;
5763 }
5764 
5765 // Whether comparisons of this struct type are simple identity
5766 // comparisons.
5767 
5768 bool
do_compare_is_identity(Gogo * gogo)5769 Struct_type::do_compare_is_identity(Gogo* gogo)
5770 {
5771   const Struct_field_list* fields = this->fields_;
5772   if (fields == NULL)
5773     return true;
5774   int64_t offset = 0;
5775   for (Struct_field_list::const_iterator pf = fields->begin();
5776        pf != fields->end();
5777        ++pf)
5778     {
5779       if (Gogo::is_sink_name(pf->field_name()))
5780 	return false;
5781 
5782       if (!pf->type()->compare_is_identity(gogo))
5783 	return false;
5784 
5785       int64_t field_align;
5786       if (!pf->type()->backend_type_align(gogo, &field_align))
5787 	return false;
5788       if ((offset & (field_align - 1)) != 0)
5789 	{
5790 	  // This struct has padding.  We don't guarantee that that
5791 	  // padding is zero-initialized for a stack variable, so we
5792 	  // can't use memcmp to compare struct values.
5793 	  return false;
5794 	}
5795 
5796       int64_t field_size;
5797       if (!pf->type()->backend_type_size(gogo, &field_size))
5798 	return false;
5799       offset += field_size;
5800     }
5801 
5802   int64_t struct_size;
5803   if (!this->backend_type_size(gogo, &struct_size))
5804     return false;
5805   if (offset != struct_size)
5806     {
5807       // Trailing padding may not be zero when on the stack.
5808       return false;
5809     }
5810 
5811   return true;
5812 }
5813 
5814 // Return whether this struct type is reflexive--whether a value of
5815 // this type is always equal to itself.
5816 
5817 bool
do_is_reflexive()5818 Struct_type::do_is_reflexive()
5819 {
5820   const Struct_field_list* fields = this->fields_;
5821   if (fields == NULL)
5822     return true;
5823   for (Struct_field_list::const_iterator pf = fields->begin();
5824        pf != fields->end();
5825        ++pf)
5826     {
5827       if (!pf->type()->is_reflexive())
5828 	return false;
5829     }
5830   return true;
5831 }
5832 
5833 // Return whether this struct type needs a key update when used as a
5834 // map key.
5835 
5836 bool
do_needs_key_update()5837 Struct_type::do_needs_key_update()
5838 {
5839   const Struct_field_list* fields = this->fields_;
5840   if (fields == NULL)
5841     return false;
5842   for (Struct_field_list::const_iterator pf = fields->begin();
5843        pf != fields->end();
5844        ++pf)
5845     {
5846       if (pf->type()->needs_key_update())
5847 	return true;
5848     }
5849   return false;
5850 }
5851 
5852 // Return whether this struct type is permitted to be in the heap.
5853 
5854 bool
do_in_heap()5855 Struct_type::do_in_heap()
5856 {
5857   const Struct_field_list* fields = this->fields_;
5858   if (fields == NULL)
5859     return true;
5860   for (Struct_field_list::const_iterator pf = fields->begin();
5861        pf != fields->end();
5862        ++pf)
5863     {
5864       if (!pf->type()->in_heap())
5865 	return false;
5866     }
5867   return true;
5868 }
5869 
5870 // Build identity and hash functions for this struct.
5871 
5872 // Hash code.
5873 
5874 unsigned int
do_hash_for_method(Gogo * gogo) const5875 Struct_type::do_hash_for_method(Gogo* gogo) const
5876 {
5877   unsigned int ret = 0;
5878   if (this->fields() != NULL)
5879     {
5880       for (Struct_field_list::const_iterator pf = this->fields()->begin();
5881 	   pf != this->fields()->end();
5882 	   ++pf)
5883 	ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5884     }
5885   ret <<= 2;
5886   if (this->is_struct_incomparable_)
5887     ret <<= 1;
5888   return ret;
5889 }
5890 
5891 // Find the local field NAME.
5892 
5893 const Struct_field*
find_local_field(const std::string & name,unsigned int * pindex) const5894 Struct_type::find_local_field(const std::string& name,
5895 			      unsigned int *pindex) const
5896 {
5897   const Struct_field_list* fields = this->fields_;
5898   if (fields == NULL)
5899     return NULL;
5900   unsigned int i = 0;
5901   for (Struct_field_list::const_iterator pf = fields->begin();
5902        pf != fields->end();
5903        ++pf, ++i)
5904     {
5905       if (pf->is_field_name(name))
5906 	{
5907 	  if (pindex != NULL)
5908 	    *pindex = i;
5909 	  return &*pf;
5910 	}
5911     }
5912   return NULL;
5913 }
5914 
5915 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5916 
5917 Field_reference_expression*
field_reference(Expression * struct_expr,const std::string & name,Location location) const5918 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5919 			     Location location) const
5920 {
5921   unsigned int depth;
5922   return this->field_reference_depth(struct_expr, name, location, NULL,
5923 				     &depth);
5924 }
5925 
5926 // Return an expression for a field, along with the depth at which it
5927 // was found.
5928 
5929 Field_reference_expression*
field_reference_depth(Expression * struct_expr,const std::string & name,Location location,Saw_named_type * saw,unsigned int * depth) const5930 Struct_type::field_reference_depth(Expression* struct_expr,
5931 				   const std::string& name,
5932 				   Location location,
5933 				   Saw_named_type* saw,
5934 				   unsigned int* depth) const
5935 {
5936   const Struct_field_list* fields = this->fields_;
5937   if (fields == NULL)
5938     return NULL;
5939 
5940   // Look for a field with this name.
5941   unsigned int i = 0;
5942   for (Struct_field_list::const_iterator pf = fields->begin();
5943        pf != fields->end();
5944        ++pf, ++i)
5945     {
5946       if (pf->is_field_name(name))
5947 	{
5948 	  *depth = 0;
5949 	  return Expression::make_field_reference(struct_expr, i, location);
5950 	}
5951     }
5952 
5953   // Look for an anonymous field which contains a field with this
5954   // name.
5955   unsigned int found_depth = 0;
5956   Field_reference_expression* ret = NULL;
5957   i = 0;
5958   for (Struct_field_list::const_iterator pf = fields->begin();
5959        pf != fields->end();
5960        ++pf, ++i)
5961     {
5962       if (!pf->is_anonymous())
5963 	continue;
5964 
5965       Struct_type* st = pf->type()->deref()->struct_type();
5966       if (st == NULL)
5967 	continue;
5968 
5969       Saw_named_type* hold_saw = saw;
5970       Saw_named_type saw_here;
5971       Named_type* nt = pf->type()->named_type();
5972       if (nt == NULL)
5973 	nt = pf->type()->deref()->named_type();
5974       if (nt != NULL)
5975 	{
5976 	  Saw_named_type* q;
5977 	  for (q = saw; q != NULL; q = q->next)
5978 	    {
5979 	      if (q->nt == nt)
5980 		{
5981 		  // If this is an error, it will be reported
5982 		  // elsewhere.
5983 		  break;
5984 		}
5985 	    }
5986 	  if (q != NULL)
5987 	    continue;
5988 	  saw_here.next = saw;
5989 	  saw_here.nt = nt;
5990 	  saw = &saw_here;
5991 	}
5992 
5993       // Look for a reference using a NULL struct expression.  If we
5994       // find one, fill in the struct expression with a reference to
5995       // this field.
5996       unsigned int subdepth;
5997       Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5998 								  location,
5999 								  saw,
6000 								  &subdepth);
6001 
6002       saw = hold_saw;
6003 
6004       if (sub == NULL)
6005 	continue;
6006 
6007       if (ret == NULL || subdepth < found_depth)
6008 	{
6009 	  if (ret != NULL)
6010 	    delete ret;
6011 	  ret = sub;
6012 	  found_depth = subdepth;
6013 	  Expression* here = Expression::make_field_reference(struct_expr, i,
6014 							      location);
6015 	  if (pf->type()->points_to() != NULL)
6016             here = Expression::make_dereference(here,
6017                                                 Expression::NIL_CHECK_DEFAULT,
6018                                                 location);
6019 	  while (sub->expr() != NULL)
6020 	    {
6021 	      sub = sub->expr()->deref()->field_reference_expression();
6022 	      go_assert(sub != NULL);
6023 	    }
6024 	  sub->set_struct_expression(here);
6025           sub->set_implicit(true);
6026 	}
6027       else if (subdepth > found_depth)
6028 	delete sub;
6029       else
6030 	{
6031 	  // We do not handle ambiguity here--it should be handled by
6032 	  // Type::bind_field_or_method.
6033 	  delete sub;
6034 	  found_depth = 0;
6035 	  ret = NULL;
6036 	}
6037     }
6038 
6039   if (ret != NULL)
6040     *depth = found_depth + 1;
6041 
6042   return ret;
6043 }
6044 
6045 // Return the total number of fields, including embedded fields.
6046 
6047 unsigned int
total_field_count() const6048 Struct_type::total_field_count() const
6049 {
6050   if (this->fields_ == NULL)
6051     return 0;
6052   unsigned int ret = 0;
6053   for (Struct_field_list::const_iterator pf = this->fields_->begin();
6054        pf != this->fields_->end();
6055        ++pf)
6056     {
6057       if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6058 	++ret;
6059       else
6060 	ret += pf->type()->struct_type()->total_field_count();
6061     }
6062   return ret;
6063 }
6064 
6065 // Return whether NAME is an unexported field, for better error reporting.
6066 
6067 bool
is_unexported_local_field(Gogo * gogo,const std::string & name) const6068 Struct_type::is_unexported_local_field(Gogo* gogo,
6069 				       const std::string& name) const
6070 {
6071   const Struct_field_list* fields = this->fields_;
6072   if (fields != NULL)
6073     {
6074       for (Struct_field_list::const_iterator pf = fields->begin();
6075 	   pf != fields->end();
6076 	   ++pf)
6077 	if (pf->is_unexported_field_name(gogo, name))
6078 	  return true;
6079     }
6080   return false;
6081 }
6082 
6083 // Finalize the methods of an unnamed struct.
6084 
6085 void
finalize_methods(Gogo * gogo)6086 Struct_type::finalize_methods(Gogo* gogo)
6087 {
6088   if (this->all_methods_ != NULL)
6089     return;
6090 
6091   // It is possible to have multiple identical structs that have
6092   // methods.  We want them to share method tables.  Otherwise we will
6093   // emit identical methods more than once, which is bad since they
6094   // will even have the same names.
6095   std::pair<Identical_structs::iterator, bool> ins =
6096     Struct_type::identical_structs.insert(std::make_pair(this, this));
6097   if (!ins.second)
6098     {
6099       // An identical struct was already entered into the hash table.
6100       // Note that finalize_methods is, fortunately, not recursive.
6101       this->all_methods_ = ins.first->second->all_methods_;
6102       return;
6103     }
6104 
6105   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6106 }
6107 
6108 // Return the method NAME, or NULL if there isn't one or if it is
6109 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
6110 // ambiguous.
6111 
6112 Method*
method_function(const std::string & name,bool * is_ambiguous) const6113 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6114 {
6115   return Type::method_function(this->all_methods_, name, is_ambiguous);
6116 }
6117 
6118 // Return a pointer to the interface method table for this type for
6119 // the interface INTERFACE.  IS_POINTER is true if this is for a
6120 // pointer to THIS.
6121 
6122 Expression*
interface_method_table(Interface_type * interface,bool is_pointer)6123 Struct_type::interface_method_table(Interface_type* interface,
6124 				    bool is_pointer)
6125 {
6126   std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6127     val(this, NULL);
6128   std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6129     Struct_type::struct_method_tables.insert(val);
6130 
6131   Struct_method_table_pair* smtp;
6132   if (!ins.second)
6133     smtp = ins.first->second;
6134   else
6135     {
6136       smtp = new Struct_method_table_pair();
6137       smtp->first = NULL;
6138       smtp->second = NULL;
6139       ins.first->second = smtp;
6140     }
6141 
6142   return Type::interface_method_table(this, interface, is_pointer,
6143 				      &smtp->first, &smtp->second);
6144 }
6145 
6146 // Convert struct fields to the backend representation.  This is not
6147 // declared in types.h so that types.h doesn't have to #include
6148 // backend.h.
6149 
6150 static void
get_backend_struct_fields(Gogo * gogo,const Struct_field_list * fields,bool use_placeholder,std::vector<Backend::Btyped_identifier> * bfields)6151 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6152 			  bool use_placeholder,
6153 			  std::vector<Backend::Btyped_identifier>* bfields)
6154 {
6155   bfields->resize(fields->size());
6156   size_t i = 0;
6157   for (Struct_field_list::const_iterator p = fields->begin();
6158        p != fields->end();
6159        ++p, ++i)
6160     {
6161       (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6162       (*bfields)[i].btype = (use_placeholder
6163 			     ? p->type()->get_backend_placeholder(gogo)
6164 			     : p->type()->get_backend(gogo));
6165       (*bfields)[i].location = p->location();
6166     }
6167   go_assert(i == fields->size());
6168 }
6169 
6170 // Get the backend representation for a struct type.
6171 
6172 Btype*
do_get_backend(Gogo * gogo)6173 Struct_type::do_get_backend(Gogo* gogo)
6174 {
6175   std::vector<Backend::Btyped_identifier> bfields;
6176   get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6177   return gogo->backend()->struct_type(bfields);
6178 }
6179 
6180 // Finish the backend representation of the fields of a struct.
6181 
6182 void
finish_backend_fields(Gogo * gogo)6183 Struct_type::finish_backend_fields(Gogo* gogo)
6184 {
6185   const Struct_field_list* fields = this->fields_;
6186   if (fields != NULL)
6187     {
6188       for (Struct_field_list::const_iterator p = fields->begin();
6189 	   p != fields->end();
6190 	   ++p)
6191 	p->type()->get_backend(gogo);
6192     }
6193 }
6194 
6195 // The type of a struct type descriptor.
6196 
6197 Type*
make_struct_type_descriptor_type()6198 Struct_type::make_struct_type_descriptor_type()
6199 {
6200   static Type* ret;
6201   if (ret == NULL)
6202     {
6203       Type* tdt = Type::make_type_descriptor_type();
6204       Type* ptdt = Type::make_type_descriptor_ptr_type();
6205 
6206       Type* uintptr_type = Type::lookup_integer_type("uintptr");
6207       Type* string_type = Type::lookup_string_type();
6208       Type* pointer_string_type = Type::make_pointer_type(string_type);
6209 
6210       Struct_type* sf =
6211 	Type::make_builtin_struct_type(5,
6212 				       "name", pointer_string_type,
6213 				       "pkgPath", pointer_string_type,
6214 				       "typ", ptdt,
6215 				       "tag", pointer_string_type,
6216 				       "offsetAnon", uintptr_type);
6217       Type* nsf = Type::make_builtin_named_type("structField", sf);
6218 
6219       Type* slice_type = Type::make_array_type(nsf, NULL);
6220 
6221       Struct_type* s = Type::make_builtin_struct_type(2,
6222 						      "", tdt,
6223 						      "fields", slice_type);
6224 
6225       ret = Type::make_builtin_named_type("StructType", s);
6226     }
6227 
6228   return ret;
6229 }
6230 
6231 // Build a type descriptor for a struct type.
6232 
6233 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)6234 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6235 {
6236   Location bloc = Linemap::predeclared_location();
6237 
6238   Type* stdt = Struct_type::make_struct_type_descriptor_type();
6239 
6240   const Struct_field_list* fields = stdt->struct_type()->fields();
6241 
6242   Expression_list* vals = new Expression_list();
6243   vals->reserve(2);
6244 
6245   const Methods* methods = this->methods();
6246   // A named struct should not have methods--the methods should attach
6247   // to the named type.
6248   go_assert(methods == NULL || name == NULL);
6249 
6250   Struct_field_list::const_iterator ps = fields->begin();
6251   go_assert(ps->is_field_name("_type"));
6252   vals->push_back(this->type_descriptor_constructor(gogo,
6253 						    RUNTIME_TYPE_KIND_STRUCT,
6254 						    name, methods, true));
6255 
6256   ++ps;
6257   go_assert(ps->is_field_name("fields"));
6258 
6259   Expression_list* elements = new Expression_list();
6260   elements->reserve(this->fields_->size());
6261   Type* element_type = ps->type()->array_type()->element_type();
6262   for (Struct_field_list::const_iterator pf = this->fields_->begin();
6263        pf != this->fields_->end();
6264        ++pf)
6265     {
6266       const Struct_field_list* f = element_type->struct_type()->fields();
6267 
6268       Expression_list* fvals = new Expression_list();
6269       fvals->reserve(5);
6270 
6271       Struct_field_list::const_iterator q = f->begin();
6272       go_assert(q->is_field_name("name"));
6273       std::string n = Gogo::unpack_hidden_name(pf->field_name());
6274       Expression* s = Expression::make_string(n, bloc);
6275       fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6276 
6277       ++q;
6278       go_assert(q->is_field_name("pkgPath"));
6279       bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6280       if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6281         fvals->push_back(Expression::make_nil(bloc));
6282       else
6283 	{
6284 	  std::string n;
6285           if (is_embedded_builtin)
6286             n = gogo->package_name();
6287           else
6288             n = Gogo::hidden_name_pkgpath(pf->field_name());
6289 	  Expression* s = Expression::make_string(n, bloc);
6290 	  fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6291 	}
6292 
6293       ++q;
6294       go_assert(q->is_field_name("typ"));
6295       fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6296 
6297       ++q;
6298       go_assert(q->is_field_name("tag"));
6299       if (!pf->has_tag())
6300 	fvals->push_back(Expression::make_nil(bloc));
6301       else
6302 	{
6303 	  Expression* s = Expression::make_string(pf->tag(), bloc);
6304 	  fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6305 	}
6306 
6307       ++q;
6308       go_assert(q->is_field_name("offsetAnon"));
6309       Type* uintptr_type = Type::lookup_integer_type("uintptr");
6310       Expression* o = Expression::make_struct_field_offset(this, &*pf);
6311       Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6312       o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6313       int av = pf->is_anonymous() ? 1 : 0;
6314       Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6315       o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6316       fvals->push_back(o);
6317 
6318       Expression* v = Expression::make_struct_composite_literal(element_type,
6319 								fvals, bloc);
6320       elements->push_back(v);
6321     }
6322 
6323   vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6324 							   elements, bloc));
6325 
6326   return Expression::make_struct_composite_literal(stdt, vals, bloc);
6327 }
6328 
6329 // Write the hash function for a struct which can not use the identity
6330 // function.
6331 
6332 void
write_hash_function(Gogo * gogo,Named_type *,Function_type * hash_fntype,Function_type * equal_fntype)6333 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6334 				 Function_type* hash_fntype,
6335 				 Function_type* equal_fntype)
6336 {
6337   Location bloc = Linemap::predeclared_location();
6338 
6339   // The pointer to the struct that we are going to hash.  This is an
6340   // argument to the hash function we are implementing here.
6341   Named_object* key_arg = gogo->lookup("key", NULL);
6342   go_assert(key_arg != NULL);
6343   Type* key_arg_type = key_arg->var_value()->type();
6344 
6345   // The seed argument to the hash function.
6346   Named_object* seed_arg = gogo->lookup("seed", NULL);
6347   go_assert(seed_arg != NULL);
6348 
6349   Type* uintptr_type = Type::lookup_integer_type("uintptr");
6350 
6351   // Make a temporary to hold the return value, initialized to the seed.
6352   Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6353   Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6354 							  bloc);
6355   gogo->add_statement(retval);
6356 
6357   // Make a temporary to hold the key as a uintptr.
6358   ref = Expression::make_var_reference(key_arg, bloc);
6359   ref = Expression::make_cast(uintptr_type, ref, bloc);
6360   Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6361 						       bloc);
6362   gogo->add_statement(key);
6363 
6364   // Loop over the struct fields.
6365   const Struct_field_list* fields = this->fields_;
6366   for (Struct_field_list::const_iterator pf = fields->begin();
6367        pf != fields->end();
6368        ++pf)
6369     {
6370       if (Gogo::is_sink_name(pf->field_name()))
6371 	continue;
6372 
6373       // Get a pointer to the value of this field.
6374       Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6375       ref = Expression::make_temporary_reference(key, bloc);
6376       Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6377 						   bloc);
6378       subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6379 
6380       // Get the hash function to use for the type of this field.
6381       Named_object* hash_fn;
6382       Named_object* equal_fn;
6383       pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6384 				 equal_fntype, &hash_fn, &equal_fn);
6385 
6386       // Call the hash function for the field, passing retval as the seed.
6387       ref = Expression::make_temporary_reference(retval, bloc);
6388       Expression_list* args = new Expression_list();
6389       args->push_back(subkey);
6390       args->push_back(ref);
6391       Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6392       Expression* call = Expression::make_call(func, args, false, bloc);
6393 
6394       // Set retval to the result.
6395       Temporary_reference_expression* tref =
6396 	Expression::make_temporary_reference(retval, bloc);
6397       tref->set_is_lvalue();
6398       Statement* s = Statement::make_assignment(tref, call, bloc);
6399       gogo->add_statement(s);
6400     }
6401 
6402   // Return retval to the caller of the hash function.
6403   Expression_list* vals = new Expression_list();
6404   ref = Expression::make_temporary_reference(retval, bloc);
6405   vals->push_back(ref);
6406   Statement* s = Statement::make_return_statement(vals, bloc);
6407   gogo->add_statement(s);
6408 }
6409 
6410 // Write the equality function for a struct which can not use the
6411 // identity function.
6412 
6413 void
write_equal_function(Gogo * gogo,Named_type * name)6414 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6415 {
6416   Location bloc = Linemap::predeclared_location();
6417 
6418   // The pointers to the structs we are going to compare.
6419   Named_object* key1_arg = gogo->lookup("key1", NULL);
6420   Named_object* key2_arg = gogo->lookup("key2", NULL);
6421   go_assert(key1_arg != NULL && key2_arg != NULL);
6422 
6423   // Build temporaries with the right types.
6424   Type* pt = Type::make_pointer_type(name != NULL
6425 				     ? static_cast<Type*>(name)
6426 				     : static_cast<Type*>(this));
6427 
6428   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6429   ref = Expression::make_unsafe_cast(pt, ref, bloc);
6430   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6431   gogo->add_statement(p1);
6432 
6433   ref = Expression::make_var_reference(key2_arg, bloc);
6434   ref = Expression::make_unsafe_cast(pt, ref, bloc);
6435   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6436   gogo->add_statement(p2);
6437 
6438   const Struct_field_list* fields = this->fields_;
6439   unsigned int field_index = 0;
6440   for (Struct_field_list::const_iterator pf = fields->begin();
6441        pf != fields->end();
6442        ++pf, ++field_index)
6443     {
6444       if (Gogo::is_sink_name(pf->field_name()))
6445 	continue;
6446 
6447       // Compare one field in both P1 and P2.
6448       Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6449       f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6450                                         bloc);
6451       f1 = Expression::make_field_reference(f1, field_index, bloc);
6452 
6453       Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6454       f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6455                                         bloc);
6456       f2 = Expression::make_field_reference(f2, field_index, bloc);
6457 
6458       Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6459 
6460       // If the values are not equal, return false.
6461       gogo->start_block(bloc);
6462       Expression_list* vals = new Expression_list();
6463       vals->push_back(Expression::make_boolean(false, bloc));
6464       Statement* s = Statement::make_return_statement(vals, bloc);
6465       gogo->add_statement(s);
6466       Block* then_block = gogo->finish_block(bloc);
6467 
6468       s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6469       gogo->add_statement(s);
6470     }
6471 
6472   // All the fields are equal, so return true.
6473   Expression_list* vals = new Expression_list();
6474   vals->push_back(Expression::make_boolean(true, bloc));
6475   Statement* s = Statement::make_return_statement(vals, bloc);
6476   gogo->add_statement(s);
6477 }
6478 
6479 // Reflection string.
6480 
6481 void
do_reflection(Gogo * gogo,std::string * ret) const6482 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6483 {
6484   ret->append("struct {");
6485 
6486   for (Struct_field_list::const_iterator p = this->fields_->begin();
6487        p != this->fields_->end();
6488        ++p)
6489     {
6490       if (p != this->fields_->begin())
6491 	ret->push_back(';');
6492       ret->push_back(' ');
6493       if (!p->is_anonymous())
6494 	{
6495 	  ret->append(Gogo::unpack_hidden_name(p->field_name()));
6496 	  ret->push_back(' ');
6497 	}
6498       if (p->is_anonymous()
6499 	  && p->type()->named_type() != NULL
6500 	  && p->type()->named_type()->is_alias())
6501 	p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6502       else
6503 	this->append_reflection(p->type(), gogo, ret);
6504 
6505       if (p->has_tag())
6506 	{
6507 	  const std::string& tag(p->tag());
6508 	  ret->append(" \"");
6509 	  for (std::string::const_iterator p = tag.begin();
6510 	       p != tag.end();
6511 	       ++p)
6512 	    {
6513 	      if (*p == '\0')
6514 		ret->append("\\x00");
6515 	      else if (*p == '\n')
6516 		ret->append("\\n");
6517 	      else if (*p == '\t')
6518 		ret->append("\\t");
6519 	      else if (*p == '"')
6520 		ret->append("\\\"");
6521 	      else if (*p == '\\')
6522 		ret->append("\\\\");
6523 	      else
6524 		ret->push_back(*p);
6525 	    }
6526 	  ret->push_back('"');
6527 	}
6528     }
6529 
6530   if (!this->fields_->empty())
6531     ret->push_back(' ');
6532 
6533   ret->push_back('}');
6534 }
6535 
6536 // If the offset of field INDEX in the backend implementation can be
6537 // determined, set *POFFSET to the offset in bytes and return true.
6538 // Otherwise, return false.
6539 
6540 bool
backend_field_offset(Gogo * gogo,unsigned int index,int64_t * poffset)6541 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6542 				  int64_t* poffset)
6543 {
6544   if (!this->is_backend_type_size_known(gogo))
6545     return false;
6546   Btype* bt = this->get_backend_placeholder(gogo);
6547   *poffset = gogo->backend()->type_field_offset(bt, index);
6548   return true;
6549 }
6550 
6551 // Export.
6552 
6553 void
do_export(Export * exp) const6554 Struct_type::do_export(Export* exp) const
6555 {
6556   exp->write_c_string("struct { ");
6557   const Struct_field_list* fields = this->fields_;
6558   go_assert(fields != NULL);
6559   for (Struct_field_list::const_iterator p = fields->begin();
6560        p != fields->end();
6561        ++p)
6562     {
6563       if (p->is_anonymous())
6564 	exp->write_string("? ");
6565       else
6566 	{
6567 	  exp->write_string(p->field_name());
6568 	  exp->write_c_string(" ");
6569 	}
6570       exp->write_type(p->type());
6571 
6572       if (p->has_tag())
6573 	{
6574 	  exp->write_c_string(" ");
6575 	  Expression* expr =
6576             Expression::make_string(p->tag(), Linemap::predeclared_location());
6577 	  expr->export_expression(exp);
6578 	  delete expr;
6579 	}
6580 
6581       exp->write_c_string("; ");
6582     }
6583   exp->write_c_string("}");
6584 }
6585 
6586 // Import.
6587 
6588 Struct_type*
do_import(Import * imp)6589 Struct_type::do_import(Import* imp)
6590 {
6591   imp->require_c_string("struct { ");
6592   Struct_field_list* fields = new Struct_field_list;
6593   if (imp->peek_char() != '}')
6594     {
6595       while (true)
6596 	{
6597 	  std::string name;
6598 	  if (imp->match_c_string("? "))
6599 	    imp->advance(2);
6600 	  else
6601 	    {
6602 	      name = imp->read_identifier();
6603 	      imp->require_c_string(" ");
6604 	    }
6605 	  Type* ftype = imp->read_type();
6606 
6607 	  Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6608 	  sf.set_is_imported();
6609 
6610 	  if (imp->peek_char() == ' ')
6611 	    {
6612 	      imp->advance(1);
6613 	      Expression* expr = Expression::import_expression(imp);
6614 	      String_expression* sexpr = expr->string_expression();
6615 	      go_assert(sexpr != NULL);
6616 	      sf.set_tag(sexpr->val());
6617 	      delete sexpr;
6618 	    }
6619 
6620 	  imp->require_c_string("; ");
6621 	  fields->push_back(sf);
6622 	  if (imp->peek_char() == '}')
6623 	    break;
6624 	}
6625     }
6626   imp->require_c_string("}");
6627 
6628   return Type::make_struct_type(fields, imp->location());
6629 }
6630 
6631 // Whether we can write this struct type to a C header file.
6632 // We can't if any of the fields are structs defined in a different package.
6633 
6634 bool
can_write_to_c_header(std::vector<const Named_object * > * requires,std::vector<const Named_object * > * declare) const6635 Struct_type::can_write_to_c_header(
6636     std::vector<const Named_object*>* requires,
6637     std::vector<const Named_object*>* declare) const
6638 {
6639   const Struct_field_list* fields = this->fields_;
6640   if (fields == NULL || fields->empty())
6641     return false;
6642   int sinks = 0;
6643   for (Struct_field_list::const_iterator p = fields->begin();
6644        p != fields->end();
6645        ++p)
6646     {
6647       if (p->is_anonymous())
6648 	return false;
6649       if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6650 	return false;
6651       if (Gogo::message_name(p->field_name()) == "_")
6652 	sinks++;
6653     }
6654   if (sinks > 1)
6655     return false;
6656   return true;
6657 }
6658 
6659 // Whether we can write the type T to a C header file.
6660 
6661 bool
can_write_type_to_c_header(const Type * t,std::vector<const Named_object * > * requires,std::vector<const Named_object * > * declare) const6662 Struct_type::can_write_type_to_c_header(
6663     const Type* t,
6664     std::vector<const Named_object*>* requires,
6665     std::vector<const Named_object*>* declare) const
6666 {
6667   t = t->forwarded();
6668   switch (t->classification())
6669     {
6670     case TYPE_ERROR:
6671     case TYPE_FORWARD:
6672       return false;
6673 
6674     case TYPE_VOID:
6675     case TYPE_BOOLEAN:
6676     case TYPE_INTEGER:
6677     case TYPE_FLOAT:
6678     case TYPE_COMPLEX:
6679     case TYPE_STRING:
6680     case TYPE_FUNCTION:
6681     case TYPE_MAP:
6682     case TYPE_CHANNEL:
6683     case TYPE_INTERFACE:
6684       return true;
6685 
6686     case TYPE_POINTER:
6687       // Don't try to handle a pointer to an array.
6688       if (t->points_to()->array_type() != NULL
6689 	  && !t->points_to()->is_slice_type())
6690 	return false;
6691 
6692       if (t->points_to()->named_type() != NULL
6693 	  && t->points_to()->struct_type() != NULL)
6694 	declare->push_back(t->points_to()->named_type()->named_object());
6695       return true;
6696 
6697     case TYPE_STRUCT:
6698       return t->struct_type()->can_write_to_c_header(requires, declare);
6699 
6700     case TYPE_ARRAY:
6701       if (t->is_slice_type())
6702 	return true;
6703       return this->can_write_type_to_c_header(t->array_type()->element_type(),
6704 					      requires, declare);
6705 
6706     case TYPE_NAMED:
6707       {
6708 	const Named_object* no = t->named_type()->named_object();
6709 	if (no->package() != NULL)
6710 	  {
6711 	    if (t->is_unsafe_pointer_type())
6712 	      return true;
6713 	    return false;
6714 	  }
6715 	if (t->struct_type() != NULL)
6716 	  {
6717 	    requires->push_back(no);
6718 	    return t->struct_type()->can_write_to_c_header(requires, declare);
6719 	  }
6720 	return this->can_write_type_to_c_header(t->base(), requires, declare);
6721       }
6722 
6723     case TYPE_CALL_MULTIPLE_RESULT:
6724     case TYPE_NIL:
6725     case TYPE_SINK:
6726     default:
6727       go_unreachable();
6728     }
6729 }
6730 
6731 // Write this struct to a C header file.
6732 
6733 void
write_to_c_header(std::ostream & os) const6734 Struct_type::write_to_c_header(std::ostream& os) const
6735 {
6736   const Struct_field_list* fields = this->fields_;
6737   for (Struct_field_list::const_iterator p = fields->begin();
6738        p != fields->end();
6739        ++p)
6740     {
6741       os << '\t';
6742       this->write_field_to_c_header(os, p->field_name(), p->type());
6743       os << ';' << std::endl;
6744     }
6745 }
6746 
6747 // Write the type of a struct field to a C header file.
6748 
6749 void
write_field_to_c_header(std::ostream & os,const std::string & name,const Type * t) const6750 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6751 				     const Type *t) const
6752 {
6753   bool print_name = true;
6754   t = t->forwarded();
6755   switch (t->classification())
6756     {
6757     case TYPE_VOID:
6758       os << "void";
6759       break;
6760 
6761     case TYPE_BOOLEAN:
6762       os << "_Bool";
6763       break;
6764 
6765     case TYPE_INTEGER:
6766       {
6767 	const Integer_type* it = t->integer_type();
6768 	if (it->is_unsigned())
6769 	  os << 'u';
6770 	os << "int" << it->bits() << "_t";
6771       }
6772       break;
6773 
6774     case TYPE_FLOAT:
6775       switch (t->float_type()->bits())
6776 	{
6777 	case 32:
6778 	  os << "float";
6779 	  break;
6780 	case 64:
6781 	  os << "double";
6782 	  break;
6783 	default:
6784 	  go_unreachable();
6785 	}
6786       break;
6787 
6788     case TYPE_COMPLEX:
6789       switch (t->complex_type()->bits())
6790 	{
6791 	case 64:
6792 	  os << "float _Complex";
6793 	  break;
6794 	case 128:
6795 	  os << "double _Complex";
6796 	  break;
6797 	default:
6798 	  go_unreachable();
6799 	}
6800       break;
6801 
6802     case TYPE_STRING:
6803       os << "String";
6804       break;
6805 
6806     case TYPE_FUNCTION:
6807       os << "FuncVal*";
6808       break;
6809 
6810     case TYPE_POINTER:
6811       {
6812 	std::vector<const Named_object*> requires;
6813 	std::vector<const Named_object*> declare;
6814 	if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6815 					      &declare))
6816 	  os << "void*";
6817 	else
6818 	  {
6819 	    this->write_field_to_c_header(os, "", t->points_to());
6820 	    os << '*';
6821 	  }
6822       }
6823       break;
6824 
6825     case TYPE_MAP:
6826       os << "Map*";
6827       break;
6828 
6829     case TYPE_CHANNEL:
6830       os << "Chan*";
6831       break;
6832 
6833     case TYPE_INTERFACE:
6834       if (t->interface_type()->is_empty())
6835 	os << "Eface";
6836       else
6837 	os << "Iface";
6838       break;
6839 
6840     case TYPE_STRUCT:
6841       os << "struct {" << std::endl;
6842       t->struct_type()->write_to_c_header(os);
6843       os << "\t}";
6844       break;
6845 
6846     case TYPE_ARRAY:
6847       if (t->is_slice_type())
6848 	os << "Slice";
6849       else
6850 	{
6851 	  const Type *ele = t;
6852 	  std::vector<const Type*> array_types;
6853 	  while (ele->array_type() != NULL && !ele->is_slice_type())
6854 	    {
6855 	      array_types.push_back(ele);
6856 	      ele = ele->array_type()->element_type();
6857 	    }
6858 	  this->write_field_to_c_header(os, "", ele);
6859 	  os << ' ' << Gogo::message_name(name);
6860 	  print_name = false;
6861 	  while (!array_types.empty())
6862 	    {
6863 	      ele = array_types.back();
6864 	      array_types.pop_back();
6865 	      os << '[';
6866 	      Numeric_constant nc;
6867 	      if (!ele->array_type()->length()->numeric_constant_value(&nc))
6868 		go_unreachable();
6869 	      mpz_t val;
6870 	      if (!nc.to_int(&val))
6871 		go_unreachable();
6872 	      char* s = mpz_get_str(NULL, 10, val);
6873 	      os << s;
6874 	      free(s);
6875 	      mpz_clear(val);
6876 	      os << ']';
6877 	    }
6878 	}
6879       break;
6880 
6881     case TYPE_NAMED:
6882       {
6883 	const Named_object* no = t->named_type()->named_object();
6884 	if (t->struct_type() != NULL)
6885 	  os << "struct " << no->message_name();
6886 	else if (t->is_unsafe_pointer_type())
6887 	  os << "void*";
6888 	else if (t == Type::lookup_integer_type("uintptr"))
6889 	  os << "uintptr_t";
6890 	else
6891 	  {
6892 	    this->write_field_to_c_header(os, name, t->base());
6893 	    print_name = false;
6894 	  }
6895       }
6896       break;
6897 
6898     case TYPE_ERROR:
6899     case TYPE_FORWARD:
6900     case TYPE_CALL_MULTIPLE_RESULT:
6901     case TYPE_NIL:
6902     case TYPE_SINK:
6903     default:
6904       go_unreachable();
6905     }
6906 
6907   if (print_name && !name.empty())
6908     os << ' ' << Gogo::message_name(name);
6909 }
6910 
6911 // Make a struct type.
6912 
6913 Struct_type*
make_struct_type(Struct_field_list * fields,Location location)6914 Type::make_struct_type(Struct_field_list* fields,
6915 		       Location location)
6916 {
6917   return new Struct_type(fields, location);
6918 }
6919 
6920 // Class Array_type.
6921 
6922 // Store the length of an array as an int64_t into *PLEN.  Return
6923 // false if the length can not be determined.  This will assert if
6924 // called for a slice.
6925 
6926 bool
int_length(int64_t * plen)6927 Array_type::int_length(int64_t* plen)
6928 {
6929   go_assert(this->length_ != NULL);
6930   Numeric_constant nc;
6931   if (!this->length_->numeric_constant_value(&nc))
6932     return false;
6933   return nc.to_memory_size(plen);
6934 }
6935 
6936 // Whether two array types are identical.
6937 
6938 bool
is_identical(const Array_type * t,Cmp_tags cmp_tags,bool errors_are_identical) const6939 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6940 			 bool errors_are_identical) const
6941 {
6942   if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6943 				    cmp_tags, errors_are_identical, NULL))
6944     return false;
6945 
6946   if (this->is_array_incomparable_ != t->is_array_incomparable_)
6947     return false;
6948 
6949   Expression* l1 = this->length();
6950   Expression* l2 = t->length();
6951 
6952   // Slices of the same element type are identical.
6953   if (l1 == NULL && l2 == NULL)
6954     return true;
6955 
6956   // Arrays of the same element type are identical if they have the
6957   // same length.
6958   if (l1 != NULL && l2 != NULL)
6959     {
6960       if (l1 == l2)
6961 	return true;
6962 
6963       // Try to determine the lengths.  If we can't, assume the arrays
6964       // are not identical.
6965       bool ret = false;
6966       Numeric_constant nc1, nc2;
6967       if (l1->numeric_constant_value(&nc1)
6968 	  && l2->numeric_constant_value(&nc2))
6969 	{
6970 	  mpz_t v1;
6971 	  if (nc1.to_int(&v1))
6972 	    {
6973 	      mpz_t v2;
6974 	      if (nc2.to_int(&v2))
6975 		{
6976 		  ret = mpz_cmp(v1, v2) == 0;
6977 		  mpz_clear(v2);
6978 		}
6979 	      mpz_clear(v1);
6980 	    }
6981 	}
6982       return ret;
6983     }
6984 
6985   // Otherwise the arrays are not identical.
6986   return false;
6987 }
6988 
6989 // Traversal.
6990 
6991 int
do_traverse(Traverse * traverse)6992 Array_type::do_traverse(Traverse* traverse)
6993 {
6994   if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6995     return TRAVERSE_EXIT;
6996   if (this->length_ != NULL
6997       && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6998     return TRAVERSE_EXIT;
6999   return TRAVERSE_CONTINUE;
7000 }
7001 
7002 // Check that the length is valid.
7003 
7004 bool
verify_length()7005 Array_type::verify_length()
7006 {
7007   if (this->length_ == NULL)
7008     return true;
7009 
7010   Type_context context(Type::lookup_integer_type("int"), false);
7011   this->length_->determine_type(&context);
7012 
7013   if (!this->length_->is_constant())
7014     {
7015       go_error_at(this->length_->location(), "array bound is not constant");
7016       return false;
7017     }
7018 
7019   Numeric_constant nc;
7020   if (!this->length_->numeric_constant_value(&nc))
7021     {
7022       if (this->length_->type()->integer_type() != NULL
7023 	  || this->length_->type()->float_type() != NULL)
7024 	go_error_at(this->length_->location(), "array bound is not constant");
7025       else
7026 	go_error_at(this->length_->location(), "array bound is not numeric");
7027       return false;
7028     }
7029 
7030   Type* int_type = Type::lookup_integer_type("int");
7031   unsigned int tbits = int_type->integer_type()->bits();
7032   unsigned long val;
7033   switch (nc.to_unsigned_long(&val))
7034     {
7035     case Numeric_constant::NC_UL_VALID:
7036       if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7037 	{
7038 	  go_error_at(this->length_->location(), "array bound overflows");
7039 	  return false;
7040 	}
7041       break;
7042     case Numeric_constant::NC_UL_NOTINT:
7043       go_error_at(this->length_->location(), "array bound truncated to integer");
7044       return false;
7045     case Numeric_constant::NC_UL_NEGATIVE:
7046       go_error_at(this->length_->location(), "negative array bound");
7047       return false;
7048     case Numeric_constant::NC_UL_BIG:
7049       {
7050 	mpz_t val;
7051 	if (!nc.to_int(&val))
7052 	  go_unreachable();
7053 	unsigned int bits = mpz_sizeinbase(val, 2);
7054 	mpz_clear(val);
7055 	if (bits >= tbits)
7056 	  {
7057 	    go_error_at(this->length_->location(), "array bound overflows");
7058 	    return false;
7059 	  }
7060       }
7061       break;
7062     default:
7063       go_unreachable();
7064     }
7065 
7066   return true;
7067 }
7068 
7069 // Verify the type.
7070 
7071 bool
do_verify()7072 Array_type::do_verify()
7073 {
7074   if (this->element_type()->is_error_type())
7075     return false;
7076   if (!this->verify_length())
7077     this->length_ = Expression::make_error(this->length_->location());
7078   return true;
7079 }
7080 
7081 // Whether the type contains pointers.  This is always true for a
7082 // slice.  For an array it is true if the element type has pointers
7083 // and the length is greater than zero.
7084 
7085 bool
do_has_pointer() const7086 Array_type::do_has_pointer() const
7087 {
7088   if (this->length_ == NULL)
7089     return true;
7090   if (!this->element_type_->has_pointer())
7091     return false;
7092 
7093   Numeric_constant nc;
7094   if (!this->length_->numeric_constant_value(&nc))
7095     {
7096       // Error reported elsewhere.
7097       return false;
7098     }
7099 
7100   unsigned long val;
7101   switch (nc.to_unsigned_long(&val))
7102     {
7103     case Numeric_constant::NC_UL_VALID:
7104       return val > 0;
7105     case Numeric_constant::NC_UL_BIG:
7106       return true;
7107     default:
7108       // Error reported elsewhere.
7109       return false;
7110     }
7111 }
7112 
7113 // Whether we can use memcmp to compare this array.
7114 
7115 bool
do_compare_is_identity(Gogo * gogo)7116 Array_type::do_compare_is_identity(Gogo* gogo)
7117 {
7118   if (this->length_ == NULL)
7119     return false;
7120 
7121   // Check for [...], which indicates that this is not a real type.
7122   if (this->length_->is_nil_expression())
7123     return false;
7124 
7125   if (!this->element_type_->compare_is_identity(gogo))
7126     return false;
7127 
7128   // If there is any padding, then we can't use memcmp.
7129   int64_t size;
7130   int64_t align;
7131   if (!this->element_type_->backend_type_size(gogo, &size)
7132       || !this->element_type_->backend_type_align(gogo, &align))
7133     return false;
7134   if ((size & (align - 1)) != 0)
7135     return false;
7136 
7137   return true;
7138 }
7139 
7140 // Array type hash code.
7141 
7142 unsigned int
do_hash_for_method(Gogo * gogo) const7143 Array_type::do_hash_for_method(Gogo* gogo) const
7144 {
7145   unsigned int ret;
7146 
7147   // There is no very convenient way to get a hash code for the
7148   // length.
7149   ret = this->element_type_->hash_for_method(gogo) + 1;
7150   if (this->is_array_incomparable_)
7151     ret <<= 1;
7152   return ret;
7153 }
7154 
7155 // Write the hash function for an array which can not use the identify
7156 // function.
7157 
7158 void
write_hash_function(Gogo * gogo,Named_type * name,Function_type * hash_fntype,Function_type * equal_fntype)7159 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7160 				Function_type* hash_fntype,
7161 				Function_type* equal_fntype)
7162 {
7163   Location bloc = Linemap::predeclared_location();
7164 
7165   // The pointer to the array that we are going to hash.  This is an
7166   // argument to the hash function we are implementing here.
7167   Named_object* key_arg = gogo->lookup("key", NULL);
7168   go_assert(key_arg != NULL);
7169   Type* key_arg_type = key_arg->var_value()->type();
7170 
7171   // The seed argument to the hash function.
7172   Named_object* seed_arg = gogo->lookup("seed", NULL);
7173   go_assert(seed_arg != NULL);
7174 
7175   Type* uintptr_type = Type::lookup_integer_type("uintptr");
7176 
7177   // Make a temporary to hold the return value, initialized to the seed.
7178   Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7179   Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7180 							  bloc);
7181   gogo->add_statement(retval);
7182 
7183   // Make a temporary to hold the key as a uintptr.
7184   ref = Expression::make_var_reference(key_arg, bloc);
7185   ref = Expression::make_cast(uintptr_type, ref, bloc);
7186   Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7187 						       bloc);
7188   gogo->add_statement(key);
7189 
7190   // Loop over the array elements.
7191   // for i = range a
7192   Type* int_type = Type::lookup_integer_type("int");
7193   Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7194   gogo->add_statement(index);
7195 
7196   Expression* iref = Expression::make_temporary_reference(index, bloc);
7197   Expression* aref = Expression::make_var_reference(key_arg, bloc);
7198   Type* pt = Type::make_pointer_type(name != NULL
7199 				     ? static_cast<Type*>(name)
7200 				     : static_cast<Type*>(this));
7201   aref = Expression::make_cast(pt, aref, bloc);
7202   For_range_statement* for_range = Statement::make_for_range_statement(iref,
7203 								       NULL,
7204 								       aref,
7205 								       bloc);
7206 
7207   gogo->start_block(bloc);
7208 
7209   // Get the hash function for the element type.
7210   Named_object* hash_fn;
7211   Named_object* equal_fn;
7212   this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7213 				      hash_fntype, equal_fntype, &hash_fn,
7214 				      &equal_fn);
7215 
7216   // Get a pointer to this element in the loop.
7217   Expression* subkey = Expression::make_temporary_reference(key, bloc);
7218   subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7219 
7220   // Get the size of each element.
7221   Expression* ele_size = Expression::make_type_info(this->element_type_,
7222 						    Expression::TYPE_INFO_SIZE);
7223 
7224   // Get the hash of this element, passing retval as the seed.
7225   ref = Expression::make_temporary_reference(retval, bloc);
7226   Expression_list* args = new Expression_list();
7227   args->push_back(subkey);
7228   args->push_back(ref);
7229   Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7230   Expression* call = Expression::make_call(func, args, false, bloc);
7231 
7232   // Set retval to the result.
7233   Temporary_reference_expression* tref =
7234     Expression::make_temporary_reference(retval, bloc);
7235   tref->set_is_lvalue();
7236   Statement* s = Statement::make_assignment(tref, call, bloc);
7237   gogo->add_statement(s);
7238 
7239   // Increase the element pointer.
7240   tref = Expression::make_temporary_reference(key, bloc);
7241   tref->set_is_lvalue();
7242   s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7243 					   bloc);
7244   Block* statements = gogo->finish_block(bloc);
7245 
7246   for_range->add_statements(statements);
7247   gogo->add_statement(for_range);
7248 
7249   // Return retval to the caller of the hash function.
7250   Expression_list* vals = new Expression_list();
7251   ref = Expression::make_temporary_reference(retval, bloc);
7252   vals->push_back(ref);
7253   s = Statement::make_return_statement(vals, bloc);
7254   gogo->add_statement(s);
7255 }
7256 
7257 // Write the equality function for an array which can not use the
7258 // identity function.
7259 
7260 void
write_equal_function(Gogo * gogo,Named_type * name)7261 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7262 {
7263   Location bloc = Linemap::predeclared_location();
7264 
7265   // The pointers to the arrays we are going to compare.
7266   Named_object* key1_arg = gogo->lookup("key1", NULL);
7267   Named_object* key2_arg = gogo->lookup("key2", NULL);
7268   go_assert(key1_arg != NULL && key2_arg != NULL);
7269 
7270   // Build temporaries for the keys with the right types.
7271   Type* pt = Type::make_pointer_type(name != NULL
7272 				     ? static_cast<Type*>(name)
7273 				     : static_cast<Type*>(this));
7274 
7275   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7276   ref = Expression::make_unsafe_cast(pt, ref, bloc);
7277   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7278   gogo->add_statement(p1);
7279 
7280   ref = Expression::make_var_reference(key2_arg, bloc);
7281   ref = Expression::make_unsafe_cast(pt, ref, bloc);
7282   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7283   gogo->add_statement(p2);
7284 
7285   // Loop over the array elements.
7286   // for i = range a
7287   Type* int_type = Type::lookup_integer_type("int");
7288   Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7289   gogo->add_statement(index);
7290 
7291   Expression* iref = Expression::make_temporary_reference(index, bloc);
7292   Expression* aref = Expression::make_temporary_reference(p1, bloc);
7293   For_range_statement* for_range = Statement::make_for_range_statement(iref,
7294 								       NULL,
7295 								       aref,
7296 								       bloc);
7297 
7298   gogo->start_block(bloc);
7299 
7300   // Compare element in P1 and P2.
7301   Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7302   e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7303   ref = Expression::make_temporary_reference(index, bloc);
7304   e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7305 
7306   Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7307   e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7308   ref = Expression::make_temporary_reference(index, bloc);
7309   e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7310 
7311   Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7312 
7313   // If the elements are not equal, return false.
7314   gogo->start_block(bloc);
7315   Expression_list* vals = new Expression_list();
7316   vals->push_back(Expression::make_boolean(false, bloc));
7317   Statement* s = Statement::make_return_statement(vals, bloc);
7318   gogo->add_statement(s);
7319   Block* then_block = gogo->finish_block(bloc);
7320 
7321   s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7322   gogo->add_statement(s);
7323 
7324   Block* statements = gogo->finish_block(bloc);
7325 
7326   for_range->add_statements(statements);
7327   gogo->add_statement(for_range);
7328 
7329   // All the elements are equal, so return true.
7330   vals = new Expression_list();
7331   vals->push_back(Expression::make_boolean(true, bloc));
7332   s = Statement::make_return_statement(vals, bloc);
7333   gogo->add_statement(s);
7334 }
7335 
7336 // Get the backend representation of the fields of a slice.  This is
7337 // not declared in types.h so that types.h doesn't have to #include
7338 // backend.h.
7339 //
7340 // We use int for the count and capacity fields.  This matches 6g.
7341 // The language more or less assumes that we can't allocate space of a
7342 // size which does not fit in int.
7343 
7344 static void
get_backend_slice_fields(Gogo * gogo,Array_type * type,bool use_placeholder,std::vector<Backend::Btyped_identifier> * bfields)7345 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7346 			 std::vector<Backend::Btyped_identifier>* bfields)
7347 {
7348   bfields->resize(3);
7349 
7350   Type* pet = Type::make_pointer_type(type->element_type());
7351   Btype* pbet = (use_placeholder
7352 		 ? pet->get_backend_placeholder(gogo)
7353 		 : pet->get_backend(gogo));
7354   Location ploc = Linemap::predeclared_location();
7355 
7356   Backend::Btyped_identifier* p = &(*bfields)[0];
7357   p->name = "__values";
7358   p->btype = pbet;
7359   p->location = ploc;
7360 
7361   Type* int_type = Type::lookup_integer_type("int");
7362 
7363   p = &(*bfields)[1];
7364   p->name = "__count";
7365   p->btype = int_type->get_backend(gogo);
7366   p->location = ploc;
7367 
7368   p = &(*bfields)[2];
7369   p->name = "__capacity";
7370   p->btype = int_type->get_backend(gogo);
7371   p->location = ploc;
7372 }
7373 
7374 // Get the backend representation for the type of this array.  A fixed array is
7375 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7376 // just like an array in C.  An open array is a struct with three
7377 // fields: a data pointer, the length, and the capacity.
7378 
7379 Btype*
do_get_backend(Gogo * gogo)7380 Array_type::do_get_backend(Gogo* gogo)
7381 {
7382   if (this->length_ == NULL)
7383     {
7384       std::vector<Backend::Btyped_identifier> bfields;
7385       get_backend_slice_fields(gogo, this, false, &bfields);
7386       return gogo->backend()->struct_type(bfields);
7387     }
7388   else
7389     {
7390       Btype* element = this->get_backend_element(gogo, false);
7391       Bexpression* len = this->get_backend_length(gogo);
7392       return gogo->backend()->array_type(element, len);
7393     }
7394 }
7395 
7396 // Return the backend representation of the element type.
7397 
7398 Btype*
get_backend_element(Gogo * gogo,bool use_placeholder)7399 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7400 {
7401   if (use_placeholder)
7402     return this->element_type_->get_backend_placeholder(gogo);
7403   else
7404     return this->element_type_->get_backend(gogo);
7405 }
7406 
7407 // Return the backend representation of the length. The length may be
7408 // computed using a function call, so we must only evaluate it once.
7409 
7410 Bexpression*
get_backend_length(Gogo * gogo)7411 Array_type::get_backend_length(Gogo* gogo)
7412 {
7413   go_assert(this->length_ != NULL);
7414   if (this->blength_ == NULL)
7415     {
7416       if (this->length_->is_error_expression())
7417         {
7418           this->blength_ = gogo->backend()->error_expression();
7419           return this->blength_;
7420         }
7421       Numeric_constant nc;
7422       mpz_t val;
7423       if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7424 	{
7425 	  if (mpz_sgn(val) < 0)
7426 	    {
7427 	      this->blength_ = gogo->backend()->error_expression();
7428 	      return this->blength_;
7429 	    }
7430 	  Type* t = nc.type();
7431 	  if (t == NULL)
7432 	    t = Type::lookup_integer_type("int");
7433 	  else if (t->is_abstract())
7434 	    t = t->make_non_abstract_type();
7435           Btype* btype = t->get_backend(gogo);
7436           this->blength_ =
7437 	    gogo->backend()->integer_constant_expression(btype, val);
7438 	  mpz_clear(val);
7439 	}
7440       else
7441 	{
7442 	  // Make up a translation context for the array length
7443 	  // expression.  FIXME: This won't work in general.
7444 	  Translate_context context(gogo, NULL, NULL, NULL);
7445 	  this->blength_ = this->length_->get_backend(&context);
7446 
7447 	  Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7448 	  this->blength_ =
7449 	    gogo->backend()->convert_expression(ibtype, this->blength_,
7450 						this->length_->location());
7451 	}
7452     }
7453   return this->blength_;
7454 }
7455 
7456 // Finish backend representation of the array.
7457 
7458 void
finish_backend_element(Gogo * gogo)7459 Array_type::finish_backend_element(Gogo* gogo)
7460 {
7461   Type* et = this->array_type()->element_type();
7462   et->get_backend(gogo);
7463   if (this->is_slice_type())
7464     {
7465       // This relies on the fact that we always use the same
7466       // structure for a pointer to any given type.
7467       Type* pet = Type::make_pointer_type(et);
7468       pet->get_backend(gogo);
7469     }
7470 }
7471 
7472 // Return an expression for a pointer to the values in ARRAY.
7473 
7474 Expression*
get_value_pointer(Gogo *,Expression * array,bool is_lvalue) const7475 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7476 {
7477   if (this->length() != NULL)
7478     {
7479       // Fixed array.
7480       go_assert(array->type()->array_type() != NULL);
7481       Type* etype = array->type()->array_type()->element_type();
7482       array = Expression::make_unary(OPERATOR_AND, array, array->location());
7483       return Expression::make_cast(Type::make_pointer_type(etype), array,
7484                                    array->location());
7485     }
7486 
7487   // Slice.
7488 
7489   if (is_lvalue)
7490     {
7491       Temporary_reference_expression* tref =
7492           array->temporary_reference_expression();
7493       Var_expression* ve = array->var_expression();
7494       if (tref != NULL)
7495         {
7496           tref = tref->copy()->temporary_reference_expression();
7497           tref->set_is_lvalue();
7498           array = tref;
7499         }
7500       else if (ve != NULL)
7501         {
7502           ve = new Var_expression(ve->named_object(), ve->location());
7503           array = ve;
7504         }
7505     }
7506 
7507   return Expression::make_slice_info(array,
7508                                      Expression::SLICE_INFO_VALUE_POINTER,
7509                                      array->location());
7510 }
7511 
7512 // Return an expression for the length of the array ARRAY which has this
7513 // type.
7514 
7515 Expression*
get_length(Gogo *,Expression * array) const7516 Array_type::get_length(Gogo*, Expression* array) const
7517 {
7518   if (this->length_ != NULL)
7519     return this->length_;
7520 
7521   // This is a slice.  We need to read the length field.
7522   return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7523                                      array->location());
7524 }
7525 
7526 // Return an expression for the capacity of the array ARRAY which has this
7527 // type.
7528 
7529 Expression*
get_capacity(Gogo *,Expression * array) const7530 Array_type::get_capacity(Gogo*, Expression* array) const
7531 {
7532   if (this->length_ != NULL)
7533     return this->length_;
7534 
7535   // This is a slice.  We need to read the capacity field.
7536   return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7537                                      array->location());
7538 }
7539 
7540 // Export.
7541 
7542 void
do_export(Export * exp) const7543 Array_type::do_export(Export* exp) const
7544 {
7545   exp->write_c_string("[");
7546   if (this->length_ != NULL)
7547     this->length_->export_expression(exp);
7548   exp->write_c_string("] ");
7549   exp->write_type(this->element_type_);
7550 }
7551 
7552 // Import.
7553 
7554 Array_type*
do_import(Import * imp)7555 Array_type::do_import(Import* imp)
7556 {
7557   imp->require_c_string("[");
7558   Expression* length;
7559   if (imp->peek_char() == ']')
7560     length = NULL;
7561   else
7562     length = Expression::import_expression(imp);
7563   imp->require_c_string("] ");
7564   Type* element_type = imp->read_type();
7565   return Type::make_array_type(element_type, length);
7566 }
7567 
7568 // The type of an array type descriptor.
7569 
7570 Type*
make_array_type_descriptor_type()7571 Array_type::make_array_type_descriptor_type()
7572 {
7573   static Type* ret;
7574   if (ret == NULL)
7575     {
7576       Type* tdt = Type::make_type_descriptor_type();
7577       Type* ptdt = Type::make_type_descriptor_ptr_type();
7578 
7579       Type* uintptr_type = Type::lookup_integer_type("uintptr");
7580 
7581       Struct_type* sf =
7582 	Type::make_builtin_struct_type(4,
7583 				       "", tdt,
7584 				       "elem", ptdt,
7585 				       "slice", ptdt,
7586 				       "len", uintptr_type);
7587 
7588       ret = Type::make_builtin_named_type("ArrayType", sf);
7589     }
7590 
7591   return ret;
7592 }
7593 
7594 // The type of an slice type descriptor.
7595 
7596 Type*
make_slice_type_descriptor_type()7597 Array_type::make_slice_type_descriptor_type()
7598 {
7599   static Type* ret;
7600   if (ret == NULL)
7601     {
7602       Type* tdt = Type::make_type_descriptor_type();
7603       Type* ptdt = Type::make_type_descriptor_ptr_type();
7604 
7605       Struct_type* sf =
7606 	Type::make_builtin_struct_type(2,
7607 				       "", tdt,
7608 				       "elem", ptdt);
7609 
7610       ret = Type::make_builtin_named_type("SliceType", sf);
7611     }
7612 
7613   return ret;
7614 }
7615 
7616 // Build a type descriptor for an array/slice type.
7617 
7618 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)7619 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7620 {
7621   if (this->length_ != NULL)
7622     return this->array_type_descriptor(gogo, name);
7623   else
7624     return this->slice_type_descriptor(gogo, name);
7625 }
7626 
7627 // Build a type descriptor for an array type.
7628 
7629 Expression*
array_type_descriptor(Gogo * gogo,Named_type * name)7630 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7631 {
7632   Location bloc = Linemap::predeclared_location();
7633 
7634   Type* atdt = Array_type::make_array_type_descriptor_type();
7635 
7636   const Struct_field_list* fields = atdt->struct_type()->fields();
7637 
7638   Expression_list* vals = new Expression_list();
7639   vals->reserve(3);
7640 
7641   Struct_field_list::const_iterator p = fields->begin();
7642   go_assert(p->is_field_name("_type"));
7643   vals->push_back(this->type_descriptor_constructor(gogo,
7644 						    RUNTIME_TYPE_KIND_ARRAY,
7645 						    name, NULL, true));
7646 
7647   ++p;
7648   go_assert(p->is_field_name("elem"));
7649   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7650 
7651   ++p;
7652   go_assert(p->is_field_name("slice"));
7653   Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7654   vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7655 
7656   ++p;
7657   go_assert(p->is_field_name("len"));
7658   vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7659 
7660   ++p;
7661   go_assert(p == fields->end());
7662 
7663   return Expression::make_struct_composite_literal(atdt, vals, bloc);
7664 }
7665 
7666 // Build a type descriptor for a slice type.
7667 
7668 Expression*
slice_type_descriptor(Gogo * gogo,Named_type * name)7669 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7670 {
7671   Location bloc = Linemap::predeclared_location();
7672 
7673   Type* stdt = Array_type::make_slice_type_descriptor_type();
7674 
7675   const Struct_field_list* fields = stdt->struct_type()->fields();
7676 
7677   Expression_list* vals = new Expression_list();
7678   vals->reserve(2);
7679 
7680   Struct_field_list::const_iterator p = fields->begin();
7681   go_assert(p->is_field_name("_type"));
7682   vals->push_back(this->type_descriptor_constructor(gogo,
7683 						    RUNTIME_TYPE_KIND_SLICE,
7684 						    name, NULL, true));
7685 
7686   ++p;
7687   go_assert(p->is_field_name("elem"));
7688   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7689 
7690   ++p;
7691   go_assert(p == fields->end());
7692 
7693   return Expression::make_struct_composite_literal(stdt, vals, bloc);
7694 }
7695 
7696 // Reflection string.
7697 
7698 void
do_reflection(Gogo * gogo,std::string * ret) const7699 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7700 {
7701   ret->push_back('[');
7702   if (this->length_ != NULL)
7703     {
7704       Numeric_constant nc;
7705       if (!this->length_->numeric_constant_value(&nc))
7706 	{
7707 	  go_assert(saw_errors());
7708 	  return;
7709 	}
7710       mpz_t val;
7711       if (!nc.to_int(&val))
7712 	{
7713 	  go_assert(saw_errors());
7714 	  return;
7715 	}
7716       char* s = mpz_get_str(NULL, 10, val);
7717       ret->append(s);
7718       free(s);
7719       mpz_clear(val);
7720     }
7721   ret->push_back(']');
7722 
7723   this->append_reflection(this->element_type_, gogo, ret);
7724 }
7725 
7726 // Make an array type.
7727 
7728 Array_type*
make_array_type(Type * element_type,Expression * length)7729 Type::make_array_type(Type* element_type, Expression* length)
7730 {
7731   return new Array_type(element_type, length);
7732 }
7733 
7734 // Class Map_type.
7735 
7736 Named_object* Map_type::zero_value;
7737 int64_t Map_type::zero_value_size;
7738 int64_t Map_type::zero_value_align;
7739 
7740 // If this map requires the "fat" functions, return the pointer to
7741 // pass as the zero value to those functions.  Otherwise, in the
7742 // normal case, return NULL.  The map requires the "fat" functions if
7743 // the value size is larger than max_zero_size bytes.  max_zero_size
7744 // must match maxZero in libgo/go/runtime/hashmap.go.
7745 
7746 Expression*
fat_zero_value(Gogo * gogo)7747 Map_type::fat_zero_value(Gogo* gogo)
7748 {
7749   int64_t valsize;
7750   if (!this->val_type_->backend_type_size(gogo, &valsize))
7751     {
7752       go_assert(saw_errors());
7753       return NULL;
7754     }
7755   if (valsize <= Map_type::max_zero_size)
7756     return NULL;
7757 
7758   if (Map_type::zero_value_size < valsize)
7759     Map_type::zero_value_size = valsize;
7760 
7761   int64_t valalign;
7762   if (!this->val_type_->backend_type_align(gogo, &valalign))
7763     {
7764       go_assert(saw_errors());
7765       return NULL;
7766     }
7767 
7768   if (Map_type::zero_value_align < valalign)
7769     Map_type::zero_value_align = valalign;
7770 
7771   Location bloc = Linemap::predeclared_location();
7772 
7773   if (Map_type::zero_value == NULL)
7774     {
7775       // The final type will be set in backend_zero_value.
7776       Type* uint8_type = Type::lookup_integer_type("uint8");
7777       Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7778       Array_type* array_type = Type::make_array_type(uint8_type, size);
7779       array_type->set_is_array_incomparable();
7780       Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7781       std::string name = gogo->map_zero_value_name();
7782       Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7783     }
7784 
7785   Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7786   z = Expression::make_unary(OPERATOR_AND, z, bloc);
7787   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7788   z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7789   return z;
7790 }
7791 
7792 // Return whether VAR is the map zero value.
7793 
7794 bool
is_zero_value(Variable * var)7795 Map_type::is_zero_value(Variable* var)
7796 {
7797   return (Map_type::zero_value != NULL
7798 	  && Map_type::zero_value->var_value() == var);
7799 }
7800 
7801 // Return the backend representation for the zero value.
7802 
7803 Bvariable*
backend_zero_value(Gogo * gogo)7804 Map_type::backend_zero_value(Gogo* gogo)
7805 {
7806   Location bloc = Linemap::predeclared_location();
7807 
7808   go_assert(Map_type::zero_value != NULL);
7809 
7810   Type* uint8_type = Type::lookup_integer_type("uint8");
7811   Btype* buint8_type = uint8_type->get_backend(gogo);
7812 
7813   Type* int_type = Type::lookup_integer_type("int");
7814 
7815   Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7816 						 int_type, bloc);
7817   Translate_context context(gogo, NULL, NULL, NULL);
7818   Bexpression* blength = e->get_backend(&context);
7819 
7820   Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7821 
7822   std::string zname = Map_type::zero_value->name();
7823   std::string asm_name(go_selectively_encode_id(zname));
7824   Bvariable* zvar =
7825       gogo->backend()->implicit_variable(zname, asm_name,
7826                                          barray_type, false, false, true,
7827 					 Map_type::zero_value_align);
7828   gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7829 					      false, false, true, NULL);
7830   return zvar;
7831 }
7832 
7833 // Traversal.
7834 
7835 int
do_traverse(Traverse * traverse)7836 Map_type::do_traverse(Traverse* traverse)
7837 {
7838   if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7839       || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7840     return TRAVERSE_EXIT;
7841   return TRAVERSE_CONTINUE;
7842 }
7843 
7844 // Check that the map type is OK.
7845 
7846 bool
do_verify()7847 Map_type::do_verify()
7848 {
7849   // The runtime support uses "map[void]void".
7850   if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7851     go_error_at(this->location_, "invalid map key type");
7852   if (!this->key_type_->in_heap())
7853     go_error_at(this->location_, "go:notinheap map key not allowed");
7854   if (!this->val_type_->in_heap())
7855     go_error_at(this->location_, "go:notinheap map value not allowed");
7856   return true;
7857 }
7858 
7859 // Whether two map types are identical.
7860 
7861 bool
is_identical(const Map_type * t,Cmp_tags cmp_tags,bool errors_are_identical) const7862 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7863 		       bool errors_are_identical) const
7864 {
7865   return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7866 				       cmp_tags, errors_are_identical, NULL)
7867 	  && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7868 					  cmp_tags, errors_are_identical,
7869 					  NULL));
7870 }
7871 
7872 // Hash code.
7873 
7874 unsigned int
do_hash_for_method(Gogo * gogo) const7875 Map_type::do_hash_for_method(Gogo* gogo) const
7876 {
7877   return (this->key_type_->hash_for_method(gogo)
7878 	  + this->val_type_->hash_for_method(gogo)
7879 	  + 2);
7880 }
7881 
7882 // Get the backend representation for a map type.  A map type is
7883 // represented as a pointer to a struct.  The struct is hmap in
7884 // runtime/hashmap.go.
7885 
7886 Btype*
do_get_backend(Gogo * gogo)7887 Map_type::do_get_backend(Gogo* gogo)
7888 {
7889   static Btype* backend_map_type;
7890   if (backend_map_type == NULL)
7891     {
7892       std::vector<Backend::Btyped_identifier> bfields(9);
7893 
7894       Location bloc = Linemap::predeclared_location();
7895 
7896       Type* int_type = Type::lookup_integer_type("int");
7897       bfields[0].name = "count";
7898       bfields[0].btype = int_type->get_backend(gogo);
7899       bfields[0].location = bloc;
7900 
7901       Type* uint8_type = Type::lookup_integer_type("uint8");
7902       bfields[1].name = "flags";
7903       bfields[1].btype = uint8_type->get_backend(gogo);
7904       bfields[1].location = bloc;
7905 
7906       bfields[2].name = "B";
7907       bfields[2].btype = bfields[1].btype;
7908       bfields[2].location = bloc;
7909 
7910       Type* uint16_type = Type::lookup_integer_type("uint16");
7911       bfields[3].name = "noverflow";
7912       bfields[3].btype = uint16_type->get_backend(gogo);
7913       bfields[3].location = bloc;
7914 
7915       Type* uint32_type = Type::lookup_integer_type("uint32");
7916       bfields[4].name = "hash0";
7917       bfields[4].btype = uint32_type->get_backend(gogo);
7918       bfields[4].location = bloc;
7919 
7920       Btype* bvt = gogo->backend()->void_type();
7921       Btype* bpvt = gogo->backend()->pointer_type(bvt);
7922       bfields[5].name = "buckets";
7923       bfields[5].btype = bpvt;
7924       bfields[5].location = bloc;
7925 
7926       bfields[6].name = "oldbuckets";
7927       bfields[6].btype = bpvt;
7928       bfields[6].location = bloc;
7929 
7930       Type* uintptr_type = Type::lookup_integer_type("uintptr");
7931       bfields[7].name = "nevacuate";
7932       bfields[7].btype = uintptr_type->get_backend(gogo);
7933       bfields[7].location = bloc;
7934 
7935       bfields[8].name = "extra";
7936       bfields[8].btype = bpvt;
7937       bfields[8].location = bloc;
7938 
7939       Btype *bt = gogo->backend()->struct_type(bfields);
7940       bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7941       backend_map_type = gogo->backend()->pointer_type(bt);
7942     }
7943   return backend_map_type;
7944 }
7945 
7946 // The type of a map type descriptor.
7947 
7948 Type*
make_map_type_descriptor_type()7949 Map_type::make_map_type_descriptor_type()
7950 {
7951   static Type* ret;
7952   if (ret == NULL)
7953     {
7954       Type* tdt = Type::make_type_descriptor_type();
7955       Type* ptdt = Type::make_type_descriptor_ptr_type();
7956       Type* uint8_type = Type::lookup_integer_type("uint8");
7957       Type* uint16_type = Type::lookup_integer_type("uint16");
7958       Type* bool_type = Type::lookup_bool_type();
7959 
7960       Struct_type* sf =
7961 	Type::make_builtin_struct_type(12,
7962 				       "", tdt,
7963 				       "key", ptdt,
7964 				       "elem", ptdt,
7965 				       "bucket", ptdt,
7966 				       "hmap", ptdt,
7967 				       "keysize", uint8_type,
7968 				       "indirectkey", bool_type,
7969 				       "valuesize", uint8_type,
7970 				       "indirectvalue", bool_type,
7971 				       "bucketsize", uint16_type,
7972 				       "reflexivekey", bool_type,
7973 				       "needkeyupdate", bool_type);
7974 
7975       ret = Type::make_builtin_named_type("MapType", sf);
7976     }
7977 
7978   return ret;
7979 }
7980 
7981 // Build a type descriptor for a map type.
7982 
7983 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)7984 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7985 {
7986   Location bloc = Linemap::predeclared_location();
7987 
7988   Type* mtdt = Map_type::make_map_type_descriptor_type();
7989   Type* uint8_type = Type::lookup_integer_type("uint8");
7990   Type* uint16_type = Type::lookup_integer_type("uint16");
7991 
7992   int64_t keysize;
7993   if (!this->key_type_->backend_type_size(gogo, &keysize))
7994     {
7995       go_error_at(this->location_, "error determining map key type size");
7996       return Expression::make_error(this->location_);
7997     }
7998 
7999   int64_t valsize;
8000   if (!this->val_type_->backend_type_size(gogo, &valsize))
8001     {
8002       go_error_at(this->location_, "error determining map value type size");
8003       return Expression::make_error(this->location_);
8004     }
8005 
8006   int64_t ptrsize;
8007   if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8008     {
8009       go_assert(saw_errors());
8010       return Expression::make_error(this->location_);
8011     }
8012 
8013   Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8014   if (bucket_type == NULL)
8015     {
8016       go_assert(saw_errors());
8017       return Expression::make_error(this->location_);
8018     }
8019 
8020   int64_t bucketsize;
8021   if (!bucket_type->backend_type_size(gogo, &bucketsize))
8022     {
8023       go_assert(saw_errors());
8024       return Expression::make_error(this->location_);
8025     }
8026 
8027   const Struct_field_list* fields = mtdt->struct_type()->fields();
8028 
8029   Expression_list* vals = new Expression_list();
8030   vals->reserve(12);
8031 
8032   Struct_field_list::const_iterator p = fields->begin();
8033   go_assert(p->is_field_name("_type"));
8034   vals->push_back(this->type_descriptor_constructor(gogo,
8035 						    RUNTIME_TYPE_KIND_MAP,
8036 						    name, NULL, true));
8037 
8038   ++p;
8039   go_assert(p->is_field_name("key"));
8040   vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8041 
8042   ++p;
8043   go_assert(p->is_field_name("elem"));
8044   vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8045 
8046   ++p;
8047   go_assert(p->is_field_name("bucket"));
8048   vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8049 
8050   ++p;
8051   go_assert(p->is_field_name("hmap"));
8052   Type* hmap_type = this->hmap_type(bucket_type);
8053   vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8054 
8055   ++p;
8056   go_assert(p->is_field_name("keysize"));
8057   if (keysize > Map_type::max_key_size)
8058     vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8059   else
8060     vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8061 
8062   ++p;
8063   go_assert(p->is_field_name("indirectkey"));
8064   vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8065 					   bloc));
8066 
8067   ++p;
8068   go_assert(p->is_field_name("valuesize"));
8069   if (valsize > Map_type::max_val_size)
8070     vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8071   else
8072     vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8073 
8074   ++p;
8075   go_assert(p->is_field_name("indirectvalue"));
8076   vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8077 					   bloc));
8078 
8079   ++p;
8080   go_assert(p->is_field_name("bucketsize"));
8081   vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8082 						 bloc));
8083 
8084   ++p;
8085   go_assert(p->is_field_name("reflexivekey"));
8086   vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8087 					   bloc));
8088 
8089   ++p;
8090   go_assert(p->is_field_name("needkeyupdate"));
8091   vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8092 					   bloc));
8093 
8094   ++p;
8095   go_assert(p == fields->end());
8096 
8097   return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8098 }
8099 
8100 // Return the bucket type to use for a map type.  This must correspond
8101 // to libgo/go/runtime/hashmap.go.
8102 
8103 Type*
bucket_type(Gogo * gogo,int64_t keysize,int64_t valsize)8104 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8105 {
8106   if (this->bucket_type_ != NULL)
8107     return this->bucket_type_;
8108 
8109   Type* key_type = this->key_type_;
8110   if (keysize > Map_type::max_key_size)
8111     key_type = Type::make_pointer_type(key_type);
8112 
8113   Type* val_type = this->val_type_;
8114   if (valsize > Map_type::max_val_size)
8115     val_type = Type::make_pointer_type(val_type);
8116 
8117   Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8118 							NULL, this->location_);
8119 
8120   Type* uint8_type = Type::lookup_integer_type("uint8");
8121   Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8122   topbits_type->set_is_array_incomparable();
8123   Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8124   keys_type->set_is_array_incomparable();
8125   Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8126   values_type->set_is_array_incomparable();
8127 
8128   // If keys and values have no pointers, the map implementation can
8129   // keep a list of overflow pointers on the side so that buckets can
8130   // be marked as having no pointers.  Arrange for the bucket to have
8131   // no pointers by changing the type of the overflow field to uintptr
8132   // in this case.  See comment on the hmap.overflow field in
8133   // libgo/go/runtime/hashmap.go.
8134   Type* overflow_type;
8135   if (!key_type->has_pointer() && !val_type->has_pointer())
8136     overflow_type = Type::lookup_integer_type("uintptr");
8137   else
8138     {
8139       // This should really be a pointer to the bucket type itself,
8140       // but that would require us to construct a Named_type for it to
8141       // give it a way to refer to itself.  Since nothing really cares
8142       // (except perhaps for someone using a debugger) just use an
8143       // unsafe pointer.
8144       overflow_type = Type::make_pointer_type(Type::make_void_type());
8145     }
8146 
8147   // Make sure the overflow pointer is the last memory in the struct,
8148   // because the runtime assumes it can use size-ptrSize as the offset
8149   // of the overflow pointer.  We double-check that property below
8150   // once the offsets and size are computed.
8151 
8152   int64_t topbits_field_size, topbits_field_align;
8153   int64_t keys_field_size, keys_field_align;
8154   int64_t values_field_size, values_field_align;
8155   int64_t overflow_field_size, overflow_field_align;
8156   if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8157       || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8158       || !keys_type->backend_type_size(gogo, &keys_field_size)
8159       || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8160       || !values_type->backend_type_size(gogo, &values_field_size)
8161       || !values_type->backend_type_field_align(gogo, &values_field_align)
8162       || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8163       || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8164     {
8165       go_assert(saw_errors());
8166       return NULL;
8167     }
8168 
8169   Struct_type* ret;
8170   int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8171 			       values_field_align);
8172   if (max_align <= overflow_field_align)
8173     ret =  make_builtin_struct_type(4,
8174 				    "topbits", topbits_type,
8175 				    "keys", keys_type,
8176 				    "values", values_type,
8177 				    "overflow", overflow_type);
8178   else
8179     {
8180       size_t off = topbits_field_size;
8181       off = ((off + keys_field_align - 1)
8182 	     &~ static_cast<size_t>(keys_field_align - 1));
8183       off += keys_field_size;
8184       off = ((off + values_field_align - 1)
8185 	     &~ static_cast<size_t>(values_field_align - 1));
8186       off += values_field_size;
8187 
8188       int64_t padded_overflow_field_size =
8189 	((overflow_field_size + max_align - 1)
8190 	 &~ static_cast<size_t>(max_align - 1));
8191 
8192       size_t ovoff = off;
8193       ovoff = ((ovoff + max_align - 1)
8194 	       &~ static_cast<size_t>(max_align - 1));
8195       size_t pad = (ovoff - off
8196 		    + padded_overflow_field_size - overflow_field_size);
8197 
8198       Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8199 							 this->location_);
8200       Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8201       pad_type->set_is_array_incomparable();
8202 
8203       ret = make_builtin_struct_type(5,
8204 				     "topbits", topbits_type,
8205 				     "keys", keys_type,
8206 				     "values", values_type,
8207 				     "pad", pad_type,
8208 				     "overflow", overflow_type);
8209     }
8210 
8211   // Verify that the overflow field is just before the end of the
8212   // bucket type.
8213 
8214   Btype* btype = ret->get_backend(gogo);
8215   int64_t offset = gogo->backend()->type_field_offset(btype,
8216 						      ret->field_count() - 1);
8217   int64_t size;
8218   if (!ret->backend_type_size(gogo, &size))
8219     {
8220       go_assert(saw_errors());
8221       return NULL;
8222     }
8223 
8224   int64_t ptr_size;
8225   if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8226     {
8227       go_assert(saw_errors());
8228       return NULL;
8229     }
8230 
8231   go_assert(offset + ptr_size == size);
8232 
8233   ret->set_is_struct_incomparable();
8234 
8235   this->bucket_type_ = ret;
8236   return ret;
8237 }
8238 
8239 // Return the hashmap type for a map type.
8240 
8241 Type*
hmap_type(Type * bucket_type)8242 Map_type::hmap_type(Type* bucket_type)
8243 {
8244   if (this->hmap_type_ != NULL)
8245     return this->hmap_type_;
8246 
8247   Type* int_type = Type::lookup_integer_type("int");
8248   Type* uint8_type = Type::lookup_integer_type("uint8");
8249   Type* uint16_type = Type::lookup_integer_type("uint16");
8250   Type* uint32_type = Type::lookup_integer_type("uint32");
8251   Type* uintptr_type = Type::lookup_integer_type("uintptr");
8252   Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8253 
8254   Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8255 
8256   Struct_type* ret = make_builtin_struct_type(9,
8257 					      "count", int_type,
8258 					      "flags", uint8_type,
8259 					      "B", uint8_type,
8260 					      "noverflow", uint16_type,
8261 					      "hash0", uint32_type,
8262 					      "buckets", ptr_bucket_type,
8263 					      "oldbuckets", ptr_bucket_type,
8264 					      "nevacuate", uintptr_type,
8265 					      "extra", void_ptr_type);
8266   ret->set_is_struct_incomparable();
8267   this->hmap_type_ = ret;
8268   return ret;
8269 }
8270 
8271 // Return the iterator type for a map type.  This is the type of the
8272 // value used when doing a range over a map.
8273 
8274 Type*
hiter_type(Gogo * gogo)8275 Map_type::hiter_type(Gogo* gogo)
8276 {
8277   if (this->hiter_type_ != NULL)
8278     return this->hiter_type_;
8279 
8280   int64_t keysize, valsize;
8281   if (!this->key_type_->backend_type_size(gogo, &keysize)
8282       || !this->val_type_->backend_type_size(gogo, &valsize))
8283     {
8284       go_assert(saw_errors());
8285       return NULL;
8286     }
8287 
8288   Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8289   Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8290   Type* uint8_type = Type::lookup_integer_type("uint8");
8291   Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8292   Type* uintptr_type = Type::lookup_integer_type("uintptr");
8293   Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8294   Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8295   Type* hmap_type = this->hmap_type(bucket_type);
8296   Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8297   Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8298   Type* bool_type = Type::lookup_bool_type();
8299 
8300   Struct_type* ret = make_builtin_struct_type(15,
8301 					      "key", key_ptr_type,
8302 					      "val", val_ptr_type,
8303 					      "t", uint8_ptr_type,
8304 					      "h", hmap_ptr_type,
8305 					      "buckets", bucket_ptr_type,
8306 					      "bptr", bucket_ptr_type,
8307 					      "overflow", void_ptr_type,
8308 					      "oldoverflow", void_ptr_type,
8309 					      "startBucket", uintptr_type,
8310 					      "offset", uint8_type,
8311 					      "wrapped", bool_type,
8312 					      "B", uint8_type,
8313 					      "i", uint8_type,
8314 					      "bucket", uintptr_type,
8315 					      "checkBucket", uintptr_type);
8316   ret->set_is_struct_incomparable();
8317   this->hiter_type_ = ret;
8318   return ret;
8319 }
8320 
8321 // Reflection string for a map.
8322 
8323 void
do_reflection(Gogo * gogo,std::string * ret) const8324 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8325 {
8326   ret->append("map[");
8327   this->append_reflection(this->key_type_, gogo, ret);
8328   ret->append("]");
8329   this->append_reflection(this->val_type_, gogo, ret);
8330 }
8331 
8332 // Export a map type.
8333 
8334 void
do_export(Export * exp) const8335 Map_type::do_export(Export* exp) const
8336 {
8337   exp->write_c_string("map [");
8338   exp->write_type(this->key_type_);
8339   exp->write_c_string("] ");
8340   exp->write_type(this->val_type_);
8341 }
8342 
8343 // Import a map type.
8344 
8345 Map_type*
do_import(Import * imp)8346 Map_type::do_import(Import* imp)
8347 {
8348   imp->require_c_string("map [");
8349   Type* key_type = imp->read_type();
8350   imp->require_c_string("] ");
8351   Type* val_type = imp->read_type();
8352   return Type::make_map_type(key_type, val_type, imp->location());
8353 }
8354 
8355 // Make a map type.
8356 
8357 Map_type*
make_map_type(Type * key_type,Type * val_type,Location location)8358 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8359 {
8360   return new Map_type(key_type, val_type, location);
8361 }
8362 
8363 // Class Channel_type.
8364 
8365 // Verify.
8366 
8367 bool
do_verify()8368 Channel_type::do_verify()
8369 {
8370   // We have no location for this error, but this is not something the
8371   // ordinary user will see.
8372   if (!this->element_type_->in_heap())
8373     go_error_at(Linemap::unknown_location(),
8374 		"chan of go:notinheap type not allowed");
8375   return true;
8376 }
8377 
8378 // Hash code.
8379 
8380 unsigned int
do_hash_for_method(Gogo * gogo) const8381 Channel_type::do_hash_for_method(Gogo* gogo) const
8382 {
8383   unsigned int ret = 0;
8384   if (this->may_send_)
8385     ret += 1;
8386   if (this->may_receive_)
8387     ret += 2;
8388   if (this->element_type_ != NULL)
8389     ret += this->element_type_->hash_for_method(gogo) << 2;
8390   return ret << 3;
8391 }
8392 
8393 // Whether this type is the same as T.
8394 
8395 bool
is_identical(const Channel_type * t,Cmp_tags cmp_tags,bool errors_are_identical) const8396 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8397 			   bool errors_are_identical) const
8398 {
8399   if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8400 				    cmp_tags, errors_are_identical, NULL))
8401     return false;
8402   return (this->may_send_ == t->may_send_
8403 	  && this->may_receive_ == t->may_receive_);
8404 }
8405 
8406 // Return the backend representation for a channel type.  A channel is a pointer
8407 // to a __go_channel struct.  The __go_channel struct is defined in
8408 // libgo/runtime/channel.h.
8409 
8410 Btype*
do_get_backend(Gogo * gogo)8411 Channel_type::do_get_backend(Gogo* gogo)
8412 {
8413   static Btype* backend_channel_type;
8414   if (backend_channel_type == NULL)
8415     {
8416       std::vector<Backend::Btyped_identifier> bfields;
8417       Btype* bt = gogo->backend()->struct_type(bfields);
8418       bt = gogo->backend()->named_type("__go_channel", bt,
8419                                        Linemap::predeclared_location());
8420       backend_channel_type = gogo->backend()->pointer_type(bt);
8421     }
8422   return backend_channel_type;
8423 }
8424 
8425 // Build a type descriptor for a channel type.
8426 
8427 Type*
make_chan_type_descriptor_type()8428 Channel_type::make_chan_type_descriptor_type()
8429 {
8430   static Type* ret;
8431   if (ret == NULL)
8432     {
8433       Type* tdt = Type::make_type_descriptor_type();
8434       Type* ptdt = Type::make_type_descriptor_ptr_type();
8435 
8436       Type* uintptr_type = Type::lookup_integer_type("uintptr");
8437 
8438       Struct_type* sf =
8439 	Type::make_builtin_struct_type(3,
8440 				       "", tdt,
8441 				       "elem", ptdt,
8442 				       "dir", uintptr_type);
8443 
8444       ret = Type::make_builtin_named_type("ChanType", sf);
8445     }
8446 
8447   return ret;
8448 }
8449 
8450 // Build a type descriptor for a map type.
8451 
8452 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)8453 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8454 {
8455   Location bloc = Linemap::predeclared_location();
8456 
8457   Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8458 
8459   const Struct_field_list* fields = ctdt->struct_type()->fields();
8460 
8461   Expression_list* vals = new Expression_list();
8462   vals->reserve(3);
8463 
8464   Struct_field_list::const_iterator p = fields->begin();
8465   go_assert(p->is_field_name("_type"));
8466   vals->push_back(this->type_descriptor_constructor(gogo,
8467 						    RUNTIME_TYPE_KIND_CHAN,
8468 						    name, NULL, true));
8469 
8470   ++p;
8471   go_assert(p->is_field_name("elem"));
8472   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8473 
8474   ++p;
8475   go_assert(p->is_field_name("dir"));
8476   // These bits must match the ones in libgo/runtime/go-type.h.
8477   int val = 0;
8478   if (this->may_receive_)
8479     val |= 1;
8480   if (this->may_send_)
8481     val |= 2;
8482   vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8483 
8484   ++p;
8485   go_assert(p == fields->end());
8486 
8487   return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8488 }
8489 
8490 // Reflection string.
8491 
8492 void
do_reflection(Gogo * gogo,std::string * ret) const8493 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8494 {
8495   if (!this->may_send_)
8496     ret->append("<-");
8497   ret->append("chan");
8498   if (!this->may_receive_)
8499     ret->append("<-");
8500   ret->push_back(' ');
8501   this->append_reflection(this->element_type_, gogo, ret);
8502 }
8503 
8504 // Export.
8505 
8506 void
do_export(Export * exp) const8507 Channel_type::do_export(Export* exp) const
8508 {
8509   exp->write_c_string("chan ");
8510   if (this->may_send_ && !this->may_receive_)
8511     exp->write_c_string("-< ");
8512   else if (this->may_receive_ && !this->may_send_)
8513     exp->write_c_string("<- ");
8514   exp->write_type(this->element_type_);
8515 }
8516 
8517 // Import.
8518 
8519 Channel_type*
do_import(Import * imp)8520 Channel_type::do_import(Import* imp)
8521 {
8522   imp->require_c_string("chan ");
8523 
8524   bool may_send;
8525   bool may_receive;
8526   if (imp->match_c_string("-< "))
8527     {
8528       imp->advance(3);
8529       may_send = true;
8530       may_receive = false;
8531     }
8532   else if (imp->match_c_string("<- "))
8533     {
8534       imp->advance(3);
8535       may_receive = true;
8536       may_send = false;
8537     }
8538   else
8539     {
8540       may_send = true;
8541       may_receive = true;
8542     }
8543 
8544   Type* element_type = imp->read_type();
8545 
8546   return Type::make_channel_type(may_send, may_receive, element_type);
8547 }
8548 
8549 // Return the type to manage a select statement with ncases case
8550 // statements.  A value of this type is allocated on the stack.  This
8551 // must match the type hselect in libgo/go/runtime/select.go.
8552 
8553 Type*
select_type(int ncases)8554 Channel_type::select_type(int ncases)
8555 {
8556   Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8557   Type* uint16_type = Type::lookup_integer_type("uint16");
8558 
8559   static Struct_type* scase_type;
8560   if (scase_type == NULL)
8561     {
8562       Type* uintptr_type = Type::lookup_integer_type("uintptr");
8563       Type* uint64_type = Type::lookup_integer_type("uint64");
8564       scase_type =
8565 	Type::make_builtin_struct_type(7,
8566 				       "elem", unsafe_pointer_type,
8567 				       "chan", unsafe_pointer_type,
8568 				       "pc", uintptr_type,
8569 				       "kind", uint16_type,
8570 				       "index", uint16_type,
8571 				       "receivedp", unsafe_pointer_type,
8572 				       "releasetime", uint64_type);
8573       scase_type->set_is_struct_incomparable();
8574     }
8575 
8576   Expression* ncases_expr =
8577     Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8578   Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8579   scases->set_is_array_incomparable();
8580   Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8581   order->set_is_array_incomparable();
8582 
8583   Struct_type* ret =
8584     Type::make_builtin_struct_type(7,
8585 				   "tcase", uint16_type,
8586 				   "ncase", uint16_type,
8587 				   "pollorder", unsafe_pointer_type,
8588 				   "lockorder", unsafe_pointer_type,
8589 				   "scase", scases,
8590 				   "lockorderarr", order,
8591 				   "pollorderarr", order);
8592   ret->set_is_struct_incomparable();
8593   return ret;
8594 }
8595 
8596 // Make a new channel type.
8597 
8598 Channel_type*
make_channel_type(bool send,bool receive,Type * element_type)8599 Type::make_channel_type(bool send, bool receive, Type* element_type)
8600 {
8601   return new Channel_type(send, receive, element_type);
8602 }
8603 
8604 // Class Interface_type.
8605 
8606 // Return the list of methods.
8607 
8608 const Typed_identifier_list*
methods() const8609 Interface_type::methods() const
8610 {
8611   go_assert(this->methods_are_finalized_ || saw_errors());
8612   return this->all_methods_;
8613 }
8614 
8615 // Return the number of methods.
8616 
8617 size_t
method_count() const8618 Interface_type::method_count() const
8619 {
8620   go_assert(this->methods_are_finalized_ || saw_errors());
8621   return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8622 }
8623 
8624 // Traversal.
8625 
8626 int
do_traverse(Traverse * traverse)8627 Interface_type::do_traverse(Traverse* traverse)
8628 {
8629   Typed_identifier_list* methods = (this->methods_are_finalized_
8630 				    ? this->all_methods_
8631 				    : this->parse_methods_);
8632   if (methods == NULL)
8633     return TRAVERSE_CONTINUE;
8634   return methods->traverse(traverse);
8635 }
8636 
8637 // Finalize the methods.  This handles interface inheritance.
8638 
8639 void
finalize_methods()8640 Interface_type::finalize_methods()
8641 {
8642   if (this->methods_are_finalized_)
8643     return;
8644   this->methods_are_finalized_ = true;
8645   if (this->parse_methods_ == NULL)
8646     return;
8647 
8648   this->all_methods_ = new Typed_identifier_list();
8649   this->all_methods_->reserve(this->parse_methods_->size());
8650   Typed_identifier_list inherit;
8651   for (Typed_identifier_list::const_iterator pm =
8652 	 this->parse_methods_->begin();
8653        pm != this->parse_methods_->end();
8654        ++pm)
8655     {
8656       const Typed_identifier* p = &*pm;
8657       if (p->name().empty())
8658 	inherit.push_back(*p);
8659       else if (this->find_method(p->name()) == NULL)
8660 	this->all_methods_->push_back(*p);
8661       else
8662 	go_error_at(p->location(), "duplicate method %qs",
8663 		 Gogo::message_name(p->name()).c_str());
8664     }
8665 
8666   std::vector<Named_type*> seen;
8667   seen.reserve(inherit.size());
8668   bool issued_recursive_error = false;
8669   while (!inherit.empty())
8670     {
8671       Type* t = inherit.back().type();
8672       Location tl = inherit.back().location();
8673       inherit.pop_back();
8674 
8675       Interface_type* it = t->interface_type();
8676       if (it == NULL)
8677 	{
8678 	  if (!t->is_error())
8679 	    go_error_at(tl, "interface contains embedded non-interface");
8680 	  continue;
8681 	}
8682       if (it == this)
8683 	{
8684 	  if (!issued_recursive_error)
8685 	    {
8686 	      go_error_at(tl, "invalid recursive interface");
8687 	      issued_recursive_error = true;
8688 	    }
8689 	  continue;
8690 	}
8691 
8692       Named_type* nt = t->named_type();
8693       if (nt != NULL && it->parse_methods_ != NULL)
8694 	{
8695 	  std::vector<Named_type*>::const_iterator q;
8696 	  for (q = seen.begin(); q != seen.end(); ++q)
8697 	    {
8698 	      if (*q == nt)
8699 		{
8700 		  go_error_at(tl, "inherited interface loop");
8701 		  break;
8702 		}
8703 	    }
8704 	  if (q != seen.end())
8705 	    continue;
8706 	  seen.push_back(nt);
8707 	}
8708 
8709       const Typed_identifier_list* imethods = it->parse_methods_;
8710       if (imethods == NULL)
8711 	continue;
8712       for (Typed_identifier_list::const_iterator q = imethods->begin();
8713 	   q != imethods->end();
8714 	   ++q)
8715 	{
8716 	  if (q->name().empty())
8717 	    inherit.push_back(*q);
8718 	  else if (this->find_method(q->name()) == NULL)
8719 	    this->all_methods_->push_back(Typed_identifier(q->name(),
8720 							   q->type(), tl));
8721 	  else
8722 	    go_error_at(tl, "inherited method %qs is ambiguous",
8723 		     Gogo::message_name(q->name()).c_str());
8724 	}
8725     }
8726 
8727   if (!this->all_methods_->empty())
8728     this->all_methods_->sort_by_name();
8729   else
8730     {
8731       delete this->all_methods_;
8732       this->all_methods_ = NULL;
8733     }
8734 }
8735 
8736 // Return the method NAME, or NULL.
8737 
8738 const Typed_identifier*
find_method(const std::string & name) const8739 Interface_type::find_method(const std::string& name) const
8740 {
8741   go_assert(this->methods_are_finalized_);
8742   if (this->all_methods_ == NULL)
8743     return NULL;
8744   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8745        p != this->all_methods_->end();
8746        ++p)
8747     if (p->name() == name)
8748       return &*p;
8749   return NULL;
8750 }
8751 
8752 // Return the method index.
8753 
8754 size_t
method_index(const std::string & name) const8755 Interface_type::method_index(const std::string& name) const
8756 {
8757   go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8758   size_t ret = 0;
8759   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8760        p != this->all_methods_->end();
8761        ++p, ++ret)
8762     if (p->name() == name)
8763       return ret;
8764   go_unreachable();
8765 }
8766 
8767 // Return whether NAME is an unexported method, for better error
8768 // reporting.
8769 
8770 bool
is_unexported_method(Gogo * gogo,const std::string & name) const8771 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8772 {
8773   go_assert(this->methods_are_finalized_);
8774   if (this->all_methods_ == NULL)
8775     return false;
8776   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8777        p != this->all_methods_->end();
8778        ++p)
8779     {
8780       const std::string& method_name(p->name());
8781       if (Gogo::is_hidden_name(method_name)
8782 	  && name == Gogo::unpack_hidden_name(method_name)
8783 	  && gogo->pack_hidden_name(name, false) != method_name)
8784 	return true;
8785     }
8786   return false;
8787 }
8788 
8789 // Whether this type is identical with T.
8790 
8791 bool
is_identical(const Interface_type * t,Cmp_tags cmp_tags,bool errors_are_identical) const8792 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
8793 			     bool errors_are_identical) const
8794 {
8795   // If methods have not been finalized, then we are asking whether
8796   // func redeclarations are the same.  This is an error, so for
8797   // simplicity we say they are never the same.
8798   if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8799     return false;
8800 
8801   // We require the same methods with the same types.  The methods
8802   // have already been sorted.
8803   if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8804     return this->all_methods_ == t->all_methods_;
8805 
8806   if (this->assume_identical(this, t) || t->assume_identical(t, this))
8807     return true;
8808 
8809   Assume_identical* hold_ai = this->assume_identical_;
8810   Assume_identical ai;
8811   ai.t1 = this;
8812   ai.t2 = t;
8813   ai.next = hold_ai;
8814   this->assume_identical_ = &ai;
8815 
8816   Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8817   Typed_identifier_list::const_iterator p2;
8818   for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8819     {
8820       if (p1 == this->all_methods_->end())
8821 	break;
8822       if (p1->name() != p2->name()
8823 	  || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
8824 					   errors_are_identical, NULL))
8825 	break;
8826     }
8827 
8828   this->assume_identical_ = hold_ai;
8829 
8830   return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8831 }
8832 
8833 // Return true if T1 and T2 are assumed to be identical during a type
8834 // comparison.
8835 
8836 bool
assume_identical(const Interface_type * t1,const Interface_type * t2) const8837 Interface_type::assume_identical(const Interface_type* t1,
8838 				 const Interface_type* t2) const
8839 {
8840   for (Assume_identical* p = this->assume_identical_;
8841        p != NULL;
8842        p = p->next)
8843     if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8844       return true;
8845   return false;
8846 }
8847 
8848 // Whether we can assign the interface type T to this type.  The types
8849 // are known to not be identical.  An interface assignment is only
8850 // permitted if T is known to implement all methods in THIS.
8851 // Otherwise a type guard is required.
8852 
8853 bool
is_compatible_for_assign(const Interface_type * t,std::string * reason) const8854 Interface_type::is_compatible_for_assign(const Interface_type* t,
8855 					 std::string* reason) const
8856 {
8857   go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8858   if (this->all_methods_ == NULL)
8859     return true;
8860   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8861        p != this->all_methods_->end();
8862        ++p)
8863     {
8864       const Typed_identifier* m = t->find_method(p->name());
8865       if (m == NULL)
8866 	{
8867 	  if (reason != NULL)
8868 	    {
8869 	      char buf[200];
8870 	      snprintf(buf, sizeof buf,
8871 		       _("need explicit conversion; missing method %s%s%s"),
8872 		       go_open_quote(), Gogo::message_name(p->name()).c_str(),
8873 		       go_close_quote());
8874 	      reason->assign(buf);
8875 	    }
8876 	  return false;
8877 	}
8878 
8879       std::string subreason;
8880       if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8881 	{
8882 	  if (reason != NULL)
8883 	    {
8884 	      std::string n = Gogo::message_name(p->name());
8885 	      size_t len = 100 + n.length() + subreason.length();
8886 	      char* buf = new char[len];
8887 	      if (subreason.empty())
8888 		snprintf(buf, len, _("incompatible type for method %s%s%s"),
8889 			 go_open_quote(), n.c_str(), go_close_quote());
8890 	      else
8891 		snprintf(buf, len,
8892 			 _("incompatible type for method %s%s%s (%s)"),
8893 			 go_open_quote(), n.c_str(), go_close_quote(),
8894 			 subreason.c_str());
8895 	      reason->assign(buf);
8896 	      delete[] buf;
8897 	    }
8898 	  return false;
8899 	}
8900     }
8901 
8902   return true;
8903 }
8904 
8905 // Hash code.
8906 
8907 unsigned int
do_hash_for_method(Gogo *) const8908 Interface_type::do_hash_for_method(Gogo*) const
8909 {
8910   go_assert(this->methods_are_finalized_);
8911   unsigned int ret = 0;
8912   if (this->all_methods_ != NULL)
8913     {
8914       for (Typed_identifier_list::const_iterator p =
8915 	     this->all_methods_->begin();
8916 	   p != this->all_methods_->end();
8917 	   ++p)
8918 	{
8919 	  ret = Type::hash_string(p->name(), ret);
8920 	  // We don't use the method type in the hash, to avoid
8921 	  // infinite recursion if an interface method uses a type
8922 	  // which is an interface which inherits from the interface
8923 	  // itself.
8924 	  // type T interface { F() interface {T}}
8925 	  ret <<= 1;
8926 	}
8927     }
8928   return ret;
8929 }
8930 
8931 // Return true if T implements the interface.  If it does not, and
8932 // REASON is not NULL, set *REASON to a useful error message.
8933 
8934 bool
implements_interface(const Type * t,std::string * reason) const8935 Interface_type::implements_interface(const Type* t, std::string* reason) const
8936 {
8937   go_assert(this->methods_are_finalized_);
8938   if (this->all_methods_ == NULL)
8939     return true;
8940 
8941   bool is_pointer = false;
8942   const Named_type* nt = t->named_type();
8943   const Struct_type* st = t->struct_type();
8944   // If we start with a named type, we don't dereference it to find
8945   // methods.
8946   if (nt == NULL)
8947     {
8948       const Type* pt = t->points_to();
8949       if (pt != NULL)
8950 	{
8951 	  // If T is a pointer to a named type, then we need to look at
8952 	  // the type to which it points.
8953 	  is_pointer = true;
8954 	  nt = pt->named_type();
8955 	  st = pt->struct_type();
8956 	}
8957     }
8958 
8959   // If we have a named type, get the methods from it rather than from
8960   // any struct type.
8961   if (nt != NULL)
8962     st = NULL;
8963 
8964   // Only named and struct types have methods.
8965   if (nt == NULL && st == NULL)
8966     {
8967       if (reason != NULL)
8968 	{
8969 	  if (t->points_to() != NULL
8970 	      && t->points_to()->interface_type() != NULL)
8971 	    reason->assign(_("pointer to interface type has no methods"));
8972 	  else
8973 	    reason->assign(_("type has no methods"));
8974 	}
8975       return false;
8976     }
8977 
8978   if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8979     {
8980       if (reason != NULL)
8981 	{
8982 	  if (t->points_to() != NULL
8983 	      && t->points_to()->interface_type() != NULL)
8984 	    reason->assign(_("pointer to interface type has no methods"));
8985 	  else
8986 	    reason->assign(_("type has no methods"));
8987 	}
8988       return false;
8989     }
8990 
8991   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8992        p != this->all_methods_->end();
8993        ++p)
8994     {
8995       bool is_ambiguous = false;
8996       Method* m = (nt != NULL
8997 		   ? nt->method_function(p->name(), &is_ambiguous)
8998 		   : st->method_function(p->name(), &is_ambiguous));
8999       if (m == NULL)
9000 	{
9001 	  if (reason != NULL)
9002 	    {
9003 	      std::string n = Gogo::message_name(p->name());
9004 	      size_t len = n.length() + 100;
9005 	      char* buf = new char[len];
9006 	      if (is_ambiguous)
9007 		snprintf(buf, len, _("ambiguous method %s%s%s"),
9008 			 go_open_quote(), n.c_str(), go_close_quote());
9009 	      else
9010 		snprintf(buf, len, _("missing method %s%s%s"),
9011 			 go_open_quote(), n.c_str(), go_close_quote());
9012 	      reason->assign(buf);
9013 	      delete[] buf;
9014 	    }
9015 	  return false;
9016 	}
9017 
9018       Function_type *p_fn_type = p->type()->function_type();
9019       Function_type* m_fn_type = m->type()->function_type();
9020       go_assert(p_fn_type != NULL && m_fn_type != NULL);
9021       std::string subreason;
9022       if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9023 				   &subreason))
9024 	{
9025 	  if (reason != NULL)
9026 	    {
9027 	      std::string n = Gogo::message_name(p->name());
9028 	      size_t len = 100 + n.length() + subreason.length();
9029 	      char* buf = new char[len];
9030 	      if (subreason.empty())
9031 		snprintf(buf, len, _("incompatible type for method %s%s%s"),
9032 			 go_open_quote(), n.c_str(), go_close_quote());
9033 	      else
9034 		snprintf(buf, len,
9035 			 _("incompatible type for method %s%s%s (%s)"),
9036 			 go_open_quote(), n.c_str(), go_close_quote(),
9037 			 subreason.c_str());
9038 	      reason->assign(buf);
9039 	      delete[] buf;
9040 	    }
9041 	  return false;
9042 	}
9043 
9044       if (!is_pointer && !m->is_value_method())
9045 	{
9046 	  if (reason != NULL)
9047 	    {
9048 	      std::string n = Gogo::message_name(p->name());
9049 	      size_t len = 100 + n.length();
9050 	      char* buf = new char[len];
9051 	      snprintf(buf, len,
9052 		       _("method %s%s%s requires a pointer receiver"),
9053 		       go_open_quote(), n.c_str(), go_close_quote());
9054 	      reason->assign(buf);
9055 	      delete[] buf;
9056 	    }
9057 	  return false;
9058 	}
9059 
9060       // If the magic //go:nointerface comment was used, the method
9061       // may not be used to implement interfaces.
9062       if (m->nointerface())
9063 	{
9064 	  if (reason != NULL)
9065 	    {
9066 	      std::string n = Gogo::message_name(p->name());
9067 	      size_t len = 100 + n.length();
9068 	      char* buf = new char[len];
9069 	      snprintf(buf, len,
9070 		       _("method %s%s%s is marked go:nointerface"),
9071 		       go_open_quote(), n.c_str(), go_close_quote());
9072 	      reason->assign(buf);
9073 	      delete[] buf;
9074 	    }
9075 	  return false;
9076 	}
9077     }
9078 
9079   return true;
9080 }
9081 
9082 // Return the backend representation of the empty interface type.  We
9083 // use the same struct for all empty interfaces.
9084 
9085 Btype*
get_backend_empty_interface_type(Gogo * gogo)9086 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9087 {
9088   static Btype* empty_interface_type;
9089   if (empty_interface_type == NULL)
9090     {
9091       std::vector<Backend::Btyped_identifier> bfields(2);
9092 
9093       Location bloc = Linemap::predeclared_location();
9094 
9095       Type* pdt = Type::make_type_descriptor_ptr_type();
9096       bfields[0].name = "__type_descriptor";
9097       bfields[0].btype = pdt->get_backend(gogo);
9098       bfields[0].location = bloc;
9099 
9100       Type* vt = Type::make_pointer_type(Type::make_void_type());
9101       bfields[1].name = "__object";
9102       bfields[1].btype = vt->get_backend(gogo);
9103       bfields[1].location = bloc;
9104 
9105       empty_interface_type = gogo->backend()->struct_type(bfields);
9106     }
9107   return empty_interface_type;
9108 }
9109 
9110 Interface_type::Bmethods_map Interface_type::bmethods_map;
9111 
9112 // Return a pointer to the backend representation of the method table.
9113 
9114 Btype*
get_backend_methods(Gogo * gogo)9115 Interface_type::get_backend_methods(Gogo* gogo)
9116 {
9117   if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9118     return this->bmethods_;
9119 
9120   std::pair<Interface_type*, Bmethods_map_entry> val;
9121   val.first = this;
9122   val.second.btype = NULL;
9123   val.second.is_placeholder = false;
9124   std::pair<Bmethods_map::iterator, bool> ins =
9125     Interface_type::bmethods_map.insert(val);
9126   if (!ins.second
9127       && ins.first->second.btype != NULL
9128       && !ins.first->second.is_placeholder)
9129     {
9130       this->bmethods_ = ins.first->second.btype;
9131       this->bmethods_is_placeholder_ = false;
9132       return this->bmethods_;
9133     }
9134 
9135   Location loc = this->location();
9136 
9137   std::vector<Backend::Btyped_identifier>
9138     mfields(this->all_methods_->size() + 1);
9139 
9140   Type* pdt = Type::make_type_descriptor_ptr_type();
9141   mfields[0].name = "__type_descriptor";
9142   mfields[0].btype = pdt->get_backend(gogo);
9143   mfields[0].location = loc;
9144 
9145   std::string last_name = "";
9146   size_t i = 1;
9147   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9148        p != this->all_methods_->end();
9149        ++p, ++i)
9150     {
9151       // The type of the method in Go only includes the parameters.
9152       // The actual method also has a receiver, which is always a
9153       // pointer.  We need to add that pointer type here in order to
9154       // generate the correct type for the backend.
9155       Function_type* ft = p->type()->function_type();
9156       go_assert(ft->receiver() == NULL);
9157 
9158       const Typed_identifier_list* params = ft->parameters();
9159       Typed_identifier_list* mparams = new Typed_identifier_list();
9160       if (params != NULL)
9161 	mparams->reserve(params->size() + 1);
9162       Type* vt = Type::make_pointer_type(Type::make_void_type());
9163       mparams->push_back(Typed_identifier("", vt, ft->location()));
9164       if (params != NULL)
9165 	{
9166 	  for (Typed_identifier_list::const_iterator pp = params->begin();
9167 	       pp != params->end();
9168 	       ++pp)
9169 	    mparams->push_back(*pp);
9170 	}
9171 
9172       Typed_identifier_list* mresults = (ft->results() == NULL
9173 					 ? NULL
9174 					 : ft->results()->copy());
9175       Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9176 						    ft->location());
9177 
9178       mfields[i].name = Gogo::unpack_hidden_name(p->name());
9179       mfields[i].btype = mft->get_backend_fntype(gogo);
9180       mfields[i].location = loc;
9181 
9182       // Sanity check: the names should be sorted.
9183       go_assert(Gogo::unpack_hidden_name(p->name())
9184 		> Gogo::unpack_hidden_name(last_name));
9185       last_name = p->name();
9186     }
9187 
9188   Btype* st = gogo->backend()->struct_type(mfields);
9189   Btype* ret = gogo->backend()->pointer_type(st);
9190 
9191   if (ins.first->second.btype != NULL
9192       && ins.first->second.is_placeholder)
9193     gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9194                                                   ret);
9195   this->bmethods_ = ret;
9196   ins.first->second.btype = ret;
9197   this->bmethods_is_placeholder_ = false;
9198   ins.first->second.is_placeholder = false;
9199   return ret;
9200 }
9201 
9202 // Return a placeholder for the pointer to the backend methods table.
9203 
9204 Btype*
get_backend_methods_placeholder(Gogo * gogo)9205 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9206 {
9207   if (this->bmethods_ == NULL)
9208     {
9209       std::pair<Interface_type*, Bmethods_map_entry> val;
9210       val.first = this;
9211       val.second.btype = NULL;
9212       val.second.is_placeholder = false;
9213       std::pair<Bmethods_map::iterator, bool> ins =
9214         Interface_type::bmethods_map.insert(val);
9215       if (!ins.second && ins.first->second.btype != NULL)
9216         {
9217           this->bmethods_ = ins.first->second.btype;
9218           this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9219           return this->bmethods_;
9220         }
9221 
9222       Location loc = this->location();
9223       Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9224       this->bmethods_ = bt;
9225       ins.first->second.btype = bt;
9226       this->bmethods_is_placeholder_ = true;
9227       ins.first->second.is_placeholder = true;
9228     }
9229   return this->bmethods_;
9230 }
9231 
9232 // Return the fields of a non-empty interface type.  This is not
9233 // declared in types.h so that types.h doesn't have to #include
9234 // backend.h.
9235 
9236 static void
get_backend_interface_fields(Gogo * gogo,Interface_type * type,bool use_placeholder,std::vector<Backend::Btyped_identifier> * bfields)9237 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9238 			     bool use_placeholder,
9239 			     std::vector<Backend::Btyped_identifier>* bfields)
9240 {
9241   Location loc = type->location();
9242 
9243   bfields->resize(2);
9244 
9245   (*bfields)[0].name = "__methods";
9246   (*bfields)[0].btype = (use_placeholder
9247 			 ? type->get_backend_methods_placeholder(gogo)
9248 			 : type->get_backend_methods(gogo));
9249   (*bfields)[0].location = loc;
9250 
9251   Type* vt = Type::make_pointer_type(Type::make_void_type());
9252   (*bfields)[1].name = "__object";
9253   (*bfields)[1].btype = vt->get_backend(gogo);
9254   (*bfields)[1].location = Linemap::predeclared_location();
9255 }
9256 
9257 // Return the backend representation for an interface type.  An interface is a
9258 // pointer to a struct.  The struct has three fields.  The first field is a
9259 // pointer to the type descriptor for the dynamic type of the object.
9260 // The second field is a pointer to a table of methods for the
9261 // interface to be used with the object.  The third field is the value
9262 // of the object itself.
9263 
9264 Btype*
do_get_backend(Gogo * gogo)9265 Interface_type::do_get_backend(Gogo* gogo)
9266 {
9267   if (this->is_empty())
9268     return Interface_type::get_backend_empty_interface_type(gogo);
9269   else
9270     {
9271       if (this->interface_btype_ != NULL)
9272 	return this->interface_btype_;
9273       this->interface_btype_ =
9274 	gogo->backend()->placeholder_struct_type("", this->location_);
9275       std::vector<Backend::Btyped_identifier> bfields;
9276       get_backend_interface_fields(gogo, this, false, &bfields);
9277       if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9278 							bfields))
9279 	this->interface_btype_ = gogo->backend()->error_type();
9280       return this->interface_btype_;
9281     }
9282 }
9283 
9284 // Finish the backend representation of the methods.
9285 
9286 void
finish_backend_methods(Gogo * gogo)9287 Interface_type::finish_backend_methods(Gogo* gogo)
9288 {
9289   if (!this->is_empty())
9290     {
9291       const Typed_identifier_list* methods = this->methods();
9292       if (methods != NULL)
9293 	{
9294 	  for (Typed_identifier_list::const_iterator p = methods->begin();
9295 	       p != methods->end();
9296 	       ++p)
9297 	    p->type()->get_backend(gogo);
9298 	}
9299 
9300       // Getting the backend methods now will set the placeholder
9301       // pointer.
9302       this->get_backend_methods(gogo);
9303     }
9304 }
9305 
9306 // The type of an interface type descriptor.
9307 
9308 Type*
make_interface_type_descriptor_type()9309 Interface_type::make_interface_type_descriptor_type()
9310 {
9311   static Type* ret;
9312   if (ret == NULL)
9313     {
9314       Type* tdt = Type::make_type_descriptor_type();
9315       Type* ptdt = Type::make_type_descriptor_ptr_type();
9316 
9317       Type* string_type = Type::lookup_string_type();
9318       Type* pointer_string_type = Type::make_pointer_type(string_type);
9319 
9320       Struct_type* sm =
9321 	Type::make_builtin_struct_type(3,
9322 				       "name", pointer_string_type,
9323 				       "pkgPath", pointer_string_type,
9324 				       "typ", ptdt);
9325 
9326       Type* nsm = Type::make_builtin_named_type("imethod", sm);
9327 
9328       Type* slice_nsm = Type::make_array_type(nsm, NULL);
9329 
9330       Struct_type* s = Type::make_builtin_struct_type(2,
9331 						      "", tdt,
9332 						      "methods", slice_nsm);
9333 
9334       ret = Type::make_builtin_named_type("InterfaceType", s);
9335     }
9336 
9337   return ret;
9338 }
9339 
9340 // Build a type descriptor for an interface type.
9341 
9342 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)9343 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9344 {
9345   Location bloc = Linemap::predeclared_location();
9346 
9347   Type* itdt = Interface_type::make_interface_type_descriptor_type();
9348 
9349   const Struct_field_list* ifields = itdt->struct_type()->fields();
9350 
9351   Expression_list* ivals = new Expression_list();
9352   ivals->reserve(2);
9353 
9354   Struct_field_list::const_iterator pif = ifields->begin();
9355   go_assert(pif->is_field_name("_type"));
9356   const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9357   ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9358 						     true));
9359 
9360   ++pif;
9361   go_assert(pif->is_field_name("methods"));
9362 
9363   Expression_list* methods = new Expression_list();
9364   if (this->all_methods_ != NULL)
9365     {
9366       Type* elemtype = pif->type()->array_type()->element_type();
9367 
9368       methods->reserve(this->all_methods_->size());
9369       for (Typed_identifier_list::const_iterator pm =
9370 	     this->all_methods_->begin();
9371 	   pm != this->all_methods_->end();
9372 	   ++pm)
9373 	{
9374 	  const Struct_field_list* mfields = elemtype->struct_type()->fields();
9375 
9376 	  Expression_list* mvals = new Expression_list();
9377 	  mvals->reserve(3);
9378 
9379 	  Struct_field_list::const_iterator pmf = mfields->begin();
9380 	  go_assert(pmf->is_field_name("name"));
9381 	  std::string s = Gogo::unpack_hidden_name(pm->name());
9382 	  Expression* e = Expression::make_string(s, bloc);
9383 	  mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9384 
9385 	  ++pmf;
9386 	  go_assert(pmf->is_field_name("pkgPath"));
9387 	  if (!Gogo::is_hidden_name(pm->name()))
9388 	    mvals->push_back(Expression::make_nil(bloc));
9389 	  else
9390 	    {
9391 	      s = Gogo::hidden_name_pkgpath(pm->name());
9392 	      e = Expression::make_string(s, bloc);
9393 	      mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9394 	    }
9395 
9396 	  ++pmf;
9397 	  go_assert(pmf->is_field_name("typ"));
9398 	  mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9399 
9400 	  ++pmf;
9401 	  go_assert(pmf == mfields->end());
9402 
9403 	  e = Expression::make_struct_composite_literal(elemtype, mvals,
9404 							bloc);
9405 	  methods->push_back(e);
9406 	}
9407     }
9408 
9409   ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9410 							    methods, bloc));
9411 
9412   ++pif;
9413   go_assert(pif == ifields->end());
9414 
9415   return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9416 }
9417 
9418 // Reflection string.
9419 
9420 void
do_reflection(Gogo * gogo,std::string * ret) const9421 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9422 {
9423   ret->append("interface {");
9424   const Typed_identifier_list* methods = this->parse_methods_;
9425   if (methods != NULL)
9426     {
9427       ret->push_back(' ');
9428       for (Typed_identifier_list::const_iterator p = methods->begin();
9429 	   p != methods->end();
9430 	   ++p)
9431 	{
9432 	  if (p != methods->begin())
9433 	    ret->append("; ");
9434 	  if (p->name().empty())
9435 	    this->append_reflection(p->type(), gogo, ret);
9436 	  else
9437 	    {
9438 	      if (!Gogo::is_hidden_name(p->name()))
9439 		ret->append(p->name());
9440 	      else if (gogo->pkgpath_from_option())
9441 		ret->append(p->name().substr(1));
9442 	      else
9443 		{
9444 		  // If no -fgo-pkgpath option, backward compatibility
9445 		  // for how this used to work before -fgo-pkgpath was
9446 		  // introduced.
9447 		  std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9448 		  ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9449 		  ret->push_back('.');
9450 		  ret->append(Gogo::unpack_hidden_name(p->name()));
9451 		}
9452 	      std::string sub = p->type()->reflection(gogo);
9453 	      go_assert(sub.compare(0, 4, "func") == 0);
9454 	      sub = sub.substr(4);
9455 	      ret->append(sub);
9456 	    }
9457 	}
9458       ret->push_back(' ');
9459     }
9460   ret->append("}");
9461 }
9462 
9463 // Export.
9464 
9465 void
do_export(Export * exp) const9466 Interface_type::do_export(Export* exp) const
9467 {
9468   exp->write_c_string("interface { ");
9469 
9470   const Typed_identifier_list* methods = this->parse_methods_;
9471   if (methods != NULL)
9472     {
9473       for (Typed_identifier_list::const_iterator pm = methods->begin();
9474 	   pm != methods->end();
9475 	   ++pm)
9476 	{
9477 	  if (pm->name().empty())
9478 	    {
9479 	      exp->write_c_string("? ");
9480 	      exp->write_type(pm->type());
9481 	    }
9482 	  else
9483 	    {
9484 	      exp->write_string(pm->name());
9485 	      exp->write_c_string(" (");
9486 
9487 	      const Function_type* fntype = pm->type()->function_type();
9488 
9489 	      bool first = true;
9490 	      const Typed_identifier_list* parameters = fntype->parameters();
9491 	      if (parameters != NULL)
9492 		{
9493 		  bool is_varargs = fntype->is_varargs();
9494 		  for (Typed_identifier_list::const_iterator pp =
9495 			 parameters->begin();
9496 		       pp != parameters->end();
9497 		       ++pp)
9498 		    {
9499 		      if (first)
9500 			first = false;
9501 		      else
9502 			exp->write_c_string(", ");
9503 		      exp->write_name(pp->name());
9504 		      exp->write_c_string(" ");
9505 		      if (!is_varargs || pp + 1 != parameters->end())
9506 			exp->write_type(pp->type());
9507 		      else
9508 			{
9509 			  exp->write_c_string("...");
9510 			  Type *pptype = pp->type();
9511 			  exp->write_type(pptype->array_type()->element_type());
9512 			}
9513 		    }
9514 		}
9515 
9516 	      exp->write_c_string(")");
9517 
9518 	      const Typed_identifier_list* results = fntype->results();
9519 	      if (results != NULL)
9520 		{
9521 		  exp->write_c_string(" ");
9522 		  if (results->size() == 1 && results->begin()->name().empty())
9523 		    exp->write_type(results->begin()->type());
9524 		  else
9525 		    {
9526 		      first = true;
9527 		      exp->write_c_string("(");
9528 		      for (Typed_identifier_list::const_iterator p =
9529 			     results->begin();
9530 			   p != results->end();
9531 			   ++p)
9532 			{
9533 			  if (first)
9534 			    first = false;
9535 			  else
9536 			    exp->write_c_string(", ");
9537 			  exp->write_name(p->name());
9538 			  exp->write_c_string(" ");
9539 			  exp->write_type(p->type());
9540 			}
9541 		      exp->write_c_string(")");
9542 		    }
9543 		}
9544 	    }
9545 
9546 	  exp->write_c_string("; ");
9547 	}
9548     }
9549 
9550   exp->write_c_string("}");
9551 }
9552 
9553 // Import an interface type.
9554 
9555 Interface_type*
do_import(Import * imp)9556 Interface_type::do_import(Import* imp)
9557 {
9558   imp->require_c_string("interface { ");
9559 
9560   Typed_identifier_list* methods = new Typed_identifier_list;
9561   while (imp->peek_char() != '}')
9562     {
9563       std::string name = imp->read_identifier();
9564 
9565       if (name == "?")
9566 	{
9567 	  imp->require_c_string(" ");
9568 	  Type* t = imp->read_type();
9569 	  methods->push_back(Typed_identifier("", t, imp->location()));
9570 	  imp->require_c_string("; ");
9571 	  continue;
9572 	}
9573 
9574       imp->require_c_string(" (");
9575 
9576       Typed_identifier_list* parameters;
9577       bool is_varargs = false;
9578       if (imp->peek_char() == ')')
9579 	parameters = NULL;
9580       else
9581 	{
9582 	  parameters = new Typed_identifier_list;
9583 	  while (true)
9584 	    {
9585 	      std::string name = imp->read_name();
9586 	      imp->require_c_string(" ");
9587 
9588 	      if (imp->match_c_string("..."))
9589 		{
9590 		  imp->advance(3);
9591 		  is_varargs = true;
9592 		}
9593 
9594 	      Type* ptype = imp->read_type();
9595 	      if (is_varargs)
9596 		ptype = Type::make_array_type(ptype, NULL);
9597 	      parameters->push_back(Typed_identifier(name, ptype,
9598 						     imp->location()));
9599 	      if (imp->peek_char() != ',')
9600 		break;
9601 	      go_assert(!is_varargs);
9602 	      imp->require_c_string(", ");
9603 	    }
9604 	}
9605       imp->require_c_string(")");
9606 
9607       Typed_identifier_list* results;
9608       if (imp->peek_char() != ' ')
9609 	results = NULL;
9610       else
9611 	{
9612 	  results = new Typed_identifier_list;
9613 	  imp->advance(1);
9614 	  if (imp->peek_char() != '(')
9615 	    {
9616 	      Type* rtype = imp->read_type();
9617 	      results->push_back(Typed_identifier("", rtype, imp->location()));
9618 	    }
9619 	  else
9620 	    {
9621 	      imp->advance(1);
9622 	      while (true)
9623 		{
9624 		  std::string name = imp->read_name();
9625 		  imp->require_c_string(" ");
9626 		  Type* rtype = imp->read_type();
9627 		  results->push_back(Typed_identifier(name, rtype,
9628 						      imp->location()));
9629 		  if (imp->peek_char() != ',')
9630 		    break;
9631 		  imp->require_c_string(", ");
9632 		}
9633 	      imp->require_c_string(")");
9634 	    }
9635 	}
9636 
9637       Function_type* fntype = Type::make_function_type(NULL, parameters,
9638 						       results,
9639 						       imp->location());
9640       if (is_varargs)
9641 	fntype->set_is_varargs();
9642       methods->push_back(Typed_identifier(name, fntype, imp->location()));
9643 
9644       imp->require_c_string("; ");
9645     }
9646 
9647   imp->require_c_string("}");
9648 
9649   if (methods->empty())
9650     {
9651       delete methods;
9652       methods = NULL;
9653     }
9654 
9655   Interface_type* ret = Type::make_interface_type(methods, imp->location());
9656   ret->package_ = imp->package();
9657   return ret;
9658 }
9659 
9660 // Make an interface type.
9661 
9662 Interface_type*
make_interface_type(Typed_identifier_list * methods,Location location)9663 Type::make_interface_type(Typed_identifier_list* methods,
9664 			  Location location)
9665 {
9666   return new Interface_type(methods, location);
9667 }
9668 
9669 // Make an empty interface type.
9670 
9671 Interface_type*
make_empty_interface_type(Location location)9672 Type::make_empty_interface_type(Location location)
9673 {
9674   Interface_type* ret = new Interface_type(NULL, location);
9675   ret->finalize_methods();
9676   return ret;
9677 }
9678 
9679 // Class Method.
9680 
9681 // Bind a method to an object.
9682 
9683 Expression*
bind_method(Expression * expr,Location location) const9684 Method::bind_method(Expression* expr, Location location) const
9685 {
9686   if (this->stub_ == NULL)
9687     {
9688       // When there is no stub object, the binding is determined by
9689       // the child class.
9690       return this->do_bind_method(expr, location);
9691     }
9692   return Expression::make_bound_method(expr, this, this->stub_, location);
9693 }
9694 
9695 // Return the named object associated with a method.  This may only be
9696 // called after methods are finalized.
9697 
9698 Named_object*
named_object() const9699 Method::named_object() const
9700 {
9701   if (this->stub_ != NULL)
9702     return this->stub_;
9703   return this->do_named_object();
9704 }
9705 
9706 // Class Named_method.
9707 
9708 // The type of the method.
9709 
9710 Function_type*
do_type() const9711 Named_method::do_type() const
9712 {
9713   if (this->named_object_->is_function())
9714     return this->named_object_->func_value()->type();
9715   else if (this->named_object_->is_function_declaration())
9716     return this->named_object_->func_declaration_value()->type();
9717   else
9718     go_unreachable();
9719 }
9720 
9721 // Return the location of the method receiver.
9722 
9723 Location
do_receiver_location() const9724 Named_method::do_receiver_location() const
9725 {
9726   return this->do_type()->receiver()->location();
9727 }
9728 
9729 // Bind a method to an object.
9730 
9731 Expression*
do_bind_method(Expression * expr,Location location) const9732 Named_method::do_bind_method(Expression* expr, Location location) const
9733 {
9734   Named_object* no = this->named_object_;
9735   Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9736 							       no, location);
9737   // If this is not a local method, and it does not use a stub, then
9738   // the real method expects a different type.  We need to cast the
9739   // first argument.
9740   if (this->depth() > 0 && !this->needs_stub_method())
9741     {
9742       Function_type* ftype = this->do_type();
9743       go_assert(ftype->is_method());
9744       Type* frtype = ftype->receiver()->type();
9745       bme->set_first_argument_type(frtype);
9746     }
9747   return bme;
9748 }
9749 
9750 // Return whether this method should not participate in interfaces.
9751 
9752 bool
do_nointerface() const9753 Named_method::do_nointerface() const
9754 {
9755   Named_object* no = this->named_object_;
9756   if (no->is_function())
9757     return no->func_value()->nointerface();
9758   else if (no->is_function_declaration())
9759     return no->func_declaration_value()->nointerface();
9760   else
9761     go_unreachable();
9762 }
9763 
9764 // Class Interface_method.
9765 
9766 // Bind a method to an object.
9767 
9768 Expression*
do_bind_method(Expression * expr,Location location) const9769 Interface_method::do_bind_method(Expression* expr,
9770 				 Location location) const
9771 {
9772   return Expression::make_interface_field_reference(expr, this->name_,
9773 						    location);
9774 }
9775 
9776 // Class Methods.
9777 
9778 // Insert a new method.  Return true if it was inserted, false
9779 // otherwise.
9780 
9781 bool
insert(const std::string & name,Method * m)9782 Methods::insert(const std::string& name, Method* m)
9783 {
9784   std::pair<Method_map::iterator, bool> ins =
9785     this->methods_.insert(std::make_pair(name, m));
9786   if (ins.second)
9787     return true;
9788   else
9789     {
9790       Method* old_method = ins.first->second;
9791       if (m->depth() < old_method->depth())
9792 	{
9793 	  delete old_method;
9794 	  ins.first->second = m;
9795 	  return true;
9796 	}
9797       else
9798 	{
9799 	  if (m->depth() == old_method->depth())
9800 	    old_method->set_is_ambiguous();
9801 	  return false;
9802 	}
9803     }
9804 }
9805 
9806 // Return the number of unambiguous methods.
9807 
9808 size_t
count() const9809 Methods::count() const
9810 {
9811   size_t ret = 0;
9812   for (Method_map::const_iterator p = this->methods_.begin();
9813        p != this->methods_.end();
9814        ++p)
9815     if (!p->second->is_ambiguous())
9816       ++ret;
9817   return ret;
9818 }
9819 
9820 // Class Named_type.
9821 
9822 // Return the name of the type.
9823 
9824 const std::string&
name() const9825 Named_type::name() const
9826 {
9827   return this->named_object_->name();
9828 }
9829 
9830 // Return the name of the type to use in an error message.
9831 
9832 std::string
message_name() const9833 Named_type::message_name() const
9834 {
9835   return this->named_object_->message_name();
9836 }
9837 
9838 // Return the base type for this type.  We have to be careful about
9839 // circular type definitions, which are invalid but may be seen here.
9840 
9841 Type*
named_base()9842 Named_type::named_base()
9843 {
9844   if (this->seen_)
9845     return this;
9846   this->seen_ = true;
9847   Type* ret = this->type_->base();
9848   this->seen_ = false;
9849   return ret;
9850 }
9851 
9852 const Type*
named_base() const9853 Named_type::named_base() const
9854 {
9855   if (this->seen_)
9856     return this;
9857   this->seen_ = true;
9858   const Type* ret = this->type_->base();
9859   this->seen_ = false;
9860   return ret;
9861 }
9862 
9863 // Return whether this is an error type.  We have to be careful about
9864 // circular type definitions, which are invalid but may be seen here.
9865 
9866 bool
is_named_error_type() const9867 Named_type::is_named_error_type() const
9868 {
9869   if (this->seen_)
9870     return false;
9871   this->seen_ = true;
9872   bool ret = this->type_->is_error_type();
9873   this->seen_ = false;
9874   return ret;
9875 }
9876 
9877 // Whether this type is comparable.  We have to be careful about
9878 // circular type definitions.
9879 
9880 bool
named_type_is_comparable(std::string * reason) const9881 Named_type::named_type_is_comparable(std::string* reason) const
9882 {
9883   if (this->seen_)
9884     return false;
9885   this->seen_ = true;
9886   bool ret = Type::are_compatible_for_comparison(true, this->type_,
9887 						 this->type_, reason);
9888   this->seen_ = false;
9889   return ret;
9890 }
9891 
9892 // Add a method to this type.
9893 
9894 Named_object*
add_method(const std::string & name,Function * function)9895 Named_type::add_method(const std::string& name, Function* function)
9896 {
9897   go_assert(!this->is_alias_);
9898   if (this->local_methods_ == NULL)
9899     this->local_methods_ = new Bindings(NULL);
9900   return this->local_methods_->add_function(name, NULL, function);
9901 }
9902 
9903 // Add a method declaration to this type.
9904 
9905 Named_object*
add_method_declaration(const std::string & name,Package * package,Function_type * type,Location location)9906 Named_type::add_method_declaration(const std::string& name, Package* package,
9907 				   Function_type* type,
9908 				   Location location)
9909 {
9910   go_assert(!this->is_alias_);
9911   if (this->local_methods_ == NULL)
9912     this->local_methods_ = new Bindings(NULL);
9913   return this->local_methods_->add_function_declaration(name, package, type,
9914 							location);
9915 }
9916 
9917 // Add an existing method to this type.
9918 
9919 void
add_existing_method(Named_object * no)9920 Named_type::add_existing_method(Named_object* no)
9921 {
9922   go_assert(!this->is_alias_);
9923   if (this->local_methods_ == NULL)
9924     this->local_methods_ = new Bindings(NULL);
9925   this->local_methods_->add_named_object(no);
9926 }
9927 
9928 // Look for a local method NAME, and returns its named object, or NULL
9929 // if not there.
9930 
9931 Named_object*
find_local_method(const std::string & name) const9932 Named_type::find_local_method(const std::string& name) const
9933 {
9934   if (this->is_error_)
9935     return NULL;
9936   if (this->is_alias_)
9937     {
9938       Named_type* nt = this->type_->named_type();
9939       if (nt != NULL)
9940 	{
9941 	  if (this->seen_alias_)
9942 	    return NULL;
9943 	  this->seen_alias_ = true;
9944 	  Named_object* ret = nt->find_local_method(name);
9945 	  this->seen_alias_ = false;
9946 	  return ret;
9947 	}
9948       return NULL;
9949     }
9950   if (this->local_methods_ == NULL)
9951     return NULL;
9952   return this->local_methods_->lookup(name);
9953 }
9954 
9955 // Return the list of local methods.
9956 
9957 const Bindings*
local_methods() const9958 Named_type::local_methods() const
9959 {
9960   if (this->is_error_)
9961     return NULL;
9962   if (this->is_alias_)
9963     {
9964       Named_type* nt = this->type_->named_type();
9965       if (nt != NULL)
9966 	{
9967 	  if (this->seen_alias_)
9968 	    return NULL;
9969 	  this->seen_alias_ = true;
9970 	  const Bindings* ret = nt->local_methods();
9971 	  this->seen_alias_ = false;
9972 	  return ret;
9973 	}
9974       return NULL;
9975     }
9976   return this->local_methods_;
9977 }
9978 
9979 // Return whether NAME is an unexported field or method, for better
9980 // error reporting.
9981 
9982 bool
is_unexported_local_method(Gogo * gogo,const std::string & name) const9983 Named_type::is_unexported_local_method(Gogo* gogo,
9984 				       const std::string& name) const
9985 {
9986   if (this->is_error_)
9987     return false;
9988   if (this->is_alias_)
9989     {
9990       Named_type* nt = this->type_->named_type();
9991       if (nt != NULL)
9992 	{
9993 	  if (this->seen_alias_)
9994 	    return false;
9995 	  this->seen_alias_ = true;
9996 	  bool ret = nt->is_unexported_local_method(gogo, name);
9997 	  this->seen_alias_ = false;
9998 	  return ret;
9999 	}
10000       return false;
10001     }
10002   Bindings* methods = this->local_methods_;
10003   if (methods != NULL)
10004     {
10005       for (Bindings::const_declarations_iterator p =
10006 	     methods->begin_declarations();
10007 	   p != methods->end_declarations();
10008 	   ++p)
10009 	{
10010 	  if (Gogo::is_hidden_name(p->first)
10011 	      && name == Gogo::unpack_hidden_name(p->first)
10012 	      && gogo->pack_hidden_name(name, false) != p->first)
10013 	    return true;
10014 	}
10015     }
10016   return false;
10017 }
10018 
10019 // Build the complete list of methods for this type, which means
10020 // recursively including all methods for anonymous fields.  Create all
10021 // stub methods.
10022 
10023 void
finalize_methods(Gogo * gogo)10024 Named_type::finalize_methods(Gogo* gogo)
10025 {
10026   if (this->is_alias_)
10027     return;
10028   if (this->all_methods_ != NULL)
10029     return;
10030 
10031   if (this->local_methods_ != NULL
10032       && (this->points_to() != NULL || this->interface_type() != NULL))
10033     {
10034       const Bindings* lm = this->local_methods_;
10035       for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10036 	   p != lm->end_declarations();
10037 	   ++p)
10038 	go_error_at(p->second->location(),
10039 		    "invalid pointer or interface receiver type");
10040       delete this->local_methods_;
10041       this->local_methods_ = NULL;
10042       return;
10043     }
10044 
10045   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10046 }
10047 
10048 // Return whether this type has any methods.
10049 
10050 bool
has_any_methods() const10051 Named_type::has_any_methods() const
10052 {
10053   if (this->is_error_)
10054     return false;
10055   if (this->is_alias_)
10056     {
10057       if (this->type_->named_type() != NULL)
10058 	{
10059 	  if (this->seen_alias_)
10060 	    return false;
10061 	  this->seen_alias_ = true;
10062 	  bool ret = this->type_->named_type()->has_any_methods();
10063 	  this->seen_alias_ = false;
10064 	  return ret;
10065 	}
10066       if (this->type_->struct_type() != NULL)
10067 	return this->type_->struct_type()->has_any_methods();
10068       return false;
10069     }
10070   return this->all_methods_ != NULL;
10071 }
10072 
10073 // Return the methods for this type.
10074 
10075 const Methods*
methods() const10076 Named_type::methods() const
10077 {
10078   if (this->is_error_)
10079     return NULL;
10080   if (this->is_alias_)
10081     {
10082       if (this->type_->named_type() != NULL)
10083 	{
10084 	  if (this->seen_alias_)
10085 	    return NULL;
10086 	  this->seen_alias_ = true;
10087 	  const Methods* ret = this->type_->named_type()->methods();
10088 	  this->seen_alias_ = false;
10089 	  return ret;
10090 	}
10091       if (this->type_->struct_type() != NULL)
10092 	return this->type_->struct_type()->methods();
10093       return NULL;
10094     }
10095   return this->all_methods_;
10096 }
10097 
10098 // Return the method NAME, or NULL if there isn't one or if it is
10099 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
10100 // ambiguous.
10101 
10102 Method*
method_function(const std::string & name,bool * is_ambiguous) const10103 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10104 {
10105   if (this->is_error_)
10106     return NULL;
10107   if (this->is_alias_)
10108     {
10109       if (is_ambiguous != NULL)
10110 	*is_ambiguous = false;
10111       if (this->type_->named_type() != NULL)
10112 	{
10113 	  if (this->seen_alias_)
10114 	    return NULL;
10115 	  this->seen_alias_ = true;
10116 	  Named_type* nt = this->type_->named_type();
10117 	  Method* ret = nt->method_function(name, is_ambiguous);
10118 	  this->seen_alias_ = false;
10119 	  return ret;
10120 	}
10121       if (this->type_->struct_type() != NULL)
10122 	return this->type_->struct_type()->method_function(name, is_ambiguous);
10123       return NULL;
10124     }
10125   return Type::method_function(this->all_methods_, name, is_ambiguous);
10126 }
10127 
10128 // Return a pointer to the interface method table for this type for
10129 // the interface INTERFACE.  IS_POINTER is true if this is for a
10130 // pointer to THIS.
10131 
10132 Expression*
interface_method_table(Interface_type * interface,bool is_pointer)10133 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10134 {
10135   if (this->is_error_)
10136     return Expression::make_error(this->location_);
10137   if (this->is_alias_)
10138     {
10139       if (this->type_->named_type() != NULL)
10140 	{
10141 	  if (this->seen_alias_)
10142 	    return Expression::make_error(this->location_);
10143 	  this->seen_alias_ = true;
10144 	  Named_type* nt = this->type_->named_type();
10145 	  Expression* ret = nt->interface_method_table(interface, is_pointer);
10146 	  this->seen_alias_ = false;
10147 	  return ret;
10148 	}
10149       if (this->type_->struct_type() != NULL)
10150 	return this->type_->struct_type()->interface_method_table(interface,
10151 								  is_pointer);
10152       go_unreachable();
10153     }
10154   return Type::interface_method_table(this, interface, is_pointer,
10155                                       &this->interface_method_tables_,
10156                                       &this->pointer_interface_method_tables_);
10157 }
10158 
10159 // Look for a use of a complete type within another type.  This is
10160 // used to check that we don't try to use a type within itself.
10161 
10162 class Find_type_use : public Traverse
10163 {
10164  public:
Find_type_use(Named_type * find_type)10165   Find_type_use(Named_type* find_type)
10166     : Traverse(traverse_types),
10167       find_type_(find_type), found_(false)
10168   { }
10169 
10170   // Whether we found the type.
10171   bool
found() const10172   found() const
10173   { return this->found_; }
10174 
10175  protected:
10176   int
10177   type(Type*);
10178 
10179  private:
10180   // The type we are looking for.
10181   Named_type* find_type_;
10182   // Whether we found the type.
10183   bool found_;
10184 };
10185 
10186 // Check for FIND_TYPE in TYPE.
10187 
10188 int
type(Type * type)10189 Find_type_use::type(Type* type)
10190 {
10191   if (type->named_type() != NULL && this->find_type_ == type->named_type())
10192     {
10193       this->found_ = true;
10194       return TRAVERSE_EXIT;
10195     }
10196 
10197   // It's OK if we see a reference to the type in any type which is
10198   // essentially a pointer: a pointer, a slice, a function, a map, or
10199   // a channel.
10200   if (type->points_to() != NULL
10201       || type->is_slice_type()
10202       || type->function_type() != NULL
10203       || type->map_type() != NULL
10204       || type->channel_type() != NULL)
10205     return TRAVERSE_SKIP_COMPONENTS;
10206 
10207   // For an interface, a reference to the type in a method type should
10208   // be ignored, but we have to consider direct inheritance.  When
10209   // this is called, there may be cases of direct inheritance
10210   // represented as a method with no name.
10211   if (type->interface_type() != NULL)
10212     {
10213       const Typed_identifier_list* methods = type->interface_type()->methods();
10214       if (methods != NULL)
10215 	{
10216 	  for (Typed_identifier_list::const_iterator p = methods->begin();
10217 	       p != methods->end();
10218 	       ++p)
10219 	    {
10220 	      if (p->name().empty())
10221 		{
10222 		  if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10223 		    return TRAVERSE_EXIT;
10224 		}
10225 	    }
10226 	}
10227       return TRAVERSE_SKIP_COMPONENTS;
10228     }
10229 
10230   // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10231   // to convert TYPE to the backend representation before we convert
10232   // FIND_TYPE_.
10233   if (type->named_type() != NULL)
10234     {
10235       switch (type->base()->classification())
10236 	{
10237 	case Type::TYPE_ERROR:
10238 	case Type::TYPE_BOOLEAN:
10239 	case Type::TYPE_INTEGER:
10240 	case Type::TYPE_FLOAT:
10241 	case Type::TYPE_COMPLEX:
10242 	case Type::TYPE_STRING:
10243 	case Type::TYPE_NIL:
10244 	  break;
10245 
10246 	case Type::TYPE_ARRAY:
10247 	case Type::TYPE_STRUCT:
10248 	  this->find_type_->add_dependency(type->named_type());
10249 	  break;
10250 
10251 	case Type::TYPE_NAMED:
10252 	case Type::TYPE_FORWARD:
10253 	  go_assert(saw_errors());
10254 	  break;
10255 
10256 	case Type::TYPE_VOID:
10257 	case Type::TYPE_SINK:
10258 	case Type::TYPE_FUNCTION:
10259 	case Type::TYPE_POINTER:
10260 	case Type::TYPE_CALL_MULTIPLE_RESULT:
10261 	case Type::TYPE_MAP:
10262 	case Type::TYPE_CHANNEL:
10263 	case Type::TYPE_INTERFACE:
10264 	default:
10265 	  go_unreachable();
10266 	}
10267     }
10268 
10269   return TRAVERSE_CONTINUE;
10270 }
10271 
10272 // Look for a circular reference of an alias.
10273 
10274 class Find_alias : public Traverse
10275 {
10276  public:
Find_alias(Named_type * find_type)10277   Find_alias(Named_type* find_type)
10278     : Traverse(traverse_types),
10279       find_type_(find_type), found_(false)
10280   { }
10281 
10282   // Whether we found the type.
10283   bool
found() const10284   found() const
10285   { return this->found_; }
10286 
10287  protected:
10288   int
10289   type(Type*);
10290 
10291  private:
10292   // The type we are looking for.
10293   Named_type* find_type_;
10294   // Whether we found the type.
10295   bool found_;
10296 };
10297 
10298 int
type(Type * type)10299 Find_alias::type(Type* type)
10300 {
10301   Named_type* nt = type->named_type();
10302   if (nt != NULL)
10303     {
10304       if (nt == this->find_type_)
10305 	{
10306 	  this->found_ = true;
10307 	  return TRAVERSE_EXIT;
10308 	}
10309 
10310       // We started from `type T1 = T2`, where T1 is find_type_ and T2
10311       // is, perhaps indirectly, the parameter TYPE.  If TYPE is not
10312       // an alias itself, it's OK if whatever T2 is defined as refers
10313       // to T1.
10314       if (!nt->is_alias())
10315 	return TRAVERSE_SKIP_COMPONENTS;
10316     }
10317 
10318   return TRAVERSE_CONTINUE;
10319 }
10320 
10321 // Verify that a named type does not refer to itself.
10322 
10323 bool
do_verify()10324 Named_type::do_verify()
10325 {
10326   if (this->is_verified_)
10327     return true;
10328   this->is_verified_ = true;
10329 
10330   if (this->is_error_)
10331     return false;
10332 
10333   if (this->is_alias_)
10334     {
10335       Find_alias find(this);
10336       Type::traverse(this->type_, &find);
10337       if (find.found())
10338 	{
10339 	  go_error_at(this->location_, "invalid recursive alias %qs",
10340 		      this->message_name().c_str());
10341 	  this->is_error_ = true;
10342 	  return false;
10343 	}
10344     }
10345 
10346   Find_type_use find(this);
10347   Type::traverse(this->type_, &find);
10348   if (find.found())
10349     {
10350       go_error_at(this->location_, "invalid recursive type %qs",
10351 		  this->message_name().c_str());
10352       this->is_error_ = true;
10353       return false;
10354     }
10355 
10356   // Check whether any of the local methods overloads an existing
10357   // struct field or interface method.  We don't need to check the
10358   // list of methods against itself: that is handled by the Bindings
10359   // code.
10360   if (this->local_methods_ != NULL)
10361     {
10362       Struct_type* st = this->type_->struct_type();
10363       if (st != NULL)
10364 	{
10365 	  for (Bindings::const_declarations_iterator p =
10366 		 this->local_methods_->begin_declarations();
10367 	       p != this->local_methods_->end_declarations();
10368 	       ++p)
10369 	    {
10370 	      const std::string& name(p->first);
10371 	      if (st != NULL && st->find_local_field(name, NULL) != NULL)
10372 		{
10373 		  go_error_at(p->second->location(),
10374 			      "method %qs redeclares struct field name",
10375 			      Gogo::message_name(name).c_str());
10376 		}
10377 	    }
10378 	}
10379     }
10380 
10381   return true;
10382 }
10383 
10384 // Return whether this type is or contains a pointer.
10385 
10386 bool
do_has_pointer() const10387 Named_type::do_has_pointer() const
10388 {
10389   if (this->seen_)
10390     return false;
10391   this->seen_ = true;
10392   bool ret = this->type_->has_pointer();
10393   this->seen_ = false;
10394   return ret;
10395 }
10396 
10397 // Return whether comparisons for this type can use the identity
10398 // function.
10399 
10400 bool
do_compare_is_identity(Gogo * gogo)10401 Named_type::do_compare_is_identity(Gogo* gogo)
10402 {
10403   // We don't use this->seen_ here because compare_is_identity may
10404   // call base() later, and that will mess up if seen_ is set here.
10405   if (this->seen_in_compare_is_identity_)
10406     return false;
10407   this->seen_in_compare_is_identity_ = true;
10408   bool ret = this->type_->compare_is_identity(gogo);
10409   this->seen_in_compare_is_identity_ = false;
10410   return ret;
10411 }
10412 
10413 // Return whether this type is reflexive--whether it is always equal
10414 // to itself.
10415 
10416 bool
do_is_reflexive()10417 Named_type::do_is_reflexive()
10418 {
10419   if (this->seen_in_compare_is_identity_)
10420     return false;
10421   this->seen_in_compare_is_identity_ = true;
10422   bool ret = this->type_->is_reflexive();
10423   this->seen_in_compare_is_identity_ = false;
10424   return ret;
10425 }
10426 
10427 // Return whether this type needs a key update when used as a map key.
10428 
10429 bool
do_needs_key_update()10430 Named_type::do_needs_key_update()
10431 {
10432   if (this->seen_in_compare_is_identity_)
10433     return true;
10434   this->seen_in_compare_is_identity_ = true;
10435   bool ret = this->type_->needs_key_update();
10436   this->seen_in_compare_is_identity_ = false;
10437   return ret;
10438 }
10439 
10440 // Return a hash code.  This is used for method lookup.  We simply
10441 // hash on the name itself.
10442 
10443 unsigned int
do_hash_for_method(Gogo * gogo) const10444 Named_type::do_hash_for_method(Gogo* gogo) const
10445 {
10446   if (this->is_error_)
10447     return 0;
10448 
10449   // Aliases are handled in Type::hash_for_method.
10450   go_assert(!this->is_alias_);
10451 
10452   const std::string& name(this->named_object()->name());
10453   unsigned int ret = Type::hash_string(name, 0);
10454 
10455   // GOGO will be NULL here when called from Type_hash_identical.
10456   // That is OK because that is only used for internal hash tables
10457   // where we are going to be comparing named types for equality.  In
10458   // other cases, which are cases where the runtime is going to
10459   // compare hash codes to see if the types are the same, we need to
10460   // include the pkgpath in the hash.
10461   if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10462     {
10463       const Package* package = this->named_object()->package();
10464       if (package == NULL)
10465 	ret = Type::hash_string(gogo->pkgpath(), ret);
10466       else
10467 	ret = Type::hash_string(package->pkgpath(), ret);
10468     }
10469 
10470   return ret;
10471 }
10472 
10473 // Convert a named type to the backend representation.  In order to
10474 // get dependencies right, we fill in a dummy structure for this type,
10475 // then convert all the dependencies, then complete this type.  When
10476 // this function is complete, the size of the type is known.
10477 
10478 void
convert(Gogo * gogo)10479 Named_type::convert(Gogo* gogo)
10480 {
10481   if (this->is_error_ || this->is_converted_)
10482     return;
10483 
10484   this->create_placeholder(gogo);
10485 
10486   // If we are called to turn unsafe.Sizeof into a constant, we may
10487   // not have verified the type yet.  We have to make sure it is
10488   // verified, since that sets the list of dependencies.
10489   this->verify();
10490 
10491   // Convert all the dependencies.  If they refer indirectly back to
10492   // this type, they will pick up the intermediate representation we just
10493   // created.
10494   for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10495        p != this->dependencies_.end();
10496        ++p)
10497     (*p)->convert(gogo);
10498 
10499   // Complete this type.
10500   Btype* bt = this->named_btype_;
10501   Type* base = this->type_->base();
10502   switch (base->classification())
10503     {
10504     case TYPE_VOID:
10505     case TYPE_BOOLEAN:
10506     case TYPE_INTEGER:
10507     case TYPE_FLOAT:
10508     case TYPE_COMPLEX:
10509     case TYPE_STRING:
10510     case TYPE_NIL:
10511       break;
10512 
10513     case TYPE_MAP:
10514     case TYPE_CHANNEL:
10515       break;
10516 
10517     case TYPE_FUNCTION:
10518     case TYPE_POINTER:
10519       // The size of these types is already correct.  We don't worry
10520       // about filling them in until later, when we also track
10521       // circular references.
10522       break;
10523 
10524     case TYPE_STRUCT:
10525       {
10526 	std::vector<Backend::Btyped_identifier> bfields;
10527 	get_backend_struct_fields(gogo, base->struct_type()->fields(),
10528 				  true, &bfields);
10529 	if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10530 	  bt = gogo->backend()->error_type();
10531       }
10532       break;
10533 
10534     case TYPE_ARRAY:
10535       // Slice types were completed in create_placeholder.
10536       if (!base->is_slice_type())
10537 	{
10538 	  Btype* bet = base->array_type()->get_backend_element(gogo, true);
10539 	  Bexpression* blen = base->array_type()->get_backend_length(gogo);
10540 	  if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10541 	    bt = gogo->backend()->error_type();
10542 	}
10543       break;
10544 
10545     case TYPE_INTERFACE:
10546       // Interface types were completed in create_placeholder.
10547       break;
10548 
10549     case TYPE_ERROR:
10550       return;
10551 
10552     default:
10553     case TYPE_SINK:
10554     case TYPE_CALL_MULTIPLE_RESULT:
10555     case TYPE_NAMED:
10556     case TYPE_FORWARD:
10557       go_unreachable();
10558     }
10559 
10560   this->named_btype_ = bt;
10561   this->is_converted_ = true;
10562   this->is_placeholder_ = false;
10563 }
10564 
10565 // Create the placeholder for a named type.  This is the first step in
10566 // converting to the backend representation.
10567 
10568 void
create_placeholder(Gogo * gogo)10569 Named_type::create_placeholder(Gogo* gogo)
10570 {
10571   if (this->is_error_)
10572     this->named_btype_ = gogo->backend()->error_type();
10573 
10574   if (this->named_btype_ != NULL)
10575     return;
10576 
10577   // Create the structure for this type.  Note that because we call
10578   // base() here, we don't attempt to represent a named type defined
10579   // as another named type.  Instead both named types will point to
10580   // different base representations.
10581   Type* base = this->type_->base();
10582   Btype* bt;
10583   bool set_name = true;
10584   switch (base->classification())
10585     {
10586     case TYPE_ERROR:
10587       this->is_error_ = true;
10588       this->named_btype_ = gogo->backend()->error_type();
10589       return;
10590 
10591     case TYPE_VOID:
10592     case TYPE_BOOLEAN:
10593     case TYPE_INTEGER:
10594     case TYPE_FLOAT:
10595     case TYPE_COMPLEX:
10596     case TYPE_STRING:
10597     case TYPE_NIL:
10598       // These are simple basic types, we can just create them
10599       // directly.
10600       bt = Type::get_named_base_btype(gogo, base);
10601       break;
10602 
10603     case TYPE_MAP:
10604     case TYPE_CHANNEL:
10605       // All maps and channels have the same backend representation.
10606       bt = Type::get_named_base_btype(gogo, base);
10607       break;
10608 
10609     case TYPE_FUNCTION:
10610     case TYPE_POINTER:
10611       {
10612 	bool for_function = base->classification() == TYPE_FUNCTION;
10613 	bt = gogo->backend()->placeholder_pointer_type(this->name(),
10614 						       this->location_,
10615 						       for_function);
10616 	set_name = false;
10617       }
10618       break;
10619 
10620     case TYPE_STRUCT:
10621       bt = gogo->backend()->placeholder_struct_type(this->name(),
10622 						    this->location_);
10623       this->is_placeholder_ = true;
10624       set_name = false;
10625       break;
10626 
10627     case TYPE_ARRAY:
10628       if (base->is_slice_type())
10629 	bt = gogo->backend()->placeholder_struct_type(this->name(),
10630 						      this->location_);
10631       else
10632 	{
10633 	  bt = gogo->backend()->placeholder_array_type(this->name(),
10634 						       this->location_);
10635 	  this->is_placeholder_ = true;
10636 	}
10637       set_name = false;
10638       break;
10639 
10640     case TYPE_INTERFACE:
10641       if (base->interface_type()->is_empty())
10642 	bt = Interface_type::get_backend_empty_interface_type(gogo);
10643       else
10644 	{
10645 	  bt = gogo->backend()->placeholder_struct_type(this->name(),
10646 							this->location_);
10647 	  set_name = false;
10648 	}
10649       break;
10650 
10651     default:
10652     case TYPE_SINK:
10653     case TYPE_CALL_MULTIPLE_RESULT:
10654     case TYPE_NAMED:
10655     case TYPE_FORWARD:
10656       go_unreachable();
10657     }
10658 
10659   if (set_name)
10660     bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10661 
10662   this->named_btype_ = bt;
10663 
10664   if (base->is_slice_type())
10665     {
10666       // We do not record slices as dependencies of other types,
10667       // because we can fill them in completely here with the final
10668       // size.
10669       std::vector<Backend::Btyped_identifier> bfields;
10670       get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10671       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10672 	this->named_btype_ = gogo->backend()->error_type();
10673     }
10674   else if (base->interface_type() != NULL
10675 	   && !base->interface_type()->is_empty())
10676     {
10677       // We do not record interfaces as dependencies of other types,
10678       // because we can fill them in completely here with the final
10679       // size.
10680       std::vector<Backend::Btyped_identifier> bfields;
10681       get_backend_interface_fields(gogo, base->interface_type(), true,
10682 				   &bfields);
10683       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10684 	this->named_btype_ = gogo->backend()->error_type();
10685     }
10686 }
10687 
10688 // Get the backend representation for a named type.
10689 
10690 Btype*
do_get_backend(Gogo * gogo)10691 Named_type::do_get_backend(Gogo* gogo)
10692 {
10693   if (this->is_error_)
10694     return gogo->backend()->error_type();
10695 
10696   Btype* bt = this->named_btype_;
10697 
10698   if (!gogo->named_types_are_converted())
10699     {
10700       // We have not completed converting named types.  NAMED_BTYPE_
10701       // is a placeholder and we shouldn't do anything further.
10702       if (bt != NULL)
10703 	return bt;
10704 
10705       // We don't build dependencies for types whose sizes do not
10706       // change or are not relevant, so we may see them here while
10707       // converting types.
10708       this->create_placeholder(gogo);
10709       bt = this->named_btype_;
10710       go_assert(bt != NULL);
10711       return bt;
10712     }
10713 
10714   // We are not converting types.  This should only be called if the
10715   // type has already been converted.
10716   if (!this->is_converted_)
10717     {
10718       go_assert(saw_errors());
10719       return gogo->backend()->error_type();
10720     }
10721 
10722   go_assert(bt != NULL);
10723 
10724   // Complete the backend representation.
10725   Type* base = this->type_->base();
10726   Btype* bt1;
10727   switch (base->classification())
10728     {
10729     case TYPE_ERROR:
10730       return gogo->backend()->error_type();
10731 
10732     case TYPE_VOID:
10733     case TYPE_BOOLEAN:
10734     case TYPE_INTEGER:
10735     case TYPE_FLOAT:
10736     case TYPE_COMPLEX:
10737     case TYPE_STRING:
10738     case TYPE_NIL:
10739     case TYPE_MAP:
10740     case TYPE_CHANNEL:
10741       return bt;
10742 
10743     case TYPE_STRUCT:
10744       if (!this->seen_in_get_backend_)
10745 	{
10746 	  this->seen_in_get_backend_ = true;
10747 	  base->struct_type()->finish_backend_fields(gogo);
10748 	  this->seen_in_get_backend_ = false;
10749 	}
10750       return bt;
10751 
10752     case TYPE_ARRAY:
10753       if (!this->seen_in_get_backend_)
10754 	{
10755 	  this->seen_in_get_backend_ = true;
10756 	  base->array_type()->finish_backend_element(gogo);
10757 	  this->seen_in_get_backend_ = false;
10758 	}
10759       return bt;
10760 
10761     case TYPE_INTERFACE:
10762       if (!this->seen_in_get_backend_)
10763 	{
10764 	  this->seen_in_get_backend_ = true;
10765 	  base->interface_type()->finish_backend_methods(gogo);
10766 	  this->seen_in_get_backend_ = false;
10767 	}
10768       return bt;
10769 
10770     case TYPE_FUNCTION:
10771       // Don't build a circular data structure.  GENERIC can't handle
10772       // it.
10773       if (this->seen_in_get_backend_)
10774 	{
10775 	  this->is_circular_ = true;
10776 	  return gogo->backend()->circular_pointer_type(bt, true);
10777 	}
10778       this->seen_in_get_backend_ = true;
10779       bt1 = Type::get_named_base_btype(gogo, base);
10780       this->seen_in_get_backend_ = false;
10781       if (this->is_circular_)
10782 	bt1 = gogo->backend()->circular_pointer_type(bt, true);
10783       if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10784 	bt = gogo->backend()->error_type();
10785       return bt;
10786 
10787     case TYPE_POINTER:
10788       // Don't build a circular data structure. GENERIC can't handle
10789       // it.
10790       if (this->seen_in_get_backend_)
10791 	{
10792 	  this->is_circular_ = true;
10793 	  return gogo->backend()->circular_pointer_type(bt, false);
10794 	}
10795       this->seen_in_get_backend_ = true;
10796       bt1 = Type::get_named_base_btype(gogo, base);
10797       this->seen_in_get_backend_ = false;
10798       if (this->is_circular_)
10799 	bt1 = gogo->backend()->circular_pointer_type(bt, false);
10800       if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10801 	bt = gogo->backend()->error_type();
10802       return bt;
10803 
10804     default:
10805     case TYPE_SINK:
10806     case TYPE_CALL_MULTIPLE_RESULT:
10807     case TYPE_NAMED:
10808     case TYPE_FORWARD:
10809       go_unreachable();
10810     }
10811 
10812   go_unreachable();
10813 }
10814 
10815 // Build a type descriptor for a named type.
10816 
10817 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)10818 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10819 {
10820   if (this->is_error_)
10821     return Expression::make_error(this->location_);
10822   if (name == NULL && this->is_alias_)
10823     {
10824       if (this->seen_alias_)
10825 	return Expression::make_error(this->location_);
10826       this->seen_alias_ = true;
10827       Expression* ret = this->type_->type_descriptor(gogo, NULL);
10828       this->seen_alias_ = false;
10829       return ret;
10830     }
10831 
10832   // If NAME is not NULL, then we don't really want the type
10833   // descriptor for this type; we want the descriptor for the
10834   // underlying type, giving it the name NAME.
10835   return this->named_type_descriptor(gogo, this->type_,
10836 				     name == NULL ? this : name);
10837 }
10838 
10839 // Add to the reflection string.  This is used mostly for the name of
10840 // the type used in a type descriptor, not for actual reflection
10841 // strings.
10842 
10843 void
do_reflection(Gogo * gogo,std::string * ret) const10844 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10845 {
10846   this->append_reflection_type_name(gogo, false, ret);
10847 }
10848 
10849 // Add to the reflection string.  For an alias we normally use the
10850 // real name, but if USE_ALIAS is true we use the alias name itself.
10851 
10852 void
append_reflection_type_name(Gogo * gogo,bool use_alias,std::string * ret) const10853 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10854 					std::string* ret) const
10855 {
10856   if (this->is_error_)
10857     return;
10858   if (this->is_alias_ && !use_alias)
10859     {
10860       if (this->seen_alias_)
10861 	return;
10862       this->seen_alias_ = true;
10863       this->append_reflection(this->type_, gogo, ret);
10864       this->seen_alias_ = false;
10865       return;
10866     }
10867   if (!this->is_builtin())
10868     {
10869       // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10870       // make a unique reflection string, so that the type
10871       // canonicalization in the reflect package will work.  In order
10872       // to be compatible with the gc compiler, we put tabs into the
10873       // package path, so that the reflect methods can discard it.
10874       const Package* package = this->named_object_->package();
10875       ret->push_back('\t');
10876       ret->append(package != NULL
10877 		  ? package->pkgpath_symbol()
10878 		  : gogo->pkgpath_symbol());
10879       ret->push_back('\t');
10880       ret->append(package != NULL
10881 		  ? package->package_name()
10882 		  : gogo->package_name());
10883       ret->push_back('.');
10884     }
10885   if (this->in_function_ != NULL)
10886     {
10887       ret->push_back('\t');
10888       const Typed_identifier* rcvr =
10889 	this->in_function_->func_value()->type()->receiver();
10890       if (rcvr != NULL)
10891 	{
10892 	  Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10893 	  ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10894 	  ret->push_back('.');
10895 	}
10896       ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10897       ret->push_back('$');
10898       if (this->in_function_index_ > 0)
10899 	{
10900 	  char buf[30];
10901 	  snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10902 	  ret->append(buf);
10903 	  ret->push_back('$');
10904 	}
10905       ret->push_back('\t');
10906     }
10907   ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10908 }
10909 
10910 // Export the type.  This is called to export a global type.
10911 
10912 void
export_named_type(Export * exp,const std::string &) const10913 Named_type::export_named_type(Export* exp, const std::string&) const
10914 {
10915   // We don't need to write the name of the type here, because it will
10916   // be written by Export::write_type anyhow.
10917   exp->write_c_string("type ");
10918   exp->write_type(this);
10919   exp->write_c_string(";\n");
10920 }
10921 
10922 // Import a named type.
10923 
10924 void
import_named_type(Import * imp,Named_type ** ptype)10925 Named_type::import_named_type(Import* imp, Named_type** ptype)
10926 {
10927   imp->require_c_string("type ");
10928   Type *type = imp->read_type();
10929   *ptype = type->named_type();
10930   go_assert(*ptype != NULL);
10931   imp->require_c_string(";\n");
10932 }
10933 
10934 // Export the type when it is referenced by another type.  In this
10935 // case Export::export_type will already have issued the name.
10936 
10937 void
do_export(Export * exp) const10938 Named_type::do_export(Export* exp) const
10939 {
10940   exp->write_type(this->type_);
10941 
10942   // To save space, we only export the methods directly attached to
10943   // this type.
10944   Bindings* methods = this->local_methods_;
10945   if (methods == NULL)
10946     return;
10947 
10948   exp->write_c_string("\n");
10949   for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10950        p != methods->end_definitions();
10951        ++p)
10952     {
10953       exp->write_c_string(" ");
10954       (*p)->export_named_object(exp);
10955     }
10956 
10957   for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10958        p != methods->end_declarations();
10959        ++p)
10960     {
10961       if (p->second->is_function_declaration())
10962 	{
10963 	  exp->write_c_string(" ");
10964 	  p->second->export_named_object(exp);
10965 	}
10966     }
10967 }
10968 
10969 // Make a named type.
10970 
10971 Named_type*
make_named_type(Named_object * named_object,Type * type,Location location)10972 Type::make_named_type(Named_object* named_object, Type* type,
10973 		      Location location)
10974 {
10975   return new Named_type(named_object, type, location);
10976 }
10977 
10978 // Finalize the methods for TYPE.  It will be a named type or a struct
10979 // type.  This sets *ALL_METHODS to the list of methods, and builds
10980 // all required stubs.
10981 
10982 void
finalize_methods(Gogo * gogo,const Type * type,Location location,Methods ** all_methods)10983 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10984 		       Methods** all_methods)
10985 {
10986   *all_methods = new Methods();
10987   std::vector<const Named_type*> seen;
10988   Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10989   if ((*all_methods)->empty())
10990     {
10991       delete *all_methods;
10992       *all_methods = NULL;
10993     }
10994   Type::build_stub_methods(gogo, type, *all_methods, location);
10995 }
10996 
10997 // Add the methods for TYPE to *METHODS.  FIELD_INDEXES is used to
10998 // build up the struct field indexes as we go.  DEPTH is the depth of
10999 // the field within TYPE.  IS_EMBEDDED_POINTER is true if we are
11000 // adding these methods for an anonymous field with pointer type.
11001 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11002 // calls the real method.  TYPES_SEEN is used to avoid infinite
11003 // recursion.
11004 
11005 void
add_methods_for_type(const Type * type,const Method::Field_indexes * field_indexes,unsigned int depth,bool is_embedded_pointer,bool needs_stub_method,std::vector<const Named_type * > * seen,Methods * methods)11006 Type::add_methods_for_type(const Type* type,
11007 			   const Method::Field_indexes* field_indexes,
11008 			   unsigned int depth,
11009 			   bool is_embedded_pointer,
11010 			   bool needs_stub_method,
11011 			   std::vector<const Named_type*>* seen,
11012 			   Methods* methods)
11013 {
11014   // Pointer types may not have methods.
11015   if (type->points_to() != NULL)
11016     return;
11017 
11018   const Named_type* nt = type->named_type();
11019   if (nt != NULL)
11020     {
11021       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11022 	   p != seen->end();
11023 	   ++p)
11024 	{
11025 	  if (*p == nt)
11026 	    return;
11027 	}
11028 
11029       seen->push_back(nt);
11030 
11031       Type::add_local_methods_for_type(nt, field_indexes, depth,
11032 				       is_embedded_pointer, needs_stub_method,
11033 				       methods);
11034     }
11035 
11036   Type::add_embedded_methods_for_type(type, field_indexes, depth,
11037 				      is_embedded_pointer, needs_stub_method,
11038 				      seen, methods);
11039 
11040   // If we are called with depth > 0, then we are looking at an
11041   // anonymous field of a struct.  If such a field has interface type,
11042   // then we need to add the interface methods.  We don't want to add
11043   // them when depth == 0, because we will already handle them
11044   // following the usual rules for an interface type.
11045   if (depth > 0)
11046     Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11047 
11048   if (nt != NULL)
11049       seen->pop_back();
11050 }
11051 
11052 // Add the local methods for the named type NT to *METHODS.  The
11053 // parameters are as for add_methods_to_type.
11054 
11055 void
add_local_methods_for_type(const Named_type * nt,const Method::Field_indexes * field_indexes,unsigned int depth,bool is_embedded_pointer,bool needs_stub_method,Methods * methods)11056 Type::add_local_methods_for_type(const Named_type* nt,
11057 				 const Method::Field_indexes* field_indexes,
11058 				 unsigned int depth,
11059 				 bool is_embedded_pointer,
11060 				 bool needs_stub_method,
11061 				 Methods* methods)
11062 {
11063   const Bindings* local_methods = nt->local_methods();
11064   if (local_methods == NULL)
11065     return;
11066 
11067   for (Bindings::const_declarations_iterator p =
11068 	 local_methods->begin_declarations();
11069        p != local_methods->end_declarations();
11070        ++p)
11071     {
11072       Named_object* no = p->second;
11073       bool is_value_method = (is_embedded_pointer
11074 			      || !Type::method_expects_pointer(no));
11075       Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11076 				   (needs_stub_method || depth > 0));
11077       if (!methods->insert(no->name(), m))
11078 	delete m;
11079     }
11080 }
11081 
11082 // Add the embedded methods for TYPE to *METHODS.  These are the
11083 // methods attached to anonymous fields.  The parameters are as for
11084 // add_methods_to_type.
11085 
11086 void
add_embedded_methods_for_type(const Type * type,const Method::Field_indexes * field_indexes,unsigned int depth,bool is_embedded_pointer,bool needs_stub_method,std::vector<const Named_type * > * seen,Methods * methods)11087 Type::add_embedded_methods_for_type(const Type* type,
11088 				    const Method::Field_indexes* field_indexes,
11089 				    unsigned int depth,
11090 				    bool is_embedded_pointer,
11091 				    bool needs_stub_method,
11092 				    std::vector<const Named_type*>* seen,
11093 				    Methods* methods)
11094 {
11095   // Look for anonymous fields in TYPE.  TYPE has fields if it is a
11096   // struct.
11097   const Struct_type* st = type->struct_type();
11098   if (st == NULL)
11099     return;
11100 
11101   const Struct_field_list* fields = st->fields();
11102   if (fields == NULL)
11103     return;
11104 
11105   unsigned int i = 0;
11106   for (Struct_field_list::const_iterator pf = fields->begin();
11107        pf != fields->end();
11108        ++pf, ++i)
11109     {
11110       if (!pf->is_anonymous())
11111 	continue;
11112 
11113       Type* ftype = pf->type();
11114       bool is_pointer = false;
11115       if (ftype->points_to() != NULL)
11116 	{
11117 	  ftype = ftype->points_to();
11118 	  is_pointer = true;
11119 	}
11120       Named_type* fnt = ftype->named_type();
11121       if (fnt == NULL)
11122 	{
11123 	  // This is an error, but it will be diagnosed elsewhere.
11124 	  continue;
11125 	}
11126 
11127       Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11128       sub_field_indexes->next = field_indexes;
11129       sub_field_indexes->field_index = i;
11130 
11131       Methods tmp_methods;
11132       Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11133 				 (is_embedded_pointer || is_pointer),
11134 				 (needs_stub_method
11135 				  || is_pointer
11136 				  || i > 0),
11137 				 seen,
11138 				 &tmp_methods);
11139       // Check if there are promoted methods that conflict with field names and
11140       // don't add them to the method map.
11141       for (Methods::const_iterator p = tmp_methods.begin();
11142 	   p != tmp_methods.end();
11143 	   ++p)
11144 	{
11145 	  bool found = false;
11146 	  for (Struct_field_list::const_iterator fp = fields->begin();
11147 	       fp != fields->end();
11148 	       ++fp)
11149 	    {
11150 	      if (fp->field_name() == p->first)
11151 		{
11152 		  found = true;
11153 		  break;
11154 		}
11155 	    }
11156 	  if (!found &&
11157 	      !methods->insert(p->first, p->second))
11158 	    delete p->second;
11159 	}
11160     }
11161 }
11162 
11163 // If TYPE is an interface type, then add its method to *METHODS.
11164 // This is for interface methods attached to an anonymous field.  The
11165 // parameters are as for add_methods_for_type.
11166 
11167 void
add_interface_methods_for_type(const Type * type,const Method::Field_indexes * field_indexes,unsigned int depth,Methods * methods)11168 Type::add_interface_methods_for_type(const Type* type,
11169 				     const Method::Field_indexes* field_indexes,
11170 				     unsigned int depth,
11171 				     Methods* methods)
11172 {
11173   const Interface_type* it = type->interface_type();
11174   if (it == NULL)
11175     return;
11176 
11177   const Typed_identifier_list* imethods = it->methods();
11178   if (imethods == NULL)
11179     return;
11180 
11181   for (Typed_identifier_list::const_iterator pm = imethods->begin();
11182        pm != imethods->end();
11183        ++pm)
11184     {
11185       Function_type* fntype = pm->type()->function_type();
11186       if (fntype == NULL)
11187 	{
11188 	  // This is an error, but it should be reported elsewhere
11189 	  // when we look at the methods for IT.
11190 	  continue;
11191 	}
11192       go_assert(!fntype->is_method());
11193       fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11194       Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11195 				       field_indexes, depth);
11196       if (!methods->insert(pm->name(), m))
11197 	delete m;
11198     }
11199 }
11200 
11201 // Build stub methods for TYPE as needed.  METHODS is the set of
11202 // methods for the type.  A stub method may be needed when a type
11203 // inherits a method from an anonymous field.  When we need the
11204 // address of the method, as in a type descriptor, we need to build a
11205 // little stub which does the required field dereferences and jumps to
11206 // the real method.  LOCATION is the location of the type definition.
11207 
11208 void
build_stub_methods(Gogo * gogo,const Type * type,const Methods * methods,Location location)11209 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11210 			 Location location)
11211 {
11212   if (methods == NULL)
11213     return;
11214   for (Methods::const_iterator p = methods->begin();
11215        p != methods->end();
11216        ++p)
11217     {
11218       Method* m = p->second;
11219       if (m->is_ambiguous() || !m->needs_stub_method())
11220 	continue;
11221 
11222       const std::string& name(p->first);
11223 
11224       // Build a stub method.
11225 
11226       const Function_type* fntype = m->type();
11227 
11228       static unsigned int counter;
11229       char buf[100];
11230       snprintf(buf, sizeof buf, "$this%u", counter);
11231       ++counter;
11232 
11233       Type* receiver_type = const_cast<Type*>(type);
11234       if (!m->is_value_method())
11235 	receiver_type = Type::make_pointer_type(receiver_type);
11236       Location receiver_location = m->receiver_location();
11237       Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11238 							receiver_location);
11239 
11240       const Typed_identifier_list* fnparams = fntype->parameters();
11241       Typed_identifier_list* stub_params;
11242       if (fnparams == NULL || fnparams->empty())
11243 	stub_params = NULL;
11244       else
11245 	{
11246 	  // We give each stub parameter a unique name.
11247 	  stub_params = new Typed_identifier_list();
11248 	  for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11249 	       pp != fnparams->end();
11250 	       ++pp)
11251 	    {
11252 	      char pbuf[100];
11253 	      snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11254 	      stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11255 						      pp->location()));
11256 	      ++counter;
11257 	    }
11258 	}
11259 
11260       const Typed_identifier_list* fnresults = fntype->results();
11261       Typed_identifier_list* stub_results;
11262       if (fnresults == NULL || fnresults->empty())
11263 	stub_results = NULL;
11264       else
11265 	{
11266 	  // We create the result parameters without any names, since
11267 	  // we won't refer to them.
11268 	  stub_results = new Typed_identifier_list();
11269 	  for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11270 	       pr != fnresults->end();
11271 	       ++pr)
11272 	    stub_results->push_back(Typed_identifier("", pr->type(),
11273 						     pr->location()));
11274 	}
11275 
11276       Function_type* stub_type = Type::make_function_type(receiver,
11277 							  stub_params,
11278 							  stub_results,
11279 							  fntype->location());
11280       if (fntype->is_varargs())
11281 	stub_type->set_is_varargs();
11282 
11283       // We only create the function in the package which creates the
11284       // type.
11285       const Package* package;
11286       if (type->named_type() == NULL)
11287 	package = NULL;
11288       else
11289 	package = type->named_type()->named_object()->package();
11290       std::string stub_name = gogo->stub_method_name(package, name);
11291       Named_object* stub;
11292       if (package != NULL)
11293 	stub = Named_object::make_function_declaration(stub_name, package,
11294 						       stub_type, location);
11295       else
11296 	{
11297 	  stub = gogo->start_function(stub_name, stub_type, false,
11298 				      fntype->location());
11299 	  Type::build_one_stub_method(gogo, m, buf, stub_params,
11300 				      fntype->is_varargs(), location);
11301 	  gogo->finish_function(fntype->location());
11302 
11303 	  if (type->named_type() == NULL && stub->is_function())
11304 	    stub->func_value()->set_is_unnamed_type_stub_method();
11305 	  if (m->nointerface() && stub->is_function())
11306 	    stub->func_value()->set_nointerface();
11307 	}
11308 
11309       m->set_stub_object(stub);
11310     }
11311 }
11312 
11313 // Build a stub method which adjusts the receiver as required to call
11314 // METHOD.  RECEIVER_NAME is the name we used for the receiver.
11315 // PARAMS is the list of function parameters.
11316 
11317 void
build_one_stub_method(Gogo * gogo,Method * method,const char * receiver_name,const Typed_identifier_list * params,bool is_varargs,Location location)11318 Type::build_one_stub_method(Gogo* gogo, Method* method,
11319 			    const char* receiver_name,
11320 			    const Typed_identifier_list* params,
11321 			    bool is_varargs,
11322 			    Location location)
11323 {
11324   Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11325   go_assert(receiver_object != NULL);
11326 
11327   Expression* expr = Expression::make_var_reference(receiver_object, location);
11328   expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11329   if (expr->type()->points_to() == NULL)
11330     expr = Expression::make_unary(OPERATOR_AND, expr, location);
11331 
11332   Expression_list* arguments;
11333   if (params == NULL || params->empty())
11334     arguments = NULL;
11335   else
11336     {
11337       arguments = new Expression_list();
11338       for (Typed_identifier_list::const_iterator p = params->begin();
11339 	   p != params->end();
11340 	   ++p)
11341 	{
11342 	  Named_object* param = gogo->lookup(p->name(), NULL);
11343 	  go_assert(param != NULL);
11344 	  Expression* param_ref = Expression::make_var_reference(param,
11345 								 location);
11346 	  arguments->push_back(param_ref);
11347 	}
11348     }
11349 
11350   Expression* func = method->bind_method(expr, location);
11351   go_assert(func != NULL);
11352   Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11353 						location);
11354 
11355   gogo->add_statement(Statement::make_return_from_call(call, location));
11356 }
11357 
11358 // Apply FIELD_INDEXES to EXPR.  The field indexes have to be applied
11359 // in reverse order.
11360 
11361 Expression*
apply_field_indexes(Expression * expr,const Method::Field_indexes * field_indexes,Location location)11362 Type::apply_field_indexes(Expression* expr,
11363 			  const Method::Field_indexes* field_indexes,
11364 			  Location location)
11365 {
11366   if (field_indexes == NULL)
11367     return expr;
11368   expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11369   Struct_type* stype = expr->type()->deref()->struct_type();
11370   go_assert(stype != NULL
11371 	     && field_indexes->field_index < stype->field_count());
11372   if (expr->type()->struct_type() == NULL)
11373     {
11374       go_assert(expr->type()->points_to() != NULL);
11375       expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11376                                           location);
11377       go_assert(expr->type()->struct_type() == stype);
11378     }
11379   return Expression::make_field_reference(expr, field_indexes->field_index,
11380 					  location);
11381 }
11382 
11383 // Return whether NO is a method for which the receiver is a pointer.
11384 
11385 bool
method_expects_pointer(const Named_object * no)11386 Type::method_expects_pointer(const Named_object* no)
11387 {
11388   const Function_type *fntype;
11389   if (no->is_function())
11390     fntype = no->func_value()->type();
11391   else if (no->is_function_declaration())
11392     fntype = no->func_declaration_value()->type();
11393   else
11394     go_unreachable();
11395   return fntype->receiver()->type()->points_to() != NULL;
11396 }
11397 
11398 // Given a set of methods for a type, METHODS, return the method NAME,
11399 // or NULL if there isn't one or if it is ambiguous.  If IS_AMBIGUOUS
11400 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11401 // but is ambiguous (and return NULL).
11402 
11403 Method*
method_function(const Methods * methods,const std::string & name,bool * is_ambiguous)11404 Type::method_function(const Methods* methods, const std::string& name,
11405 		      bool* is_ambiguous)
11406 {
11407   if (is_ambiguous != NULL)
11408     *is_ambiguous = false;
11409   if (methods == NULL)
11410     return NULL;
11411   Methods::const_iterator p = methods->find(name);
11412   if (p == methods->end())
11413     return NULL;
11414   Method* m = p->second;
11415   if (m->is_ambiguous())
11416     {
11417       if (is_ambiguous != NULL)
11418 	*is_ambiguous = true;
11419       return NULL;
11420     }
11421   return m;
11422 }
11423 
11424 // Return a pointer to the interface method table for TYPE for the
11425 // interface INTERFACE.
11426 
11427 Expression*
interface_method_table(Type * type,Interface_type * interface,bool is_pointer,Interface_method_tables ** method_tables,Interface_method_tables ** pointer_tables)11428 Type::interface_method_table(Type* type,
11429 			     Interface_type *interface,
11430 			     bool is_pointer,
11431 			     Interface_method_tables** method_tables,
11432 			     Interface_method_tables** pointer_tables)
11433 {
11434   go_assert(!interface->is_empty());
11435 
11436   Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11437 
11438   if (*pimt == NULL)
11439     *pimt = new Interface_method_tables(5);
11440 
11441   std::pair<Interface_type*, Expression*> val(interface, NULL);
11442   std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11443 
11444   Location loc = Linemap::predeclared_location();
11445   if (ins.second)
11446     {
11447       // This is a new entry in the hash table.
11448       go_assert(ins.first->second == NULL);
11449       ins.first->second =
11450 	Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11451     }
11452   return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11453 }
11454 
11455 // Look for field or method NAME for TYPE.  Return an Expression for
11456 // the field or method bound to EXPR.  If there is no such field or
11457 // method, give an appropriate error and return an error expression.
11458 
11459 Expression*
bind_field_or_method(Gogo * gogo,const Type * type,Expression * expr,const std::string & name,Location location)11460 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11461 			   const std::string& name,
11462 			   Location location)
11463 {
11464   if (type->deref()->is_error_type())
11465     return Expression::make_error(location);
11466 
11467   const Named_type* nt = type->deref()->named_type();
11468   const Struct_type* st = type->deref()->struct_type();
11469   const Interface_type* it = type->interface_type();
11470 
11471   // If this is a pointer to a pointer, then it is possible that the
11472   // pointed-to type has methods.
11473   bool dereferenced = false;
11474   if (nt == NULL
11475       && st == NULL
11476       && it == NULL
11477       && type->points_to() != NULL
11478       && type->points_to()->points_to() != NULL)
11479     {
11480       expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11481                                           location);
11482       type = type->points_to();
11483       if (type->deref()->is_error_type())
11484 	return Expression::make_error(location);
11485       nt = type->points_to()->named_type();
11486       st = type->points_to()->struct_type();
11487       dereferenced = true;
11488     }
11489 
11490   bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11491 				  || expr->is_addressable());
11492   std::vector<const Named_type*> seen;
11493   bool is_method = false;
11494   bool found_pointer_method = false;
11495   std::string ambig1;
11496   std::string ambig2;
11497   if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11498 				 &seen, NULL, &is_method,
11499 				 &found_pointer_method, &ambig1, &ambig2))
11500     {
11501       Expression* ret;
11502       if (!is_method)
11503 	{
11504 	  go_assert(st != NULL);
11505 	  if (type->struct_type() == NULL)
11506 	    {
11507               if (dereferenced)
11508                 {
11509                   go_error_at(location, "pointer type has no field %qs",
11510                               Gogo::message_name(name).c_str());
11511                   return Expression::make_error(location);
11512                 }
11513 	      go_assert(type->points_to() != NULL);
11514               expr = Expression::make_dereference(expr,
11515                                                   Expression::NIL_CHECK_DEFAULT,
11516                                                   location);
11517 	      go_assert(expr->type()->struct_type() == st);
11518 	    }
11519 	  ret = st->field_reference(expr, name, location);
11520           if (ret == NULL)
11521             {
11522               go_error_at(location, "type has no field %qs",
11523                           Gogo::message_name(name).c_str());
11524               return Expression::make_error(location);
11525             }
11526 	}
11527       else if (it != NULL && it->find_method(name) != NULL)
11528 	ret = Expression::make_interface_field_reference(expr, name,
11529 							 location);
11530       else
11531 	{
11532 	  Method* m;
11533 	  if (nt != NULL)
11534 	    m = nt->method_function(name, NULL);
11535 	  else if (st != NULL)
11536 	    m = st->method_function(name, NULL);
11537 	  else
11538 	    go_unreachable();
11539 	  go_assert(m != NULL);
11540 	  if (dereferenced)
11541 	    {
11542 	      go_error_at(location,
11543 			  "calling method %qs requires explicit dereference",
11544 			  Gogo::message_name(name).c_str());
11545 	      return Expression::make_error(location);
11546 	    }
11547 	  if (!m->is_value_method() && expr->type()->points_to() == NULL)
11548 	    expr = Expression::make_unary(OPERATOR_AND, expr, location);
11549 	  ret = m->bind_method(expr, location);
11550 	}
11551       go_assert(ret != NULL);
11552       return ret;
11553     }
11554   else
11555     {
11556       if (Gogo::is_erroneous_name(name))
11557 	{
11558 	  // An error was already reported.
11559 	}
11560       else if (!ambig1.empty())
11561 	go_error_at(location, "%qs is ambiguous via %qs and %qs",
11562 		    Gogo::message_name(name).c_str(), ambig1.c_str(),
11563 		    ambig2.c_str());
11564       else if (found_pointer_method)
11565 	go_error_at(location, "method requires a pointer receiver");
11566       else if (nt == NULL && st == NULL && it == NULL)
11567 	go_error_at(location,
11568 		    ("reference to field %qs in object which "
11569 		     "has no fields or methods"),
11570 		    Gogo::message_name(name).c_str());
11571       else
11572 	{
11573 	  bool is_unexported;
11574 	  // The test for 'a' and 'z' is to handle builtin names,
11575 	  // which are not hidden.
11576 	  if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11577 	    is_unexported = false;
11578 	  else
11579 	    {
11580 	      std::string unpacked = Gogo::unpack_hidden_name(name);
11581 	      seen.clear();
11582 	      is_unexported = Type::is_unexported_field_or_method(gogo, type,
11583 								  unpacked,
11584 								  &seen);
11585 	    }
11586 	  if (is_unexported)
11587 	    go_error_at(location, "reference to unexported field or method %qs",
11588 			Gogo::message_name(name).c_str());
11589 	  else
11590 	    go_error_at(location, "reference to undefined field or method %qs",
11591 			Gogo::message_name(name).c_str());
11592 	}
11593       return Expression::make_error(location);
11594     }
11595 }
11596 
11597 // Look in TYPE for a field or method named NAME, return true if one
11598 // is found.  This looks through embedded anonymous fields and handles
11599 // ambiguity.  If a method is found, sets *IS_METHOD to true;
11600 // otherwise, if a field is found, set it to false.  If
11601 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11602 // whose address can not be taken.  SEEN is used to avoid infinite
11603 // recursion on invalid types.
11604 
11605 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11606 // method we couldn't use because it requires a pointer.  LEVEL is
11607 // used for recursive calls, and can be NULL for a non-recursive call.
11608 // When this function returns false because it finds that the name is
11609 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11610 // and *AMBIG2.  If the name is not found at all, *AMBIG1 and *AMBIG2
11611 // will be unchanged.
11612 
11613 // This function just returns whether or not there is a field or
11614 // method, and whether it is a field or method.  It doesn't build an
11615 // expression to refer to it.  If it is a method, we then look in the
11616 // list of all methods for the type.  If it is a field, the search has
11617 // to be done again, looking only for fields, and building up the
11618 // expression as we go.
11619 
11620 bool
find_field_or_method(const Type * type,const std::string & name,bool receiver_can_be_pointer,std::vector<const Named_type * > * seen,int * level,bool * is_method,bool * found_pointer_method,std::string * ambig1,std::string * ambig2)11621 Type::find_field_or_method(const Type* type,
11622 			   const std::string& name,
11623 			   bool receiver_can_be_pointer,
11624 			   std::vector<const Named_type*>* seen,
11625 			   int* level,
11626 			   bool* is_method,
11627 			   bool* found_pointer_method,
11628 			   std::string* ambig1,
11629 			   std::string* ambig2)
11630 {
11631   // Named types can have locally defined methods.
11632   const Named_type* nt = type->unalias()->named_type();
11633   if (nt == NULL && type->points_to() != NULL)
11634     nt = type->points_to()->unalias()->named_type();
11635   if (nt != NULL)
11636     {
11637       Named_object* no = nt->find_local_method(name);
11638       if (no != NULL)
11639 	{
11640 	  if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11641 	    {
11642 	      *is_method = true;
11643 	      return true;
11644 	    }
11645 
11646 	  // Record that we have found a pointer method in order to
11647 	  // give a better error message if we don't find anything
11648 	  // else.
11649 	  *found_pointer_method = true;
11650 	}
11651 
11652       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11653 	   p != seen->end();
11654 	   ++p)
11655 	{
11656 	  if (*p == nt)
11657 	    {
11658 	      // We've already seen this type when searching for methods.
11659 	      return false;
11660 	    }
11661 	}
11662     }
11663 
11664   // Interface types can have methods.
11665   const Interface_type* it = type->interface_type();
11666   if (it != NULL && it->find_method(name) != NULL)
11667     {
11668       *is_method = true;
11669       return true;
11670     }
11671 
11672   // Struct types can have fields.  They can also inherit fields and
11673   // methods from anonymous fields.
11674   const Struct_type* st = type->deref()->struct_type();
11675   if (st == NULL)
11676     return false;
11677   const Struct_field_list* fields = st->fields();
11678   if (fields == NULL)
11679     return false;
11680 
11681   if (nt != NULL)
11682     seen->push_back(nt);
11683 
11684   int found_level = 0;
11685   bool found_is_method = false;
11686   std::string found_ambig1;
11687   std::string found_ambig2;
11688   const Struct_field* found_parent = NULL;
11689   for (Struct_field_list::const_iterator pf = fields->begin();
11690        pf != fields->end();
11691        ++pf)
11692     {
11693       if (pf->is_field_name(name))
11694 	{
11695 	  *is_method = false;
11696 	  if (nt != NULL)
11697 	    seen->pop_back();
11698 	  return true;
11699 	}
11700 
11701       if (!pf->is_anonymous())
11702 	continue;
11703 
11704       if (pf->type()->deref()->is_error_type()
11705 	  || pf->type()->deref()->is_undefined())
11706 	continue;
11707 
11708       Named_type* fnt = pf->type()->named_type();
11709       if (fnt == NULL)
11710 	fnt = pf->type()->deref()->named_type();
11711       go_assert(fnt != NULL);
11712 
11713       // Methods with pointer receivers on embedded field are
11714       // inherited by the pointer to struct, and also by the struct
11715       // type if the field itself is a pointer.
11716       bool can_be_pointer = (receiver_can_be_pointer
11717 			     || pf->type()->points_to() != NULL);
11718       int sublevel = level == NULL ? 1 : *level + 1;
11719       bool sub_is_method;
11720       std::string subambig1;
11721       std::string subambig2;
11722       bool subfound = Type::find_field_or_method(fnt,
11723 						 name,
11724 						 can_be_pointer,
11725 						 seen,
11726 						 &sublevel,
11727 						 &sub_is_method,
11728 						 found_pointer_method,
11729 						 &subambig1,
11730 						 &subambig2);
11731       if (!subfound)
11732 	{
11733 	  if (!subambig1.empty())
11734 	    {
11735 	      // The name was found via this field, but is ambiguous.
11736 	      // if the ambiguity is lower or at the same level as
11737 	      // anything else we have already found, then we want to
11738 	      // pass the ambiguity back to the caller.
11739 	      if (found_level == 0 || sublevel <= found_level)
11740 		{
11741 		  found_ambig1 = (Gogo::message_name(pf->field_name())
11742 				  + '.' + subambig1);
11743 		  found_ambig2 = (Gogo::message_name(pf->field_name())
11744 				  + '.' + subambig2);
11745 		  found_level = sublevel;
11746 		}
11747 	    }
11748 	}
11749       else
11750 	{
11751 	  // The name was found via this field.  Use the level to see
11752 	  // if we want to use this one, or whether it introduces an
11753 	  // ambiguity.
11754 	  if (found_level == 0 || sublevel < found_level)
11755 	    {
11756 	      found_level = sublevel;
11757 	      found_is_method = sub_is_method;
11758 	      found_ambig1.clear();
11759 	      found_ambig2.clear();
11760 	      found_parent = &*pf;
11761 	    }
11762 	  else if (sublevel > found_level)
11763 	    ;
11764 	  else if (found_ambig1.empty())
11765 	    {
11766 	      // We found an ambiguity.
11767 	      go_assert(found_parent != NULL);
11768 	      found_ambig1 = Gogo::message_name(found_parent->field_name());
11769 	      found_ambig2 = Gogo::message_name(pf->field_name());
11770 	    }
11771 	  else
11772 	    {
11773 	      // We found an ambiguity, but we already know of one.
11774 	      // Just report the earlier one.
11775 	    }
11776 	}
11777     }
11778 
11779   // Here if we didn't find anything FOUND_LEVEL is 0.  If we found
11780   // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11781   // FOUND_AMBIG2 are not empty.  If we found the field, FOUND_LEVEL
11782   // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11783 
11784   if (nt != NULL)
11785     seen->pop_back();
11786 
11787   if (found_level == 0)
11788     return false;
11789   else if (found_is_method
11790 	   && type->named_type() != NULL
11791 	   && type->points_to() != NULL)
11792     {
11793       // If this is a method inherited from a struct field in a named pointer
11794       // type, it is invalid to automatically dereference the pointer to the
11795       // struct to find this method.
11796       if (level != NULL)
11797 	*level = found_level;
11798       *is_method = true;
11799       return false;
11800     }
11801   else if (!found_ambig1.empty())
11802     {
11803       go_assert(!found_ambig1.empty());
11804       ambig1->assign(found_ambig1);
11805       ambig2->assign(found_ambig2);
11806       if (level != NULL)
11807 	*level = found_level;
11808       return false;
11809     }
11810   else
11811     {
11812       if (level != NULL)
11813 	*level = found_level;
11814       *is_method = found_is_method;
11815       return true;
11816     }
11817 }
11818 
11819 // Return whether NAME is an unexported field or method for TYPE.
11820 
11821 bool
is_unexported_field_or_method(Gogo * gogo,const Type * type,const std::string & name,std::vector<const Named_type * > * seen)11822 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11823 				    const std::string& name,
11824 				    std::vector<const Named_type*>* seen)
11825 {
11826   const Named_type* nt = type->named_type();
11827   if (nt == NULL)
11828     nt = type->deref()->named_type();
11829   if (nt != NULL)
11830     {
11831       if (nt->is_unexported_local_method(gogo, name))
11832 	return true;
11833 
11834       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11835 	   p != seen->end();
11836 	   ++p)
11837 	{
11838 	  if (*p == nt)
11839 	    {
11840 	      // We've already seen this type.
11841 	      return false;
11842 	    }
11843 	}
11844     }
11845 
11846   const Interface_type* it = type->interface_type();
11847   if (it != NULL && it->is_unexported_method(gogo, name))
11848     return true;
11849 
11850   type = type->deref();
11851 
11852   const Struct_type* st = type->struct_type();
11853   if (st != NULL && st->is_unexported_local_field(gogo, name))
11854     return true;
11855 
11856   if (st == NULL)
11857     return false;
11858 
11859   const Struct_field_list* fields = st->fields();
11860   if (fields == NULL)
11861     return false;
11862 
11863   if (nt != NULL)
11864     seen->push_back(nt);
11865 
11866   for (Struct_field_list::const_iterator pf = fields->begin();
11867        pf != fields->end();
11868        ++pf)
11869     {
11870       if (pf->is_anonymous()
11871 	  && !pf->type()->deref()->is_error_type()
11872 	  && !pf->type()->deref()->is_undefined())
11873 	{
11874 	  Named_type* subtype = pf->type()->named_type();
11875 	  if (subtype == NULL)
11876 	    subtype = pf->type()->deref()->named_type();
11877 	  if (subtype == NULL)
11878 	    {
11879 	      // This is an error, but it will be diagnosed elsewhere.
11880 	      continue;
11881 	    }
11882 	  if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11883 	    {
11884 	      if (nt != NULL)
11885 		seen->pop_back();
11886 	      return true;
11887 	    }
11888 	}
11889     }
11890 
11891   if (nt != NULL)
11892     seen->pop_back();
11893 
11894   return false;
11895 }
11896 
11897 // Class Forward_declaration.
11898 
Forward_declaration_type(Named_object * named_object)11899 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11900   : Type(TYPE_FORWARD),
11901     named_object_(named_object->resolve()), warned_(false)
11902 {
11903   go_assert(this->named_object_->is_unknown()
11904 	     || this->named_object_->is_type_declaration());
11905 }
11906 
11907 // Return the named object.
11908 
11909 Named_object*
named_object()11910 Forward_declaration_type::named_object()
11911 {
11912   return this->named_object_->resolve();
11913 }
11914 
11915 const Named_object*
named_object() const11916 Forward_declaration_type::named_object() const
11917 {
11918   return this->named_object_->resolve();
11919 }
11920 
11921 // Return the name of the forward declared type.
11922 
11923 const std::string&
name() const11924 Forward_declaration_type::name() const
11925 {
11926   return this->named_object()->name();
11927 }
11928 
11929 // Warn about a use of a type which has been declared but not defined.
11930 
11931 void
warn() const11932 Forward_declaration_type::warn() const
11933 {
11934   Named_object* no = this->named_object_->resolve();
11935   if (no->is_unknown())
11936     {
11937       // The name was not defined anywhere.
11938       if (!this->warned_)
11939 	{
11940 	  go_error_at(this->named_object_->location(),
11941 		      "use of undefined type %qs",
11942 		      no->message_name().c_str());
11943 	  this->warned_ = true;
11944 	}
11945     }
11946   else if (no->is_type_declaration())
11947     {
11948       // The name was seen as a type, but the type was never defined.
11949       if (no->type_declaration_value()->using_type())
11950 	{
11951 	  go_error_at(this->named_object_->location(),
11952 		      "use of undefined type %qs",
11953 		      no->message_name().c_str());
11954 	  this->warned_ = true;
11955 	}
11956     }
11957   else
11958     {
11959       // The name was defined, but not as a type.
11960       if (!this->warned_)
11961 	{
11962 	  go_error_at(this->named_object_->location(), "expected type");
11963 	  this->warned_ = true;
11964 	}
11965     }
11966 }
11967 
11968 // Get the base type of a declaration.  This gives an error if the
11969 // type has not yet been defined.
11970 
11971 Type*
real_type()11972 Forward_declaration_type::real_type()
11973 {
11974   if (this->is_defined())
11975     {
11976       Named_type* nt = this->named_object()->type_value();
11977       if (!nt->is_valid())
11978 	return Type::make_error_type();
11979       return this->named_object()->type_value();
11980     }
11981   else
11982     {
11983       this->warn();
11984       return Type::make_error_type();
11985     }
11986 }
11987 
11988 const Type*
real_type() const11989 Forward_declaration_type::real_type() const
11990 {
11991   if (this->is_defined())
11992     {
11993       const Named_type* nt = this->named_object()->type_value();
11994       if (!nt->is_valid())
11995 	return Type::make_error_type();
11996       return this->named_object()->type_value();
11997     }
11998   else
11999     {
12000       this->warn();
12001       return Type::make_error_type();
12002     }
12003 }
12004 
12005 // Return whether the base type is defined.
12006 
12007 bool
is_defined() const12008 Forward_declaration_type::is_defined() const
12009 {
12010   return this->named_object()->is_type();
12011 }
12012 
12013 // Add a method.  This is used when methods are defined before the
12014 // type.
12015 
12016 Named_object*
add_method(const std::string & name,Function * function)12017 Forward_declaration_type::add_method(const std::string& name,
12018 				     Function* function)
12019 {
12020   Named_object* no = this->named_object();
12021   if (no->is_unknown())
12022     no->declare_as_type();
12023   return no->type_declaration_value()->add_method(name, function);
12024 }
12025 
12026 // Add a method declaration.  This is used when methods are declared
12027 // before the type.
12028 
12029 Named_object*
add_method_declaration(const std::string & name,Package * package,Function_type * type,Location location)12030 Forward_declaration_type::add_method_declaration(const std::string& name,
12031 						 Package* package,
12032 						 Function_type* type,
12033 						 Location location)
12034 {
12035   Named_object* no = this->named_object();
12036   if (no->is_unknown())
12037     no->declare_as_type();
12038   Type_declaration* td = no->type_declaration_value();
12039   return td->add_method_declaration(name, package, type, location);
12040 }
12041 
12042 // Add an already created object as a method.
12043 
12044 void
add_existing_method(Named_object * nom)12045 Forward_declaration_type::add_existing_method(Named_object* nom)
12046 {
12047   Named_object* no = this->named_object();
12048   if (no->is_unknown())
12049     no->declare_as_type();
12050   no->type_declaration_value()->add_existing_method(nom);
12051 }
12052 
12053 // Traversal.
12054 
12055 int
do_traverse(Traverse * traverse)12056 Forward_declaration_type::do_traverse(Traverse* traverse)
12057 {
12058   if (this->is_defined()
12059       && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12060     return TRAVERSE_EXIT;
12061   return TRAVERSE_CONTINUE;
12062 }
12063 
12064 // Verify the type.
12065 
12066 bool
do_verify()12067 Forward_declaration_type::do_verify()
12068 {
12069   if (!this->is_defined() && !this->is_nil_constant_as_type())
12070     {
12071       this->warn();
12072       return false;
12073     }
12074   return true;
12075 }
12076 
12077 // Get the backend representation for the type.
12078 
12079 Btype*
do_get_backend(Gogo * gogo)12080 Forward_declaration_type::do_get_backend(Gogo* gogo)
12081 {
12082   if (this->is_defined())
12083     return Type::get_named_base_btype(gogo, this->real_type());
12084 
12085   if (this->warned_)
12086     return gogo->backend()->error_type();
12087 
12088   // We represent an undefined type as a struct with no fields.  That
12089   // should work fine for the backend, since the same case can arise
12090   // in C.
12091   std::vector<Backend::Btyped_identifier> fields;
12092   Btype* bt = gogo->backend()->struct_type(fields);
12093   return gogo->backend()->named_type(this->name(), bt,
12094 				     this->named_object()->location());
12095 }
12096 
12097 // Build a type descriptor for a forwarded type.
12098 
12099 Expression*
do_type_descriptor(Gogo * gogo,Named_type * name)12100 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12101 {
12102   Location ploc = Linemap::predeclared_location();
12103   if (!this->is_defined())
12104     return Expression::make_error(ploc);
12105   else
12106     {
12107       Type* t = this->real_type();
12108       if (name != NULL)
12109 	return this->named_type_descriptor(gogo, t, name);
12110       else
12111 	return Expression::make_error(this->named_object_->location());
12112     }
12113 }
12114 
12115 // The reflection string.
12116 
12117 void
do_reflection(Gogo * gogo,std::string * ret) const12118 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12119 {
12120   this->append_reflection(this->real_type(), gogo, ret);
12121 }
12122 
12123 // Export a forward declaration.  This can happen when a defined type
12124 // refers to a type which is only declared (and is presumably defined
12125 // in some other file in the same package).
12126 
12127 void
do_export(Export *) const12128 Forward_declaration_type::do_export(Export*) const
12129 {
12130   // If there is a base type, that should be exported instead of this.
12131   go_assert(!this->is_defined());
12132 
12133   // We don't output anything.
12134 }
12135 
12136 // Make a forward declaration.
12137 
12138 Type*
make_forward_declaration(Named_object * named_object)12139 Type::make_forward_declaration(Named_object* named_object)
12140 {
12141   return new Forward_declaration_type(named_object);
12142 }
12143 
12144 // Class Typed_identifier_list.
12145 
12146 // Sort the entries by name.
12147 
12148 struct Typed_identifier_list_sort
12149 {
12150  public:
12151   bool
operator ()Typed_identifier_list_sort12152   operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12153   {
12154     return (Gogo::unpack_hidden_name(t1.name())
12155 	    < Gogo::unpack_hidden_name(t2.name()));
12156   }
12157 };
12158 
12159 void
sort_by_name()12160 Typed_identifier_list::sort_by_name()
12161 {
12162   std::sort(this->entries_.begin(), this->entries_.end(),
12163 	    Typed_identifier_list_sort());
12164 }
12165 
12166 // Traverse types.
12167 
12168 int
traverse(Traverse * traverse)12169 Typed_identifier_list::traverse(Traverse* traverse)
12170 {
12171   for (Typed_identifier_list::const_iterator p = this->begin();
12172        p != this->end();
12173        ++p)
12174     {
12175       if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12176 	return TRAVERSE_EXIT;
12177     }
12178   return TRAVERSE_CONTINUE;
12179 }
12180 
12181 // Copy the list.
12182 
12183 Typed_identifier_list*
copy() const12184 Typed_identifier_list::copy() const
12185 {
12186   Typed_identifier_list* ret = new Typed_identifier_list();
12187   for (Typed_identifier_list::const_iterator p = this->begin();
12188        p != this->end();
12189        ++p)
12190     ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12191   return ret;
12192 }
12193