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