OSDN Git Service

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