OSDN Git Service

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