OSDN Git Service

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