OSDN Git Service

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