OSDN Git Service

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